• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

TotalTechGeek / json-logic-engine / 12225498498

08 Dec 2024 09:43PM UTC coverage: 91.802% (-0.5%) from 92.254%
12225498498

Pull #38

github

web-flow
Merge 4ec11ff6b into 91d18201d
Pull Request #38: Modified RFC6901

786 of 893 branches covered (88.02%)

Branch coverage included in aggregate %.

12 of 15 new or added lines in 2 files covered. (80.0%)

6 existing lines in 3 files now uncovered.

793 of 827 relevant lines covered (95.89%)

31860.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.22
/defaultMethods.js
1
// @ts-check
2
'use strict'
3

4
import asyncIterators from './async_iterators.js'
5
import { Sync, isSync } from './constants.js'
6
import declareSync from './utilities/declareSync.js'
7
import { build, buildString } from './compiler.js'
8
import chainingSupported from './utilities/chainingSupported.js'
9
import InvalidControlInput from './errors/InvalidControlInput.js'
10
import { splitPathMemoized } from './utilities/splitPath.js'
11

12
function isDeterministic (method, engine, buildState) {
13
  if (Array.isArray(method)) {
23,376✔
14
    return method.every((i) => isDeterministic(i, engine, buildState))
14,880✔
15
  }
16
  if (method && typeof method === 'object') {
18,312✔
17
    const func = Object.keys(method)[0]
5,166✔
18
    const lower = method[func]
5,166✔
19

20
    if (engine.isData(method, func)) return true
5,166✔
21
    if (!engine.methods[func]) throw new Error(`Method '${func}' was not found in the Logic Engine.`)
5,082!
22

23
    if (engine.methods[func].traverse === false) {
5,082✔
24
      return typeof engine.methods[func].deterministic === 'function'
168!
25
        ? engine.methods[func].deterministic(lower, buildState)
26
        : engine.methods[func].deterministic
27
    }
28
    return typeof engine.methods[func].deterministic === 'function'
4,914✔
29
      ? engine.methods[func].deterministic(lower, buildState)
30
      : engine.methods[func].deterministic &&
2,490✔
31
          isDeterministic(lower, engine, buildState)
32
  }
33
  return true
13,146✔
34
}
35

36
function isSyncDeep (method, engine, buildState) {
37
  if (Array.isArray(method)) {
24,780✔
38
    return method.every((i) => isSyncDeep(i, engine, buildState))
13,512✔
39
  }
40

41
  if (method && typeof method === 'object') {
19,752✔
42
    const func = Object.keys(method)[0]
7,884✔
43
    const lower = method[func]
7,884✔
44
    if (engine.isData(method, func)) return true
7,884✔
45
    if (!engine.methods[func]) throw new Error(`Method '${func}' was not found in the Logic Engine.`)
7,842!
46
    if (engine.methods[func].traverse === false) return typeof engine.methods[func][Sync] === 'function' ? engine.methods[func][Sync](lower, buildState) : engine.methods[func][Sync]
7,842!
47
    return typeof engine.methods[func][Sync] === 'function' ? engine.methods[func][Sync](lower, buildState) : engine.methods[func][Sync] && isSyncDeep(lower, engine, buildState)
4,998!
48
  }
49

50
  return true
11,868✔
51
}
52

