Skip to content

Commit

Permalink
refactor(bundle): update exports to ease bundling
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudBuchholz committed Jan 30, 2024
1 parent 13445f5 commit 283485a
Show file tree
Hide file tree
Showing 7 changed files with 136 additions and 110 deletions.
25 changes: 22 additions & 3 deletions reserve/build/bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,28 @@ while (stack.length) {
module.exports = 'reserve'
} else {
module.exports = `$export_${path.replace('.js', '').replace('/', '_')}`
const exportNames = content.match(/module\.exports\s+=\s+\{([^^}]*)\}/)
if (exportNames) {
module.names = exportNames[1]
const exportNames = []
const exportValues = []
const exports = content.match(/module\.exports\s+=\s+\{([^^}]*)\}/)
if (exports !== null && !path.startsWith('handlers/')) {
const [, exported] = exports
exported
.split('\n')
.map(line => line.trim())
.filter(line => !!line)
.filter(line => !line.startsWith('//'))
.forEach(line => {
const [name, value] = line.replace(',', '').split(': ')
if (!name.match(/^\$?\w+$/i)) {
throw new Error(`Invalid export "${name}" for module ${path}`)
}
exportNames.push(name)
exportValues.push(value)
})
}
if (exportNames.length) {
module['exports.names'] = exportNames
module['exports.values'] = exportValues
}
}
modules[path] = module
Expand Down
32 changes: 15 additions & 17 deletions reserve/src/mapping.js → reserve/src/checkMapping.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,22 +77,20 @@ function checkHandler (configuration, mapping) {
return handler
}

