jsonot

package module
v0.0.0-...-6b222bd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2026 License: Apache-2.0 Imports: 12 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

jsonot

PR Check Release Go Version License

简体中文

jsonot is a Go library for JSON Operational Transformation (OT). It helps you apply JSON OT operations, transform concurrent edits, build collaboration backends, and generate diff / revert operations for versioned JSON documents.

The project is inspired by ylgrgyq/json0-rs.

What is jsonot?

Use jsonot when you need a Go-native JSON OT engine for scenarios such as:

  • collaborative editing in Go
  • WebSocket collaborative editor backends
  • ShareDB-style backends in Go
  • JSON diff / revert and version restore flows
  • server-authoritative merge pipelines for rich text or structured JSON documents

If you are searching for a Go OT library, JSON OT for Go, or a ShareDB alternative in Go, this repository is the main entry point.

Who is it for?

jsonot is a good fit when you need:

  • a backend OT core for collaborative editors
  • server-side rebasing with Transform
  • document restore and rollback with Diff
  • a small Go package instead of a full collaboration platform
  • a Go package that you can embed inside your own WebSocket or HTTP services

Start here

Choose the entry point that matches your goal:

What problems does jsonot solve?

1. Collaborative editing in Go

jsonot provides the OT core needed to rebase concurrent operations and keep a server-authoritative document consistent.

2. JSON diff, revert, and version restore

Diff can generate JSON OT that transforms one version of a document into another, which is useful for rollback, restore, comparison, and audit flows.

3. ShareDB-style backend building blocks

The sharedb package shows how to layer snapshots, versions, submit, and subscribe APIs on top of the core OT engine.

Features

  • Apply JSON OT operations to objects, arrays, numbers, and text values
  • Transform concurrent operations with Transform
  • Compose multiple operations into a single operation
  • Generate diff / revert operations from two JSON documents with Diff
  • Build operations with the provided builders
  • Switch between the default Sonic backend and the AJSON backend
  • Use the lightweight sharedb package for ShareDB-style backend flows
  • Explore runnable collaboration demos for WebSocket text editing and BlockNote documents

Capability matrix

Capability jsonot Where to start
Apply JSON OT to documents Yes Apply, Quick start
Rebase concurrent operations Yes Transform, Transforming concurrent operations
Compose multiple ops Yes Compose
Generate diff / revert operations Yes Generating revert operations from two versions
ShareDB-style backend abstraction Yes jsonot/sharedb
WebSocket collaboration demo Yes examples/websocket
Rich text collaboration demo Yes examples/blocknote-collab

Scenario matrix

Scenario Recommended starting point
Build a collaborative editor backend in Go WebSocket demo
Build a rich text collaboration backend BlockNote demo
Build a ShareDB-like backend in Go jsonot/sharedb
Restore an older JSON version Diff
Rebase concurrent client operations on the server Transform

Quick start

package main

import (
"context"
"fmt"

"github.com/edocevol/jsonot"
)

func main() {
ot := jsonot.NewJSONOperationTransformer()

doc, _ := jsonot.UnmarshalValue([]byte(`{
"name": "json0",
"hobbies": ["reading", "coding", "music"],
"info": {"email": "example@mail.qq.com"}
}`))

rawOps, _ := jsonot.UnmarshalValue([]byte(`[
{"p": ["hobbies", "2"], "ld": "music"},
{"p": ["hobbies", "3"], "li": "movie"},
{"p": ["info", "email"], "od": "example@mail.qq.com"}
]`))

components := ot.OperationComponentsFromValue(rawOps)
op := jsonot.NewOperation(components.MustGet())

result := ot.Apply(context.Background(), doc, op)
fmt.Println(string(result.MustGet().RawMessage()))
}

Operation format

Operation components are represented as JSON objects. The p field is the target path.

Built-in actions
  • li: list insert
  • ld: list delete
  • lm: list move
  • oi: object insert
  • od: object delete
  • na: number add subtype
  • t + o: custom subtype name and operand

Examples:

{"p": ["todos", "1"], "li": {"title": "review"}}
{"p": ["profile", "name"], "oi": "jsonot"}
{"p": ["counter"], "na": 1}
{"p": ["content"], "t": "text", "o": {"p": 5, "i": " world"}}

Building operations in Go

ot := jsonot.NewJSONOperationTransformer()
factory := ot.OperationFactory()

component := factory.ObjectOperationBuilder(
jsonot.NewPathFromKeys([]string{"profile", "name"}),
).Insert(jsonot.ValueFromPrimitive("jsonot")).Build()

op := jsonot.NewOperation([]*jsonot.OperationComponent{component.MustGet()})

Transforming concurrent operations

Use Transform when two operations were created from the same base document and need to be rebased against each other.

leftPrime, rightPrime, err := ot.Transform(context.Background(), leftOp, rightOp)

After that, apply leftPrime after rightOp, or rightPrime after leftOp.

Generating revert operations from two versions

Use Diff to generate JSON OT that transforms one document into another.

current, _ := jsonot.UnmarshalValue([]byte(`{"version":2,"items":[1,2,3]}`))
previous, _ := jsonot.UnmarshalValue([]byte(`{"version":1,"items":[1,3]}`))

revertOp := ot.Diff(context.Background(), current, previous)
restored := ot.Apply(context.Background(), current, revertOp.MustGet())

This is useful for version comparison and restore flows. When a structure changes too much, Diff falls back to replacing that subtree, including the root document when needed.

Value backends

The library uses Sonic by default.

jsonot.UseSonic()
jsonot.UseAJSON()

Switch the backend before creating or parsing values so all Value instances come from the same implementation.

Demos and guides

How is jsonot different?

jsonot vs CRDT

If you prefer a server-authoritative merge flow and explicit rebasing with Transform, jsonot gives you an OT-centric path instead of a CRDT data model.

jsonot vs ShareDB

ShareDB is a full collaboration system. jsonot focuses on a Go-native OT engine plus lightweight backend primitives that you can embed in your own services.

jsonot vs plain JSON diff

Plain diff can tell you what changed. jsonot also helps you transform and rebase concurrent operations before applying them.

FAQ

Is jsonot a Go library for collaborative editing?

Yes. The core package handles OT transforms and applies operations, while the examples show how to build collaborative editing servers in Go.

Can jsonot be used as a ShareDB alternative in Go?

Yes, when you want Go-native OT primitives and lightweight backend abstractions instead of the full ShareDB stack. Start with jsonot/sharedb.

Can jsonot generate rollback operations from two JSON versions?

Yes. Use Diff to derive an operation that transforms the current document into an earlier version.

Can I use jsonot with rich text editors?

Yes. The BlockNote demo shows a rich text collaboration backend that sends snapshots and merges them with Diff, Transform, and Apply.

What is the smallest runnable path?
  1. go get github.com/edocevol/jsonot
  2. copy the quick-start example from this README
  3. run go test ./...
  4. open one of the demos when you need an end-to-end collaboration flow

Trust signals

  • CI runs go test ./... in PR Check
  • tag pushes validate tests before publishing a GitHub release in Release Tag
  • the repository includes runnable demos and a dedicated sharedb package

Testing

go test ./...

Documentation

Index

Constants

View Source
const (
	// NumberAddSubTypeName is the name of the number add subtype
	NumberAddSubTypeName = "na"
	// TextSubTypeName is the name of the text subtype
	TextSubTypeName = "text"
)
View Source
const (
	// TextOperandOffsetKey 是文本操作偏移量的键名
	TextOperandOffsetKey = "p"
	// TextOperandInsertKey 是文本操作插入值的键名
	TextOperandInsertKey = "i"
	// TextOperandDeleteKey 是文本操作删除值的键名
	TextOperandDeleteKey = "d"
)
View Source
const SubTypeOperand = "o"

SubTypeOperand 定义了子类型操作的操作数类型

Variables

This section is empty.

Functions

func ApplyToValue

func ApplyToValue(val Value, paths Path, operator Operator) error

ApplyToValue 将操作应用到值上

func IndexFunc

func IndexFunc(arr []Value, search Value, inputIndex int) int

IndexFunc is a helper function to find the index of a value in an array

func IsEquivalentToNoop

func IsEquivalentToNoop(op *OperationComponent) bool

IsEquivalentToNoop 判断一个操作是否等价于 Noop

func IsError

func IsError(err error, code ErrCode) bool

IsError checks if the error is of a specific type

func IsErrorSonicValue

func IsErrorSonicValue(node *ast.Node) bool

IsErrorSonicValue 检查节点是否为 SonicValue 错误类型

