This repository has been archived by the owner on Mar 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlave.js
443 lines (362 loc) · 11.4 KB
/
lave.js
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
'use strict'
export default function(object, options) {
if (!options) options = {}
var functions = new Set
var placeholder = Math.random().toString(36).replace(/../, '_')
var functionPattern = RegExp(`${placeholder}(\\d+)`, 'g')
let cache = new Globals
let statements = []
let expression = getExpression(object)
statements.push({type: 'ExpressionStatement', expression})
let declarations = getDeclarations(statements)
if (declarations.length) statements.unshift({
type: 'VariableDeclaration',
declarations,
kind: 'var'
})
switch (options.format || 'expression') {
case 'expression':
break
case 'module':
statements.push({
type: 'ExportDefaultDeclaration',
declaration: statements.pop().expression
})
break
case 'function':
statements.push({
type: 'ReturnStatement',
argument: statements.pop().expression
})
statements = [{
type: 'ExpressionStatement',
expression: {
type: 'FunctionExpression',
params: [],
body: {
type: 'BlockStatement',
body: statements
}
}
}]
break
default:
throw new Error(`Unsupported format: ${options.format}`)
}
let program = {
type: 'Program',
body: statements
}
if (!options.generate) return program
let code = options.generate(program)
return code.replace(functionPattern, (_, i) => {
return Array.from(functions)[i].toString().replace(/^function |^/, 'function ')
})
function getExpression(value) {
if (cache.has(value)) return cache.get(value)
let node = new Object
cache.set(value, node)
if (Object(value) !== value) {
if (value < 0) {
node.type = 'UnaryExpression'
node.operator = '-'
node.argument = getExpression(Math.abs(value))
return node
}
node.value = value
node.type = 'Literal'
return node
}
let prototype = Object.getPrototypeOf(value)
let propertyNames = Object.getOwnPropertyNames(value)
let properties = new Map(propertyNames.map(name =>
[name, Object.getOwnPropertyDescriptor(value, name)]
))
switch (prototype) {
case String.prototype:
for (let pair of properties) {
properties.delete(pair[0])
if (pair[0] == 'length') break
} // fallthrough
case Number.prototype:
case Boolean.prototype:
node.type = 'CallExpression'
node.callee = getExpression(Object)
node.arguments = [getExpression(value.valueOf())]
break
case RegExp.prototype:
properties.delete('source')
properties.delete('global')
properties.delete('ignoreCase')
properties.delete('multiline')
properties.delete('lastIndex')
node.type = 'Literal'
node.value = value
break
case Date.prototype:
node.type = 'NewExpression'
node.callee = getExpression(Date)
node.arguments = [getExpression(value.valueOf())]
break
case Buffer.prototype:
for (let pair of properties) {
properties.delete(pair[0])
if (pair[0] == 'length') break
}
node.type = 'CallExpression'
node.callee = getExpression(Buffer)
node.arguments = [
getExpression(value.toString('base64')),
getExpression('base64')
]
break
case Error.prototype:
case EvalError.prototype:
case RangeError.prototype:
case ReferenceError.prototype:
case SyntaxError.prototype:
case TypeError.prototype:
case URIError.prototype:
properties.delete('message')
properties.delete('stack')
node.type = 'NewExpression'
node.callee = getExpression(value.constructor)
node.arguments = [getExpression(value.message)]
break
case Function.prototype:
if (isNativeFunction(value)) {
throw new Error('Native code cannot be serialized.')
}
properties.delete('length')
properties.delete('name')
properties.delete('arguments')
properties.delete('caller')
if (value.prototype && Object.getOwnPropertyNames(value.prototype).length < 2) {
properties.delete('prototype')
}
if (options.generate) {
functions.add(value)
let index = Array.from(functions).indexOf(value)
node.type = 'Identifier'
node.name = placeholder + index
break
}
node.type = 'CallExpression'
node.callee = getExpression(eval)
node.arguments = [getExpression(`(${value.toString()})`)]
break
case Array.prototype:
node.elements = []
let length = properties.get('length').value
let lastIndex = String(length - 1)
if (!length || properties.has(lastIndex)) properties.delete('length')
for (let property of properties) {
if (property[0] != node.elements.length) break
let element = getExpression(property[1].value)
if (element.type) {
node.elements.push(element)
properties.delete(property[0])
}
else node.elements.push(null)
}
node.type = 'ArrayExpression'
break
case Set.prototype:
case WeakSet.prototype:
let members = Array.from(value)
let index = 0
for (let member of members) {
let element = getExpression(member)
if (element.type) index++
else break
}
node.type = 'NewExpression'
node.callee = getExpression(value.constructor)
node.arguments = []
if (index > 0) {
node.arguments.push(getExpression(members.slice(0, index)))
}
for (let member of members.slice(index)) {
statements.push({
type: 'ExpressionStatement',
expression: {
type: 'CallExpression',
callee: {
type: 'MemberExpression',
object: node,
computed: false,
property: {type: 'Identifier', name: 'add'}
},
arguments: [getExpression(member)]
}
})
}
break
case Map.prototype:
case WeakMap.prototype:
let entries = Array.from(value)
for (let entry of entries) {
let element = getExpression(entry[1])
if (!element.type) {
entry.pop()
statements.push({
type: 'ExpressionStatement',
expression: {
type: 'CallExpression',
callee: {
type: 'MemberExpression',
object: node,
computed: false,
property: {type: 'Identifier', name: 'set'}
},
arguments: [getExpression(entry[0]), element]
}
})
}
}
node.arguments = [getExpression(entries)]
node.callee = getExpression(value.constructor)
node.type = 'NewExpression'
break
case Object.prototype:
node.properties = []
for (let property of properties) {
let element = getExpression(property[1].value)
if (!element.type) {
node.properties.push({
type: 'Property',
key: getExpression(property[0]),
value: getExpression(null)
})
continue
}
properties.delete(property[0])
node.properties.push({
type: 'Property',
key: getExpression(property[0]),
value: getExpression(property[1].value)
})
}
node.type = 'ObjectExpression'
break
default:
node.type = 'CallExpression'
node.callee = getExpression(Object.create)
node.arguments = [getExpression(prototype)]
break
}
for (let property of properties) {
statements.push({
type: 'ExpressionStatement',
expression: {
type: 'AssignmentExpression',
operator: '=',
left: {
type: 'MemberExpression',
object: node,
computed: !isNaN(property[0]),
property: {type:
'Identifier',
name: property[0]
}
},
right: getExpression(property[1].value)
}
})
}
return node
}
function getDeclarations(statements) {
let sites = function crawl(sites, object, key, value) {
if (Object(value) !== value) return
if (value.type == 'Identifier') return
if (value.type == 'Literal') return
let valueSites = sites.get(value)
if (valueSites) return valueSites.push({object, key})
sites.set(value, [{object, key}])
for (let property in value) {
crawl(sites, value, property, value[property])
}
return sites
}(new Map, {'': statements}, '', statements)
let declarations = []
for (let entry of sites) {
if (entry[1].length < 2) continue
let id = {type: 'Identifier'}
for (let site of entry[1]) site.object[site.key] = id
declarations.push({
type: 'VariableDeclarator',
id,
init: entry[0]
})
}
declarations.sort((a, b) => has(a.init, b.id) - has(b.init, a.id))
let ids = new Identifiers
for (let declaration of declarations) declaration.id.name = ids.next()
return declarations
}
}
class Identifiers {
constructor() { this.id = 0 }
next() {
let id = (this.id++).toString(36)
try { Function(`var ${id}`); return id }
catch (e) { return this.next() }
}
}
function has(parent, child) {
if (parent === child) return true
if (Object(parent) !== parent) return false
for (let key in parent) {
if (has(parent[key], child)) return true
}
return false
}
let nativeCode = String(Object).match(/{.*/)[0]
function isNativeFunction(fn) {
let source = String(fn)
let index = source.indexOf(nativeCode)
if (index < 0) return false
let length = index + nativeCode.length
return length === source.length
}
function Globals() {
let globals = new Map([
[NaN, {type: 'Identifier', name: 'NaN'}],
[null, {type: 'Literal', value: null}],
[undefined, {type: 'Identifier', name: 'undefined'}],
[Infinity, {type: 'Identifier', name: 'Infinity'}],
[(0,eval)('this'), {
type: 'CallExpression',
callee: {
type: 'SequenceExpression',
expressions: [
{type: 'Literal', value: 0},
{type: 'Identifier', name: 'eval'}
]
},
"arguments": [{type: 'Literal', value: 'this'}]
}]
])
return crawl(globals, (0, eval)('this'))
}
const STANDARD_GLOBALS = require('vm')
.runInNewContext('Object.getOwnPropertyNames(this)')
.concat('Buffer')
function crawl(map, value, object) {
let names = object ? Object.getOwnPropertyNames(value) : STANDARD_GLOBALS
let properties = []
for (let name of names) {
let descriptor = Object.getOwnPropertyDescriptor(value, name)
if (Object(descriptor.value) !== descriptor.value) continue
if (map.has(descriptor.value)) continue
let property = {type: 'Identifier', name}
if (object) property = {type: 'MemberExpression', object, property}
map.set(descriptor.value, property)
properties.push({value: descriptor.value, object: property})
}
for (let property of properties) {
crawl(map, property.value, property.object)
}
return map
}