53
const defaultMethods = {
54✔
54
  '+': (data) => {
55
    if (typeof data === 'string') return +data
482,724✔
56
    if (typeof data === 'number') return +data
482,712!
57
    let res = 0
482,712✔
58
    for (let i = 0; i < data.length; i++) res += +data[i]
965,412✔
59
    return res
482,712✔
60
  },
61
  '*': (data) => {
62
    let res = 1
864✔
63
    for (let i = 0; i < data.length; i++) res *= +data[i]
1,752✔
64
    return res
864✔
65
  },
66
  '/': (data) => {
67
    let res = data[0]
300✔
68
    for (let i = 1; i < data.length; i++) res /= +data[i]
324✔
69
    return res
300✔
70
  },
71
  '-': (data) => {
72
    if (typeof data === 'string') return -data
516✔
73
    if (typeof data === 'number') return -data
504!
74
    if (data.length === 1) return -data[0]
504✔
75
    let res = data[0]
264✔
76
    for (let i = 1; i < data.length; i++) res -= +data[i]
288✔
77
    return res
264✔
78
  },
79
  '%': (data) => {
80
    let res = data[0]
504✔
81
    for (let i = 1; i < data.length; i++) res %= +data[i]
528✔
82
    return res
504✔
83
  },
84
  max: (data) => Math.max(...data),
732✔
85
  min: (data) => Math.min(...data),
336✔
86
  in: ([item, array]) => (array || []).includes(item),
456✔
87
  '>': ([a, b]) => a > b,
1,452✔
88
  '<': ([a, b, c]) => (c === undefined ? a < b : a < b && b < c),
1,680✔
89
  preserve: {
90
    traverse: false,
91
    method: declareSync((i) => i, true),
1,626✔
92
    [Sync]: () => true
462✔
93
  },
94
  if: {
95
    method: (input, context, above, engine) => {
96
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
3,234!
97

98
      if (input.length === 1) return engine.run(input[0], context, { above })
3,234✔
99
      if (input.length < 2) return null
3,006✔
100

101
      input = [...input]
2,922✔
102
      if (input.length % 2 !== 1) input.push(null)
2,922✔
103

104
      // fallback to the default if the condition is false
105
      const onFalse = input.pop()
2,922✔
106

107
      // while there are still conditions
108
      while (input.length) {
2,922✔
109
        const check = input.shift()
3,678✔
110
        const onTrue = input.shift()
3,678✔
111

112
        const test = engine.run(check, context, { above })
3,678✔
113

114
        // if the condition is true, run the true branch
115
        if (engine.truthy(test)) return engine.run(onTrue, context, { above })
3,678✔
116
      }
117

118
      return engine.run(onFalse, context, { above })
942✔
119
    },
120
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
3,612✔
121
    deterministic: (data, buildState) => {
122
      return isDeterministic(data, buildState.engine, buildState)
3,216✔
123
    },
124
    asyncMethod: async (input, context, above, engine) => {
125
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
102!
126

127
      // check the bounds
128
      if (input.length === 1) return engine.run(input[0], context, { above })
102✔
129
      if (input.length < 2) return null
66✔
130

131
      input = [...input]
54✔
132

133
      if (input.length % 2 !== 1) input.push(null)
54✔
134

135
      // fallback to the default if the condition is false
136
      const onFalse = input.pop()
54✔
137

138
      // while there are still conditions
139
      while (input.length) {
54✔
140
        const check = input.shift()
54✔
141
        const onTrue = input.shift()
54✔
142

143
        const test = await engine.run(check, context, { above })
54✔
144

145
        // if the condition is true, run the true branch
146
        if (engine.truthy(test)) return engine.run(onTrue, context, { above })
54✔
147
      }
148

149
      return engine.run(onFalse, context, { above })
18✔
150
    },
151
    traverse: false
152
  },
153
  '<=': ([a, b, c]) => (c === undefined ? a <= b : a <= b && b <= c),
696✔
154
  '>=': ([a, b]) => a >= b,
1,380✔
155
  // eslint-disable-next-line eqeqeq
156
  '==': ([a, b]) => a == b,
840✔
157
  '===': ([a, b]) => a === b,
1,608✔
158
  // eslint-disable-next-line eqeqeq
159
  '!=': ([a, b]) => a != b,
516✔
160
  '!==': ([a, b]) => a !== b,
576✔
161
  xor: ([a, b]) => a ^ b,
264✔
162
  or: (arr, _1, _2, engine) => {
163
    for (let i = 0; i < arr.length; i++) {
1,584✔
164
      if (engine.truthy(arr[i])) return arr[i]
2,556✔
165
    }
166
    return arr[arr.length - 1]
312✔
167
  },
168
  and: (arr, _1, _2, engine) => {
169
    for (let i = 0; i < arr.length; i++) {
2,112✔
170
      if (!engine.truthy(arr[i])) return arr[i]
3,564✔
171
    }
172
    return arr[arr.length - 1]
852✔
173
  },
174
  substr: ([string, from, end]) => {
175
    if (end < 0) {
720✔
176
      const result = string.substr(from)
192✔
177
      return result.substr(0, result.length + end)
192✔
178
    }
179
    return string.substr(from, end)
528✔
180
  },
181
  length: ([i]) => {
182
    if (typeof i === 'string' || Array.isArray(i)) return i.length
144✔
183
    if (i && typeof i === 'object') return Object.keys(i).length
96✔
184
    return 0
24✔
185
  },
186
  get: {
187
    method: ([data, key, defaultValue], context, above, engine) => {
188
      const notFound = defaultValue === undefined ? null : defaultValue
480✔
189

190
      const subProps = splitPathMemoized(String(key))
480✔
191
      for (let i = 0; i < subProps.length; i++) {
480✔
192
        if (data === null || data === undefined) {
480!
193
          return notFound
×
194
        }
195
        // Descending into context
196
        data = data[subProps[i]]
480✔
197
        if (data === undefined) {
480✔
198
          return notFound
48✔
199
        }
200
      }
201
      if (engine.allowFunctions || typeof data[key] !== 'function') {
432!
202
        return data
432✔
203
      }
204
    }
205
  },
206
  // Adding this to spec something out, not to merge it.
207
  val: {
208
    method: (args, context) => {
209
      let result = context
576✔
210
      for (let i = 0; i < args.length; i++) {
576✔
211
        if (args[i] === null) continue
864✔
212
        if (result === null || result === undefined) return null
768!
213
        result = result[args[i]]
768✔
214
      }
215
      if (typeof result === 'undefined') return null
576!
216
      return result
576✔
217
    },
218
    deterministic: false
219
  },
220
  var: (key, context, above, engine) => {
221
    let b
222
    if (Array.isArray(key)) {
22,458✔
223
      b = key[1]
16,488✔
224
      key = key[0]
16,488✔
225
    }
226
    let iter = 0
22,458✔
227
    while (
22,458✔
228
      typeof key === 'string' &&
63,168✔
229
      key.startsWith('../') &&
230
      iter < above.length
231
    ) {
232
      context = above[iter++]
6,132✔
233
      key = key.substring(3)
6,132✔
234
      // A performance optimization that allows you to pass the previous above array without spreading it as the last argument
235
      if (iter === above.length && Array.isArray(context)) {
6,132✔
236
        iter = 0
288✔
237
        above = context
288✔
238
        context = above[iter++]
288✔
239
      }
240
    }
241

242
    const notFound = b === undefined ? null : b
22,458✔
243
    if (typeof key === 'undefined' || key === '' || key === null) {
22,458✔
244
      if (engine.allowFunctions || typeof context !== 'function') {
3,096!
245
        return context
3,096✔
246
      }
247
      return null
×
248
    }
249
    const subProps = splitPathMemoized(String(key))
19,362✔
250
    for (let i = 0; i < subProps.length; i++) {
19,362✔
251
      if (context === null || context === undefined) {
21,930✔
252
        return notFound
96✔
253
      }
254
      // Descending into context
255
      context = context[subProps[i]]
21,834✔
256
      if (context === undefined) {
21,834✔
257
        return notFound
3,144✔
258
      }
259
    }
260
    if (engine.allowFunctions || typeof context !== 'function') {
16,122✔
261
      return context
16,050✔
262
    }
263
    return null
72✔
264
  },
265
  missing: (checked, context, above, engine) => {
266
    return (Array.isArray(checked) ? checked : [checked]).filter((key) => {
2,736!
267
      return defaultMethods.var(key, context, above, engine) === null
4,656✔
268
    })
269
  },
270
  missing_some: ([needCount, options], context, above, engine) => {
271
    const missing = defaultMethods.missing(options, context, above, engine)
864✔
272
    if (options.length - missing.length >= needCount) {
864✔
273
      return []
576✔
274
    } else {
275
      return missing
288✔
276
    }
277
  },
278
  map: createArrayIterativeMethod('map'),
279
  some: createArrayIterativeMethod('some', true),
280
  all: createArrayIterativeMethod('every', true),
281
  none: {
282
    traverse: false,
283
    // todo: add async build & build
284
    method: (val, context, above, engine) => {
285
      return !defaultMethods.some.method(val, context, above, engine)
192✔
286
    },
287
    asyncMethod: async (val, context, above, engine) => {
288
      return !(await defaultMethods.some.asyncMethod(
192✔
289
        val,
290
        context,
291
        above,
292
        engine
293
      ))
294
    },
295
    compile: (data, buildState) => {
296
      const result = defaultMethods.some.compile(data, buildState)
384✔
297
      return result ? buildState.compile`!(${result})` : false
384!
298
    }
299
  },
300
  merge: (arrays) => (Array.isArray(arrays) ? [].concat(...arrays) : [arrays]),
1,140!
301
  every: createArrayIterativeMethod('every'),
302
  filter: createArrayIterativeMethod('filter'),
303
  reduce: {
304
    deterministic: (data, buildState) => {
305
      return (
420✔
306
        isDeterministic(data[0], buildState.engine, buildState) &&
480✔
307
        isDeterministic(data[1], buildState.engine, {
308
          ...buildState,
309
          insideIterator: true
310
        })
311
      )
312
    },
313
    compile: (data, buildState) => {
314
      if (!Array.isArray(data)) throw new InvalidControlInput(data)
336!
315
      const { async } = buildState
336✔
316
      let [selector, mapper, defaultValue] = data
336✔
317
      selector = buildString(selector, buildState)
336✔
318
      if (typeof defaultValue !== 'undefined') {
336!
319
        defaultValue = buildString(defaultValue, buildState)
336✔
320
      }
321
      const mapState = {
336✔
322
        ...buildState,
323
        extraArguments: 'above',
324
        avoidInlineAsync: true
325
      }
326
      mapper = build(mapper, mapState)
336✔
327
      const aboveArray = mapper.aboveDetected ? '[null, context, above]' : 'null'
336!
328

329
      buildState.methods.push(mapper)
336✔
330
      if (async) {
336✔
331
        if (!isSync(mapper) || selector.includes('await')) {
168!
332
          buildState.detectAsync = true
×
333
          if (typeof defaultValue !== 'undefined') {
×
334
            return `await asyncIterators.reduce(${selector} || [], (a,b) => methods[${
×
335
              buildState.methods.length - 1
336
            }]({ accumulator: a, current: b }, ${aboveArray}), ${defaultValue})`
337
          }
338
          return `await asyncIterators.reduce(${selector} || [], (a,b) => methods[${
×
339
            buildState.methods.length - 1
340
          }]({ accumulator: a, current: b }, ${aboveArray}))`
341
        }
342
      }
343
      if (typeof defaultValue !== 'undefined') {
336!
344
        return `(${selector} || []).reduce((a,b) => methods[${
336✔
345
          buildState.methods.length - 1
346
        }]({ accumulator: a, current: b }, ${aboveArray}), ${defaultValue})`
347
      }
348
      return `(${selector} || []).reduce((a,b) => methods[${
×
349
        buildState.methods.length - 1
350
      }]({ accumulator: a, current: b }, ${aboveArray}))`
351
    },
352
    method: (input, context, above, engine) => {
353
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
432✔
354
      let [selector, mapper, defaultValue] = input
408✔
355
      defaultValue = engine.run(defaultValue, context, {
408✔
356
        above
357
      })
358
      selector =
408✔
359
        engine.run(selector, context, {
456✔
360
          above
361
        }) || []
362
      const func = (accumulator, current) => {
408✔
363
        return engine.run(
1,410✔
364
          mapper,
365
          {
366
            accumulator,
367
            current
368
          },
369
          {
370
            above: [selector, context, above]
371
          }
372
        )
373
      }
374
      if (typeof defaultValue === 'undefined') {
408✔
375
        return selector.reduce(func)
54✔
376
      }
377
      return selector.reduce(func, defaultValue)
354✔
378
    },
379
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
408✔
380
    asyncMethod: async (input, context, above, engine) => {
381
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
24!
382
      let [selector, mapper, defaultValue] = input
24✔
383
      defaultValue = await engine.run(defaultValue, context, {
24✔
384
        above
385
      })
386
      selector =
24✔
387
        (await engine.run(selector, context, {
24!
388
          above
389
        })) || []
390
      return asyncIterators.reduce(
24✔
391
        selector,
392
        (accumulator, current) => {
393
          return engine.run(
102✔
394
            mapper,
395
            {
396
              accumulator,
397
              current
398
            },
399
            {
400
              above: [selector, context, above]
401
            }
402
          )
403
        },
404
        defaultValue
405
      )
406
    },
407
    traverse: false
408
  },
409
  '!': (value, _1, _2, engine) => Array.isArray(value) ? !engine.truthy(value[0]) : !engine.truthy(value),
816!
410
  '!!': (value, _1, _2, engine) => Boolean(Array.isArray(value) ? engine.truthy(value[0]) : engine.truthy(value)),
324!
411
  cat: (arr) => {
412
    if (typeof arr === 'string') return arr
912!
413
    let res = ''
912✔
414
    for (let i = 0; i < arr.length; i++) res += arr[i]
2,244✔
415
    return res
912✔
416
  },
417
  keys: ([obj]) => typeof obj === 'object' ? Object.keys(obj) : [],
48✔
418
  pipe: {
419
    traverse: false,
420
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
168✔
421
    method: (args, context, above, engine) => {
422
      if (!Array.isArray(args)) throw new Error('Data for pipe must be an array')
108!
423
      let answer = engine.run(args[0], context, { above: [args, context, above] })
108✔
424
      for (let i = 1; i < args.length; i++) answer = engine.run(args[i], answer, { above: [args, context, above] })
108✔
425
      return answer
108✔
426
    },
427
    asyncMethod: async (args, context, above, engine) => {
428
      if (!Array.isArray(args)) throw new Error('Data for pipe must be an array')
60!
429
      let answer = await engine.run(args[0], context, { above: [args, context, above] })
60✔
430
      for (let i = 1; i < args.length; i++) answer = await engine.run(args[i], answer, { above: [args, context, above] })
96✔
431
      return answer
60✔
432
    },
433
    compile: (args, buildState) => {
434
      let res = buildState.compile`${args[0]}`
48✔
435
      for (let i = 1; i < args.length; i++) res = buildState.compile`${build(args[i], { ...buildState, extraArguments: 'above' })}(${res}, [null, context, above])`
48✔
436
      return res
48✔
437
    },
438
    deterministic: (data, buildState) => {
439
      if (!Array.isArray(data)) return false
192!
440
      data = [...data]
192✔
441
      const first = data.shift()
192✔
442
      return isDeterministic(first, buildState.engine, buildState) && isDeterministic(data, buildState.engine, { ...buildState, insideIterator: true })
192✔
443
    }
444
  },
445
  eachKey: {
446
    traverse: false,
447
    [Sync]: (data, buildState) => isSyncDeep(Object.values(data[Object.keys(data)[0]]), buildState.engine, buildState),
30✔
448
    method: (object, context, above, engine) => {
449
      const result = Object.keys(object).reduce((accumulator, key) => {
78✔
450
        const item = object[key]
138✔
451
        Object.defineProperty(accumulator, key, {
138✔
452
          enumerable: true,
453
          value: engine.run(item, context, { above })
454
        })
455
        return accumulator
138✔
456
      }, {})
457
      return result
78✔
458
    },
459
    deterministic: (data, buildState) => {
460
      if (data && typeof data === 'object') {
192!
461
        return Object.values(data).every((i) => {
192✔
462
          return isDeterministic(i, buildState.engine, buildState)
252✔
463
        })
464
      }
465
      throw new InvalidControlInput(data)
×
466
    },
467
    compile: (data, buildState) => {
468
      // what's nice about this is that I don't have to worry about whether it's async or not, the lower entries take care of that ;)
469
      // however, this is not engineered support yields, I will have to make a note of that & possibly support it at a later point.
470
      if (data && typeof data === 'object') {
168!
471
        const result = `({ ${Object.keys(data)
168✔
472
          .reduce((accumulator, key) => {
473
            accumulator.push(
240✔
474
              // @ts-ignore Never[] is not accurate
475
              `${JSON.stringify(key)}: ${buildString(data[key], buildState)}`
476
            )
477
            return accumulator
240✔
478
          }, [])
479
          .join(',')} })`
480
        return result
168✔
481
      }
482
      throw new InvalidControlInput(data)
×
483
    },
484
    asyncMethod: async (object, context, above, engine) => {
485
      const result = await asyncIterators.reduce(
18✔
486
        Object.keys(object),
487
        async (accumulator, key) => {
488
          const item = object[key]
30✔
489
          Object.defineProperty(accumulator, key, {
30✔
490
            enumerable: true,
491
            value: await engine.run(item, context, { above })
492
          })
493
          return accumulator
30✔
494
        },
495
        {}
496
      )
497
      return result
18✔
498
    }
499
  }
500
}
501