func IsSameOperand

func IsSameOperand(opA, opB *OperationComponent) bool

IsSameOperand 判断两个操作是否操作相同的操作数

func IsSimpleValue

func IsSimpleValue(v Value) bool

IsSimpleValue 检查 ValueBrian 是否是简单值

func NewOperationComponent

func NewOperationComponent(path Path, operator Operator) mo.Result[*OperationComponent]

NewOperationComponent creates a new operation component.

func RouteGetOnArray

func RouteGetOnArray(val *ValueBrian, paths Path, valType ValueType) (mo.Option[*ValueBrian], error)

RouteGetOnArray 从数组上获取路径

func RouteGetOnObject

func RouteGetOnObject(obj *ValueBrian, paths Path, valType ValueType) (mo.Option[*ValueBrian], error)

RouteGetOnObject 从对象上获取路径

func RouteGetOnValue

func RouteGetOnValue(val *ValueBrian, paths Path, valType ValueType) (mo.Option[*ValueBrian], error)

RouteGetOnValue 从值中获取路由

func RouteSetOnArray

func RouteSetOnArray(arr *ValueBrian, paths Path, newValue *ValueBrian) error

RouteSetOnArray 在数组上设置路由

func RouteSetOnObject

func RouteSetOnObject(obj *ValueBrian, paths Path, newValue *ValueBrian) error

RouteSetOnObject 在对象上设置路由

func RouteSetOnValue

func RouteSetOnValue(val *ValueBrian, paths Path, newValue *ValueBrian) error

RouteSetOnValue 在值上设置路由

func SetEnableDebug

func SetEnableDebug()

SetEnableDebug 控制是否启用调试日志

func SetLogger

func SetLogger(l Logger)

SetLogger 设置日志记录器

func SubString

func SubString(s string, start, end int) string

SubString 返回一个子字符串操作的子类型操作

func SubTypeTryFromValue

func SubTypeTryFromValue(value Value) mo.Result[SubType]

SubTypeTryFromValue 将 Value 转换为 SubType

func UseAJSON

func UseAJSON()

UseAJSON 切换到 AJSON 实现

func UseSonic

func UseSonic()

UseSonic 用于切换到 Sonic 实现

Types

type AJSONValue

type AJSONValue struct {
	// contains filtered or unexported fields
}

AJSONValue 定义了 JSON Object 的节点

func NewAJSONValue

func NewAJSONValue(node *ajson.Node) *AJSONValue

NewAJSONValue 创建一个新的 AJSONValue

func (*AJSONValue) DeleteKey

func (n *AJSONValue) DeleteKey(key string) error

DeleteKey deletes a key from the JSON object

func (*AJSONValue) Equals

func (n *AJSONValue) Equals(otherNode Value) bool

Equals checks if two JSON nodes are equal

func (*AJSONValue) Format

func (n *AJSONValue) Format(st fmt.State, _ rune)

Format 实现 fmt.Formatter 接口,用于格式化输出

func (*AJSONValue) GetArray

func (n *AJSONValue) GetArray() mo.Result[[]Value]

GetArray retrieves the array from the JSON node

func (*AJSONValue) GetByPath

func (n *AJSONValue) GetByPath(path ...any) mo.Option[Value]

GetByPath retrieves a value by path from the JSON object

func (*AJSONValue) GetInt

func (n *AJSONValue) GetInt() mo.Result[int]

GetInt retrieves the integer value from the JSON node

func (*AJSONValue) GetIntKey

func (n *AJSONValue) GetIntKey(key string) mo.Option[int]

GetIntKey retrieves an integer key from the JSON object

func (*AJSONValue) GetKey

func (n *AJSONValue) GetKey(key string) mo.Option[Value]

GetKey retrieves a key from the JSON object

func (*AJSONValue) GetMap

func (n *AJSONValue) GetMap() mo.Result[map[string]Value]

GetMap retrieves the map from the JSON node

func (*AJSONValue) GetNumeric

func (n *AJSONValue) GetNumeric() mo.Result[float64]

GetNumeric retrieves the numeric value from the JSON node

func (*AJSONValue) GetString

func (n *AJSONValue) GetString() mo.Result[string]

GetString retrieves the string value from the JSON node

func (*AJSONValue) GetStringKey

func (n *AJSONValue) GetStringKey(key string) mo.Option[string]

GetStringKey retrieves a string key from the JSON object

func (*AJSONValue) HasKey

func (n *AJSONValue) HasKey(key string) bool

HasKey checks if the JSON object has a specific key

func (*AJSONValue) IsArray

func (n *AJSONValue) IsArray() bool

IsArray returns true if the node is an array type

func (*AJSONValue) IsBool

func (n *AJSONValue) IsBool() bool

IsBool 返回节点是否为布尔类型

func (*AJSONValue) IsInt

func (n *AJSONValue) IsInt() bool

IsInt 返回节点是否为整数类型

func (*AJSONValue) IsNull

func (n *AJSONValue) IsNull() bool

IsNull 返回节点是否为 null 类型

func (*AJSONValue) IsNumeric

func (n *AJSONValue) IsNumeric() bool

IsNumeric 返回节点是否为数字类型

func (*AJSONValue) IsObject

func (n *AJSONValue) IsObject() bool

IsObject returns true if the node is an object type

func (*AJSONValue) IsString

func (n *AJSONValue) IsString() bool

IsString returns true if the node is a string type

func (*AJSONValue) PackAny

func (n *AJSONValue) PackAny()

PackAny parses any type of data into the JSON node

func (*AJSONValue) RawMessage

func (n *AJSONValue) RawMessage() json.RawMessage

RawMessage returns the raw JSON message of the node

func (*AJSONValue) SetKey

func (n *AJSONValue) SetKey(key string, value Value) error

SetKey sets a key-value pair in the JSON object

func (*AJSONValue) Size

func (n *AJSONValue) Size() int

Size returns the number of properties in the JSON object

func (*AJSONValue) Type

func (n *AJSONValue) Type() ValueType

Type returns the type of the JSON node

func (*AJSONValue) Unmarshal

func (n *AJSONValue) Unmarshal(data []byte) error

Unmarshal implements JSON decoding

func (*AJSONValue) UpdateArray

func (n *AJSONValue) UpdateArray(values []Value) error

UpdateArray 从传入的 Value 数组更新当前 Value

func (*AJSONValue) UpdateObject

func (n *AJSONValue) UpdateObject(values Value) error

UpdateObject 从传入的 Value 更新当前 Value

type AJSONValueFactory

type AJSONValueFactory struct{}

AJSONValueFactory 用于创建 AJSONValue 的工厂

func (AJSONValueFactory) FromAny

func (vf AJSONValueFactory) FromAny(a any) Value

FromAny 创建一个新的 JSON Object 节点

func (AJSONValueFactory) FromArray

func (vf AJSONValueFactory) FromArray(values []Value) Value

FromArray 创建一个新的 JSON Array 节点

func (AJSONValueFactory) FromPrimitive

func (vf AJSONValueFactory) FromPrimitive(pt any) Value

FromPrimitive 创建一个新的 JSON Object 节点

func (AJSONValueFactory) Unmarshal

func (vf AJSONValueFactory) Unmarshal(bytes []byte) (Value, error)

Unmarshal 实现了 ValueFactory 接口的 Unmarshal 方法

type Action

type Action string

Action 表达了 JSON Object 的操作类型

const (
	// ActionNoop 表示不执行任何操作
	ActionNoop Action = ""
	// ActionListInsert 表示在列表中插入元素
	ActionListInsert Action = "li"
	// ActionListDelete 表示在列表中删除元素
	ActionListDelete Action = "ld"
	// ActionListReplace 表示在列表中替换元素
	ActionListReplace Action = "lr"
	// ActionListMove 表示在列表中移动元素
	ActionListMove Action = "lm"
	// ActionObjectInsert 表示在对象中插入元素
	ActionObjectInsert Action = "oi"
	// ActionObjectDelete 表示在对象中删除元素
	ActionObjectDelete Action = "od"
	// ActionObjectReplace 表示在对象中替换元素
	ActionObjectReplace Action = "or"
	// ActionSubType 表示自定义子类型的操作
	ActionSubType Action = "t"
)

type ApplierOperator

type ApplierOperator interface {
	// ApplyOnValue 应用操作到 Value 上
	ApplyOnValue(val Value, paths Path) mo.Result[Value]
}

ApplierOperator 定义了应用操作的接口

type Custom

type Custom struct {
	Name string
}

Custom 是一个自定义操作的子类型

