-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringify.mjs
More file actions
89 lines (68 loc) · 2.39 KB
/
stringify.mjs
File metadata and controls
89 lines (68 loc) · 2.39 KB
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
import Debug from './debug.mjs'
import { SendScriptSerializationError } from './error.mjs'
import {
awaitSymbol,
call,
ref
} from './symbol.mjs'
const debug = Debug.extend('stringify')
const keywords = ['ref', 'call', 'quote', 'await', 'leaf']
const isKeyword = (v) => keywords.includes(v)
const isPlainObject = (value) => {
if (!value || typeof value !== 'object') return false
const proto = Object.getPrototypeOf(value)
return proto === Object.prototype || proto === null
}
// Recursively transform a program tree, encoding SendScript operators and leaf values
function transformValue (value, leafSerializer) {
debug(value)
if (value === null) {
return null
}
// Normalize SendScript wrapper functions (ref, call, await)
if (typeof value === 'function' && typeof value.toJSON === 'function') {
return transformValue(value.toJSON(), leafSerializer)
}
// Encode SendScript operators
if (value && value[ref]) {
return ['ref', ...value.path]
}
if (value && value[call]) {
return ['call', transformValue(value.ref, leafSerializer), transformValue(value.args, leafSerializer)]
}
if (value && value[awaitSymbol]) {
return ['await', transformValue(value.ref, leafSerializer)]
}
// Handle arrays: quote keyword operators, transform other arrays recursively
if (Array.isArray(value)) {
const [operator, ...rest] = value
if (isKeyword(operator)) {
// Quote reserved keyword strings to preserve them as data
return [['quote', operator], ...rest.map((item) => transformValue(item, leafSerializer))]
}
return value.map((item) => transformValue(item, leafSerializer))
}
// Recurse into plain objects
if (isPlainObject(value)) {
const result = {}
for (const key of Object.keys(value)) {
result[key] = transformValue(value[key], leafSerializer)
}
return result
}
// Encode non-JSON leaf values (Date, RegExp, BigInt, etc.)
return ['leaf', leafSerializer(value)]
}
function strictStringify (x) {
const typeOf = typeof x
if (typeOf === 'object' || typeOf === 'function' || x === undefined) {
throw new SendScriptSerializationError(`Cannot and should not attempt to serialize ${x}`)
}
return JSON.stringify(x)
}
export default function stringify (leafSerializer = strictStringify) {
function stringify (program) {
return JSON.stringify(transformValue(program, leafSerializer))
}
return stringify
}