502
function createArrayIterativeMethod (name, useTruthy = false) {
162✔
503
  return {
270✔
504
    deterministic: (data, buildState) => {
505
      return (
2,496✔
506
        isDeterministic(data[0], buildState.engine, buildState) &&
3,042✔
507
        isDeterministic(data[1], buildState.engine, {
508
          ...buildState,
509
          insideIterator: true
510
        })
511
      )
512
    },
513
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
1,326✔
514
    method: (input, context, above, engine) => {
515
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
1,890✔
516
      let [selector, mapper] = input
1,866✔
517
      selector =
1,866✔
518
        engine.run(selector, context, {
1,914✔
519
          above
520
        }) || []
521

522
      return selector[name]((i, index) => {
1,866✔
523
        const result = engine.run(mapper, i, {
4,530✔
524
          above: [{ item: selector, index }, context, above]
525
        })
526
        return useTruthy ? engine.truthy(result) : result
4,530✔
527
      })
528
    },
529
    asyncMethod: async (input, context, above, engine) => {
530
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
642!
531
      let [selector, mapper] = input
642✔
532
      selector =
642✔
533
        (await engine.run(selector, context, {
642!
534
          above
535
        })) || []
536
      return asyncIterators[name](selector, (i, index) => {
642✔
537
        const result = engine.run(mapper, i, {
1,110✔
538
          above: [{ item: selector, index }, context, above]
539
        })
540
        return useTruthy ? engine.truthy(result) : result
1,110✔
541
      })
542
    },
543
    compile: (data, buildState) => {
544
      if (!Array.isArray(data)) throw new InvalidControlInput(data)
1,602!
545
      const { async } = buildState
1,602✔
546
      const [selector, mapper] = data
1,602✔
547

548
      const mapState = {
1,602✔
549
        ...buildState,
550
        avoidInlineAsync: true,
551
        iteratorCompile: true,
552
        extraArguments: 'index, above'
553
      }
554

555
      const method = build(mapper, mapState)
1,602✔
556
      const aboveArray = method.aboveDetected ? buildState.compile`[{ item: null }, context, above]` : buildState.compile`null`
1,602✔
557

558
      if (async) {
1,602✔
559
        if (!isSyncDeep(mapper, buildState.engine, buildState)) {
810✔
560
          buildState.detectAsync = true
18✔
561
          return buildState.compile`await asyncIterators[${name}](${selector} || [], async (i, x) => ${method}(i, x, ${aboveArray}))`
18✔
562
        }
563
      }
564

565
      return buildState.compile`(${selector} || [])[${name}]((i, x) => ${method}(i, x, ${aboveArray}))`
1,584✔
566
    },
567
    traverse: false
568
  }
569
}
570
defaultMethods['?:'] = defaultMethods.if
54✔
571
// declare all of the functions here synchronous
572
Object.keys(defaultMethods).forEach((item) => {
54✔
573
  if (typeof defaultMethods[item] === 'function') {
2,322✔
574
    defaultMethods[item][Sync] = true
1,566✔
575
  }
576
  defaultMethods[item].deterministic =
2,322✔
577
    typeof defaultMethods[item].deterministic === 'undefined'
2,322✔
578
      ? true
579
      : defaultMethods[item].deterministic
580
})
581
// @ts-ignore Allow custom attribute
582
defaultMethods.var.deterministic = (data, buildState) => {
54✔
583
  return buildState.insideIterator && !String(data).includes('../../')
16,092✔
584
}
585
Object.assign(defaultMethods.missing, {
54✔
586
  deterministic: false
587
})
588
Object.assign(defaultMethods.missing_some, {
54✔
589
  deterministic: false
590
})
591
// @ts-ignore Allow custom attribute
592
defaultMethods['<'].compile = function (data, buildState) {
54✔
593
  if (!Array.isArray(data)) return false
600✔
594
  if (data.length === 2) return buildState.compile`(${data[0]} < ${data[1]})`
576✔
595
  if (data.length === 3) return buildState.compile`(${data[0]} < ${data[1]} && ${data[1]} < ${data[2]})`
72!
596
  return false
×
597
}
598
// @ts-ignore Allow custom attribute
599
defaultMethods['<='].compile = function (data, buildState) {
54✔
600
  if (!Array.isArray(data)) return false
168✔
601
  if (data.length === 2) return buildState.compile`(${data[0]} <= ${data[1]})`
144✔
602
  if (data.length === 3) return buildState.compile`(${data[0]} <= ${data[1]} && ${data[1]} <= ${data[2]})`
48!
603
  return false
×
604
}
605
// @ts-ignore Allow custom attribute
606
defaultMethods.min.compile = function (data, buildState) {
54✔
607
  if (!Array.isArray(data)) return false
120✔
608
  return `Math.min(${data
96✔
609
    .map((i) => buildString(i, buildState))
240✔
610
    .join(', ')})`
611
}
612
// @ts-ignore Allow custom attribute
613
defaultMethods.max.compile = function (data, buildState) {
54✔
614
  if (!Array.isArray(data)) return false
264✔
615
  return `Math.max(${data
144✔
616
    .map((i) => buildString(i, buildState))
336✔
617
    .join(', ')})`
618
}
619
// @ts-ignore Allow custom attribute
620
defaultMethods['>'].compile = function (data, buildState) {
54✔
621
  if (!Array.isArray(data)) return false
384✔
622
  if (data.length !== 2) return false
360!
623
  return buildState.compile`(${data[0]} > ${data[1]})`
360✔
624
}
625
// @ts-ignore Allow custom attribute
626
defaultMethods['>='].compile = function (data, buildState) {
54✔
627
  if (!Array.isArray(data)) return false
456✔
628
  if (data.length !== 2) return false
432!
629
  return buildState.compile`(${data[0]} >= ${data[1]})`
432✔
630
}
631
// @ts-ignore Allow custom attribute
632
defaultMethods['=='].compile = function (data, buildState) {
54✔
633
  if (!Array.isArray(data)) return false
240✔
634
  if (data.length !== 2) return false
216!
635
  return buildState.compile`(${data[0]} == ${data[1]})`
216✔
636
}
637
// @ts-ignore Allow custom attribute
638
defaultMethods['!='].compile = function (data, buildState) {
54✔
639
  if (!Array.isArray(data)) return false
96✔
640
  if (data.length !== 2) return false
72!
641
  return buildState.compile`(${data[0]} != ${data[1]})`
72✔
642
}
643
// @ts-ignore Allow custom attribute
644
defaultMethods.if.compile = function (data, buildState) {
54✔
645
  if (!Array.isArray(data)) return false
1,416!
646
  if (data.length < 3) return false
1,416✔
647

648
  data = [...data]
1,272✔
649
  if (data.length % 2 !== 1) data.push(null)
1,272✔
650
  const onFalse = data.pop()
1,272✔
651

652
  let res = buildState.compile``
1,272✔
653
  while (data.length) {
1,272✔
654
    const condition = data.shift()
1,896✔
655
    const onTrue = data.shift()
1,896✔
656
    res = buildState.compile`${res} engine.truthy(${condition}) ? ${onTrue} : `
1,896✔
657
  }
658

659
  return buildState.compile`(${res} ${onFalse})`
1,272✔
660
}
661
// @ts-ignore Allow custom attribute
662
defaultMethods['==='].compile = function (data, buildState) {
54✔
663
  if (!Array.isArray(data)) return false
240✔
664
  if (data.length !== 2) return false
216!
665
  return buildState.compile`(${data[0]} === ${data[1]})`
216✔
666
}
667
// @ts-ignore Allow custom attribute
668
defaultMethods['+'].compile = function (data, buildState) {
54✔
669
  if (Array.isArray(data)) {
786✔
670
    return `(${data
762✔
671
      .map((i) => `(+${buildString(i, buildState)})`)
1,578✔
672
      .join(' + ')})`
673
  } else if (typeof data === 'string' || typeof data === 'number') {
24!
674
    return `(+${buildString(data, buildState)})`
×
675
  } else {
676
    return `([].concat(${buildString(
24✔
677
      data,
678
      buildState
679
    )})).reduce((a,b) => (+a)+(+b), 0)`
680
  }
681
}
682