func NewCustom

func NewCustom(name string) *Custom

NewCustom 创建一个自定义操作的子类型

func (Custom) TypeName

func (c Custom) TypeName() string

TypeName 返回子类型的名称

type ErrCode

type ErrCode int

ErrCode is an error code type

const (
	// Ok indicates no error
	Ok ErrCode = iota
	// InvalidParameter indicates an invalid parameter error
	InvalidParameter
	// InvalidOperation indicates an invalid operation error
	InvalidOperation
	// InvalidPathFormat indicates an invalid path format error
	InvalidPathFormat
	// InvalidPathElement indicates an invalid path element error
	InvalidPathElement
	// BadPath indicates a bad path error
	BadPath
	// UnexpectedError indicates an unexpected error
	UnexpectedError
	// ConflictSubType indicates a conflict with a subtype name
	ConflictSubType
)

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error represents a generic error in the JSON operations

func NewError

func NewError(code ErrCode) *Error

NewError creates a new Error with the given message

func (*Error) Append

func (e *Error) Append(format string, args ...interface{}) *Error

Append adds a message to the error

func (*Error) Error

func (e *Error) Error() string

Error returns the error message

func (*Error) Wrap

func (e *Error) Wrap(err error) *Error

Wrap wraps the error with a message

type FmtLogger

type FmtLogger struct{}

FmtLogger 实现 Logger 接口的日志记录器

func (FmtLogger) ContextDebugf

func (f FmtLogger) ContextDebugf(_ interface{}, format string, args ...interface{})

ContextDebugf 打印上下文调试日志

func (FmtLogger) ContextErrorf

func (f FmtLogger) ContextErrorf(_ interface{}, format string, args ...interface{})

ContextErrorf 打印上下文错误日志

func (FmtLogger) Debugf

func (f FmtLogger) Debugf(format string, args ...interface{})

Debugf 打印调试日志

func (FmtLogger) Errorf

func (f FmtLogger) Errorf(format string, args ...interface{})

Errorf 打印错误日志

type JSONOperationTransformer

type JSONOperationTransformer struct {
	// contains filtered or unexported fields
}

JSONOperationTransformer 是一个实现了 OperationTransformer 接口的结构体

func NewJSONOperationTransformer

func NewJSONOperationTransformer() *JSONOperationTransformer

NewJSONOperationTransformer 创建一个新的 JSONOperationTransformer

func (*JSONOperationTransformer) Applies

func (ot *JSONOperationTransformer) Applies(
	ctx context.Context, value Value, operations []*Operation,
) mo.Result[Value]

Applies 将多个操作应用到给定的 JSON 节点上

func (*JSONOperationTransformer) Apply

func (ot *JSONOperationTransformer) Apply(
	_ context.Context, value Value, operations *Operation,
) mo.Result[Value]

Apply 将操作应用到给定的 JSON 节点上

func (*JSONOperationTransformer) Diff

Diff generates an operation that transforms from into to.

func (*JSONOperationTransformer) OperationComponentFromValue

func (ot *JSONOperationTransformer) OperationComponentFromValue(value Value) mo.Result[*OperationComponent]

OperationComponentFromValue 创建一个操作组件

func (*JSONOperationTransformer) OperationComponentsFromValue

func (ot *JSONOperationTransformer) OperationComponentsFromValue(
	node Value,
) mo.Result[[]*OperationComponent]

OperationComponentsFromValue 创建一个操作组件

func (*JSONOperationTransformer) OperationFactory

func (ot *JSONOperationTransformer) OperationFactory() *OperationFactory

OperationFactory 返回操作工厂

func (*JSONOperationTransformer) OperationFromValueArray

func (ot *JSONOperationTransformer) OperationFromValueArray(values []Value) mo.Result[*Operation]

OperationFromValueArray 创建一个操作

func (*JSONOperationTransformer) RegisterSubType

func (ot *JSONOperationTransformer) RegisterSubType(subType string, fn SubTypeFunctions)

RegisterSubType 注册子类型函数

func (*JSONOperationTransformer) Transform

func (ot *JSONOperationTransformer) Transform(
	_ context.Context, left, right *Operation,
) (newLeft, newRight *Operation, err error)

Transform 将操作转换为另一种形式

func (*JSONOperationTransformer) UnregisterSubType

func (ot *JSONOperationTransformer) UnregisterSubType(subType string)

UnregisterSubType 注销子类型函数

type ListDelete

type ListDelete struct {
	OlvValue Value
}

ListDelete creates a list delete operator.

func NewListDelete

func NewListDelete(oldValue Value) *ListDelete

NewListDelete creates a list delete operator.

func (*ListDelete) Action

func (l *ListDelete) Action() Action

Action returns the action of the operator.

func (*ListDelete) Clone

func (l *ListDelete) Clone() Operator

Clone returns a copy of the operator.

func (*ListDelete) Format

func (l *ListDelete) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*ListDelete) Validates

func (l *ListDelete) Validates() error

Validates returns nil if the operator is valid.

type ListInsert

type ListInsert struct {
	NewValue Value
}

ListInsert creates a list insert operator.

func NewListInsert

func NewListInsert(newValue Value) *ListInsert

NewListInsert creates a list insert operator.

func (*ListInsert) Action

func (l *ListInsert) Action() Action

Action returns the action of the operator.

func (*ListInsert) Clone

func (l *ListInsert) Clone() Operator

Clone returns a copy of the operator.

func (*ListInsert) Format

func (l *ListInsert) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*ListInsert) Validates

func (l *ListInsert) Validates() error

Validates returns nil if the operator is valid.

type ListMove

type ListMove struct {
	NewIndex int
}

ListMove creates a list move operator.

func NewListMove

func NewListMove(newIndex int) *ListMove

NewListMove creates a list move operator.

func (*ListMove) Action

func (l *ListMove) Action() Action

Action returns the action of the operator.

func (*ListMove) Clone

func (l *ListMove) Clone() Operator

Clone returns a copy of the operator.

func (*ListMove) Format

func (l *ListMove) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*ListMove) Validates

func (l *ListMove) Validates() error

Validates returns nil if the operator is valid.

type ListOperationBuilder

type ListOperationBuilder struct {
	// contains filtered or unexported fields
}

ListOperationBuilder is a builder for list operations.

func NewListOperationBuilder

func NewListOperationBuilder(path Path) *ListOperationBuilder

NewListOperationBuilder creates a new list operation builder.

func (*ListOperationBuilder) Build

Build builds the operation component.

func (*ListOperationBuilder) Delete

Delete sets the delete value.

func (*ListOperationBuilder) Insert

Insert sets the insert value.

func (*ListOperationBuilder) MoveTo

func (b *ListOperationBuilder) MoveTo(newIndex int) *ListOperationBuilder

MoveTo sets the new index.

func (*ListOperationBuilder) Replace

func (b *ListOperationBuilder) Replace(oldVal, newVal Value) *ListOperationBuilder

Replace sets the replacement values.

type ListReplace

type ListReplace struct {
	NewValue Value
	OldValue Value
}

ListReplace creates a list replace operator.

func NewListReplace

func NewListReplace(newValue, oldValue Value) *ListReplace

NewListReplace creates a list replace operator.

func (*ListReplace) Action

func (l *ListReplace) Action() Action

Action returns the action of the operator.

func (*ListReplace) Clone

func (l *ListReplace) Clone() Operator

Clone returns a copy of the operator.

func (*ListReplace) Format

func (l *ListReplace) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*ListReplace) Validates

func (l *ListReplace) Validates() error

Validates returns nil if the operator is valid.

type Logger

type Logger interface {
	// Debugf 打印调试日志
	Debugf(format string, args ...interface{})
	// ContextDebugf 打印上下文调试日志
	ContextDebugf(ctx interface{}, format string, args ...interface{})
	// Errorf 打印错误日志
	Errorf(format string, args ...interface{})
	// ContextErrorf 打印上下文错误日志
	ContextErrorf(ctx interface{}, format string, args ...interface{})
}

Logger 日志接口

type Noop

type Noop struct{}

Noop creates a noop operator.

func NewNoop

func NewNoop() *Noop

NewNoop creates a noop operator.

func (Noop) Action

func (n Noop) Action() Action

Action returns the action of the operator.

func (Noop) Clone

func (n Noop) Clone() Operator

Clone returns a copy of the operator.

func (Noop) Format

func (n Noop) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (Noop) Validates

func (n Noop) Validates() error

Validates returns nil if the operator is valid.

type NumberAdd

type NumberAdd struct {
}

