UNPKG

2.38 kBJavaScriptView Raw
1'use strict'
2
3const { validate } = require('./schema')
4const checkMethod = require('./checkMethod')
5const buildMatch = require('./buildMatch')
6const {
7 $configurationInterface,
8 $handlerMethod,
9 $handlerSchema,
10 $mappingChecked,
11 $mappingMatch,
12 $mappingMethod
13} = require('./symbols')
14
15function checkCwd (mapping) {
16 if (!mapping.cwd) {
17 mapping.cwd = process.cwd()
18 }
19}
20
21function invalidMatch () {
22 throw new Error('Invalid mapping match')
23}
24
25const matchTypes = {
26 undefined: mapping => {
27 mapping.match = /(.*)/
28 },
29 string: (mapping, match) => {
30 mapping.match = new RegExp(mapping.match)
31 },
32 object: (mapping, match) => {
33 if (!(mapping.match instanceof RegExp)) {
34 invalidMatch()
35 }
36 }
37}
38
39'boolean,number,bigint,symbol,function'
40 .split(',')
41 .forEach(type => {
42 matchTypes[type] = invalidMatch
43 })
44
45function checkMatch (mapping) {
46 matchTypes[typeof mapping.match](mapping, mapping.match)
47}
48
49function notTrueOnly (value) {
50 return value !== undefined && value !== true
51}
52
53function checkInvertMatch (mapping) {
54 if (notTrueOnly(mapping['invert-match'])) {
55 throw new Error('Invalid mapping invert-match')
56 }
57}
58
59function checkIfMatch (mapping) {
60 const ifMatch = mapping['if-match']
61 if (!['undefined', 'function'].includes(typeof ifMatch)) {
62 throw new Error('Invalid mapping if-match')
63 }
64}
65
66function checkExcludeFromHoldingList (mapping) {
67 if (notTrueOnly(mapping['exclude-from-holding-list'])) {
68 throw new Error('Invalid mapping exclude-from-holding-list')
69 }
70}
71
72function checkHandler (configuration, mapping) {
73 const { handler } = configuration.handler(mapping)
74 if (!handler) {
75 throw new Error('Unknown handler for mapping: ' + JSON.stringify(mapping))
76 }
77 return handler
78}
79
80module.exports = {
81 async check (configuration, mapping) {
82 checkCwd(mapping)
83 checkMatch(mapping)
84 checkInvertMatch(mapping)
85 checkIfMatch(mapping)
86 checkExcludeFromHoldingList(mapping)
87 const handler = checkHandler(configuration, mapping)
88 checkMethod(mapping, $mappingMethod, handler[$handlerMethod])
89 if (handler[$handlerSchema]) {
90 validate(handler[$handlerSchema], mapping)
91 }
92 if (handler.validate) {
93 await handler.validate(mapping, configuration[$configurationInterface])
94 }
95 mapping[$mappingMatch] = buildMatch(mapping)
96 mapping[$mappingChecked] = true
97 }
98}