683
// @ts-ignore Allow custom attribute
684
defaultMethods['%'].compile = function (data, buildState) {
54✔
685
  if (Array.isArray(data)) {
168✔
686
    return `(${data
144✔
687
      .map((i) => `(+${buildString(i, buildState)})`)
288✔
688
      .join(' % ')})`
689
  } else {
690
    return `(${buildString(data, buildState)}).reduce((a,b) => (+a)%(+b))`
24✔
691
  }
692
}
693

694
// @ts-ignore Allow custom attribute
695
defaultMethods.or.compile = function (data, buildState) {
54✔
696
  if (!buildState.engine.truthy.IDENTITY) return false
384✔
697
  if (Array.isArray(data)) {
24!
698
    return `(${data.map((i) => buildString(i, buildState)).join(' || ')})`
×
699
  } else {
700
    return `(${buildString(data, buildState)}).reduce((a,b) => a||b, false)`
24✔
701
  }
702
}
703

704
// @ts-ignore Allow custom attribute
705
defaultMethods.in.compile = function (data, buildState) {
54✔
706
  if (!Array.isArray(data)) return false
216!
707
  return buildState.compile`(${data[1]} || []).includes(${data[0]})`
216✔
708
}
709

710
// @ts-ignore Allow custom attribute
711
defaultMethods.and.compile = function (data, buildState) {
54✔
712
  if (!buildState.engine.truthy.IDENTITY) return false
528✔
713
  if (Array.isArray(data)) {
24!
714
    return `(${data.map((i) => buildString(i, buildState)).join(' && ')})`
×
715
  } else {
716
    return `(${buildString(data, buildState)}).reduce((a,b) => a&&b, true)`
24✔
717
  }
718
}
719