NumberAdd 是一个数字相加的子类型

func NewNumberAdd

func NewNumberAdd() *NumberAdd

NewNumberAdd 创建一个数字相加的子类型

func (*NumberAdd) TypeName

func (*NumberAdd) TypeName() string

TypeName 返回子类型的名称

type NumberAddOperationBuilder

type NumberAddOperationBuilder struct {
	// contains filtered or unexported fields
}

NumberAddOperationBuilder is a builder for number add operations.

func NewNumberAddOperationBuilder

func NewNumberAddOperationBuilder(path Path, subTypeFunctions SubTypeFunctions) *NumberAddOperationBuilder

NewNumberAddOperationBuilder creates a new number add operation builder.

func (*NumberAddOperationBuilder) AddFloat

AddFloat sets the add value as a float.

func (*NumberAddOperationBuilder) AddInt

AddInt sets the add value as an integer.

func (*NumberAddOperationBuilder) Build

Build builds the operation component.

type NumberAddSubType

type NumberAddSubType struct {
}

NumberAddSubType 返回数字相加的子类型操作

func NewNumberAddSubType

func NewNumberAddSubType() *NumberAddSubType

NewNumberAddSubType 创建一个数字相加的子类型操作

func (*NumberAddSubType) Apply

func (n *NumberAddSubType) Apply(
	val mo.Option[Value], subTypeOperand Value,
) mo.Result[mo.Option[Value]]

Apply 实现 SubTypeFunctions 接口的 Apply 方法

func (*NumberAddSubType) Invert

func (n *NumberAddSubType) Invert(subType SubType, _ Path, subTypeOperand Value) mo.Result[Operator]

Invert 实现 SubTypeFunctions 接口的 Invert 方法

func (*NumberAddSubType) Merge

func (n *NumberAddSubType) Merge(baseOperand Value, other Operator) mo.Option[Operator]

Merge 实现 SubTypeFunctions 接口的 Merge 方法

func (*NumberAddSubType) OperatorName

func (n *NumberAddSubType) OperatorName() string

OperatorName 实现 SubTypeFunctions 接口的 OperatorName 方法

func (*NumberAddSubType) Transform

func (n *NumberAddSubType) Transform(newVal, _ Value, _ TransformSide) mo.Result[[]Value]

Transform 实现 SubTypeFunctions 接口的 Transform 方法

该方法用于转换新值和基础值,返回一个节点数组

func (*NumberAddSubType) ValidateOperand

func (n *NumberAddSubType) ValidateOperand(val Value) error

ValidateOperand 实现 SubTypeFunctions 接口的 ValidateOperand 方法

type ObjectDelete

type ObjectDelete struct {
	OldValue Value
}

ObjectDelete creates an object delete operator.

func NewObjectDelete

func NewObjectDelete(value Value) *ObjectDelete

NewObjectDelete creates an object delete operator.

func (*ObjectDelete) Action

func (o *ObjectDelete) Action() Action

Action returns the action of the operator.

func (*ObjectDelete) Clone

func (o *ObjectDelete) Clone() Operator

Clone returns a copy of the operator.

func (*ObjectDelete) Format

func (o *ObjectDelete) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*ObjectDelete) Validates

func (o *ObjectDelete) Validates() error

Validates returns nil if the operator is valid.

type ObjectInsert

type ObjectInsert struct {
	NewValue Value
}

ObjectInsert creates an object insert operator.

func NewObjectInsert

func NewObjectInsert(newValue Value) *ObjectInsert

NewObjectInsert creates an object insert operator.

func (*ObjectInsert) Action

func (o *ObjectInsert) Action() Action

Action returns the action of the operator.

func (*ObjectInsert) Clone

func (o *ObjectInsert) Clone() Operator

Clone returns a copy of the operator.

func (*ObjectInsert) Format

func (o *ObjectInsert) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*ObjectInsert) Validates

func (o *ObjectInsert) Validates() error

Validates returns nil if the operator is valid.

type ObjectOperationBuilder

type ObjectOperationBuilder struct {
	// contains filtered or unexported fields
}

ObjectOperationBuilder is a builder for object operations.

func NewObjectOperationBuilder

func NewObjectOperationBuilder(path Path) *ObjectOperationBuilder

NewObjectOperationBuilder creates a new object operation builder.

func (*ObjectOperationBuilder) Build

Build builds the operation component.

func (*ObjectOperationBuilder) Delete

Delete sets the delete value.

func (*ObjectOperationBuilder) Insert

Insert sets the insert value.

func (*ObjectOperationBuilder) Replace

func (b *ObjectOperationBuilder) Replace(oldVal, newVal Value) *ObjectOperationBuilder

Replace sets the replacement values.

type ObjectReplace

type ObjectReplace struct {
	NewValue Value
	OldValue Value
}

ObjectReplace creates an object replace operator.

func NewObjectReplace

func NewObjectReplace(newValue, oldValue Value) *ObjectReplace

NewObjectReplace creates an object replace operator.

func (*ObjectReplace) Action

func (o *ObjectReplace) Action() Action

Action returns the action of the operator.

func (*ObjectReplace) Clone

func (o *ObjectReplace) Clone() Operator

Clone returns a copy of the operator.

func (*ObjectReplace) Format

func (o *ObjectReplace) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*ObjectReplace) Validates

func (o *ObjectReplace) Validates() error

Validates returns nil if the operator is valid.

type Operation

type Operation struct {
	Operations *list.List
}

Operation 一个操作由多个操作组件组成

func EmptyOperation

func EmptyOperation() *Operation

EmptyOperation creates an empty operation.

func NewOperation

func NewOperation(operations []*OperationComponent) *Operation

NewOperation creates a new operation.

func (*Operation) Append

func (o *Operation) Append(op *OperationComponent)

Append appends an operation component to the operation.

func (*Operation) Array

func (o *Operation) Array() []*OperationComponent

Array returns the operation as an array of

func (*Operation) Compose

func (o *Operation) Compose(other *Operation)

Compose composes the operation with another operation.

func (*Operation) Format

func (o *Operation) Format(st fmt.State, verb rune)

Format returns a string representation of the operation.

func (*Operation) IsEmpty

func (o *Operation) IsEmpty() bool

IsEmpty returns true if the operation is empty.

func (*Operation) Len

func (o *Operation) Len() int

Len returns the length of the operation.

func (*Operation) ToValue

func (o *Operation) ToValue() Value

ToValue converts the operation to a Value.

func (*Operation) Validation

func (o *Operation) Validation() error

Validation validates the operation.

type OperationComponent

type OperationComponent struct {
	Operator Operator
	Path     Path
}

OperationComponent is a component of an operation.

func (*OperationComponent) Clone

Clone clones the operation component.

func (*OperationComponent) CloneNotNoop

func (oc *OperationComponent) CloneNotNoop() mo.Option[*OperationComponent]

CloneNotNoop clones the operation component if it is not a noop.

func (*OperationComponent) Format

func (oc *OperationComponent) Format(st fmt.State, _ rune)

Format formats the operation component according to the fmt.Formatter interface.

func (*OperationComponent) Invert

Invert inverts the operation component.

func (*OperationComponent) Merge

Merge merges the operation component with another operation component.

func (*OperationComponent) MergeListInsert

func (oc *OperationComponent) MergeListInsert(op *OperationComponent, v1 *ListInsert) mo.Option[Operator]

MergeListInsert merges a ListInsert operation with another operation.

func (*OperationComponent) MergeListReplace

func (oc *OperationComponent) MergeListReplace(op *OperationComponent, v1 *ListReplace) mo.Option[Operator]

MergeListReplace merges a ListReplace operation with another operation.

func (*OperationComponent) MergeObjectInsert

func (oc *OperationComponent) MergeObjectInsert(op *OperationComponent, v1 *ObjectInsert) mo.Option[Operator]

MergeObjectInsert merges an ObjectInsert operation with another operation.

func (*OperationComponent) MergeObjectReplace

func (oc *OperationComponent) MergeObjectReplace(op *OperationComponent, v1 *ObjectReplace) mo.Option[Operator]

MergeObjectReplace merges an ObjectReplace operation with another operation.

func (*OperationComponent) Noop

Noop creates a noop operation component.

func (*OperationComponent) NotNoop

NotNoop returns the operation component if it is not a noop.

func (*OperationComponent) OperatePathLen

func (oc *OperationComponent) OperatePathLen() int

OperatePathLen returns the length of the path of the operation component.

func (*OperationComponent) ToValue

func (oc *OperationComponent) ToValue() Value