module.exports = {
async check (configuration, mapping) {
checkCwd(configuration, mapping)
checkMatch(mapping)
checkInvertMatch(mapping)
checkIfMatch(mapping)
checkExcludeFromHoldingList(mapping)
const handler = checkHandler(configuration, mapping)
checkMethod(mapping, $mappingMethod, handler[$handlerMethod])
if (handler[$handlerSchema]) {
validate(handler[$handlerSchema], mapping)
}
if (handler.validate) {
await handler.validate(mapping, configuration[$configurationInterface])
}
mapping[$mappingMatch] = buildMatch(mapping)
mapping[$mappingChecked] = true
module.exports = async (configuration, mapping) => {
checkCwd(configuration, mapping)
checkMatch(mapping)
checkInvertMatch(mapping)
checkIfMatch(mapping)
checkExcludeFromHoldingList(mapping)
const handler = checkHandler(configuration, mapping)
checkMethod(mapping, $mappingMethod, handler[$handlerMethod])
if (handler[$handlerSchema]) {
validate(handler[$handlerSchema], mapping)
}
if (handler.validate) {
await handler.validate(mapping, configuration[$configurationInterface])
}
mapping[$mappingMatch] = buildMatch(mapping)
mapping[$mappingChecked] = true
}
66 changes: 34 additions & 32 deletions reserve/src/configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const { readFile, stat, dirname, isAbsolute, join } = require('./node-api')
const IConfiguration = require('./iconfiguration')
const { check } = require('./mapping')
const checkMapping = require('./checkMapping')
const checkMethod = require('./checkMethod')
const { parse } = require('./schema')
const {
Expand Down Expand Up @@ -152,7 +152,7 @@ async function checkMappings (configuration) {
const configurationInterface = new IConfiguration(configuration)
configuration[$configurationInterface] = configurationInterface
for (const mapping of configuration.mappings) {
await check(configuration, mapping)
await checkMapping(configuration, mapping)
}
}

Expand Down Expand Up @@ -199,36 +199,38 @@ function extend (filePath, configuration) {
return configuration
}

module.exports = {
checkHandler,
async function check (configuration) {
if (typeof configuration !== 'object' || configuration === null) {
throw new Error('Configuration must be an object')
}
const checkedConfiguration = Object.assign({}, configuration)
applyDefaults(checkedConfiguration)
await setHandlers(checkedConfiguration)
await checkListeners(checkedConfiguration)
await checkProtocol(checkedConfiguration)
await checkMappings(checkedConfiguration)
checkedConfiguration[$configurationRequests] = {
lastId: 0,
holding: null,
contexts: {}
}
return checkedConfiguration
}

async check (configuration) {
if (typeof configuration !== 'object' || configuration === null) {
throw new Error('Configuration must be an object')
}
const checkedConfiguration = Object.assign({}, configuration)
applyDefaults(checkedConfiguration)
await setHandlers(checkedConfiguration)
await checkListeners(checkedConfiguration)
await checkProtocol(checkedConfiguration)
await checkMappings(checkedConfiguration)
checkedConfiguration[$configurationRequests] = {
lastId: 0,
holding: null,
contexts: {}
}
return checkedConfiguration
},

async read (fileName) {
let filePath
if (isAbsolute(fileName)) {
filePath = fileName
} else {
filePath = join(process.cwd(), fileName)
}
return stat(filePath)
.then(() => readFile(filePath).then(buffer => JSON.parse(buffer.toString())))
.then(configuration => extend(filePath, configuration))
async function read (fileName) {
let filePath
if (isAbsolute(fileName)) {
filePath = fileName
} else {
filePath = join(process.cwd(), fileName)
}
return stat(filePath)
.then(() => readFile(filePath).then(buffer => JSON.parse(buffer.toString())))
.then(configuration => extend(filePath, configuration))
}

module.exports = {
checkHandler,
check,
read
}
96 changes: 50 additions & 46 deletions reserve/src/event.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,64 @@
'use strict'

const names = 'created,ready,incoming,error,redirecting,redirected,aborted,closed'.split(',')
const events = {}
names.forEach((name, index) => {
events['EVENT_' + name.toUpperCase()] = index
})

module.exports = {
...events,

newEventEmitter () {
const registry = []
function newEventEmitter () {
const registry = []

const register = (event, callback) => {
const eventIndex = names.indexOf(event)
if (eventIndex === -1) {
throw new Error('Unknown event name')
}
if (typeof callback !== 'function') {
throw new Error('Invalid callback')
}
if (registry[eventIndex] === undefined) {
registry[eventIndex] = []
}
registry[eventIndex].push(callback)
const register = (event, callback) => {
const eventIndex = names.indexOf(event)
if (eventIndex === -1) {
throw new Error('Unknown event name')
}
if (typeof callback !== 'function') {
throw new Error('Invalid callback')
}
if (registry[eventIndex] === undefined) {
registry[eventIndex] = []
}
registry[eventIndex].push(callback)
}

const on = function (event, callback) {
if (event === '*') {
names.forEach(name => register(name, callback))
} else {
register(event, callback)
}
return this
const on = function (event, callback) {
if (event === '*') {
names.forEach(name => register(name, callback))
} else {
register(event, callback)
}
return this
}

const emit = (eventIndex, ...parameters) => {
const callbacks = registry[eventIndex]
if (callbacks !== undefined) {
const event = Object.assign({
eventName: names[eventIndex]
}, ...parameters)
try {
for (const callback of callbacks) {
callback(event)
}
} catch (e) {
if (eventIndex === events.EVENT_CREATED) {
throw e
}
const emit = (eventIndex, ...parameters) => {
const callbacks = registry[eventIndex]
if (callbacks !== undefined) {
const event = Object.assign({
eventName: names[eventIndex]
}, ...parameters)
try {
for (const callback of callbacks) {
callback(event)
}
} catch (e) {
if (eventIndex === 0) {
throw e
}
return callbacks.length
}
return 0
return callbacks.length
}

return { on, emit }
return 0
}

return { on, emit }
}

module.exports = {
EVENT_CREATED: 0,
EVENT_READY: 1,
EVENT_INCOMING: 2,
EVENT_ERROR: 3,
EVENT_REDIRECTING: 4,
EVENT_REDIRECTED: 5,
EVENT_ABORTED: 6,
EVENT_CLOSED: 7,
newEventEmitter
}
4 changes: 2 additions & 2 deletions reserve/src/iconfiguration.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict'

const { check } = require('./mapping')
const checkMapping = require('./checkMapping')
const dispatcher = require('./dispatcher')
const {
$configuration,
Expand All @@ -13,7 +13,7 @@ const {
async function checkMappings (configuration, mappings) {
for (const mapping of mappings) {
if (!mapping[$mappingChecked]) {
await check(configuration, mapping)
await checkMapping(configuration, mapping)
}
}
}
Expand Down
19 changes: 11 additions & 8 deletions reserve/src/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function parseProperty (name, value) {
return { name, types, defaultValue }
}

function validate (property, object, value = property.defaultValue) {
function validateProperty (property, object, value = property.defaultValue) {
const { name, types } = property
if (value === undefined) {
throw new Error(`Missing property ${name}`)
Expand All @@ -25,12 +25,15 @@ function validate (property, object, value = property.defaultValue) {
object[property.name] = value
}

module.exports = {
parse (schema) {
return Object.keys(schema).map(name => parseProperty(name, schema[name]))
},
function parse (schema) {
return Object.keys(schema).map(name => parseProperty(name, schema[name]))
}

validate (schema, object) {
schema.forEach(property => validate(property, object, object[property.name]))
}
function validate (schema, object) {
schema.forEach(property => validateProperty(property, object, object[property.name]))
}

module.exports = {
parse,
validate
}
4 changes: 2 additions & 2 deletions reserve/tests/mocha/wrap-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const Request = require('../../src/mock/Request')
const Response = require('../../src/mock/Response')
const IConfiguration = require('../../src/iconfiguration')
const { check } = require('../../src/mapping')
const checkMapping = require('../../src/checkMapping')
const { checkHandler } = require('../../src/configuration')
const { $handlerPrefix, $configurationInterface } = require('../../src/symbols')

Expand All @@ -30,7 +30,7 @@ module.exports = (handler, defaults = {}) => {
let mappingReady
if (mapping !== null && (!mapping || !mapping[$checked])) {
mapping = { ...defaults.mapping, ...mapping, [$checked]: true }
mappingReady = check(configuration, mapping)
mappingReady = checkMapping(configuration, mapping)
} else {
mappingReady = Promise.resolve()
}
Expand Down

0 comments on commit 283485a

Please sign in to comment.