720
// @ts-ignore Allow custom attribute
721
defaultMethods['-'].compile = function (data, buildState) {
54✔
722
  if (Array.isArray(data)) {
216✔
723
    return `${data.length === 1 ? '-' : ''}(${data
192✔
724
      .map((i) => `(+${buildString(i, buildState)})`)
264✔
725
      .join(' - ')})`
726
  }
727
  if (typeof data === 'string' || typeof data === 'number') {
24!
728
    return `(-${buildString(data, buildState)})`
×
729
  } else {
730
    return `((a=>(a.length===1?a[0]=-a[0]:a)&0||a)([].concat(${buildString(
24✔
731
      data,
732
      buildState
733
    )}))).reduce((a,b) => (+a)-(+b))`
734
  }
735
}
736
// @ts-ignore Allow custom attribute
737
defaultMethods['/'].compile = function (data, buildState) {
54✔
738
  if (Array.isArray(data)) {
120✔
739
    return `(${data
96✔
740
      .map((i) => `(+${buildString(i, buildState)})`)
192✔
741
      .join(' / ')})`
742
  } else {
743
    return `(${buildString(data, buildState)}).reduce((a,b) => (+a)/(+b))`
24✔
744
  }
745
}
746
// @ts-ignore Allow custom attribute
747
defaultMethods['*'].compile = function (data, buildState) {
54✔
748
  if (Array.isArray(data)) {
336✔
749
    return `(${data
312✔
750
      .map((i) => `(+${buildString(i, buildState)})`)
624✔
751
      .join(' * ')})`
752
  } else {
753
    return `(${buildString(data, buildState)}).reduce((a,b) => (+a)*(+b))`
24✔
754
  }
755
}
756
// @ts-ignore Allow custom attribute
757
defaultMethods.cat.compile = function (data, buildState) {
54✔
758
  if (typeof data === 'string') return JSON.stringify(data)
384!
759
  if (!Array.isArray(data)) return false
384✔
760
  let res = buildState.compile`''`
288✔
761
  for (let i = 0; i < data.length; i++) res = buildState.compile`${res} + ${data[i]}`
648✔
762
  return buildState.compile`(${res})`
288✔
763
}
764