ToValue converts the operation component to a Value.

func (*OperationComponent) Validation

func (oc *OperationComponent) Validation() error

Validation validates the operation component.

type OperationFactory

type OperationFactory struct {
	// contains filtered or unexported fields
}

func NewOperationFactory

func NewOperationFactory(holder SubTypeFunctionsHolder) *OperationFactory

NewOperationFactory creates a new operation factory with the given subtype functions holder.

func (*OperationFactory) ListOperationBuilder

func (f *OperationFactory) ListOperationBuilder(path Path) *ListOperationBuilder

ListOperationBuilder creates a new list operation builder for the given path.

func (*OperationFactory) MapToOperator

func (f *OperationFactory) MapToOperator(obj Value) mo.Result[Operator]

MapToOperator converts a map to an operator.

func (*OperationFactory) MapToOperatorForListDelete

func (f *OperationFactory) MapToOperatorForListDelete(obj Value) mo.Result[Operator]

MapToOperatorForListDelete converts a map to a ListDelete operator.

func (*OperationFactory) MapToOperatorForListInsert

func (f *OperationFactory) MapToOperatorForListInsert(obj Value) mo.Result[Operator]

MapToOperatorForListInsert converts a map to a ListInsert operator.

func (*OperationFactory) MapToOperatorForListMove

func (f *OperationFactory) MapToOperatorForListMove(obj Value) mo.Result[Operator]

MapToOperatorForListMove 将 map 转换为 ListMove 操作

func (*OperationFactory) MapToOperatorForListReplace

func (f *OperationFactory) MapToOperatorForListReplace(obj Value) mo.Result[Operator]

MapToOperatorForListReplace converts a map to a ListReplace operator.

func (*OperationFactory) MapToOperatorForNoop

func (f *OperationFactory) MapToOperatorForNoop(obj Value) mo.Result[Operator]

MapToOperatorForNoop converts a map to a Noop operator.

func (*OperationFactory) MapToOperatorForNumberAdd

func (f *OperationFactory) MapToOperatorForNumberAdd(obj Value) mo.Result[Operator]

MapToOperatorForNumberAdd converts a map to a number add operator.

func (*OperationFactory) MapToOperatorForObjectDelete

func (f *OperationFactory) MapToOperatorForObjectDelete(obj Value) mo.Result[Operator]

MapToOperatorForObjectDelete converts a map to an ObjectDelete operator.

func (*OperationFactory) MapToOperatorForObjectInsert

func (f *OperationFactory) MapToOperatorForObjectInsert(obj Value) mo.Result[Operator]

MapToOperatorForObjectInsert converts a map to an ObjectInsert operator.

func (*OperationFactory) MapToOperatorForObjectReplace

func (f *OperationFactory) MapToOperatorForObjectReplace(obj Value) mo.Result[Operator]

MapToOperatorForObjectReplace converts a map to an ObjectReplace operator.

func (*OperationFactory) MapToOperatorForSubType

func (f *OperationFactory) MapToOperatorForSubType(obj Value) mo.Result[Operator]

MapToOperatorForSubType 自定义子类型操作

func (*OperationFactory) NumberAddOperationBuilder

func (f *OperationFactory) NumberAddOperationBuilder(path Path) *NumberAddOperationBuilder

NumberAddOperationBuilder creates a new number add operation builder for the given path.

func (*OperationFactory) ObjectOperationBuilder

func (f *OperationFactory) ObjectOperationBuilder(path Path) *ObjectOperationBuilder

ObjectOperationBuilder creates a new object operation builder for the given path.

func (*OperationFactory) OperationComponentFromValue

func (f *OperationFactory) OperationComponentFromValue(val Value) mo.Result[*OperationComponent]

OperationComponentFromValue creates an operation component from a value.

func (*OperationFactory) OperatorFromValue

func (f *OperationFactory) OperatorFromValue(val Value) mo.Result[Operator]

OperatorFromValue creates an operator from a value.

func (*OperationFactory) TextOperationBuilder

func (f *OperationFactory) TextOperationBuilder(path Path) *TextOperationBuilder

TextOperationBuilder creates a new text operation builder for the given path.

func (*OperationFactory) ValidateOperationObjectSize

func (f *OperationFactory) ValidateOperationObjectSize(val Value, expectSize int) mo.Result[bool]

ValidateOperationObjectSize 检查操作对象的大小是否超过限制

type OperationTransformer

type OperationTransformer interface {
	// OperationFromValueArray 创建一个操作
	OperationFromValueArray(values []Value) mo.Result[*Operation]
	// OperationComponentsFromValue 创建一个操作组件
	OperationComponentsFromValue(node Value) mo.Result[[]*OperationComponent]
	// Apply 将操作应用到给定的 JSON 节点上
	Apply(ctx context.Context, value Value, operation *Operation) mo.Result[Value]
	// Applies 将多个操作应用到给定的 JSON 节点上
	Applies(ctx context.Context, value Value, operations []*Operation) mo.Result[Value]
	// Transform 对操作进行转换
	Transform(ctx context.Context, left, right *Operation) (leftN, rightN *Operation, err error)
}

OperationTransformer 是一个接口,用于转换 JSON 操作

type Operator

type Operator interface {
	Format(f fmt.State, verb rune)
	Action() Action
	Validates() error
	Clone() Operator
}

Operator is a type of operation that can be applied to a JSON value.

type Path

type Path struct {
	Paths []PathElement
}

Path is a path of json object

func NewPathFromIndexes

func NewPathFromIndexes(indexes []int) Path

NewPathFromIndexes create a new Path from indexes

func NewPathFromKeys

func NewPathFromKeys(keys []string) Path

NewPathFromKeys create a new Path from keys

func (*Path) Clone

func (p *Path) Clone() Path

Clone create a copy of the path

func (*Path) CommonPathPrefix

func (p *Path) CommonPathPrefix(path Path) *Path

CommonPathPrefix get the common path prefix

func (*Path) DecreaseIndex

func (p *Path) DecreaseIndex(index int) bool

DecreaseIndex decrease the index at index

func (*Path) Equal

func (p *Path) Equal(other Path) bool

Equal check if two path is equal

func (*Path) FirstIndexPath

func (p *Path) FirstIndexPath() mo.Option[int]

FirstIndexPath get the first index of path

func (*Path) FirstKeyPath

func (p *Path) FirstKeyPath() mo.Option[string]

FirstKeyPath get the first key of path

func (*Path) Format

func (p *Path) Format(st fmt.State, verb rune)

Format formats the path as a string

func (*Path) FromValue

func (p *Path) FromValue(path Value)

FromValue create a new Path from a Value

func (*Path) Get

func (p *Path) Get(index int) mo.Option[PathElement]

Get try to get the path element at index

func (*Path) GetElements

func (p *Path) GetElements() []PathElement

GetElements get the path elements

func (*Path) GetIndexAt

func (p *Path) GetIndexAt(index int) mo.Option[int]

GetIndexAt get the index at index

func (*Path) GetKeyAt

func (p *Path) GetKeyAt(index int) mo.Option[string]

GetKeyAt get the key at index

func (*Path) GetMutElements

func (p *Path) GetMutElements() *[]PathElement

GetMutElements get the path elements

func (*Path) IncreaseIndex

func (p *Path) IncreaseIndex(index int) bool

IncreaseIndex increase the index at index

func (*Path) IsEmpty

func (p *Path) IsEmpty() bool

IsEmpty check if the path is empty

func (*Path) IsPrefixOf

func (p *Path) IsPrefixOf(other Path) bool

IsPrefixOf check if the path is prefix of another path

func (*Path) Last

func (p *Path) Last() mo.Option[PathElement]

Last get the last path element

func (*Path) Len

func (p *Path) Len() int

Len get the length of path

func (*Path) MaxCommonPath

func (p *Path) MaxCommonPath(path Path) *Path

MaxCommonPath get the max common path

func (*Path) NextLevel

func (p *Path) NextLevel() Path

NextLevel get the next level path

func (*Path) Replace

func (p *Path) Replace(index int, pathElem PathElement) mo.Option[PathElement]

Replace try to replace the path element at index

func (*Path) SplitAt

func (p *Path) SplitAt(mid int) (left, right Path)

SplitAt split the path at index

func (*Path) String

func (p *Path) String() string

String 实现 fmt.Stringer trait for Path

func (*Path) ToValue

func (p *Path) ToValue() Value

ToValue convert the Path to a Value

func (*Path) UnmarshalJSON

func (p *Path) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshal json to path

type PathElement

