-
-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathserialize.ts
More file actions
316 lines (264 loc) · 8.34 KB
/
Copy pathserialize.ts
File metadata and controls
316 lines (264 loc) · 8.34 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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import type { array } from "./arrays.ts"
import { domainOf, type Primitive } from "./domain.ts"
import { serializePrimitive, type SerializablePrimitive } from "./primitive.ts"
import { stringAndSymbolicEntriesOf, type dict } from "./records.ts"
import { isDotAccessible, register } from "./registry.ts"
export type SerializationOptions = {
onCycle?: (value: object) => string
onSymbol?: (value: symbol) => string
onFunction?: (value: Function) => string
onUndefined?: string
onBigInt?: (value: bigint) => string
}
export type JsonStructure = JsonObject | JsonArray
export interface JsonObject {
[k: string]: Json
}
export type JsonArray = Json[]
export type JsonPrimitive = string | boolean | number | null
export type Json = JsonStructure | JsonPrimitive
export const snapshot = <t>(
data: t,
opts: SerializationOptions = {}
): snapshot<t> =>
_serialize(
data,
{
onUndefined: `$ark.undefined`,
onBigInt: n => `$ark.bigint-${n}`,
...opts
},
[]
) as never
export type snapshot<t, depth extends 1[] = []> =
unknown extends t ? unknown
: t extends Primitive ? snapshotPrimitive<t>
: t extends { toJSON: () => infer serialized } ? serialized
: t extends Function ? `Function(${string})`
: t extends Date ? string
: depth["length"] extends 10 ? unknown
: t extends array<infer item> ? array<snapshot<item, [...depth, 1]>>
: {
[k in keyof t as snapshotPrimitive<k>]: snapshot<t[k], [...depth, 1]>
}
type snapshotPrimitive<t> = t extends symbol ? `Symbol(${string})` : t
export type PrintableOptions = {
indent?: number
quoteKeys?: boolean
}
export const print = (data: unknown, opts?: PrintableOptions): void =>
console.log(printable(data, opts))
export const printable = (data: unknown, opts?: PrintableOptions): string => {
switch (domainOf(data)) {
case "object":
const o = data as dict
const ctorName = o.constructor?.name ?? "Object"
return (
ctorName === "Object" || ctorName === "Array" ?
opts?.quoteKeys === false ?
stringifyUnquoted(o, opts?.indent ?? 0, "")
: _printableStringify(o, printableOpts, [], opts?.indent ?? 0, "")
: stringifyUnquoted(o, opts?.indent ?? 0, "")
)
case "symbol":
return printableOpts.onSymbol(data as symbol)
default:
return serializePrimitive(data as SerializablePrimitive)
}
}
const stringifyUnquoted = (
value: unknown,
indent: number,
currentIndent: string
): string => {
if (typeof value === "function") return printableOpts.onFunction(value)
if (typeof value !== "object" || value === null)
return serializePrimitive(value as never)
const nextIndent = currentIndent + " ".repeat(indent)
if (Array.isArray(value)) {
if (value.length === 0) return "[]"
const items = value
.map(item => stringifyUnquoted(item, indent, nextIndent))
.join(",\n" + nextIndent)
return indent ? `[\n${nextIndent}${items}\n${currentIndent}]` : `[${items}]`
}
const ctorName = value.constructor?.name ?? "Object"
if (ctorName === "Object") {
const keyValues = stringAndSymbolicEntriesOf(value).map(([key, val]) => {
const stringifiedKey =
typeof key === "symbol" ? printableOpts.onSymbol(key)
: isDotAccessible(key) ? key
: JSON.stringify(key)
const stringifiedValue = stringifyUnquoted(val, indent, nextIndent)
return `${nextIndent}${stringifiedKey}: ${stringifiedValue}`
})
if (keyValues.length === 0) return "{}"
return indent ?
`{\n${keyValues.join(",\n")}\n${currentIndent}}`
: `{${keyValues.join(", ")}}`
}
if (value instanceof Date) return describeCollapsibleDate(value)
if ("expression" in value && typeof value.expression === "string")
return value.expression
return ctorName
}
const printableOpts = {
onCycle: () => "(cycle)",
onSymbol: v => `Symbol(${register(v)})`,
onFunction: v => `Function(${register(v)})`
} satisfies SerializationOptions
const _printableStringify = (
data: unknown,
opts: SerializationOptions,
seen: unknown[],
indent: number,
currentIndent: string
): string => {
if (typeof data === "function") return printableOpts.onFunction(data)
if (typeof data === "bigint") return `${data}n`
if (typeof data === "symbol") return JSON.stringify(printableOpts.onSymbol(data))
if (typeof data === "undefined") return JSON.stringify("undefined")
if (typeof data !== "object" || data === null) return JSON.stringify(data)
const o = data as object
if (seen.includes(o)) return JSON.stringify("(cycle)")
const nextSeen = [...seen, o]
const nextIndent = currentIndent + " ".repeat(indent)
if ("toJSON" in o && typeof (o as any).toJSON === "function")
return _printableStringify((o as any).toJSON(), opts, nextSeen, indent, nextIndent)
if (Array.isArray(o)) {
if (o.length === 0) return "[]"
const items = o.map(item =>
_printableStringify(item, opts, nextSeen, indent, nextIndent)
)
if (indent) {
return `[\n${nextIndent}${items.join(",\n" + nextIndent)}\n${currentIndent}]`
}
return `[${items.join(",")}]`
}
if (o instanceof Date) return JSON.stringify(o.toDateString())
const keyValues: string[] = []
for (const k in o) {
const serializedValue = _printableStringify(
(o as any)[k],
opts,
nextSeen,
indent,
nextIndent
)
const serializedKey = JSON.stringify(k)
if (indent) {
keyValues.push(`${nextIndent}${serializedKey}: ${serializedValue}`)
} else {
keyValues.push(`${serializedKey}:${serializedValue}`)
}
}
for (const s of Object.getOwnPropertySymbols(o)) {
const serializedValue = _printableStringify(
(o as any)[s],
opts,
nextSeen,
indent,
nextIndent
)
const serializedKey = JSON.stringify(printableOpts.onSymbol(s))
if (indent) {
keyValues.push(`${nextIndent}${serializedKey}: ${serializedValue}`)
} else {
keyValues.push(`${serializedKey}:${serializedValue}`)
}
}
if (keyValues.length === 0) return "{}"
if (indent) {
return `{\n${keyValues.join(",\n")}\n${currentIndent}}`
}
return `{${keyValues.join(",")}}`
}
const _serialize = (
data: unknown,
opts: SerializationOptions,
seen: unknown[]
): unknown => {
switch (domainOf(data)) {
case "object": {
const o = data as object
if ("toJSON" in o && typeof o.toJSON === "function") return o.toJSON()
if (typeof o === "function") return printableOpts.onFunction(o)
if (seen.includes(o)) return "(cycle)"
const nextSeen = [...seen, o]
if (Array.isArray(o))
return o.map(item => _serialize(item, opts, nextSeen))
if (o instanceof Date) return o.toDateString()
const result: Record<string, unknown> = {}
for (const k in o) result[k] = _serialize((o as any)[k], opts, nextSeen)
for (const s of Object.getOwnPropertySymbols(o)) {
result[opts.onSymbol?.(s as symbol) ?? s.toString()] = _serialize(
(o as any)[s],
opts,
nextSeen
)
}
return result
}
case "symbol":
return printableOpts.onSymbol(data as symbol)
case "bigint":
return opts.onBigInt?.(data as bigint) ?? `${data}n`
case "undefined":
return opts.onUndefined ?? "undefined"
case "string":
return (data as string).replace(/\\/g, "\\\\")
default:
return data
}
}
/**
* Converts a Date instance to a human-readable description relative to its precision
*/
export const describeCollapsibleDate = (date: Date): string => {
const year = date.getFullYear()
const month = date.getMonth()
const dayOfMonth = date.getDate()
const hours = date.getHours()
const minutes = date.getMinutes()
const seconds = date.getSeconds()
const milliseconds = date.getMilliseconds()
if (
month === 0 &&
dayOfMonth === 1 &&
hours === 0 &&
minutes === 0 &&
seconds === 0 &&
milliseconds === 0
)
return `${year}`
const datePortion = `${months[month]} ${dayOfMonth}, ${year}`
if (hours === 0 && minutes === 0 && seconds === 0 && milliseconds === 0)
return datePortion
let timePortion = date.toLocaleTimeString()
const suffix =
timePortion.endsWith(" AM") || timePortion.endsWith(" PM") ?
timePortion.slice(-3)
: ""
if (suffix) timePortion = timePortion.slice(0, -suffix.length)
if (milliseconds) timePortion += `.${pad(milliseconds, 3)}`
else if (timeWithUnnecessarySeconds.test(timePortion))
timePortion = timePortion.slice(0, -3)
return `${timePortion + suffix}, ${datePortion}`
}
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
const timeWithUnnecessarySeconds = /:\d\d:00$/
const pad = (value: number, length: number) =>
String(value).padStart(length, "0")