An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
♻️ Migrate snippet API contracts https://github.com/siyuan-note/siyuan/issues/19378
Daniel26c7de4a5609
diff --git a/app/src/config/util/snippets.ts b/app/src/config/util/snippets.tsindex 504b633df8..472ad5eacf 100644--- a/app/src/config/util/snippets.ts+++ b/app/src/config/util/snippets.ts@@ -234,7 +234,7 @@ const genSnippet = (options: ISnippet) => {};const setSnippetPost = (dialog: Dialog, snippets: ISnippet[], removeIds: string[]) => {- fetchPost("/api/snippet/setSnippet", {snippets}, () => {+ fetchPost("/api/snippet/setSnippet", {snippets: snippets.map(item => ({...item, id: item.id || ""}))}, () => {let cssChanged = false;removeIds.forEach(item => {const rmElement = document.querySelector(item);diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 118940dd9a..fcc812f118 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -130,6 +130,8 @@ export type FileAnnotationRefRequestInput = { "id": string; "notebook"?: stringexport type FullBlockInfo = { "box": string; "path": string; "rootChildID": string; "rootID": string; "rootIcon": string; "rootTitle": string; "rootTitleEmpty": boolean; };+export type GetSnippetRequestInput = { "enabled": number; "keyword"?: string | null; "type": string; };+export type GetTagRequestInput = { "app"?: string | null; "ignoreMaxListHint"?: boolean | null; "sort"?: number | null; };export type HeadingChildrenRequestInput = { "id": string; "removeFoldAttr"?: boolean | null; };@@ -246,6 +248,14 @@ export type SetNotebookIconRequestInput = { "icon": string; "notebook": string;export type SetSnapshotMemoRequestInput = { "id": string; "memo": string; };+export type SetSnippetRequestInput = { "snippets": Array<SnippetInput>; };++export type Snippet = { "content": string; "disabledInPublish": boolean; "enabled": boolean; "id": string; "name": string; "type": string; };++export type SnippetInput = { "content": string; "disabledInPublish"?: boolean | null; "enabled": boolean; "id": string; "name": string; "type": string; };++export type SnippetsData = { "snippets": Array<Snippet | null>; };+export type SwapBlockRefRequestInput = { "defID": string; "includeChildren": boolean; "refID": string; };export type TagData = { "children": Array<TagData | null> | null; "count": number; "depth": number; "label": string; "name": string; "type": string; };@@ -682,9 +692,6 @@ export type APILegacyPOSTPath ="/api/setting/setSnippet" |"/api/setting/setTheme" |"/api/setting/setVariables" |- "/api/snippet/getSnippet" |- "/api/snippet/removeSnippet" |- "/api/snippet/setSnippet" |"/api/storage/batchUpdateRecentDocCloseTime" |"/api/storage/getCriteria" |"/api/storage/getInlineStyles" |@@ -1363,6 +1370,21 @@ export interface APIPOSTRoutes {response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "json";};+ "/api/snippet/getSnippet": {+ request: GetSnippetRequestInput;+ response: { "code": 0; "data": SnippetsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/snippet/removeSnippet": {+ request: TrimmedIDRequestInput;+ response: { "code": 0; "data": Snippet | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/snippet/setSnippet": {+ request: SetSnippetRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/sqlite/flushTransaction": {request: EmptyRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/kernel/api/contract_snippet.go b/kernel/api/contract_snippet.gonew file mode 100644index 0000000000..a3f48277a3--- /dev/null+++ b/kernel/api/contract_snippet.go@@ -0,0 +1,24 @@+package api++import (+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+)++func snippetContract(value *conf.Snippet) *apicontract.Snippet {+ if value == nil {+ return nil+ }+ return &apicontract.Snippet{ID: value.ID, Name: value.Name, Type: value.Type, Content: value.Content, Enabled: value.Enabled, DisabledInPublish: value.DisabledInPublish}+}++func snippetContracts(values []*conf.Snippet) []*apicontract.Snippet {+ if values == nil {+ return nil+ }+ result := make([]*apicontract.Snippet, len(values))+ for i, value := range values {+ result[i] = snippetContract(value)+ }+ return result+}diff --git a/kernel/api/contract_snippet_test.go b/kernel/api/contract_snippet_test.gonew file mode 100644index 0000000000..aba465f6a4--- /dev/null+++ b/kernel/api/contract_snippet_test.go@@ -0,0 +1,52 @@+package api++import (+ "encoding/json"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractSnippetResponses(t *testing.T) {+ previous := util.SnippetsPath+ util.SnippetsPath = t.TempDir()+ t.Cleanup(func() { util.SnippetsPath = previous })+ engine := gin.New()+ engine.POST("/api/snippet/setSnippet", setSnippet)+ engine.POST("/api/snippet/getSnippet", getSnippet)+ engine.POST("/api/snippet/removeSnippet", removeSnippet)+ for _, entry := range []struct {+ path, body string+ code int+ }{+ {"/api/snippet/setSnippet", `{"snippets":[{"id":"sample","name":"Example","type":"css","content":"body {}","enabled":true,"disabledInPublish":null}]}`, 0},+ {"/api/snippet/getSnippet", `{"type":" all ","enabled":2,"keyword":null}`, 0},+ {"/api/snippet/setSnippet", `{"snippets":[{"id":"bad","name":"bad","type":"css","content":"</style>","enabled":true}]}`, -1},+ {"/api/snippet/removeSnippet", `{"id":" sample "}`, 0},+ {"/api/snippet/getSnippet", `{"type":"css","enabled":2}`, 0},+ } {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", entry.path, strings.NewReader(entry.body)))+ requireAPIContract(t, "POST", entry.path, recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != entry.code {+ t.Fatalf("%s: %s, %v", entry.path, recorder.Body.String(), err)+ }+ }+}++func TestAPIContractSnippetModelConversion(t *testing.T) {+ for _, value := range []*conf.Snippet{nil, {ID: "id", Name: "name", Type: "css", Content: "body {}", Enabled: true, DisabledInPublish: true}} {+ before, _ := json.Marshal(value)+ after, err := json.Marshal(snippetContract(value))+ if err != nil || string(before) != string(after) {+ t.Fatalf("snippet JSON changed: %s != %s, %v", before, after, err)+ }+ }+}diff --git a/kernel/api/snippet.go b/kernel/api/snippet.goindex 66bc030168..e69406ab0b 100644--- a/kernel/api/snippet.go+++ b/kernel/api/snippet.go@@ -17,7 +17,7 @@package apiimport (- "net/http"+ "github.com/siyuan-note/siyuan/kernel/apicontract""strings""github.com/88250/gulu"@@ -25,28 +25,12 @@ import ("github.com/gin-gonic/gin""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model"- "github.com/siyuan-note/siyuan/kernel/util")-func getSnippet(c *gin.Context) {+var getSnippet = contractHandler(apicontract.GetSnippet, func(c *gin.Context, request apicontract.GetSnippetRequest) apicontract.Response[apicontract.SnippetsData] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- var typ string // js/css/all- var enabledArg float64 // 0:禁用,1:启用,2:全部- var keyword string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("type", &typ, true, true),- util.BindJsonArg("enabled", &enabledArg, true, false),- util.BindJsonArg("keyword", &keyword, false, false),- ) {- return- }+ typ, enabledArg, keyword := request.Type, request.Enabled, request.Keywordenabled := trueif 0 == int(enabledArg) {@@ -57,7 +41,7 @@ func getSnippet(c *gin.Context) {if err != nil {ret.Code = -1ret.Msg = "load snippets failed: " + err.Error()- return+ return contractFailure[apicontract.SnippetsData](ret)}isPublish := model.IsReadOnlyRoleContext(c)@@ -92,34 +76,15 @@ func getSnippet(c *gin.Context) {snippets = []*conf.Snippet{}}- ret.Data = map[string]any{- "snippets": snippets,- }-}+ return apicontract.Success(apicontract.SnippetsData{Snippets: snippetContracts(snippets)})+})-func setSnippet(c *gin.Context) {+var setSnippet = contractHandler(apicontract.SetSnippet, func(c *gin.Context, request apicontract.SetSnippetRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }- snippetsArg := arg["snippets"].([]any)var snippets []*conf.Snippet- for _, s := range snippetsArg {- m := s.(map[string]any)- snippet := &conf.Snippet{- ID: m["id"].(string),- Name: m["name"].(string),- Type: m["type"].(string),- Content: m["content"].(string),- Enabled: m["enabled"].(bool),- }- if nil != m["disabledInPublish"] {- snippet.DisabledInPublish = m["disabledInPublish"].(bool)- }+ for _, s := range request.Snippets {+ snippet := &conf.Snippet{ID: s.ID, Name: s.Name, Type: s.Type, Content: s.Content, Enabled: s.Enabled, DisabledInPublish: s.DisabledInPublish}if "" == snippet.ID {snippet.ID = ast.NewNodeID()}@@ -127,7 +92,7 @@ func setSnippet(c *gin.Context) {if strings.Contains(strings.ToLower(snippet.Content), "</style") || strings.Contains(strings.ToLower(snippet.Content), "<script") {ret.Code = -1ret.Msg = "invalid css snippet content"- return+ return contractFailure[apicontract.Null](ret)}}snippets = append(snippets, snippet)@@ -137,28 +102,21 @@ func setSnippet(c *gin.Context) {if err != nil {ret.Code = -1ret.Msg = "set snippet failed: " + err.Error()- return+ return contractFailure[apicontract.Null](ret)}-}-func removeSnippet(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)+ return apicontract.Success(apicontract.Null{})+})- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }+var removeSnippet = contractHandler(apicontract.RemoveSnippet, func(c *gin.Context, request apicontract.TrimmedIDRequest) apicontract.Response[*apicontract.Snippet] {+ ret := gulu.Ret.NewResult()- var id string- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {- return- }+ id := request.IDsnippet, err := model.RemoveSnippet(id)if err != nil {ret.Code = -1ret.Msg = "remove snippet failed: " + err.Error()- return+ return contractFailure[*apicontract.Snippet](ret)}- ret.Data = snippet-}+ return apicontract.Success(snippetContract(snippet))+})diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex afa96b26be..3dfaeccd7d 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -376,3 +376,7 @@ var ReloadIcon = define[EmptyRequest, Null]("reloadIcon", "/api/ui/reloadIcon",var ReloadTheme = define[EmptyRequest, Null]("reloadTheme", "/api/ui/reloadTheme", NoBody, ResponseOptions{}, "POST")var FlushTransaction = define[EmptyRequest, Null]("flushTransaction", "/api/sqlite/flushTransaction", NoBody, ResponseOptions{}, "POST")++var GetSnippet = define[GetSnippetRequest, SnippetsData]("getSnippet", "/api/snippet/getSnippet", JSONBody, ResponseOptions{}, "POST")+var SetSnippet = define[SetSnippetRequest, Null]("setSnippet", "/api/snippet/setSnippet", JSONBody, ResponseOptions{}, "POST")+var RemoveSnippet = define[TrimmedIDRequest, *Snippet]("removeSnippet", "/api/snippet/removeSnippet", JSONBody, ResponseOptions{}, "POST")diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.jsonindex aa264ef2ea..85fbd9f7d1 100644--- a/kernel/apicontract/legacy_routes.json+++ b/kernel/apicontract/legacy_routes.json@@ -380,9 +380,6 @@{"method":"POST","path":"/api/setting/setSnippet","handler":"setConfSnippet"},{"method":"POST","path":"/api/setting/setTheme","handler":"setTheme"},{"method":"POST","path":"/api/setting/setVariables","handler":"setVariables"},- {"method":"POST","path":"/api/snippet/getSnippet","handler":"getSnippet"},- {"method":"POST","path":"/api/snippet/removeSnippet","handler":"removeSnippet"},- {"method":"POST","path":"/api/snippet/setSnippet","handler":"setSnippet"},{"method":"POST","path":"/api/storage/batchUpdateRecentDocCloseTime","handler":"batchUpdateRecentDocCloseTime"},{"method":"POST","path":"/api/storage/getCriteria","handler":"getCriteria"},{"method":"POST","path":"/api/storage/getInlineStyles","handler":"getInlineStyles"},diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 0369046bd1..e896885036 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -1893,6 +1893,32 @@],"additionalProperties": false},+ "GetSnippetRequestInput": {+ "type": "object",+ "properties": {+ "enabled": {+ "type": "number"+ },+ "keyword": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "type": {+ "type": "string"+ }+ },+ "required": [+ "enabled",+ "type"+ ],+ "additionalProperties": false+ },"GetTagRequestInput": {"type": "object","properties": {@@ -3675,6 +3701,113 @@],"additionalProperties": false},+ "SetSnippetRequestInput": {+ "type": "object",+ "properties": {+ "snippets": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/SnippetInput"+ }+ }+ },+ "required": [+ "snippets"+ ],+ "additionalProperties": false+ },+ "Snippet": {+ "type": "object",+ "properties": {+ "content": {+ "type": "string"+ },+ "disabledInPublish": {+ "type": "boolean"+ },+ "enabled": {+ "type": "boolean"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "type": {+ "type": "string"+ }+ },+ "required": [+ "content",+ "disabledInPublish",+ "enabled",+ "id",+ "name",+ "type"+ ],+ "additionalProperties": false+ },+ "SnippetInput": {+ "type": "object",+ "properties": {+ "content": {+ "type": "string"+ },+ "disabledInPublish": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "enabled": {+ "type": "boolean"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "type": {+ "type": "string"+ }+ },+ "required": [+ "content",+ "enabled",+ "id",+ "name",+ "type"+ ],+ "additionalProperties": false+ },+ "SnippetsData": {+ "type": "object",+ "properties": {+ "snippets": {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/Snippet"+ },+ {+ "type": "null"+ }+ ]+ }+ }+ },+ "required": [+ "snippets"+ ],+ "additionalProperties": false+ },"SwapBlockRefRequestInput": {"type": "object","properties": {@@ -13444,6 +13577,238 @@]}},+ {+ "method": "POST",+ "path": "/api/snippet/getSnippet",+ "handler": "getSnippet",+ "body": "json",+ "request": {+ "$ref": "#/$defs/GetSnippetRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/SnippetsData"+ },+ "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/snippet/removeSnippet",+ "handler": "removeSnippet",+ "body": "json",+ "request": {+ "$ref": "#/$defs/TrimmedIDRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "$ref": "#/$defs/Snippet"+ },+ {+ "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/snippet/setSnippet",+ "handler": "setSnippet",+ "body": "json",+ "request": {+ "$ref": "#/$defs/SetSnippetRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "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/sqlite/flushTransaction",diff --git a/kernel/apicontract/snippet.go b/kernel/apicontract/snippet.gonew file mode 100644index 0000000000..25a184942a--- /dev/null+++ b/kernel/apicontract/snippet.go@@ -0,0 +1,21 @@+package apicontract++type Snippet struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Type string `json:"type"`+ Enabled bool `json:"enabled"`+ DisabledInPublish bool `json:"disabledInPublish" api:"optional,nullable"`+ Content string `json:"content"`+}+type SnippetsData struct {+ Snippets []*Snippet `json:"snippets" api:"nonnullable"`+}+type GetSnippetRequest struct {+ Type string `json:"type" api:"trim"`+ Enabled float64 `json:"enabled"`+ Keyword string `json:"keyword" api:"optional,nullable"`+}+type SetSnippetRequest struct {+ Snippets []Snippet `json:"snippets"`+}