type PathElement struct {
	Key   string
	Index int
}

PathElement is a element of path

func PathElementFromIndex

func PathElementFromIndex(i int) PathElement

PathElementFromIndex create a PathElement from index

func PathElementFromKey

func PathElementFromKey(k string) PathElement

PathElementFromKey create a PathElement from key

func (PathElement) Equals

func (pe PathElement) Equals(other PathElement) bool

Equals checks if two PathElement are equal

type PrimitiveType

type PrimitiveType interface {
	string | int | int64 | float64 | bool
}

PrimitiveType 定义了支持的原始类型

type SonicValue

type SonicValue struct {
	// contains filtered or unexported fields
}

SonicValue 定义了 JSON Object 的节点

func NewSonicValue

func NewSonicValue(node *ast.Node) *SonicValue

NewSonicValue 创建一个新的 SonicValue

func (*SonicValue) DeleteKey

func (n *SonicValue) DeleteKey(key string) error

DeleteKey 从对象中删除指定的键名

func (*SonicValue) Equals

func (n *SonicValue) Equals(other Value) bool

Equals 检查两个节点是否相等

func (*SonicValue) Format

func (n *SonicValue) Format(st fmt.State, verb rune)

Format 实现 fmt.Formatter 接口,用于格式化输出

func (*SonicValue) GetArray

func (n *SonicValue) GetArray() mo.Result[[]Value]

GetArray 返回节点的数组,如果节点是数组类型

func (*SonicValue) GetByPath

func (n *SonicValue) GetByPath(path ...any) mo.Option[Value]

GetByPath 返回节点的键名,如果节点是对象类型且存在键名

func (*SonicValue) GetIndex

func (n *SonicValue) GetIndex(index int) mo.Option[Value]

GetIndex 返回节点的索引值,如果节点是数组类型且存在索引

func (*SonicValue) GetInt

func (n *SonicValue) GetInt() mo.Result[int]

GetInt 返回节点的整数值,如果节点是数字类型

func (*SonicValue) GetIntKey

func (n *SonicValue) GetIntKey(key string) mo.Option[int]

GetIntKey 返回节点的整数键名,如果节点是对象类型且存在整数键名

func (*SonicValue) GetKey

func (n *SonicValue) GetKey(key string) mo.Option[Value]

GetKey 返回节点的键名,如果节点是对象类型且存在键名

func (*SonicValue) GetMap

func (n *SonicValue) GetMap() mo.Result[map[string]Value]

GetMap 返回节点的映射,如果节点是对象类型

func (*SonicValue) GetNumeric

func (n *SonicValue) GetNumeric() mo.Result[float64]

GetNumeric 返回节点的数字值,如果节点是数字类型

func (*SonicValue) GetString

func (n *SonicValue) GetString() mo.Result[string]

GetString 返回节点的字符串值,如果节点是字符串类型

func (*SonicValue) GetStringKey

func (n *SonicValue) GetStringKey(key string) mo.Option[string]

GetStringKey 返回节点的字符串键名,如果节点是对象类型且存在字符串键名

func (*SonicValue) HasKey

func (n *SonicValue) HasKey(key string) bool

HasKey 检查对象中是否存在指定的键名

func (*SonicValue) IsArray

func (n *SonicValue) IsArray() bool

IsArray 返回节点是否为数组类型

func (*SonicValue) IsBool

func (n *SonicValue) IsBool() bool

IsBool 返回节点是否为布尔类型

func (*SonicValue) IsFloat

func (n *SonicValue) IsFloat() bool

IsFloat 返回节点是否为浮点数类型

func (*SonicValue) IsInt

func (n *SonicValue) IsInt() bool

IsInt 返回节点是否为整数类型

func (*SonicValue) IsNull

func (n *SonicValue) IsNull() bool

IsNull 返回节点是否为 null 类型

func (*SonicValue) IsNumber

func (n *SonicValue) IsNumber() bool

IsNumber 返回节点是否为数字类型

func (*SonicValue) IsNumeric

func (n *SonicValue) IsNumeric() bool

IsNumeric 返回节点是否为数字类型

func (*SonicValue) IsObject

func (n *SonicValue) IsObject() bool

IsObject 返回节点是否为对象类型

func (*SonicValue) IsString

func (n *SonicValue) IsString() bool

IsString 返回节点是否为字符串类型

func (*SonicValue) PackAny

func (n *SonicValue) PackAny()

PackAny 将 SonicValue 解包为 ast.NewValue

func (*SonicValue) RawMessage

func (n *SonicValue) RawMessage() json.RawMessage

RawMessage 返回节点的原始字节数据

func (*SonicValue) SetKey

func (n *SonicValue) SetKey(key string, value Value) error

SetKey 设置对象中的键名和值

func (*SonicValue) Size

func (n *SonicValue) Size() int

Size 返回对象的属性数量

func (*SonicValue) Type

func (n *SonicValue) Type() ValueType

Type 返回节点的类型

func (*SonicValue) Unmarshal

func (n *SonicValue) Unmarshal(data []byte) error

Unmarshal 实现 JSON 的解码

func (*SonicValue) UpdateArray

func (n *SonicValue) UpdateArray(values []Value) error

UpdateArray 从传入的 Value 数组更新当前 Value

func (*SonicValue) UpdateObject

func (n *SonicValue) UpdateObject(value Value) error

UpdateObject 从传入的 Value 更新当前 Value

type SonicValueFactory

type SonicValueFactory struct{}

SonicValueFactory 用于创建 SonicValue 的工厂

func (SonicValueFactory) FromAny

func (vf SonicValueFactory) FromAny(data any) Value

FromAny 创建一个新的 JSON Object 节点

func (SonicValueFactory) FromArray

func (vf SonicValueFactory) FromArray(values []Value) Value

FromArray 创建一个新的 JSON Array 节点

func (SonicValueFactory) FromPrimitive

func (vf SonicValueFactory) FromPrimitive(data any) Value

FromPrimitive 创建一个新的 JSON Object 节点

func (SonicValueFactory) Unmarshal

func (vf SonicValueFactory) Unmarshal(bytes []byte) (Value, error)

Unmarshal 实现了 ValueFactory 接口的 Unmarshal 方法

type SubType

type SubType interface {
	// TypeName 返回子类型的名称
	TypeName() string
}

SubType 定义非 json 操作的子类型

type SubTypeAction

type SubTypeAction string

SubTypeAction 定义了子类型操作的类型

const (
	// ActionSubTypeNumberAdd 表示在数字类型上执行加法操作
	ActionSubTypeNumberAdd SubTypeAction = "na"
	// ActionSubTypeText 表示文本子类型的操作
	ActionSubTypeText SubTypeAction = "text"
)

type SubTypeFunctions

type SubTypeFunctions interface {
	OperatorName() string
	Invert(subType SubType, path Path, subTypeOperand Value) mo.Result[Operator]
	Merge(baseOperand Value, other Operator) mo.Option[Operator]
	Transform(newVal, baseVal Value, side TransformSide) mo.Result[[]Value]
	Apply(val mo.Option[Value], subTypeOperand Value) mo.Result[mo.Option[Value]]
	ValidateOperand(val Value) error
}

SubTypeFunctions 定义非 json 操作的子类型操作

type SubTypeFunctionsHolder

type SubTypeFunctionsHolder interface {
	Register(subType SubTypeAction, fn SubTypeFunctions)
	Unregister(subType SubTypeAction)
	Get(subType SubTypeAction) mo.Option[SubTypeFunctions]
}

SubTypeFunctionsHolder 定义了子类型操作的持有者接口

type SubTypeFunctionsHolderImpl

type SubTypeFunctionsHolderImpl struct {
	// contains filtered or unexported fields
}

SubTypeFunctionsHolderImpl 子类型操作的持有者

func NewSubTypeFunctionsHolder

func NewSubTypeFunctionsHolder() *SubTypeFunctionsHolderImpl

NewSubTypeFunctionsHolder 创建一个子类型操作的持有者

func (*SubTypeFunctionsHolderImpl) Get

Get 获取一个子类型操作

func (*SubTypeFunctionsHolderImpl) Register

func (sfh *SubTypeFunctionsHolderImpl) Register(subType SubTypeAction, fn SubTypeFunctions)

Register 注册一个子类型操作

func (*SubTypeFunctionsHolderImpl) Unregister

func (sfh *SubTypeFunctionsHolderImpl) Unregister(subType SubTypeAction)

Unregister 注销一个子类型操作

type SubTypeOperationBuilder

type SubTypeOperationBuilder struct {
	// contains filtered or unexported fields
}

