Skip to content

Commit

Permalink
refactor: migrate from cjs to esm (#88)
Browse files Browse the repository at this point in the history
* Migration to ESM
* update building to support esm

---------

Co-authored-by: csmig <csmig@csmig.com>
  • Loading branch information
Matte22 and csmig authored Feb 9, 2024
1 parent 331a8b6 commit 7302f24
Show file tree
Hide file tree
Showing 15 changed files with 639 additions and 214 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ watched/
.vscode/
.env
*.log
log.json
log.json
bundle.js
3 changes: 3 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ printf "[BUILD_TASK] Fetching node_modules\n"
rm -rf ./node_modules
npm ci

# bundle
npx esbuild index.js --bundle --platform=node --outfile=bundle.js

# version=$(git describe --tags | sed 's/\(.*\)-.*/\1/')
version=$(jq -r .version package.json)
printf "\n[BUILD_TASK] Using version string: $version\n"
Expand Down
54 changes: 27 additions & 27 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
#!/usr/bin/env node

const minApiVersion = '1.2.7'

const { logger, getSymbol } = require('./lib/logger')
const config = require('./lib/args')
if (!config) {
import { logger, getSymbol } from './lib/logger.js'
import { options, configValid } from './lib/args.js'
if (!configValid) {
logger.error({ component: 'main', message: 'invalid configuration... Exiting'})
logger.end()
return
process.exit(1)
}
const auth = require('./lib/auth')
const api = require('./lib/api')
const {serializeError} = require('serialize-error')
import startFsEventWatcher from './lib/events.js'
import { getOpenIDConfiguration, getToken } from './lib/auth.js'
import * as api from './lib/api.js'
import { serializeError } from 'serialize-error'
import startScanner from './lib/scan.js'
import semverGte from 'semver/functions/gte.js'

const minApiVersion = '1.2.7'

run()

Expand All @@ -19,22 +22,20 @@ async function run() {
logger.info({
component: 'main',
message: 'running',
config: getObfuscatedConfig(config)
options: getObfuscatedConfig(options)
})

await preflightServices()
if (config.mode === 'events') {
const watcher = require('./lib/events')
watcher.startFsEventWatcher()
if (options.mode === 'events') {
startFsEventWatcher()
}
else if (config.mode === 'scan') {
const scanner = require('./lib/scan')
scanner.startScanner()
else if (options.mode === 'scan') {
startScanner()
}
}
catch (e) {
logError(e)
await logger.end()
logger.end()
}
}

Expand Down Expand Up @@ -63,25 +64,24 @@ function logError(e) {
}

async function hasMinApiVersion () {
const semverGte = require('semver/functions/gte')
const [remoteApiVersion] = await api.getDefinition('$.info.version')
logger.info({ component: 'main', message: `preflight API version`, minApiVersion, remoteApiVersion})
if (semverGte(remoteApiVersion, minApiVersion)) {
return true
}
else {
throw( `Remote API version ${remoteApiVersion} is not compatible with this release.` )
throw new Error(`Remote API version ${remoteApiVersion} is not compatible with this release.`)
}
}

async function preflightServices () {
await hasMinApiVersion()
await auth.getOpenIDConfiguration()
await auth.getToken()
await getOpenIDConfiguration()
await getToken()
logger.info({ component: 'main', message: `preflight token request suceeded`})
const promises = [
api.getCollection(config.collectionId),
api.getCollectionAssets(config.collectionId),
api.getCollection(options.collectionId),
api.getCollectionAssets(options.collectionId),
api.getInstalledStigs(),
api.getScapBenchmarkMap()
]
Expand All @@ -100,8 +100,8 @@ async function preflightServices () {
logger.info({ component: 'main', message: `prefilght api requests suceeded`})
}

function getObfuscatedConfig (config) {
const securedConfig = {...config}
function getObfuscatedConfig (options) {
const securedConfig = {...options}
if (securedConfig.clientSecret) {
securedConfig.clientSecret = '[hidden]'
}
Expand All @@ -119,7 +119,7 @@ async function refreshUser() {

async function refreshCollection() {
try {
await api.getCollection(config.collectionId)
await api.getCollection(options.collectionId)
}
catch (e) {
logError(e)
Expand Down
62 changes: 30 additions & 32 deletions lib/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@

const got = require('got')
const config = require('./args')
const auth = require('./auth')
const { logger, getSymbol } = require('./logger')
const { serializeError } = require('serialize-error')
import got from 'got'
import { options } from './args.js'
import { getToken, tokens } from './auth.js'
import { logger, getSymbol } from './logger.js'

const cache = {
collection: null,
Expand All @@ -13,21 +11,21 @@ const cache = {
scapBenchmarkMap: null,
stigs: null
}

module.exports.cache = cache
const _cache = cache
export { _cache as cache }

async function apiGet(endpoint, authenticate = true) {
try {
const options = {
const requestOptions = {
responseType: 'json'
}
if (authenticate) {
await auth.getToken()
options.headers = {
Authorization: `Bearer ${auth.tokens.access_token}`
await getToken()
requestOptions.headers = {
Authorization: `Bearer ${tokens.access_token}`
}
}
const response = await got.get(`${config.api}${endpoint}`, options)
const response = await got.get(`${options.api}${endpoint}`, requestOptions)
logResponse (response )
return response.body
}
Expand All @@ -38,38 +36,38 @@ async function apiGet(endpoint, authenticate = true) {
}
}

module.exports.getScapBenchmarkMap = async function () {
export async function getScapBenchmarkMap() {
const response = await apiGet('/stigs/scap-maps')
cache.scapBenchmarkMap = new Map(response.map(apiScapMap => [apiScapMap.scapBenchmarkId, apiScapMap.benchmarkId]))
return cache.scapBenchmarkMap
}

module.exports.getDefinition = async function (jsonPath) {
export async function getDefinition(jsonPath) {
cache.definition = await apiGet(`/op/definition${jsonPath ? '?jsonpath=' + encodeURIComponent(jsonPath) : ''}`, false)
return cache.definition
}

module.exports.getCollection = async function (collectionId) {
export async function getCollection(collectionId) {
cache.collection = await apiGet(`/collections/${collectionId}`)
return cache.collection
}

module.exports.getCollectionAssets = async function (collectionId) {
export async function getCollectionAssets(collectionId) {
cache.assets = await apiGet(`/assets?collectionId=${collectionId}&projection=stigs`)
return cache.assets
}

module.exports.getInstalledStigs = async function () {
export async function getInstalledStigs() {
cache.stigs = await apiGet('/stigs')
return cache.stigs
}

module.exports.createOrGetAsset = async function (asset) {
export async function createOrGetAsset(asset) {
try {
await auth.getToken()
const response = await got.post(`${config.api}/assets?projection=stigs`, {
await getToken()
const response = await got.post(`${options.api}/assets?projection=stigs`, {
headers: {
Authorization: `Bearer ${auth.tokens.access_token}`
Authorization: `Bearer ${tokens.access_token}`
},
json: asset,
responseType: 'json'
Expand All @@ -87,12 +85,12 @@ module.exports.createOrGetAsset = async function (asset) {
}
}

module.exports.patchAsset = async function (assetId, body) {
export async function patchAsset(assetId, body) {
try {
await auth.getToken()
const response = await got.patch(`${config.api}/assets/${assetId}?projection=stigs`, {
await getToken()
const response = await got.patch(`${options.api}/assets/${assetId}?projection=stigs`, {
headers: {
Authorization: `Bearer ${auth.tokens.access_token}`
Authorization: `Bearer ${tokens.access_token}`
},
json: body,
responseType: 'json'
Expand All @@ -106,12 +104,12 @@ module.exports.patchAsset = async function (assetId, body) {
}
}

module.exports.postReviews = async function (collectionId, assetId, reviews) {
export async function postReviews(collectionId, assetId, reviews) {
try {
await auth.getToken()
const response = await got.post(`${config.api}/collections/${collectionId}/reviews/${assetId}`, {
await getToken()
const response = await got.post(`${options.api}/collections/${collectionId}/reviews/${assetId}`, {
headers: {
Authorization: `Bearer ${auth.tokens.access_token}`
Authorization: `Bearer ${tokens.access_token}`
},
json: reviews,
responseType: 'json'
Expand All @@ -125,12 +123,12 @@ module.exports.postReviews = async function (collectionId, assetId, reviews) {
}
}

module.exports.getUser = async function () {
export async function getUser() {
cache.user = await apiGet('/user')
return cache.user
}

module.exports.canUserAccept = function () {
export function canUserAccept() {
const curUser = cache.user
const apiCollection = cache.collection
const userGrant = curUser.collectionGrants.find( i => i.collection.collectionId === apiCollection.collectionId )?.accessLevel
Expand Down
Loading

0 comments on commit 7302f24

Please sign in to comment.