-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatchpack.ts
281 lines (220 loc) · 8.55 KB
/
patchpack.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import * as notepack from "notepack.io"
import { check, IReversibleJsonPatch, ISchemaNode, MAP_NODE, ARRAY_NODE, TSchemaPatch, Type, ISchemaType } from "./common"
import { Schema } from "./schema"
interface IBuildMeta {
parent?: ISchemaNode
key: number | string
index: number
updateSchema?: boolean
checkDeleted?: boolean
}
export class PatchPack {
public schema!: Schema
constructor (types?: { [type: string]: string[] | Type<any> }) {
this.schema = new Schema(types || {})
}
public encodeState(value: any, includeTypes = true, updateSchema = true): Buffer {
// encode root node
const encoded = this.encodeNode(value, { key: "", index: -1, updateSchema })
// encode snapshot nodes and schema
const snapshot = [ encoded, ...includeTypes ? [this.schema.types] : [] ]
// return packed snapshot
return notepack.encode(snapshot)
}
public decodeState(buffer: Buffer, updateSchema = true): any {
const [encodedNode, types] = notepack.decode(buffer)
// apply schema types
this.schema.init(types)
// decode snapshot
return this.decodeNode(encodedNode, { key: "", index: -1, updateSchema })
}
private encodeNode(value: any, meta: IBuildMeta): any {
const { parent, key = "", index = -1, updateSchema = true, checkDeleted } = meta
// add key to map schema keys
if (parent && parent.type === MAP_NODE && updateSchema) {
parent.keys!.push(key as string)
}
let node: ISchemaNode | undefined
if (!parent) {
node = this.schema.root
} else {
// get child node
if (checkDeleted) {
node = this.schema.getDeletedNode(parent, key)!
}
if (!node) {
node = this.schema.getChildNode(parent, key)!
}
}
const data = []
if (Array.isArray(value)) {
if (!node && updateSchema) {
// create schema node
node = this.schema.createNode(this.schema.nextId, parent, ARRAY_NODE, key, index)
}
check(!node, `Cannot encode value - node not found on path: ${this.schema.getNodePath(parent, key)}`)
// set encoded node type and id
data.push(ARRAY_NODE, node.id)
// set encoded node items
for(let i = 0; i < value.length; i++) {
data.push(this.encodeNode(value[i], { parent: node, key: i, index: i, updateSchema }))
}
} else if (typeof value === "object" && value) {
// check value type
const type = node ? node.type as ISchemaType : this.schema.findType(value) || MAP_NODE
if (!node && updateSchema) {
// create schema node
node = this.schema.createNode(this.schema.nextId, parent, type, key, index)
}
check(!node, `Cannot encode value - node not found on path: ${this.schema.getNodePath(parent, key)}`)
data.push(type !== MAP_NODE ? type.index : MAP_NODE, node.id)
if (type !== MAP_NODE) {
// set encoded props
Object.keys(value).forEach((k) => {
data.push(this.encodeNode(value[k], { ...meta, parent: node, key: k, index: type.props.indexOf(k) }))
})
} else {
// set map items
Object.keys(value).forEach((k, i) => {
data.push(k, this.encodeNode(value[k], { ...meta, parent: node, key: k, index: i }))
})
}
} else {
// check type
check (typeof value === "function" || typeof value === "symbol",
`Cannot encode value - wrong value on path ${ this.schema.getNodePath(parent, key) }`)
return value
}
return data
}
private decodeNode (encoded: any, meta: IBuildMeta): any {
// check if encoded primitive value
if (!encoded || !Array.isArray(encoded)) { return encoded }
const { parent, key, index, updateSchema = true, checkDeleted = false } = meta
const [ type, id, ...data ] = encoded
const schemaType = this.schema.getType(type)!
check(!schemaType, `Cannot decode state - unknown type: ${type}`)
let node: ISchemaNode | undefined
// create schema node
if (updateSchema) {
node = this.schema.createNode(id, parent, schemaType, key, index)
} else {
// get child node
if (checkDeleted) {
node = this.schema.getDeletedNode(parent, key)!
}
if (!node && parent) {
node = this.schema.getChildNode(parent, key)!
}
}
check(!node, `Cannot decode value - node for ${this.schema.getNodePath(parent, key)} not found}`)
const result = {} as any
if (schemaType === ARRAY_NODE) {
return data.map((item: any, i: number) => {
return this.decodeNode(item, { parent: node, index: i, key: i })
})
} else if (schemaType === MAP_NODE) {
// decode map items
for (let i = 0; i < data.length; i += 2) {
const childIndex = node!.keys!.push(data[i]) - 1
const value = this.decodeNode(data[i+1], { parent: node, key: data[i], index: childIndex })
if (value !== undefined) {
result[data[i]] = value
}
}
} else {
// decode type props
for (let i = 0; i < schemaType.props.length; i++) {
const prop = schemaType.props[i]
const value = this.decodeNode(data[i], { parent: node, key: prop, index: i })
if (value !== undefined) {
result[prop] = value
}
}
}
return result
}
public encodePatch(patch: IReversibleJsonPatch, updateSchema = true): Buffer {
const path = patch.path[0] === "/" ? patch.path.slice(1) : patch.path
const pathArr = path.split("/").reverse()
const key = pathArr.splice(0,1)[0]
if (updateSchema) {
this.schema.clearDeleted()
}
let parent: ISchemaNode = this.schema.root!
check (!parent,`Cannot encode patch, you need to build schema first!`)
while (pathArr.length) {
parent = this.schema.getChildNode(parent, pathArr.pop()!)!
check(!parent, `Cannot add new node - wrong path: ${patch.path}`)
}
const op = ["add", "replace", "remove"].indexOf(patch.op) as any
const index = this.schema.getChildIndex(parent, key)
const data: TSchemaPatch = [ op, parent.id, index ]
const node = this.schema.getChildNode(parent, key)
if (patch.op !== "remove") {
if (node && updateSchema) {
this.schema.deleteNode(node)
}
if (parent.type === MAP_NODE && patch.op === "add") {
data.push([key, this.encodeNode(patch.value, { parent, key, index, updateSchema })])
} else {
data.push(this.encodeNode(patch.value, { parent, key, index, updateSchema }))
}
}
if (patch.op !== "add" && "oldValue" in patch) {
data.push(this.encodeNode(patch.oldValue, { parent, key, index, updateSchema: false, checkDeleted: true }))
}
// delete old node
if (patch.op !== "remove" && node && updateSchema) {
this.schema.deleteNode(node)
}
return notepack.encode(data)
}
public decodePatch (buffer: Buffer, updateSchema = true): IReversibleJsonPatch {
// encode patch
const encodedPatch = notepack.decode<TSchemaPatch>(buffer)
const [opIndex, nodeId, propIndex, ...values] = encodedPatch
const parent = this.schema.getNode(nodeId)!
check (!parent, `Cannot decode patch - schema for node with id ${nodeId} not found`)
const patch: any = { op: ["add", "replace", "remove"][opIndex], path: '' }
// get kety from new map item or from schema
const key = parent.type === MAP_NODE && patch.op === "add"
? values[0][0]
: this.schema.getChildName(parent, propIndex)
// get node from schema
const node = this.schema.getChildNode(parent, key)
if (values.length && patch.op !== "remove") {
// revome old node
if (node) {
this.schema.deleteNode(node)
}
// decode value
const value = values.reverse().pop()
if (parent.type === MAP_NODE && patch.op === "add") {
parent.keys?.push(key as string)
patch.value = this.decodeNode(value[1], { parent, key, index: propIndex, updateSchema })
} else {
patch.value = this.decodeNode(value, { parent, key, index: propIndex, updateSchema })
}
}
if (values.length && patch.op !== "add") {
patch.oldValue = this.decodeNode(values.pop(), {
parent, key, index: propIndex, updateSchema: false, checkDeleted: true
})
}
if (node && patch.op === "remove") {
this.schema.deleteNode(node)
}
patch.path = this.schema.getNodePath(parent, key)
if (values.length) {
throw new Error(`Unhandled params: ${values.toString()}`)
}
return patch
}
public static encode(value: any): Buffer {
return notepack.encode(value)
}
public static decode(buffer: Buffer): any {
return notepack.decode(buffer)
}
}