SubTypeOperationBuilder is a builder for subtype operations.

func NewSubTypeOperationBuilder

func NewSubTypeOperationBuilder(path Path, subType SubType, subTypeFunction SubTypeFunctions) *SubTypeOperationBuilder

NewSubTypeOperationBuilder creates a new subtype operation builder.

func (*SubTypeOperationBuilder) Build

Build builds the operation component for subtype operations.

func (*SubTypeOperationBuilder) SubTypeFunctions

SubTypeFunctions sets the subtype functions.

func (*SubTypeOperationBuilder) SubTypeOperand

func (b *SubTypeOperationBuilder) SubTypeOperand(val Value) *SubTypeOperationBuilder

SubTypeOperand sets the subtype operand value.

type SubTypeOperator

type SubTypeOperator struct {
	SubType SubType
	Value   Value
	// SubTypeFunctions holds the functions for the subtype operations.
	SubTypeFunctions SubTypeFunctions
}

SubTypeOperator is an operator that has a subtype.

func NewSubTypeOperator

func NewSubTypeOperator(subType SubType, val Value, subTypeFunctions SubTypeFunctions) *SubTypeOperator

NewSubTypeOperator creates a new SubTypeOperator.

func (*SubTypeOperator) Action

func (s *SubTypeOperator) Action() Action

Action returns the action of the operator.

func (*SubTypeOperator) Clone

func (s *SubTypeOperator) Clone() Operator

Clone returns a copy of the operator.

func (*SubTypeOperator) Format

func (s *SubTypeOperator) Format(f fmt.State, _ rune)

Format formats the operator for debugging.

func (*SubTypeOperator) Validates

func (s *SubTypeOperator) Validates() error

Validates returns nil if the operator is valid.

type Text

type Text struct {
}

Text 是一个文本操作的子类型

func NewText

func NewText() *Text

NewText 创建一个文本操作的子类型

func (Text) TypeName

func (Text) TypeName() string

TypeName 返回子类型的名称

type TextOperand

type TextOperand struct {
	InsertVal mo.Option[string] `json:"i,omitempty"`
	DeleteVal mo.Option[string] `json:"d,omitempty"`
	Offset    int               `json:"p,omitempty"`
}

TextOperand 是一个文本操作的子类型操作

func NewDeleteTextOperand

func NewDeleteTextOperand(offset int, deleteVal string) *TextOperand

NewDeleteTextOperand 创建一个文本删除操作的子类型操作

func NewInsertTextOperand

func NewInsertTextOperand(offset int, insertVal string) *TextOperand

NewInsertTextOperand 创建一个文本插入操作的子类型操作

func (*TextOperand) FromValue

func (t *TextOperand) FromValue(node Value) error

FromValue 将节点转换为 TextOperand

func (*TextOperand) GetDeleteVal

func (t *TextOperand) GetDeleteVal() mo.Option[string]

GetDeleteVal 返回删除的值,如果是删除操作

func (*TextOperand) GetInsertVal

func (t *TextOperand) GetInsertVal() mo.Option[string]

GetInsertVal 返回插入的值,如果是插入操作

func (*TextOperand) GetOffset

func (t *TextOperand) GetOffset() int

GetOffset 返回操作的偏移量

func (*TextOperand) InvertObject

func (t *TextOperand) InvertObject() mo.Result[*TextOperand]

InvertObject 将传入的 TextOperand 反转为一个新的 TextOperand

func (*TextOperand) IsDelete

func (t *TextOperand) IsDelete() bool

IsDelete 返回 true 如果是删除操作

func (*TextOperand) IsInsert

func (t *TextOperand) IsInsert() bool

IsInsert 返回 true 如果是插入操作

func (*TextOperand) MustGetDeleteVal

func (t *TextOperand) MustGetDeleteVal() string

MustGetDeleteVal 返回删除的值,如果是删除操作,否则会 panic

func (*TextOperand) MustGetInsertVal

func (t *TextOperand) MustGetInsertVal() string

MustGetInsertVal 返回插入的值,如果是插入操作,否则会 panic

func (*TextOperand) ToValue

func (t *TextOperand) ToValue() Value

ToValue 将 TextOperand 转换为节点

func (*TextOperand) TransformPosition

func (t *TextOperand) TransformPosition(pos int, insertAfter bool) int

TransformPosition 返回一个新的偏移量

type TextOperationBuilder

type TextOperationBuilder struct {
	// contains filtered or unexported fields
}

TextOperationBuilder is a builder for text operations.

func NewTextOperationBuilder

func NewTextOperationBuilder(path Path, subTypeFunction SubTypeFunctions) *TextOperationBuilder

NewTextOperationBuilder creates a new text operation builder.

func (*TextOperationBuilder) Build

Build builds the operation component for text operations.

func (*TextOperationBuilder) DeleteStr

func (b *TextOperationBuilder) DeleteStr(offset int, val mo.Option[string]) *TextOperationBuilder

DeleteStr sets the delete value as a string.

func (*TextOperationBuilder) InsertStr

func (b *TextOperationBuilder) InsertStr(offset int, val mo.Option[string]) *TextOperationBuilder

InsertStr sets the insert value as a string.

type TextSubType

type TextSubType struct {
}

TextSubType 是一个文本操作的子类型操作

func NewTextSubType

func NewTextSubType() *TextSubType

NewTextSubType 创建一个文本操作的子类型操作

func (*TextSubType) Apply

func (t *TextSubType) Apply(val mo.Option[Value], subTypeOperand Value) mo.Result[mo.Option[Value]]

Apply 实现 SubTypeFunctions 接口的 Apply 方法

该方法用于应用文本操作的子类型操作

func (*TextSubType) Invert

func (t *TextSubType) Invert(subType SubType, _ Path, subTypeOperand Value) mo.Result[Operator]

Invert 实现 SubTypeFunctions 接口的 Invert 方法

该方法用于反转文本操作的子类型操作

func (*TextSubType) Merge

func (t *TextSubType) Merge(baseOperand Value, other Operator) mo.Option[Operator]

Merge 实现 SubTypeFunctions 接口的 Merge 方法

该方法用于合并两个文本操作的子类型操作

func (*TextSubType) OperatorName

func (t *TextSubType) OperatorName() string

OperatorName 实现 SubTypeFunctions 接口的 OperatorName 方法

func (*TextSubType) Transform

func (t *TextSubType) Transform(newVal, baseVal Value, side TransformSide) mo.Result[[]Value]

Transform 实现 SubTypeFunctions 接口的 Transform 方法

该方法用于转换新值和基础值,返回一个节点数组

func (*TextSubType) ValidateOperand

func (t *TextSubType) ValidateOperand(val Value) error

ValidateOperand 实现 SubTypeFunctions 接口的 ValidateOperand 方法

该方法用于验证操作数是否有效

type TransformSide

type TransformSide int

TransformSide 表示转换的方向

const (
	// TransformSideLeft 表示转换的方向是从左边
	TransformSideLeft TransformSide = iota
	// TransformSideRight 表示转换的方向是从右边
	TransformSideRight
)

type Transformer

type Transformer struct {
}

Transformer 表示一个操作转换器

func NewTransformer

func NewTransformer() *Transformer

NewTransformer 创建一个操作转换器

func (*Transformer) Consume

func (t *Transformer) Consume(
	op *OperationComponent,
	commonPath *Path, other *OperationComponent,
)

Consume 消费一个操作

func (*Transformer) Transform

func (t *Transformer) Transform(
	operation, baseOperation *Operation,
) (leftTransformed, rightTransformed mo.Result[*Operation], err error)

Transform 对一个操作进行转换

func (*Transformer) TransformComponent

func (t *Transformer) TransformComponent(
	newOp *OperationComponent, baseOp *OperationComponent, side TransformSide,
) (mo.Result[[]*OperationComponent], error)

TransformComponent 对一个操作组件进行转换

func (*Transformer) TransformComponentForListDelete

func (t *Transformer) TransformComponentForListDelete(
	newOp, baseOp *OperationComponent,
	_ TransformSide,
	_ *ListDelete,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForListDelete 对一个 ListDelete 操作进行转换

func (*Transformer) TransformComponentForListInsert

func (t *Transformer) TransformComponentForListInsert(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	_ *ListInsert,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForListInsert 对一个 ListInsert 操作进行转换

func (*Transformer) TransformComponentForListMove

func (t *Transformer) TransformComponentForListMove(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	listMove *ListMove,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForListMove 对一个 ListMove 操作进行转换

func (*Transformer) TransformComponentForListMoveWithListInsert

func (t *Transformer) TransformComponentForListMoveWithListInsert(
	newOp, baseOp *OperationComponent,
	_ TransformSide,
	listMove *ListMove,
	_ *ListInsert,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForListMoveWithListInsert 对一个 ListMove 操作进行转换

func (*Transformer) TransformComponentForListMoveWithListMove

func (t *Transformer) TransformComponentForListMoveWithListMove(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	listMove, newListMove *ListMove,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForListMoveWithListMove 对一个 ListMove 操作进行转换

func (*Transformer) TransformComponentForListReplace

func (t *Transformer) TransformComponentForListReplace(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	listReplace *ListReplace,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForListReplace 对一个 ListReplace 操作进行转换

func (*Transformer) TransformComponentForObjectDelete

func (t *Transformer) TransformComponentForObjectDelete(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	_ *ObjectDelete,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForObjectDelete 对一个 ObjectDelete 操作进行转换

func (*Transformer) TransformComponentForObjectInsert

func (t *Transformer) TransformComponentForObjectInsert(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	objectInsert *ObjectInsert,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForObjectInsert 对一个 ObjectInsert 操作进行转换

func (*Transformer) TransformComponentForObjectReplace

func (t *Transformer) TransformComponentForObjectReplace(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	objectReplace *ObjectReplace,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForObjectReplace 对一个 ObjectReplace 操作进行转换

func (*Transformer) TransformComponentForSubType

func (t *Transformer) TransformComponentForSubType(
	newOp, baseOp *OperationComponent,
	side TransformSide,
	baseOperator *SubTypeOperator,
) (mo.Result[[]*OperationComponent], error)

TransformComponentForSubType 对一个操作组件进行子类型转换

func (*Transformer) TransformComponentOperator

func (t *Transformer) TransformComponentOperator(
	newOp *OperationComponent, baseOp *OperationComponent, side TransformSide,
) (mo.Result[[]*OperationComponent], error)

TransformComponentOperator 对一个操作组件的操作数进行转换

func (*Transformer) TransformMatrix

func (t *Transformer) TransformMatrix(
	operation, baseOperation *Operation,
) (lop, rop mo.Result[*Operation], err error)

TransformMatrix 对一个操作矩阵进行转换

要求左右的操作都是非空的

func (*Transformer) TransformMulti

func (t *Transformer) TransformMulti(
	operation *Operation, baseOperation *OperationComponent,
) (newOp mo.Result[*Operation], components mo.Result[*OperationComponent], err error)

TransformMulti 对多个操作进行转换

type Value

type Value interface {
	Format(st fmt.State, verb rune)
	// Type 返回节点的类型
	Type() ValueType
	// IsBool 返回节点是否为布尔类型
	IsBool() bool
	// IsNull 返回节点是否为 null 类型
	IsNull() bool
	// IsNumeric 返回节点是否为数字类型
	IsNumeric() bool
	// IsInt 返回节点是否为整数类型
	IsInt() bool
	// IsString 返回节点是否为字符串类型
	IsString() bool
	// IsArray 返回节点是否为数组类型
	IsArray() bool
	// IsObject 返回节点是否为对象类型
	IsObject() bool
	// Unmarshal 实现 JSON 的解码
	Unmarshal(data []byte) error
	// PackAny 解析任意类型的数据, sonic 类型的实现需要此方法
	PackAny()
	// GetKey 返回节点的键名,如果是对象类型
	GetKey(key string) mo.Option[Value]
	// GetByPath 返回节点的键名,如果是对象类型
	GetByPath(path ...any) mo.Option[Value]
	// GetStringKey 返回节点的键名,如果是对象类型
	GetStringKey(key string) mo.Option[string]
	// GetIntKey 返回节点的键名,如果是对象类型
	GetIntKey(key string) mo.Option[int]
	// GetArray 返回节点的数组,如果是数组类型
	GetArray() mo.Result[[]Value]
	// GetMap 返回节点的对象,如果是对象类型
	GetMap() mo.Result[map[string]Value]
	// GetNumeric 返回节点的数字值,如果是数字类型
	GetNumeric() mo.Result[float64]
	// GetInt 返回节点的整数值,如果是数字类型
	GetInt() mo.Result[int]
	// GetString 返回节点的字符串值,如果是字符串类型
	GetString() mo.Result[string]
	// UpdateArray 从传入的 Value 数组更新当前 Value
	UpdateArray(values []Value) error
	// UpdateObject 从传入的 Value 更新当前 Value
	UpdateObject(value Value) error
	// SetKey 设置对象中的键名,如果是对象类型
	SetKey(key string, value Value) error
	// DeleteKey 删除对象中的键名,如果是对象类型
	DeleteKey(key string) error
	// HasKey 检查节点是否包含指定的键名,如果是对象类型
	HasKey(key string) bool
	// Size 返回对象的属性数量
	Size() int
	// Equals 检查两个节点是否相等
	Equals(other Value) bool
	// RawMessage 返回节点的原始消息
	RawMessage() json.RawMessage
}

Value 定义了 JSON Object 的节点接口

func ApplyListDelete

func ApplyListDelete(arr []Value, op *ListDelete, index int) []Value

ApplyListDelete 从数组中删除元素

func ApplyListInsert

func ApplyListInsert(arr []Value, op *ListInsert, index int) []Value

ApplyListInsert 在数组中插入元素

func ApplyListMove

func ApplyListMove(arr []Value, op *ListMove, index int) []Value

ApplyListMove 在数组中移动元素

func ApplyListReplace

func ApplyListReplace(arr []Value, op *ListReplace, index int) []Value

ApplyListReplace 在数组中替换元素

func ApplyToArray

func ApplyToArray(arr []Value, paths Path, operator Operator) ([]Value, error)

ApplyToArray 将操作应用到值上

func ApplyToObject

func ApplyToObject(obj Value, paths Path, operator Operator) (Value, error)

ApplyToObject 将操作应用到对象上

func ApplyToRootValue

func ApplyToRootValue(val Value, operator Operator) (Value, error)

ApplyToRootValue applies an operator directly on the root value.

func NewValue

func NewValue(valueType ValueType) Value

NewValue 创建一个新的 ValueBrian

func UnmarshalValue

func UnmarshalValue(data []byte) (Value, error)

UnmarshalValue 创建一个新的 JSON Object 节点

func ValueFromAny

func ValueFromAny(data any) Value

ValueFromAny 创建一个新的 JSON Object 节点

func ValueFromArray

func ValueFromArray(arr []Value) Value

ValueFromArray 创建一个新的 JSON Array 节点

func ValueFromPrimitive

func ValueFromPrimitive[T string | int | int64 | float64](data T) Value

ValueFromPrimitive 创建一个新的 JSON Object 节点

type ValueBrian

type ValueBrian struct {
	Value         Value
	Parent        *ValueBrian
	KeyInParent   string
	IndexInParent int
}

ValueBrian 定义了 value 的血统信息

type ValueFactory

type ValueFactory interface {
	// Unmarshal unmarshal JSON data into a Value
	Unmarshal([]byte) (Value, error)
	// FromPrimitive create a primitive JSON Object from a primitive type
	FromPrimitive(data any) Value
	// FromAny create a new JSON Object node from any type
	FromAny(any) Value
	// FromArray create a new JSON Array node from a slice of Value
	FromArray([]Value) Value
}

ValueFactory 接口定义了一个工厂方法,用于从 JSON 数据反序列化为 Value 类型

func NewAJSONValueFactory

func NewAJSONValueFactory() ValueFactory

NewAJSONValueFactory 创建一个新的 AJSONValueFactory 实例

func NewSonicValueFactory

func NewSonicValueFactory() ValueFactory

NewSonicValueFactory 创建一个新的 SonicValueFactory 实例

type ValueType

type ValueType int

ValueType 定义了 JSON Object 的节点类型

const (
	// Null is reflection of nil.(interface{})
	Null ValueType = iota
	// Numeric is reflection of float64
	Numeric
	// String is reflection of string
	String
	// Bool is reflection of bool
	Bool
	// Array is reflection of []*Value
	Array
	// Object is reflection of map[string]*Value
	Object
	// Any is reflection of any
	Any
)

func OperatorForValueType

func OperatorForValueType(op Operator) ValueType

OperatorForValueType returns an operator for the given value type.

func (ValueType) Format

func (nt ValueType) Format(st fmt.State, _ rune)

Format implements fmt.Formatter interface for ValueType

Directories

Path Synopsis
sharedb module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址