-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransformer.js
493 lines (373 loc) · 11.7 KB
/
transformer.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import { createHash, randomUUID } from 'node:crypto'
import { existsSync, readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import parse from './parser.js'
const {
dateFns: { add, format, formatISO, formatRFC7231 },
jsonpath: { default: jp },
lodashEs: { isFinite: _isFinite, isInteger, merge, setWith }
} = await import('./dependencies.js')
const assertInteger = something => {
let value = something
if (value.startsWith('-')) {
value = value.slice(1)
}
const coerced = Number(value)
if (!isInteger(coerced) || !_isFinite(coerced)) {
throw new Error(`"${value}" is not a integer number`)
}
}
export const evaluate = id => {
const [fn, ...args] = id.slice(1).split(' ')
switch (fn) {
case 'datetime':
return formatDatetime(new Date(), args.join(' '))
case 'guid':
case 'uuid':
return randomUUID()
case 'processEnv':
return processEnv()
case 'randomInt':
return randomInt()
default:
throw new Error(`not implemented: $${fn}`)
}
function formatDatetime(date, expr) {
const [_, dateFormat, offset, offsetUnit] = expr.match(
`^(iso8601|rfc1123|"[^"]+"|'[^']+')(?:\\s+(\\d+)\\s+(\\w+))?$`
)
let finalDate = date
if (offset && offsetUnit) {
const unitLookup = {
y: 'years',
M: 'months',
w: 'weeks',
d: 'days',
h: 'hours',
m: 'minutes',
s: 'seconds'
}
finalDate = add(finalDate, { [unitLookup[offsetUnit]]: Number(offset) })
}
const lookup = {
iso8601: date => formatISO(date),
rfc1123: date => formatRFC7231(date)
}
if (dateFormat in lookup) return lookup[dateFormat](finalDate)
return format(finalDate, JSON.parse(dateFormat))
}
function processEnv() {
return process.env[args[0]]
}
function randomInt() {
let [min, max] = args
min ||= `${Number.MIN_SAFE_INTEGER}`
max ||= `${Number.MAX_SAFE_INTEGER}`
assertInteger(min)
assertInteger(max)
min = Number(min)
max = Number(max)
const delta = Number(max) - Number(min)
const random = Math.trunc(delta * Math.random())
return min + random
}
}
export const evaluateJsonPath = (
request,
rawExpr,
{ ignoreFirstSegment = true } = {}
) => {
const jsonPath = (
ignoreFirstSegment ? rawExpr.split('.').slice(1).join('.') : rawExpr
).trim()
const results = jp.query(request, jsonPath)
return results.length <= 1 ? results[0] : results
}
export const makeInterpolate = ({
env = {},
globalVariables = {},
requests = {},
variables = {}
} = {}) => {
const envVariables = Object.fromEntries(
Object.entries(env).map(([name, value]) => [name, { global: true, value }])
)
return text => {
if (text === undefined || text === null) {
return text
}
const context = { env: envVariables, variables }
function visit(text, path, { isGlobal = false } = {}) {
const brokenAtStart = String(text)?.split('{{') ?? []
const segments = [brokenAtStart.shift()]
for (const start of brokenAtStart) {
const endIndex = start.indexOf('}}')
const id = start.slice(0, endIndex)
if (id[0] === '$') {
segments.push(evaluate(id, context))
} else {
if (path.includes(id)) {
throw new Error(
`variable cycle found: ${path.concat([id]).join(' -> ')}`
)
}
if (isGlobal && !(id in globalVariables) && !(id in envVariables)) {
throw new Error(`variable not found on global scope: ${id}`)
}
const [maybeRequestId] = id.split('.')
if (
!(id in envVariables) &&
!(id in globalVariables) &&
!(maybeRequestId in requests) &&
!(id in variables)
)
throw new Error(`variable not found: ${id}`)
let variable
if (maybeRequestId in requests) {
variable = {
global: true,
value: evaluateJsonPath(requests[maybeRequestId], id)
}
}
variable =
variable ??
(!isGlobal && id in variables
? variables[id]
: id in globalVariables
? globalVariables[id]
: envVariables[id])
variable.value = visit(variable.value, [...path, id], {
isGlobal: id in globalVariables && !(id in variables)
})
segments.push(variable.value)
}
segments.push(start.slice(endIndex + 2))
}
return segments.join('')
}
return visit(text, [])
}
}
export const setJsonPath = (request, jsonPath, value) => {
const targetPaths = jp.paths(request, jsonPath)
for (const targetPath of targetPaths) {
setWith(request, targetPath.slice(1), value, Object)
}
}
export const test = async (
{ request },
{ env, fetch, globalVariables, requests } = {}
) => {
fetch =
fetch ??
(await import('jest-dot-http-files/dependencies')).nodeFetch.default
const interpolate = makeInterpolate({
env,
globalVariables,
requests,
variables: request.variables
})
const url = interpolate(request.url)
const headers = request.headers?.map(([k, v]) => [k, interpolate(v)])
const requestContentType = headers?.find(([k]) =>
/^content-type$/i.test(k)
)?.[1]
let body = request.body
if (body && /json/i.test(requestContentType)) {
body = JSON.stringify(body)
}
body = interpolate(body)
const fetchResponse = await fetch(url, {
method: request.method,
headers,
...(['GET', 'HEAD'].includes(request.method) ? {} : { body })
})
let responseBody
const responseContentType = fetchResponse.headers.get('content-type')
if (responseContentType.startsWith('text/')) {
responseBody = await fetchResponse.text()
} else if (responseContentType.indexOf('json') > -1) {
const jsonText = await fetchResponse.text()
responseBody = JSON.parse(jsonText || 'null')
} else {
responseBody = (await fetchResponse.buffer()).toString('hex')
}
const response = {
status: fetchResponse.status,
statusText: fetchResponse.statusText,
headers: Array.from(fetchResponse.headers),
...(responseBody ? { body: responseBody } : {})
}
const ignoreHeaders = ['age', 'date']
let ignoreHeadersRegex
try {
ignoreHeadersRegex =
request.meta?.ignoreHeaders?.value &&
new RegExp(request.meta.ignoreHeaders?.value)
} catch (e) {
console.error(e)
throw e
}
response.headers = response.headers.map(([k, v]) => [k, v])
const modifiedRequest = {
...request
}
if (body && /json/i.test(requestContentType)) {
body = JSON.parse(body)
}
modifiedRequest.url = url
modifiedRequest.headers = headers
if (body) modifiedRequest.body = body
const outcome = {
request: modifiedRequest,
response
}
if (request.meta?.name?.value) {
requests[request.meta.name.value] = outcome
}
if (request.meta?.ignore?.value) {
for (const { value: jsonPath } of request.meta.ignore.value) {
setJsonPath(outcome, jsonPath, expect.anything())
}
}
for (const header of outcome.request.headers ?? []) {
if (
ignoreHeaders.includes(header[0]) ||
ignoreHeadersRegex?.test(header[0])
) {
header[1] = expect.anything()
}
}
for (const header of outcome.response.headers) {
if (
ignoreHeaders.includes(header[0]) ||
ignoreHeadersRegex?.test(header[0])
) {
header[1] = expect.anything()
}
}
return outcome
}
export default {
process: (src, filename = '') => {
const requests = parse(src)
let envs = {}
if (filename) {
const envPath = join(dirname(filename), 'http-client.env.json')
const userEnvPath = join(dirname(filename), 'http-client.env.json.user')
envs = merge(
envs,
existsSync(envPath) ? JSON.parse(readFileSync(envPath, 'utf-8')) : {},
existsSync(userEnvPath)
? JSON.parse(readFileSync(userEnvPath, 'utf-8'))
: {}
)
}
const env = envs[process.env.NODE_ENV]
const globalVariables = Object.fromEntries(
requests.flatMap(({ variables = {} }) =>
Object.entries(variables).filter(([, { global }]) => global)
)
)
const code = `
const { randomUUID } = require('node:crypto')
describe(${JSON.stringify(filename)}, () => {
// TODO: immerjs as peer dep to freeze stuff
let get
let jp
let setWith
let requests
const env = ${JSON.stringify(env, null, 2)}
const globalVariables = ${JSON.stringify(globalVariables, null, 2)}
beforeAll(async () => {
const { lodashEs, jsonpath } = await import('jest-dot-http-files/dependencies')
get = lodashEs.get
jp = jsonpath.default
setWith = lodashEs.setWith
requests = {}
})
const assertInteger = ${assertInteger.toString()}
const evaluate = ${evaluate.toString()}
const evaluateJsonPath = ${evaluateJsonPath.toString()}
const makeInterpolate = ${makeInterpolate.toString()}
const setJsonPath = ${setJsonPath.toString()}
${requests
.filter(request => request.url)
.map(request => {
const interpolate = makeInterpolate({
env,
globalVariables,
variables: request.variables
})
const title =
request.meta?.title?.value ??
`${request.method} ${interpolate(request.url)}`
const assertions = request.meta?.expect?.value ?? []
if (request.meta?.status?.value) {
const [code, text] = request.meta.status.value
assertions.push(['$.response.status', code])
text && assertions.push(['$.response.statusText', text])
}
return `
/**
* ${filename}
*/
test${
request.meta?.only?.value
? '.only'
: request.meta?.skip?.value
? '.skip'
: ''
}(${JSON.stringify(title)}, async () => {
${
request.meta?.throws?.value
? 'await expect(async () => {'
: ''
}
const outcome = await (${test.toString()})(${JSON.stringify(
{
env,
request
},
null,
2
)}, { env, globalVariables, requests })
expect(outcome).toMatchSnapshot()
${assertions
.map(([jsonPath, value]) => {
return `
expect(evaluateJsonPath(outcome, ${JSON.stringify(
jsonPath
)}, { ignoreFirstSegment: false })).toStrictEqual(${JSON.stringify(
value
)})
`
})
.join('\n')}
${
request.meta?.throws?.value
? `}).rejects.toThrow(${
typeof request.meta.throws.value === 'boolean'
? ''
: `/${request.meta.throws.value}/g`
})`
: ''
}
})
`
})
.join('')}
})
`
return {
geCacheKey: (text, path, { configString }) => {
return createHash('sha1')
.update(text)
.update(path)
.update(configString)
.digest('hex')
},
code
}
}
}