Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Complete block API contract migration https://github.com/siyuan-note/siyuan/issues/19378

Daniel320f6ecd1d24
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 3c472cf369..5680b7393a 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -72,6 +72,8 @@ export type ChangeMasterPasswordRequestInput = { "newPassword": string; "oldPass
export type ChangeSortNotebookRequestInput = { "notebooks": Array<string>; };
+export type CheckBlockRefRequestInput = { "deletedIDs"?: Array<string>; "exactIDs"?: Array<string>; "id"?: string | null; "ids"?: Array<string>; "notebook"?: string | null; "paths"?: Array<string>; "scope"?: string; };
+
export type CheckBlocksExistRequestInput = { "id"?: string | null; "ids": Array<JSONValue>; "notebook"?: string | null; };
export type CheckSnapshotData = { "changed": boolean; };
@@ -100,6 +102,10 @@ export type DeleteBlockRequestInput = { "id": string; };
export type DocAttrView = { "id": string; "name": string; };
+export type DocHeadingLevelData = { "counts": Array<number>; "title": string; "transaction": BlockTransaction | null; "withSubheadingCounts": Array<number>; };
+
+export type DocHeadingLevelRequestInput = { "id"?: string | null; "notebook"?: string | null; "source"?: number | null; "target"?: number | null; "withSubheadings"?: boolean | null; };
+
export type DocInfo = { "attrViews": Array<DocAttrView | null> | null; "ial": Record<string, string> | null; "icon": string; "id": string; "name": string; "refCount": number; "refIDs": Array<string> | null; "rootID": string; "subFileCount": number; };
export type DocOrdersRequestInput = { "id": string; };
@@ -128,6 +134,8 @@ export type HeadingChildrenRequestInput = { "id": string; "removeFoldAttr"?: boo
export type HeadingFoldRequestInput = { "id": string; "scope": string; };
+export type HeadingLevelRequestInput = { "id"?: string; "ids"?: Array<string>; "level": number; };
+
export type ImportNotebookCryptoBackupRequestInput = { "file": Blob; "password"?: string; };
export type InsertBlockRequestInput = { "data": string; "dataType": string; "nextID"?: string | null; "parentID"?: string | null; "previousID"?: string | null; };
@@ -210,6 +218,10 @@ export type ReorderData = { "changed": boolean; "notebook"?: string; "parentPath
export type ReorderNotebooksRequestInput = { "position"?: string | null; "sourceIDs"?: Array<string> | null; "targetID"?: string | null; };
+export type SearchBlock = { "alias": string; "box": string; "children": Array<SearchBlock | null> | null; "content": string; "count": number; "created": string; "defID": string; "defPath": string; "depth": number; "fcontent": string; "folded": boolean; "hPath": string; "ial": Record<string, string> | null; "id": string; "markdown": string; "memo": string; "name": string; "number"?: string; "parentID": string; "path": string; "refCount": number; "refText": string; "refs": Array<SearchBlock | null> | null; "riffCard": SearchBlockCard | null; "riffCardID": string; "rootID": string; "sort": number; "subType": string; "tag": string; "type": string; "updated": string; };
+
+export type SearchBlockCard = { "due": string; "lapses": number; "lastReview": string; "reps": number; "state": number; };
+
export type SearchHistoryData = { "histories": Array<string> | null; "pageCount": number; "totalCount": number; };
export type SearchHistoryRequestInput = { "notebook"?: string | null; "op"?: string | null; "page"?: number | null; "query"?: string | null; "type"?: number | null; };
@@ -432,10 +444,6 @@ export type APILegacyPOSTPath =
"/api/bazaar/uninstallBazaarTheme" |
"/api/bazaar/uninstallBazaarWidget" |
"/api/bazaar/updateBazaarPackage" |
- "/api/block/checkBlockRef" |
- "/api/block/getDocHeadingLevelTransaction" |
- "/api/block/getHeadingLevelTransaction" |
- "/api/block/getRecentUpdatedBlocks" |
"/api/bookmark/getBookmark" |
"/api/broadcast/getChannelInfo" |
"/api/broadcast/getChannels" |
@@ -857,6 +865,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": BlockFoldData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/block/checkBlockRef": {
+ request: CheckBlockRefRequestInput;
+ response: { "code": 0; "data": boolean; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | boolean; "msg": string; };
+ body: "json";
+ };
"/api/block/checkBlocksExist": {
request: CheckBlocksExistRequestInput;
response: { "code": 0; "data": Record<string, boolean> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -972,6 +985,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": Array<string> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/block/getDocHeadingLevelTransaction": {
+ request: DocHeadingLevelRequestInput;
+ response: { "code": 0; "data": DocHeadingLevelData | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "structJSON";
+ };
"/api/block/getDocInfo": {
request: BlockQueryRequestInput;
response: { "code": 0; "data": DocInfo | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -1007,11 +1025,21 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": BlockTransaction | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/block/getHeadingLevelTransaction": {
+ request: HeadingLevelRequestInput;
+ response: { "code": 0; "data": BlockTransaction | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/block/getOrderedListContinueStart": {
request: BlockQueryRequestInput;
response: { "code": 0; "data": OrderedListStartData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/block/getRecentUpdatedBlocks": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": Array<SearchBlock | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
"/api/block/getRefIDs": {
request: RefIDsRequestInput;
response: { "code": 0; "data": RefIDsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.ts
index b95579fe20..4b0c75f776 100644
--- a/app/tests/api-contract.types.ts
+++ b/app/tests/api-contract.types.ts
@@ -121,6 +121,35 @@ fetchPost("/api/block/getHeadingDeleteTransaction", {id: "id"}, response => {
});
declare const notebooks: APIPOSTRoutes["/api/notebook/lsNotebooks"]["response"];
+
+fetchPost("/api/block/checkBlockRef", {scope: "blocks", ids: ["id"]}, response => {
+ const hasReference: boolean = response.data;
+ void hasReference;
+});
+// @ts-expect-error 引用检查仅接受字符串数组。
+fetchPost("/api/block/checkBlockRef", {ids: [42]});
+// @ts-expect-error 标题级别必须为数字。
+fetchPost("/api/block/getHeadingLevelTransaction", {id: "id", level: "2"});
+// @ts-expect-error 文档标题转换开关必须为布尔值。
+fetchPost("/api/block/getDocHeadingLevelTransaction", {id: "id", withSubheadings: "true"});
+fetchPost("/api/block/getDocHeadingLevelTransaction", {id: "id"}, response => {
+ if (response.data) {
+ const counts: number[] = response.data.counts;
+ // @ts-expect-error 标题转换结果没有内容字段。
+ void response.data.content;
+ void counts;
+ }
+});
+fetchPost("/api/block/getRecentUpdatedBlocks", {}, response => {
+ const block = response.data?.[0];
+ if (block) {
+ const content: string = block.content;
+ // @ts-expect-error 最近更新块的内容不是数字。
+ const invalid: number = block.content;
+ void [content, invalid];
+ }
+});
+
if (notebooks.code === 0) {
// @ts-expect-error 成功码下的空数据也必须在严格模式下被检查。
void notebooks.data.notebooks;
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 2028317743..ad959d4ec7 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -48,6 +48,8 @@ Notebook configuration updates use a typed partial object. The `legacyobject` fi
Heading transaction queries return `BlockTransaction` with typed operations and preserve empty, null, and undo-operation payloads. `BlockOperationResult` declares the finite union of text, block ID arrays, and null. Conversion from the model's polymorphic fields rejects unsupported types; attribute-view operations require their own payload contracts. The editor's operation type also accepts the empty column-type field returned by non-attribute-view operations.
+All `/api/block/` routes use contracts. Heading-level queries retain batch-ID precedence, deduplication, fractional-level truncation, document struct binding, and message display durations. Document conversion results include the six heading counts and typed transactions. Reference checks validate only the fields used by the selected scope, preserve ignored fields and notebook trimming rules, and retain boolean error payloads, publish filtering, and notebook leases through response serialization. These exceptional input rules use private, endpoint-specific typed decoders; ordinary endpoints continue to use field declarations. Recent-update results use a recursive `SearchBlock` payload, including nullable references, children, and card metadata.
+
## Multipart requests
Use `MultipartBody` for file uploads. Request structs declare string fields and `*multipart.FileHeader` fields using their wire names; file schemas use `type: string` and `format: binary`, generating `Blob` declarations. The adapter retains Gin multipart parsing and binds the first value for repeated fields. File contents remain available through `Open`, so handlers preserve their read and recovery logic. Unsupported field types and binding options fail generation.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index 448c58952c..b1f4d2361e 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -48,6 +48,8 @@
标题事务查询使用 `BlockTransaction` 返回有类型的操作,保留空数组、空值和撤销操作载荷。`BlockOperationResult` 明确声明文本、块 ID 数组和空值的有限联合类型。业务模型中的多态字段转换时拒绝不支持的类型,属性视图操作需要单独声明其载荷契约。编辑器操作类型同时接受非属性视图操作返回的空列类型字段。
+全部 `/api/block/` 路由已使用契约。标题级别查询保留批量 ID 优先、去重、小数级别截断、文档结构体绑定和消息展示时长。文档转换结果包含六级标题计数和有类型的事务。引用检查仅校验所选范围使用的字段,保留忽略字段及笔记本参数去空白规则,并保留布尔错误载荷、发布过滤和持续到响应序列化完成的笔记本租约。这些特殊输入规则使用私有的入口专用类型解码函数,普通接口继续通过字段声明解码。最近更新结果使用递归的 `SearchBlock` 载荷,包含可为空的引用、子块和卡片元数据。
+
## 文件上传请求
文件上传使用 `MultipartBody`。请求结构体以线协议字段名声明字符串和 `*multipart.FileHeader` 字段;文件 schema 使用 `type: string` 与 `format: binary`,生成 `Blob` 类型。适配器保留 Gin 的表单解析方式,重复字段取首值;文件内容继续通过 `Open` 读取,处理函数保留读取及恢复逻辑。未支持的字段类型和绑定选项会使生成失败。
diff --git a/kernel/api/block.go b/kernel/api/block.go
index 8b9ff80a71..8a3163519b 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -35,51 +35,14 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-func checkBlockRef(c *gin.Context) {
+var checkBlockRef = contractHandler(apicontract.CheckBlockRef, func(c *gin.Context, request apicontract.CheckBlockRefRequest) apicontract.Response[bool] {
ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
-
- scope := ""
- if scopeArg, exists := arg["scope"]; exists {
- var valid bool
- scope, valid = scopeArg.(string)
- if !valid {
- ret.Code = -1
- ret.Msg = "Field [scope] should be of type [String]"
- return
- }
- }
- if "" == strings.TrimSpace(scope) {
- scope = "blocks"
- }
- switch scope {
+ switch request.Scope {
case "blocks":
- ids, parsed := parseBlockRefStringArray(arg, "ids", ret, true)
- if !parsed {
- return
- }
- var exactIDs []string
- if _, exists := arg["exactIDs"]; exists {
- exactIDs, parsed = parseBlockRefStringArray(arg, "exactIDs", ret, false)
- if !parsed {
- return
- }
- }
- var deletedIDs []string
- if _, exists := arg["deletedIDs"]; exists {
- deletedIDs, parsed = parseBlockRefStringArray(arg, "deletedIDs", ret, false)
- if !parsed {
- return
- }
- }
+ ids, exactIDs, deletedIDs := request.IDs, request.ExactIDs, request.DeletedIDs
for _, id := range ids {
if util.InvalidIDPattern(id, ret) {
- return
+ return contractFailure[bool](ret)
}
}
idSet := map[string]struct{}{}
@@ -88,48 +51,41 @@ func checkBlockRef(c *gin.Context) {
}
for _, id := range exactIDs {
if util.InvalidIDPattern(id, ret) {
- return
+ return contractFailure[bool](ret)
}
if _, exists := idSet[id]; !exists {
ret.Code = -1
ret.Msg = "Field [exactIDs] should be a subset of field [ids]"
- return
+ return contractFailure[bool](ret)
}
}
for _, id := range deletedIDs {
if util.InvalidIDPattern(id, ret) {
- return
+ return contractFailure[bool](ret)
}
if _, exists := idSet[id]; !exists {
ret.Code = -1
ret.Msg = "Field [deletedIDs] should be a subset of field [ids]"
- return
+ return contractFailure[bool](ret)
}
}
- notebook, valid := util.ParseJsonArg[string]("notebook", arg, ret, false, false)
- if !valid {
- return
- }
+ notebook := request.Notebook
if "" != notebook && util.InvalidIDPattern(notebook, ret) {
- return
+ return contractFailure[bool](ret)
}
- if !holdBlockRequest(c, ret, notebook, arg, true) {
- return
+ if err := holdEncryptedBlockRequests(c, notebook, append([]string{request.ID}, request.IDs...), true); err != nil {
+ return apicontract.Failure[bool](-1, err.Error())
}
ids = filterBlockIDsByPublishAccess(c, ids, notebook)
exactIDs = filterBlockIDsByPublishAccess(c, exactIDs, notebook)
deletedIDs = filterBlockIDsByPublishAccess(c, deletedIDs, notebook)
- var err error
- ret.Data, err = model.CheckBlockRefInBox(ids, exactIDs, deletedIDs, notebook)
+ data, err := model.CheckBlockRefInBox(ids, exactIDs, deletedIDs, notebook)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
+ return apicontract.CheckBlockRef.FailureWithData(-1, err.Error(), data)
}
+ return apicontract.Success(data)
case "documents":
- paths, parsed := parseBlockRefStringArray(arg, "paths", ret, true)
- if !parsed {
- return
- }
+ paths := request.Paths
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
var accessiblePaths []string
@@ -141,25 +97,20 @@ func checkBlockRef(c *gin.Context) {
paths = accessiblePaths
}
if 0 == len(paths) {
- ret.Data = false
- return
+ return apicontract.Success(false)
}
- var err error
- ret.Data, err = model.CheckDocsRef(paths)
+ data, err := model.CheckDocsRef(paths)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
+ return apicontract.CheckBlockRef.FailureWithData(-1, err.Error(), data)
}
+ return apicontract.Success(data)
case "notebook":
- var notebook string
- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("notebook", &notebook, true, true)) {
- return
- }
+ notebook := request.Notebook
if util.InvalidIDPattern(notebook, ret) {
- return
+ return contractFailure[bool](ret)
}
- if !holdBlockRequest(c, ret, notebook, arg) {
- return
+ if err := holdEncryptedBlockRequests(c, notebook, append([]string{request.ID}, request.IDs...), false); err != nil {
+ return apicontract.Failure[bool](-1, err.Error())
}
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
@@ -171,39 +122,20 @@ func checkBlockRef(c *gin.Context) {
}
}
if !accessible {
- ret.Data = false
- return
+ return apicontract.Success(false)
}
}
- var err error
- ret.Data, err = model.CheckNotebookRef(notebook)
+ data, err := model.CheckNotebookRef(notebook)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
+ return apicontract.CheckBlockRef.FailureWithData(-1, err.Error(), data)
}
+ return apicontract.Success(data)
default:
ret.Code = -1
ret.Msg = "invalid block ref check scope"
}
-}
-
-func parseBlockRefStringArray(arg map[string]any, key string, ret *gulu.Result, rejectEmpty bool) (values []string, ok bool) {
- var raw []any
- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg(key, &raw, true, rejectEmpty)) {
- return
- }
- for _, value := range raw {
- str, isString := value.(string)
- if !isString || "" == strings.TrimSpace(str) {
- ret.Code = -1
- ret.Msg = fmt.Sprintf("Field [%s] should contain non-empty strings", key)
- return nil, false
- }
- values = append(values, str)
- }
- values = gulu.Str.RemoveDuplicatedElem(values)
- return values, true
-}
+ return contractFailure[bool](ret)
+})
var getBlockTreeInfos = contractHandler(apicontract.GetBlockTreeInfos, func(c *gin.Context, request apicontract.BlocksQueryRequest) apicontract.Response[map[string]*apicontract.BlockTreeInfo] {
boxID, err := holdContractBlockRequest(c, request.Notebook, request.ID, request.IDs, false)
@@ -311,63 +243,32 @@ var getHeadingInsertTransaction = contractHandler(apicontract.GetHeadingInsertTr
return blockTransactionResponse(transaction)
})
-func getDocHeadingLevelTransaction(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
- var arg struct {
- ID string `json:"id"`
- Notebook string `json:"notebook"`
- Source int `json:"source"`
- Target int `json:"target"`
- WithSubheadings bool `json:"withSubheadings"`
- }
- if err := c.ShouldBindJSON(&arg); err != nil || arg.ID == "" ||
- arg.Source < 0 || arg.Source > 6 || arg.Target < 0 || arg.Target > 6 ||
- (arg.Source == 0) != (arg.Target == 0) {
- ret.Code = -1
- ret.Msg = "invalid heading conversion parameters"
- return
+var getDocHeadingLevelTransaction = contractHandler(apicontract.GetDocHeadingLevelTransaction, func(c *gin.Context, request apicontract.DocHeadingLevelRequest) apicontract.Response[*apicontract.DocHeadingLevelData] {
+ if request.ID == "" || request.Source < 0 || request.Source > 6 || request.Target < 0 || request.Target > 6 || (request.Source == 0) != (request.Target == 0) {
+ return apicontract.Failure[*apicontract.DocHeadingLevelData](-1, "invalid heading conversion parameters")
}
- result, err := model.GetDocHeadingLevelTransaction(arg.ID, arg.Notebook, arg.Source, arg.Target, arg.WithSubheadings)
+ result, err := model.GetDocHeadingLevelTransaction(request.ID, request.Notebook, request.Source, request.Target, request.WithSubheadings)
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[*apicontract.DocHeadingLevelData](-1, err.Error())
}
- ret.Data = result
-}
-
-func getHeadingLevelTransaction(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
+ transaction, err := blockTransactionContract(result.Transaction)
+ if err != nil {
+ return apicontract.Failure[*apicontract.DocHeadingLevelData](-1, err.Error())
}
+ return apicontract.Success(&apicontract.DocHeadingLevelData{Counts: result.Counts[:], WithSubheadingCounts: result.WithSubheadingCounts[:], Title: result.Title, Transaction: transaction})
+})
- level := int(arg["level"].(float64))
-
- var ids []string
- if idsArg, ok := arg["ids"].([]any); ok {
- for _, id := range idsArg {
- ids = append(ids, id.(string))
- }
- ids = gulu.Str.RemoveDuplicatedElem(ids)
- } else {
- ids = []string{arg["id"].(string)}
+var getHeadingLevelTransaction = contractHandler(apicontract.GetHeadingLevelTransaction, func(c *gin.Context, request apicontract.HeadingLevelRequest) apicontract.Response[*apicontract.BlockTransaction] {
+ ids := request.IDs
+ if ids == nil {
+ ids = []string{request.ID}
}
-
- transaction, err := model.GetHeadingLevelBatchTransaction(ids, level)
+ transaction, err := model.GetHeadingLevelBatchTransaction(ids, int(request.Level))
if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- ret.Data = map[string]any{"closeTimeout": 7000}
- return
+ return apicontract.FailureWithTimeout[*apicontract.BlockTransaction](-1, err.Error(), 7000)
}
-
- ret.Data = transaction
-}
+ return blockTransactionResponse(transaction)
+})
var getHeadingFoldTransaction = contractHandler(apicontract.GetHeadingFoldTransaction, func(c *gin.Context, request apicontract.HeadingFoldRequest) apicontract.Response[*apicontract.BlockTransaction] {
id := request.ID
@@ -534,17 +435,14 @@ var getDocsInfo = contractHandler(apicontract.GetDocsInfo, func(c *gin.Context,
return apicontract.Success(docInfoContracts(info))
})
-func getRecentUpdatedBlocks(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
+var getRecentUpdatedBlocks = contractHandler(apicontract.GetRecentUpdatedBlocks, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[[]*apicontract.SearchBlock] {
blocks := model.RecentUpdatedBlocks()
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks)
}
- ret.Data = blocks
-}
+ return apicontract.Success(searchBlockContracts(blocks))
+})
var getContentWordCount = contractHandler(apicontract.GetContentWordCount, func(c *gin.Context, request apicontract.ContentWordCountRequest) apicontract.Response[apicontract.WordCountData] {
return apicontract.Success(apicontract.WordCountData{ReqID: request.ReqID, Stat: blockStatContract(filesys.ContentStat(request.Content))})
diff --git a/kernel/api/block_test.go b/kernel/api/block_test.go
index 034983a51f..1ff14022c1 100644
--- a/kernel/api/block_test.go
+++ b/kernel/api/block_test.go
@@ -29,7 +29,6 @@ import (
"testing"
"time"
- "github.com/88250/gulu"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
"github.com/gin-gonic/gin"
@@ -159,21 +158,6 @@ func testGetBlockInfoRecovery(t *testing.T, name string) {
}
}
-func TestParseBlockRefStringArrayEmptyHandling(t *testing.T) {
- arg := map[string]any{"ids": []any{}}
-
- requiredResult := gulu.Ret.NewResult()
- if _, ok := parseBlockRefStringArray(arg, "ids", requiredResult, true); ok || requiredResult.Code != -1 {
- t.Fatalf("expected an empty required array to be rejected, got code %d", requiredResult.Code)
- }
-
- optionalResult := gulu.Ret.NewResult()
- values, ok := parseBlockRefStringArray(arg, "ids", optionalResult, false)
- if !ok || optionalResult.Code != 0 || len(values) != 0 {
- t.Fatalf("expected an empty optional array to be accepted, got code %d and values %v", optionalResult.Code, values)
- }
-}
-
func TestCheckBlockRefRejectsDeletedIDsOutsideIDs(t *testing.T) {
gin.SetMode(gin.TestMode)
engine := gin.New()
diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.go
index 8d38281445..096ee57041 100644
--- a/kernel/api/box_lease_test.go
+++ b/kernel/api/box_lease_test.go
@@ -61,6 +61,18 @@ func TestContractRefIDsNotebookResponseLease(t *testing.T) {
runNotebookResponseLease(t, true, false)
}
+func TestContractCheckBlockRefNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, false, true)
+}
+
+func TestContractCheckBlockRefExplicitNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, true, false)
+}
+
+func TestContractCheckClosedNotebookRefNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, true, false)
+}
+
func TestContractDocInfoNotebookResponseLease(t *testing.T) {
runNotebookResponseLease(t, true, false)
}
@@ -202,6 +214,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator); c.Next() })
engine.POST("/api/block/getBlockKramdown", getBlockKramdown)
engine.POST("/api/block/getRefIDs", getRefIDs)
+ engine.POST("/api/block/checkBlockRef", checkBlockRef)
engine.POST("/api/block/getDocInfo", getDocInfo)
engine.POST("/api/block/getTreeStat", getTreeStat)
engine.POST("/api/block/getBlockBreadcrumb", getBlockBreadcrumb)
@@ -235,6 +248,14 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
}
typedQuery := false
switch t.Name() {
+ case "TestContractCheckBlockRefNotebookResponseLease":
+ endpoint, typedQuery = "/api/block/checkBlockRef", true
+ case "TestContractCheckBlockRefExplicitNotebookResponseLease":
+ endpoint, typedQuery = "/api/block/checkBlockRef", true
+ args["ids"] = []string{boxIDs[0]}
+ case "TestContractCheckClosedNotebookRefNotebookResponseLease":
+ endpoint, typedQuery = "/api/block/checkBlockRef", true
+ args["scope"] = "notebook"
case "TestContractDocInfoNotebookResponseLease":
endpoint, typedQuery = "/api/block/getDocInfo", true
case "TestContractTreeStatNotebookResponseLease":
@@ -299,11 +320,20 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
if typedQuery {
requireAPIContract(t, http.MethodPost, endpoint, writer.ResponseRecorder)
var response struct {
- Code int `json:"code"`
+ Code int `json:"code"`
+ Data json.RawMessage `json:"data"`
}
- if err := json.Unmarshal(body, &response); err != nil || response.Code != 0 {
+ wantCode := 0
+ if t.Name() == "TestContractCheckClosedNotebookRefNotebookResponseLease" {
+ // 此夹具仅解锁密钥,未挂载笔记本;业务失败也必须保持布尔载荷和响应租约。
+ wantCode = -1
+ }
+ if err := json.Unmarshal(body, &response); err != nil || response.Code != wantCode {
t.Fatalf("typed query failed: %s, %v", body, err)
}
+ if wantCode == -1 && string(response.Data) != "false" {
+ t.Fatalf("reference error lost boolean data: %s", body)
+ }
}
remaining := len(boxIDs)
if lockedBeforeResponse {
diff --git a/kernel/api/contract_block_remaining_test.go b/kernel/api/contract_block_remaining_test.go
new file mode 100644
index 0000000000..d8feb803f0
--- /dev/null
+++ b/kernel/api/contract_block_remaining_test.go
@@ -0,0 +1,104 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func TestAPIContractSearchBlockConversion(t *testing.T) {
+ for _, blocks := range [][]*model.Block{nil, {}, {nil, {Box: "box", Path: "/path", HPath: "/title", ID: "id", RootID: "root", ParentID: "parent", Name: "name", Alias: "alias", Memo: "memo", Tag: "tag", Content: "content", Number: "1", FContent: "fcontent", Markdown: "markdown", Folded: true, Type: "NodeParagraph", SubType: "sub", RefText: "ref", Refs: []*model.Block{{ID: "ref"}}, DefID: "def", DefPath: "/def", IAL: map[string]string{"name": "value"}, Children: []*model.Block{}, Depth: 1, Count: 2, RefCount: 3, Sort: 4, Created: "created", Updated: "updated", RiffCardID: "card", RiffCard: &model.RiffCard{Due: time.Date(2026, 9, 13, 12, 0, 0, 123, time.FixedZone("offset", 8*60*60)), Reps: 2, Lapses: 1, State: 2}}}} {
+ before, err := json.Marshal(blocks)
+ if err != nil {
+ t.Fatal(err)
+ }
+ after, err := json.Marshal(searchBlockContracts(blocks))
+ if err != nil || string(before) != string(after) {
+ t.Fatalf("block JSON changed: %s != %s, %v", before, after, err)
+ }
+ }
+}
+
+func testAPIContractRemainingBlockQueries(t *testing.T, engine *gin.Engine, boxID, docID, headingID string) {
+ engine.POST("/api/block/getDocHeadingLevelTransaction", getDocHeadingLevelTransaction)
+ engine.POST("/api/block/getHeadingLevelTransaction", getHeadingLevelTransaction)
+ engine.POST("/api/block/getRecentUpdatedBlocks", getRecentUpdatedBlocks)
+ engine.POST("/api/block/checkBlockRef", checkBlockRef)
+ post := func(name, body string, code int) json.RawMessage {
+ t.Helper()
+ path := "/api/block/" + name
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(body)))
+ requireAPIContract(t, "POST", path, recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data json.RawMessage `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != code {
+ t.Fatalf("%s: %s, %v", name, recorder.Body.String(), err)
+ }
+ return response.Data
+ }
+ for _, body := range []string{"", "null", `{"id":"x","source":0,"target":1}`, `{"id":"x","source":7,"target":1}`, `{"id":42}`} {
+ post("getDocHeadingLevelTransaction", body, -1)
+ }
+ for _, entry := range []struct {
+ source, target int
+ children bool
+ }{{0, 0, false}, {1, 3, false}, {1, 2, true}, {6, 1, true}} {
+ input := map[string]interface{}{"id": docID, "notebook": boxID, "source": entry.source, "target": entry.target, "withSubheadings": entry.children}
+ body, _ := json.Marshal(input)
+ data := post("getDocHeadingLevelTransaction", string(body), 0)
+ want, err := model.GetDocHeadingLevelTransaction(docID, boxID, entry.source, entry.target, entry.children)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // 时间戳由每次事务查询生成,比较其余完整载荷。
+ var got model.DocHeadingLevelResult
+ if err = json.Unmarshal(data, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Transaction != nil && want.Transaction != nil {
+ got.Transaction.Timestamp = want.Transaction.Timestamp
+ }
+ actualJSON, _ := json.Marshal(got)
+ wantJSON, _ := json.Marshal(want)
+ if string(actualJSON) != string(wantJSON) {
+ t.Fatalf("document heading JSON changed: %s != %s", actualJSON, wantJSON)
+ }
+ }
+ for _, body := range []string{`{"id":"` + headingID + `","level":3.9}`, `{"ids":["` + headingID + `","` + headingID + `"],"id":false,"level":3}`} {
+ data := post("getHeadingLevelTransaction", body, 0)
+ var got model.Transaction
+ if err := json.Unmarshal(data, &got); err != nil {
+ t.Fatal(err)
+ }
+ want, err := model.GetHeadingLevelBatchTransaction([]string{headingID}, 3)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got.Timestamp = want.Timestamp
+ actualJSON, _ := json.Marshal(got)
+ wantJSON, _ := json.Marshal(want)
+ if string(actualJSON) != string(wantJSON) {
+ t.Fatalf("heading JSON changed: %s != %s", actualJSON, wantJSON)
+ }
+ }
+ post("getHeadingLevelTransaction", `{"ids":[],"level":2}`, 0)
+ data := post("getRecentUpdatedBlocks", "not JSON", 0)
+ want, _ := json.Marshal(model.RecentUpdatedBlocks())
+ if string(data) != string(want) {
+ t.Fatalf("recent blocks changed: %s != %s", data, want)
+ }
+ for _, body := range []string{`{"ids":["` + headingID + `"],"exactIDs":[],"deletedIDs":[]}`, `{"scope":"notebook","notebook":" ` + boxID + ` "}`, `{"scope":"documents","paths":["` + boxID + `/` + docID + `.sy"]}`} {
+ if data := post("checkBlockRef", body, 0); string(data) != "false" {
+ t.Fatalf("unexpected reference: %s", data)
+ }
+ }
+ post("checkBlockRef", `{"ids":["`+headingID+`"],"deletedIDs":["`+docID+`"]}`, -1)
+}
diff --git a/kernel/api/contract_block_transaction_test.go b/kernel/api/contract_block_transaction_test.go
index 0b4e2c4ca9..9e17bacd6a 100644
--- a/kernel/api/contract_block_transaction_test.go
+++ b/kernel/api/contract_block_transaction_test.go
@@ -113,6 +113,7 @@ func TestAPIContractHeadingTransactions(t *testing.T) {
engine.POST("/api/block/getHeadingDeleteTransaction", getHeadingDeleteTransaction)
engine.POST("/api/block/getHeadingInsertTransaction", getHeadingInsertTransaction)
engine.POST("/api/block/getHeadingFoldTransaction", getHeadingFoldTransaction)
+ testAPIContractRemainingBlockQueries(t, engine, box.ID, docID, heading.ID)
for _, entry := range []struct {
path, id, scope string
code int
diff --git a/kernel/api/contract_search_block.go b/kernel/api/contract_search_block.go
new file mode 100644
index 0000000000..9bf650a118
--- /dev/null
+++ b/kernel/api/contract_search_block.go
@@ -0,0 +1,36 @@
+package api
+
+import (
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func searchBlockContracts(blocks []*model.Block) []*apicontract.SearchBlock {
+ if blocks == nil {
+ return nil
+ }
+ result := make([]*apicontract.SearchBlock, len(blocks))
+ for i, block := range blocks {
+ if block == nil {
+ continue
+ }
+ converted := &apicontract.SearchBlock{
+ Box: block.Box, Path: block.Path, HPath: block.HPath, ID: block.ID, RootID: block.RootID,
+ ParentID: block.ParentID, Name: block.Name, Alias: block.Alias, Memo: block.Memo, Tag: block.Tag,
+ Content: block.Content, Number: block.Number, FContent: block.FContent, Markdown: block.Markdown,
+ Folded: block.Folded, Type: block.Type, SubType: block.SubType, RefText: block.RefText,
+ Refs: searchBlockContracts(block.Refs), DefID: block.DefID, DefPath: block.DefPath, IAL: block.IAL,
+ Children: searchBlockContracts(block.Children), Depth: block.Depth, Count: block.Count,
+ RefCount: block.RefCount, Sort: block.Sort, Created: block.Created, Updated: block.Updated,
+ RiffCardID: block.RiffCardID,
+ }
+ if card := block.RiffCard; card != nil {
+ converted.RiffCard = &apicontract.SearchBlockCard{Due: card.Due.Format(time.RFC3339Nano),
+ Reps: card.Reps, Lapses: card.Lapses, State: int(card.State), LastReview: card.LastReview.Format(time.RFC3339Nano)}
+ }
+ result[i] = converted
+ }
+ return result
+}
diff --git a/kernel/apicontract/block_remaining.go b/kernel/apicontract/block_remaining.go
new file mode 100644
index 0000000000..91083c7c99
--- /dev/null
+++ b/kernel/apicontract/block_remaining.go
@@ -0,0 +1,179 @@
+package apicontract
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+)
+
+type CheckBlockRefRequest struct {
+ Scope string `json:"scope" api:"optional"`
+ IDs []string `json:"ids" api:"optional"`
+ ExactIDs []string `json:"exactIDs" api:"optional"`
+ DeletedIDs []string `json:"deletedIDs" api:"optional"`
+ Paths []string `json:"paths" api:"optional"`
+ Notebook string `json:"notebook" api:"optional,nullable"`
+ ID string `json:"id" api:"optional,nullable,ignoretype"`
+}
+
+type HeadingLevelRequest struct {
+ Level float64 `json:"level"`
+ IDs []string `json:"ids" api:"optional"`
+ ID string `json:"id" api:"optional"`
+}
+
+type DocHeadingLevelRequest struct {
+ ID string `json:"id" api:"optional,nullable"`
+ Notebook string `json:"notebook" api:"optional,nullable"`
+ Source int `json:"source" api:"optional,nullable"`
+ Target int `json:"target" api:"optional,nullable"`
+ WithSubheadings bool `json:"withSubheadings" api:"optional,nullable"`
+}
+
+type DocHeadingLevelData struct {
+ Counts []int `json:"counts" api:"nonnullable"`
+ WithSubheadingCounts []int `json:"withSubheadingCounts" api:"nonnullable"`
+ Title string `json:"title"`
+ Transaction *BlockTransaction `json:"transaction"`
+}
+
+// 特殊解码仅保留这些入口的条件参数和结构体绑定语义,响应仍受各自的契约约束。
+func init() {
+ CheckBlockRef.decodeRequest = decodeCheckBlockRef
+ GetHeadingLevelTransaction.decodeRequest = decodeHeadingLevel
+ GetDocHeadingLevelTransaction.decodeRequest = func(reader io.Reader) (request DocHeadingLevelRequest, err error) {
+ if json.NewDecoder(reader).Decode(&request) != nil {
+ err = errors.New("invalid heading conversion parameters")
+ }
+ return
+ }
+}
+
+func blockRequestFields(reader io.Reader, path string) (fields map[string]json.RawMessage, err error) {
+ err = json.NewDecoder(reader).Decode(&fields)
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ err = errors.New("the request body is empty or truncated (EOF)")
+ }
+ err = fmt.Errorf("Parses request [%s] failed: %s", path, err)
+ }
+ return
+}
+
+func decodeCheckBlockRef(reader io.Reader) (request CheckBlockRefRequest, err error) {
+ fields, err := blockRequestFields(reader, "/api/block/checkBlockRef")
+ if err != nil {
+ return request, err
+ }
+ if raw, present := fields["scope"]; present {
+ if bytes.Equal(raw, []byte("null")) || json.Unmarshal(raw, &request.Scope) != nil {
+ return request, errors.New("Field [scope] should be of type [String]")
+ }
+ }
+ if strings.TrimSpace(request.Scope) == "" {
+ request.Scope = "blocks"
+ }
+ readArray := func(key string, required, nonempty bool) ([]string, error) {
+ raw, present := fields[key]
+ if !present && !required {
+ return nil, nil
+ }
+ if !present || bytes.Equal(raw, []byte("null")) {
+ return nil, fmt.Errorf("Field [%s] is required", key)
+ }
+ var entries []json.RawMessage
+ if json.Unmarshal(raw, &entries) != nil {
+ return nil, fmt.Errorf("Field [%s] should be of type [Array]", key)
+ }
+ if nonempty && len(entries) == 0 {
+ return nil, fmt.Errorf("Field [%s] must not be empty", key)
+ }
+ var values []string
+ seen := map[string]bool{}
+ for _, entry := range entries {
+ var value string
+ if json.Unmarshal(entry, &value) != nil || strings.TrimSpace(value) == "" {
+ return nil, fmt.Errorf("Field [%s] should contain non-empty strings", key)
+ }
+ if !seen[value] {
+ values = append(values, value)
+ seen[value] = true
+ }
+ }
+ return values, nil
+ }
+ switch request.Scope {
+ case "blocks":
+ if request.IDs, err = readArray("ids", true, true); err != nil {
+ return
+ }
+ if request.ExactIDs, err = readArray("exactIDs", false, false); err != nil {
+ return
+ }
+ if request.DeletedIDs, err = readArray("deletedIDs", false, false); err != nil {
+ return
+ }
+ case "documents":
+ request.Paths, err = readArray("paths", true, true)
+ return
+ case "notebook":
+ // 附带块 ID 只参与租约准入,沿用仅收集字符串的规则。
+ var entries []json.RawMessage
+ if json.Unmarshal(fields["ids"], &entries) == nil {
+ for _, entry := range entries {
+ var id string
+ if !bytes.Equal(entry, []byte("null")) && json.Unmarshal(entry, &id) == nil {
+ request.IDs = append(request.IDs, id)
+ }
+ }
+ }
+ default:
+ return request, errors.New("invalid block ref check scope")
+ }
+ if raw := fields["notebook"]; len(raw) != 0 && !bytes.Equal(raw, []byte("null")) {
+ if json.Unmarshal(raw, &request.Notebook) != nil {
+ return request, errors.New("Field [notebook] should be of type [String]")
+ }
+ } else if request.Scope == "notebook" {
+ return request, errors.New("Field [notebook] is required")
+ }
+ if request.Scope == "notebook" {
+ request.Notebook = strings.TrimSpace(request.Notebook)
+ if request.Notebook == "" {
+ return request, errors.New("Field [notebook] must not be empty")
+ }
+ }
+ _ = json.Unmarshal(fields["id"], &request.ID)
+ return
+}
+
+func decodeHeadingLevel(reader io.Reader) (request HeadingLevelRequest, err error) {
+ fields, err := blockRequestFields(reader, "/api/block/getHeadingLevelTransaction")
+ if err != nil {
+ return request, err
+ }
+ if len(fields["level"]) == 0 || bytes.Equal(fields["level"], []byte("null")) || json.Unmarshal(fields["level"], &request.Level) != nil {
+ return request, errors.New("Field [level] should be of type [Number]")
+ }
+ var entries []json.RawMessage
+ if raw := fields["ids"]; len(raw) > 0 && !bytes.Equal(raw, []byte("null")) && json.Unmarshal(raw, &entries) == nil {
+ request.IDs = []string{}
+ seen := map[string]bool{}
+ for _, entry := range entries {
+ var id string
+ if bytes.Equal(entry, []byte("null")) || json.Unmarshal(entry, &id) != nil {
+ return request, errors.New("Field [ids] should contain strings")
+ }
+ if !seen[id] {
+ request.IDs = append(request.IDs, id)
+ seen[id] = true
+ }
+ }
+ } else if len(fields["id"]) == 0 || bytes.Equal(fields["id"], []byte("null")) || json.Unmarshal(fields["id"], &request.ID) != nil {
+ return request, errors.New("Field [id] should be of type [String]")
+ }
+ return
+}
diff --git a/kernel/apicontract/block_remaining_test.go b/kernel/apicontract/block_remaining_test.go
new file mode 100644
index 0000000000..33269bd5fa
--- /dev/null
+++ b/kernel/apicontract/block_remaining_test.go
@@ -0,0 +1,61 @@
+package apicontract
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestBlockRefConditionalInputs(t *testing.T) {
+ for _, entry := range []struct{ body, message string }{
+ {`{"ids":[]}`, "Field [ids] must not be empty"},
+ {`{"ids":null}`, "Field [ids] is required"},
+ {`{"ids":[null]}`, "Field [ids] should contain non-empty strings"},
+ {`{"ids":["x"],"exactIDs":null}`, "Field [exactIDs] is required"},
+ {`{"ids":["x"],"deletedIDs":[12]}`, "Field [deletedIDs] should contain non-empty strings"},
+ {`{"scope":null}`, "Field [scope] should be of type [String]"},
+ {`{"scope":" blocks "}`, "invalid block ref check scope"},
+ {`{"scope":"documents","paths":[]}`, "Field [paths] must not be empty"},
+ {`{"scope":"notebook","notebook":" "}`, "Field [notebook] must not be empty"},
+ } {
+ if _, err := CheckBlockRef.Decode(strings.NewReader(entry.body)); err == nil || err.Error() != entry.message {
+ t.Fatalf("%s: expected %q, got %v", entry.body, entry.message, err)
+ }
+ }
+ request, err := CheckBlockRef.Decode(strings.NewReader(`{"scope":" ","ids":[" a "," a "],"exactIDs":[],"deletedIDs":[],"paths":42,"notebook":null}`))
+ if err != nil || request.Scope != "blocks" || !reflect.DeepEqual(request.IDs, []string{" a "}) {
+ t.Fatalf("block inputs changed: %+v, %v", request, err)
+ }
+ request, err = CheckBlockRef.Decode(strings.NewReader(`{"scope":"documents","paths":["p","p"],"notebook":42,"ids":false}`))
+ if err != nil || !reflect.DeepEqual(request.Paths, []string{"p"}) {
+ t.Fatalf("document inputs changed: %+v, %v", request, err)
+ }
+ request, err = CheckBlockRef.Decode(strings.NewReader(`{"scope":"notebook","notebook":" box ","ids":[null,42,"id"],"id":42}`))
+ if err != nil || request.Notebook != "box" || !reflect.DeepEqual(request.IDs, []string{"id"}) {
+ t.Fatalf("notebook inputs changed: %+v, %v", request, err)
+ }
+}
+
+func TestHeadingLevelInputCompatibility(t *testing.T) {
+ for _, body := range []string{`{"id":"id","ids":null,"level":2.9}`, `{"id":"id","ids":42,"level":2.9}`} {
+ request, err := GetHeadingLevelTransaction.Decode(strings.NewReader(body))
+ if err != nil || request.ID != "id" || request.IDs != nil || int(request.Level) != 2 {
+ t.Fatalf("single heading changed: %+v, %v", request, err)
+ }
+ }
+ for _, body := range []string{`{"ids":[],"id":false,"level":2}`, `{"ids":["a","a"],"id":false,"level":2}`} {
+ request, err := GetHeadingLevelTransaction.Decode(strings.NewReader(body))
+ if err != nil || request.IDs == nil || len(request.IDs) > 1 {
+ t.Fatalf("batch heading changed: %+v, %v", request, err)
+ }
+ }
+ request, err := GetDocHeadingLevelTransaction.Decode(strings.NewReader(`{"ID":"doc","SOURCE":2,"target":3,"withSubheadings":null}`))
+ if err != nil || request.ID != "doc" || request.Source != 2 || request.Target != 3 {
+ t.Fatalf("struct binding changed: %+v, %v", request, err)
+ }
+ for _, body := range []string{"", "{", `{"source":2.5}`, `{"id":42}`} {
+ if _, err := GetDocHeadingLevelTransaction.Decode(strings.NewReader(body)); err == nil || err.Error() != "invalid heading conversion parameters" {
+ t.Fatalf("binding error changed: %v", err)
+ }
+ }
+}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index c06ada7699..88dc270732 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1,7 +1,10 @@
// 包 apicontract 定义 HTTP 接口的线协议,不依赖内核启动或持久化模型。
package apicontract
-import "reflect"
+import (
+ "io"
+ "reflect"
+)
type BodyMode string
@@ -27,7 +30,8 @@ type Definition struct {
}
type Endpoint[Request, Data any] struct {
- definition Definition
+ definition Definition
+ decodeRequest func(io.Reader) (Request, error)
}
type ResponseOptions struct {
@@ -342,3 +346,11 @@ var UpdateBlock = define[UpdateBlockRequest, []*BlockTransaction]("updateBlock",
var BatchUpdateBlock = define[BatchUpdateBlockRequest, []*BlockTransaction]("batchUpdateBlock", "/api/block/batchUpdateBlock", JSONBody, ResponseOptions{}, "POST")
var DeleteBlock = define[DeleteBlockRequest, []*BlockTransaction]("deleteBlock", "/api/block/deleteBlock", JSONBody, ResponseOptions{}, "POST")
+
+var CheckBlockRef = define[CheckBlockRefRequest, bool]("checkBlockRef", "/api/block/checkBlockRef", JSONBody, ResponseOptions{DataOnError: true}, "POST")
+
+var GetHeadingLevelTransaction = define[HeadingLevelRequest, *BlockTransaction]("getHeadingLevelTransaction", "/api/block/getHeadingLevelTransaction", JSONBody, ResponseOptions{}, "POST")
+
+var GetDocHeadingLevelTransaction = define[DocHeadingLevelRequest, *DocHeadingLevelData]("getDocHeadingLevelTransaction", "/api/block/getDocHeadingLevelTransaction", StructJSONBody, ResponseOptions{}, "POST")
+
+var GetRecentUpdatedBlocks = define[EmptyRequest, []*SearchBlock]("getRecentUpdatedBlocks", "/api/block/getRecentUpdatedBlocks", NoBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/decode.go b/kernel/apicontract/decode.go
index 9ea5324a75..6a55bd07df 100644
--- a/kernel/apicontract/decode.go
+++ b/kernel/apicontract/decode.go
@@ -18,6 +18,9 @@ func (e Endpoint[Request, Data]) Decode(reader io.Reader) (request Request, err
if reader == nil {
reader = bytes.NewReader(nil)
}
+ if e.decodeRequest != nil {
+ return e.decodeRequest(reader)
+ }
if e.definition.Body == StructJSONBody {
err = json.NewDecoder(reader).Decode(&request)
if err != nil {
diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.json
index 032eb4e8d8..a59b7a88fa 100644
--- a/kernel/apicontract/legacy_routes.json
+++ b/kernel/apicontract/legacy_routes.json
@@ -159,10 +159,6 @@
{"method":"POST","path":"/api/bazaar/uninstallBazaarTheme","handler":"uninstallBazaarTheme"},
{"method":"POST","path":"/api/bazaar/uninstallBazaarWidget","handler":"uninstallBazaarWidget"},
{"method":"POST","path":"/api/bazaar/updateBazaarPackage","handler":"updateBazaarPackage"},
- {"method":"POST","path":"/api/block/checkBlockRef","handler":"checkBlockRef"},
- {"method":"POST","path":"/api/block/getDocHeadingLevelTransaction","handler":"getDocHeadingLevelTransaction"},
- {"method":"POST","path":"/api/block/getHeadingLevelTransaction","handler":"getHeadingLevelTransaction"},
- {"method":"POST","path":"/api/block/getRecentUpdatedBlocks","handler":"getRecentUpdatedBlocks"},
{"method":"POST","path":"/api/bookmark/getBookmark","handler":"getBookmark"},
{"method":"POST","path":"/api/broadcast/getChannelInfo","handler":"getChannelInfo"},
{"method":"POST","path":"/api/broadcast/getChannels","handler":"getChannels"},
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 0aadbf8a2c..622859e6fd 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -1133,6 +1133,59 @@
],
"additionalProperties": false
},
+ "CheckBlockRefRequestInput": {
+ "type": "object",
+ "properties": {
+ "deletedIDs": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "exactIDs": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "notebook": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "paths": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "scope": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false
+ },
"CheckBlocksExistRequestInput": {
"type": "object",
"properties": {
@@ -1371,6 +1424,99 @@
],
"additionalProperties": false
},
+ "DocHeadingLevelData": {
+ "type": "object",
+ "properties": {
+ "counts": {
+ "type": "array",
+ "items": {
+ "type": "integer"
+ }
+ },
+ "title": {
+ "type": "string"
+ },
+ "transaction": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BlockTransaction"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "withSubheadingCounts": {
+ "type": "array",
+ "items": {
+ "type": "integer"
+ }
+ }
+ },
+ "required": [
+ "counts",
+ "title",
+ "transaction",
+ "withSubheadingCounts"
+ ],
+ "additionalProperties": false
+ },
+ "DocHeadingLevelRequestInput": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "notebook": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "source": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "target": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "withSubheadings": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "additionalProperties": false
+ },
"DocInfo": {
"type": "object",
"properties": {
@@ -1776,6 +1922,27 @@
],
"additionalProperties": false
},
+ "HeadingLevelRequestInput": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "level": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "level"
+ ],
+ "additionalProperties": false
+ },
"ImportNotebookCryptoBackupRequestInput": {
"type": "object",
"properties": {
@@ -3000,6 +3167,216 @@
},
"additionalProperties": false
},
+ "SearchBlock": {
+ "type": "object",
+ "properties": {
+ "alias": {
+ "type": "string"
+ },
+ "box": {
+ "type": "string"
+ },
+ "children": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SearchBlock"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "content": {
+ "type": "string"
+ },
+ "count": {
+ "type": "integer"
+ },
+ "created": {
+ "type": "string"
+ },
+ "defID": {
+ "type": "string"
+ },
+ "defPath": {
+ "type": "string"
+ },
+ "depth": {
+ "type": "integer"
+ },
+ "fcontent": {
+ "type": "string"
+ },
+ "folded": {
+ "type": "boolean"
+ },
+ "hPath": {
+ "type": "string"
+ },
+ "ial": {
+ "anyOf": [
+ {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "id": {
+ "type": "string"
+ },
+ "markdown": {
+ "type": "string"
+ },
+ "memo": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "number": {
+ "type": "string"
+ },
+ "parentID": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "refCount": {
+ "type": "integer"
+ },
+ "refText": {
+ "type": "string"
+ },
+ "refs": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SearchBlock"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "riffCard": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SearchBlockCard"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "riffCardID": {
+ "type": "string"
+ },
+ "rootID": {
+ "type": "string"
+ },
+ "sort": {
+ "type": "integer"
+ },
+ "subType": {
+ "type": "string"
+ },
+ "tag": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string"
+ },
+ "updated": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "alias",
+ "box",
+ "children",
+ "content",
+ "count",
+ "created",
+ "defID",
+ "defPath",
+ "depth",
+ "fcontent",
+ "folded",
+ "hPath",
+ "ial",
+ "id",
+ "markdown",
+ "memo",
+ "name",
+ "parentID",
+ "path",
+ "refCount",
+ "refText",
+ "refs",
+ "riffCard",
+ "riffCardID",
+ "rootID",
+ "sort",
+ "subType",
+ "tag",
+ "type",
+ "updated"
+ ],
+ "additionalProperties": false
+ },
+ "SearchBlockCard": {
+ "type": "object",
+ "properties": {
+ "due": {
+ "type": "string"
+ },
+ "lapses": {
+ "type": "integer"
+ },
+ "lastReview": {
+ "type": "string"
+ },
+ "reps": {
+ "type": "integer"
+ },
+ "state": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "due",
+ "lapses",
+ "lastReview",
+ "reps",
+ "state"
+ ],
+ "additionalProperties": false
+ },
"SearchHistoryData": {
"type": "object",
"properties": {
@@ -4908,7 +5285,82 @@
]
},
"data": {
- "type": "boolean"
+ "type": "boolean"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/block/checkBlockFold",
+ "handler": "checkBlockFold",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/BlockQueryRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/BlockFoldData"
},
"msg": {
"type": "string"
@@ -4965,11 +5417,11 @@
},
{
"method": "POST",
- "path": "/api/block/checkBlockFold",
- "handler": "checkBlockFold",
+ "path": "/api/block/checkBlockRef",
+ "handler": "checkBlockRef",
"body": "json",
"request": {
- "$ref": "#/$defs/BlockQueryRequestInput"
+ "$ref": "#/$defs/CheckBlockRefRequestInput"
},
"response": {
"anyOf": [
@@ -4983,7 +5435,7 @@
]
},
"data": {
- "$ref": "#/$defs/BlockFoldData"
+ "type": "boolean"
},
"msg": {
"type": "string"
@@ -5021,6 +5473,9 @@
},
{
"type": "null"
+ },
+ {
+ "type": "boolean"
}
]
},
@@ -6895,6 +7350,88 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/block/getDocHeadingLevelTransaction",
+ "handler": "getDocHeadingLevelTransaction",
+ "body": "structJSON",
+ "request": {
+ "$ref": "#/$defs/DocHeadingLevelRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DocHeadingLevelData"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/block/getDocInfo",
@@ -7475,6 +8012,88 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/block/getHeadingLevelTransaction",
+ "handler": "getHeadingLevelTransaction",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/HeadingLevelRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BlockTransaction"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/block/getOrderedListContinueStart",
@@ -7550,6 +8169,98 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/block/getRecentUpdatedBlocks",
+ "handler": "getRecentUpdatedBlocks",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SearchBlock"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/block/getRefIDs",
diff --git a/kernel/apicontract/search_block.go b/kernel/apicontract/search_block.go
new file mode 100644
index 0000000000..23bf3a30b1
--- /dev/null
+++ b/kernel/apicontract/search_block.go
@@ -0,0 +1,43 @@
+package apicontract
+
+type SearchBlock struct {
+ Box string `json:"box"`
+ Path string `json:"path"`
+ HPath string `json:"hPath"`
+ ID string `json:"id"`
+ RootID string `json:"rootID"`
+ ParentID string `json:"parentID"`
+ Name string `json:"name"`
+ Alias string `json:"alias"`
+ Memo string `json:"memo"`
+ Tag string `json:"tag"`
+ Content string `json:"content"`
+ Number string `json:"number,omitempty"`
+ FContent string `json:"fcontent"`
+ Markdown string `json:"markdown"`
+ Folded bool `json:"folded"`
+ Type string `json:"type"`
+ SubType string `json:"subType"`
+ RefText string `json:"refText"`
+ Refs []*SearchBlock `json:"refs"`
+ DefID string `json:"defID"`
+ DefPath string `json:"defPath"`
+ IAL map[string]string `json:"ial"`
+ Children []*SearchBlock `json:"children"`
+ Depth int `json:"depth"`
+ Count int `json:"count"`
+ RefCount int `json:"refCount"`
+ Sort int `json:"sort"`
+ Created string `json:"created"`
+ Updated string `json:"updated"`
+ RiffCardID string `json:"riffCardID"`
+ RiffCard *SearchBlockCard `json:"riffCard"`
+}
+
+type SearchBlockCard struct {
+ Due string `json:"due"`
+ Reps uint64 `json:"reps"`
+ Lapses uint64 `json:"lapses"`
+ State int `json:"state"`
+ LastReview string `json:"lastReview"`
+}