765
// @ts-ignore Allow custom attribute
766
defaultMethods['!'].compile = function (
54✔
767
  data,
768
  buildState
769
) {
770
  if (Array.isArray(data)) return buildState.compile`(!engine.truthy(${data[0]}))`
264!
771
  return buildState.compile`(!engine.truthy(${data}))`
×
772
}
773

774
defaultMethods.not = defaultMethods['!']
54✔
775

776
// @ts-ignore Allow custom attribute
777
defaultMethods['!!'].compile = function (data, buildState) {
54✔
778
  if (Array.isArray(data)) return buildState.compile`(!!engine.truthy(${data[0]}))`
96!
779
  return `(!!engine.truthy(${data}))`
×
780
}
781
defaultMethods.none.deterministic = defaultMethods.some.deterministic
54✔
782
defaultMethods.get.compile = function (data, buildState) {
54✔
783
  let defaultValue = null
396✔
784
  let key = data
396✔
785
  let obj = null
396✔
786
  if (Array.isArray(data) && data.length <= 3) {
396!
787
    obj = data[0]
396✔
788
    key = data[1]
396✔
789
    defaultValue = typeof data[2] === 'undefined' ? null : data[2]
396✔
790

791
    // Bail out if the key is dynamic; dynamic keys are not really optimized by this block.
792
    if (key && typeof key === 'object') return false
396✔
793

794
    key = key.toString()
288✔
795
    const pieces = splitPathMemoized(key)
288✔
796
    if (!chainingSupported) {
288✔
UNCOV
797
      return `(((a,b) => (typeof a === 'undefined' || a === null) ? b : a)(${pieces.reduce(
48✔
798
        (text, i) => {
UNCOV
799
          return `(${text}||0)[${JSON.stringify(i)}]`
48✔
800
        },
801
        `(${buildString(obj, buildState)}||0)`
802
      )}, ${buildString(defaultValue, buildState)}))`
803
    }
804
    return `((${buildString(obj, buildState)})${pieces
240✔
805
      .map((i) => `?.[${buildString(i, buildState)}]`)
240✔
806
      .join('')} ?? ${buildString(defaultValue, buildState)})`
807
  }
808
  return false
×
809
}
810
// @ts-ignore Allow custom attribute
811
defaultMethods.var.compile = function (data, buildState) {
54✔
812
  let key = data
7,734✔
813
  let defaultValue = null
7,734✔
814
  buildState.varTop = buildState.varTop || new Set()
7,734✔
815
  if (
7,734!
816
    !key ||
38,670✔
817
    typeof data === 'string' ||
818
    typeof data === 'number' ||
819
    (Array.isArray(data) && data.length <= 2)
820
  ) {
821
    if (Array.isArray(data)) {
7,734!
822
      key = data[0]
7,734✔
823
      defaultValue = typeof data[1] === 'undefined' ? null : data[1]
7,734✔
824
    }
825

826
    if (key === '../index' && buildState.iteratorCompile) return 'index'
7,734✔
827

828
    // this counts the number of var accesses to determine if they're all just using this override.
829
    // this allows for a small optimization :)
830
    if (typeof key === 'undefined' || key === null || key === '') return 'context'
7,686✔
831
    if (typeof key !== 'string' && typeof key !== 'number') return false
6,708✔
832

833
    key = key.toString()
6,660✔
834
    if (key.includes('../')) return false
6,660✔
835

836
    const pieces = splitPathMemoized(key)
6,318✔
837
    const [top] = pieces
6,318✔
838
    buildState.varTop.add(top)
6,318✔
839

840
    if (!buildState.engine.allowFunctions) buildState.methods.preventFunctions = a => typeof a === 'function' ? null : a
9,012✔
841
    else buildState.methods.preventFunctions = a => a
60✔
842

843
    // support older versions of node
844
    if (!chainingSupported) {
6,318✔
UNCOV
845
      return `(methods.preventFunctions(((a,b) => (typeof a === 'undefined' || a === null) ? b : a)(${pieces.reduce(
1,053✔
UNCOV
846
        (text, i) => `(${text}||0)[${JSON.stringify(i)}]`,
1,253✔
847
        '(context||0)'
848
      )}, ${buildString(defaultValue, buildState)})))`
849
    }
850
    return `(methods.preventFunctions(context${pieces
5,265✔
851
      .map((i) => `?.[${JSON.stringify(i)}]`)
6,265✔
852
      .join('')} ?? ${buildString(defaultValue, buildState)}))`
853
  }
854
  return false
×
855
}
856

857
// @ts-ignore Allowing a optimizeUnary attribute that can be used for performance optimizations
858
defaultMethods['+'].optimizeUnary = defaultMethods['-'].optimizeUnary = defaultMethods.var.optimizeUnary = defaultMethods['!'].optimizeUnary = defaultMethods['!!'].optimizeUnary = defaultMethods.cat.optimizeUnary = true
54✔
859

860
export default {
861
  ...defaultMethods
862
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc