diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9335d3e..a2d5db6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,12 +13,22 @@ jobs: runs-on: ubuntu-latest if: github.event.pull_request.draft == false steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6 with: ref: ${{ github.event.pull_request.head.sha }} - - name: Docker Build Deploy - run: docker build -t deploy . + - uses: actions/setup-node@v4 + with: + node-version: 24 + + - name: Install Dependencies + run: npm install + + - name: Lint + run: npm run lint + + - name: Build + run: npm run build - - name: Docker Deploy Lint - run: docker run deploy + - name: Test + run: npm test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5e7db5a..e229731 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ jobs: steps: - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v4 with: node-version: 24 diff --git a/.gitignore b/.gitignore index 3c3629e..b947077 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -node_modules +node_modules/ +dist/ diff --git a/Dockerfile b/Dockerfile index bc13fdf..1e68fad 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,9 @@ -FROM node:16-alpine3.14 +FROM node:24-alpine ENV HOME=/home/oa-deploy WORKDIR $HOME COPY ./ $HOME -RUN npm install -g npm@8 \ - && npm update \ - && npm install +RUN npm install CMD npm run lint diff --git a/cli.js b/cli.js deleted file mode 100755 index bd7f3d2..0000000 --- a/cli.js +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env node - -import fs from 'node:fs'; -import path from 'node:path'; -import minimist from 'minimist'; -import inquirer from 'inquirer'; -import Git from './lib/git.js'; -import Help from './lib/help.js'; - -import GH from './lib/gh.js'; -import Context from './lib/context.js'; -import artifacts from './lib/artifacts.js'; -import Tags from './lib/tags.js'; -import mode from './lib/commands.js'; - -const argv = minimist(process.argv, { - boolean: ['help', 'version', 'debug', 'force'], - string: ['profile', 'region', 'template', 'name'], - alias: { - version: 'v' - } -}); - -if (argv.version) { - console.log('openaddresses-deploy@' + JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url))).version); - process.exit(0); -} - -if (!argv._[2] || argv._[2] === 'help' || (!argv._[2] && argv.help)) Help.main(); - -const command = argv._[2]; - -if (mode[command] && argv.help) { - mode[command].help(); - process.exit(0); -} else if (argv.help) { - console.error('Subcommand not found!'); - process.exit(1); -} - -try { - await main(); -} catch (err) { - console.error(`Unknown Error: ${err.message}`); - if (argv.debug) throw err; -} - -async function main() { - if (['create', 'update', 'delete', 'cancel'].indexOf(command) > -1) { - const context = await Context.generate(argv); - - if (!argv._[3] && !argv.name) { - console.error(`Stack name required: run deploy ${command} --help`); - process.exit(1); - } - - const gh = new GH(context); - - // Ensure config & template buckets exist - await mode.init.bucket(context); - - if (['create', 'update'].includes(command)) { - if (Git.uncommitted()) { - const res = await inquirer.prompt([{ - type: 'boolean', - name: 'uncommitted', - default: 'N', - message: 'You have uncommitted changes! Continue? (y/N)' - }]); - - if (res.uncommitted.toLowerCase() !== 'y') return; - } - - if (!Git.pushed()) { - const res = await inquirer.prompt([{ - type: 'boolean', - name: 'unpushed', - default: 'N', - message: 'You have commits that haven\'t been pushed! Continue? (y/N)' - }]); - - if (res.unpushed.toLowerCase() !== 'y') return; - } - - try { - await artifacts(context); - } catch (err) { - console.error(`Artifacts Check Failed: ${err.message}`); - if (argv.debug) throw err; - process.exit(1); - } - - if (context.github) await gh.deployment(argv._[3]); - - if (context.tags && ['create', 'update'].includes(command)) { - let existingTemplate = null; - - if (command === 'update') existingTemplate = await context.cfn.lookup.info(`${context.repo}-${context.name}`, context.region, true, false); - - context.cfn.commands.config.tags = await Tags.request(context, existingTemplate); - } - } - - const template = await context.cfn.template.read(new URL(path.resolve(process.cwd(), context.template), 'file://')); - const cf_path = `/tmp/${hash()}.json`; - - fs.writeFileSync(cf_path, JSON.stringify(template.body, null, 4)); - - const parameters = new Map([ - ['GitSha', context.sha] - ]); - if (command === 'create') { - try { - await context.cfn.commands.create(context.name, cf_path, { parameters }); - - fs.unlinkSync(cf_path); - - if (context.github) await gh.deployment(argv._[3], true); - } catch (err) { - console.error(`Create failed: ${err.message}`); - if (context.github) await gh.deployment(argv._[3], false); - if (argv.debug) throw err; - } - } else if (command === 'update') { - try { - await context.cfn.commands.update(context.name, cf_path, { parameters }); - - fs.unlinkSync(cf_path); - - await gh.deployment(argv._[3], true); - } catch (err) { - console.error(`Update failed: ${err.message}`); - - if (err && context.github && err.execution === 'UNAVAILABLE' && err.status === 'FAILED') { - await gh.deployment(argv._[3], true); - } else if (context.github) { - await gh.deployment(argv._[3], false); - } - - if (argv.debug) throw err; - } - } else if (command === 'delete') { - try { - await context.cfn.commands.delete(context.name); - fs.unlinkSync(cf_path); - } catch (err) { - console.error(`Delete failed: ${err.message}`); - if (argv.debug) throw err; - } - } else if (command === 'cancel') { - try { - await context.cfn.commands.cancel(context.name); - fs.unlinkSync(cf_path); - - if (context.github) await gh.deployment(argv._[3], false); - } catch (err) { - console.error(`Cancel failed: ${err.message}`); - if (argv.debug) throw err; - } - } - } else if (mode[command]) { - if (['init'].includes(command)) { - mode[command].main(process.argv); - } else if (['env'].includes(command)) { - argv.template = false; - const context = await Context.generate(argv); - mode[command].main(context, process.argv); - } else { - const context = await Context.generate(argv); - - try { - await mode[command].main(context, process.argv); - } catch (err) { - console.error(`Command failed: ${err.message}`); - if (argv.debug) throw err; - } - } - } else { - console.error('Subcommand not found!'); - process.exit(1); - } -} - -function hash() { - return Math.random().toString(36).substring(2, 15); -} diff --git a/cli.ts b/cli.ts new file mode 100644 index 0000000..a6f84e9 --- /dev/null +++ b/cli.ts @@ -0,0 +1,239 @@ +#!/usr/bin/env node + +import fs from 'node:fs'; +import path from 'node:path'; +import inquirer from 'inquirer'; +import { parseArgs } from 'node:util'; +import artifacts from './lib/artifacts.js'; +import mode from './lib/commands.js'; +import Context from './lib/context.js'; +import GH from './lib/gh.js'; +import Git from './lib/git.js'; +import Help from './lib/help.js'; +import Tags from './lib/tags.js'; +import type { DeployArgv } from './lib/types.js'; + +const { values, positionals } = parseArgs({ + args: process.argv.slice(2), + options: { + help: { type: 'boolean' }, + version: { type: 'boolean', short: 'v' }, + debug: { type: 'boolean' }, + force: { type: 'boolean' }, + profile: { type: 'string' }, + region: { type: 'string' }, + template: { type: 'string' }, + name: { type: 'string' } + }, + allowPositionals: true, + strict: false +}); +const argv = { ...values, _: positionals } as DeployArgv; + +if (argv.version) { + const packageJson = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')) as { version: string }; + console.log(`openaddresses-deploy@${packageJson.version}`); + process.exit(0); +} + +if (!argv._[0] || argv._[0] === 'help' || (!argv._[0] && argv.help)) { + Help.main(); +} + +const command = String(argv._[0]); + +if (mode[command] && argv.help) { + mode[command].help(); + process.exit(0); +} else if (argv.help) { + console.error('Subcommand not found!'); + process.exit(1); +} + +try { + await main(); +} catch (error) { + const err = asError(error); + console.error(`Unknown Error: ${err.message}`); + if (argv.debug) { + throw err; + } +} + +async function main(): Promise { + if (['create', 'update', 'delete', 'cancel'].includes(command)) { + const context = await Context.generate(argv); + + if (!argv._[1] && !argv.name) { + console.error(`Stack name required: run deploy ${command} --help`); + process.exit(1); + } + + const gh = new GH(context); + + await mode.init.bucket?.(context); + + if (['create', 'update'].includes(command)) { + if (Git.uncommitted()) { + const response = await inquirer.prompt<{ uncommitted: boolean }>([{ + type: 'confirm', + name: 'uncommitted', + default: false, + message: 'You have uncommitted changes. Continue?' + }]); + + if (!response.uncommitted) { + return; + } + } + + if (!Git.pushed()) { + const response = await inquirer.prompt<{ unpushed: boolean }>([{ + type: 'confirm', + name: 'unpushed', + default: false, + message: 'You have commits that have not been pushed. Continue?' + }]); + + if (!response.unpushed) { + return; + } + } + + try { + await artifacts(context); + } catch (error) { + const err = asError(error); + console.error(`Artifacts Check Failed: ${err.message}`); + if (argv.debug) { + throw err; + } + process.exit(1); + } + + if (context.github) { + await gh.deployment(String(argv._[1] ?? context.name)); + } + + if (context.tags.length > 0) { + let existingTemplate = null; + + if (command === 'update') { + existingTemplate = await context.cfn.lookup.info(`${context.repo}-${context.name}`); + } + + context.cfn.commands.config.tags = await Tags.request(context, existingTemplate); + } + } + + if (!context.template) { + throw new Error('CloudFormation template is required for this command'); + } + + const template = await context.cfn.template.read(new URL(path.resolve(process.cwd(), context.template), 'file://')); + const cloudFormationPath = `/tmp/${hash()}.json`; + + fs.writeFileSync(cloudFormationPath, JSON.stringify(template.body, null, 4)); + + const parameters = new Map([ + ['GitSha', context.sha] + ]); + + if (command === 'create') { + await runDeploymentCommand('Create failed', async () => { + await context.cfn.commands.create(context.name, cloudFormationPath, { parameters }); + fs.unlinkSync(cloudFormationPath); + + if (context.github) { + await gh.deployment(String(argv._[1] ?? context.name), true); + } + }); + } else if (command === 'update') { + await runDeploymentCommand('Update failed', async () => { + await context.cfn.commands.update(context.name, cloudFormationPath, { parameters }); + fs.unlinkSync(cloudFormationPath); + + if (context.github) { + await gh.deployment(String(argv._[1] ?? context.name), true); + } + }, async (error) => { + if (!context.github) { + return; + } + + const err = error as { execution?: string; status?: string }; + if (err.execution === 'UNAVAILABLE' && err.status === 'FAILED') { + await gh.deployment(String(argv._[1] ?? context.name), true); + } else { + await gh.deployment(String(argv._[1] ?? context.name), false); + } + }); + } else if (command === 'delete') { + await runDeploymentCommand('Delete failed', async () => { + await context.cfn.commands.delete(context.name); + fs.unlinkSync(cloudFormationPath); + }); + } else if (command === 'cancel') { + await runDeploymentCommand('Cancel failed', async () => { + await context.cfn.commands.cancel(context.name); + fs.unlinkSync(cloudFormationPath); + + if (context.github) { + await gh.deployment(String(argv._[1] ?? context.name), false); + } + }); + } + } else if (mode[command]) { + if (command === 'init') { + await mode[command].main?.(process.argv.slice(2)); + } else if (command === 'env') { + argv.template = false; + const context = await Context.generate(argv); + await mode[command].main?.(context, process.argv.slice(2)); + } else { + const context = await Context.generate(argv); + + try { + await mode[command].main?.(context, process.argv.slice(2)); + } catch (error) { + const err = asError(error); + console.error(`Command failed: ${err.message}`); + if (argv.debug) { + throw err; + } + } + } + } else { + console.error('Subcommand not found!'); + process.exit(1); + } +} + +async function runDeploymentCommand( + message: string, + run: () => Promise, + onError?: (_error: unknown) => Promise +): Promise { + try { + await run(); + } catch (error) { + const err = asError(error); + console.error(`${message}: ${err.message}`); + + if (onError) { + await onError(error); + } + + if (argv.debug) { + throw err; + } + } +} + +function hash(): string { + return Math.random().toString(36).substring(2, 15); +} + +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} diff --git a/docs/assets/anchor.js b/docs/assets/anchor.js deleted file mode 100644 index 1f573dc..0000000 --- a/docs/assets/anchor.js +++ /dev/null @@ -1,350 +0,0 @@ -/*! - * AnchorJS - v4.0.0 - 2017-06-02 - * https://github.com/bryanbraun/anchorjs - * Copyright (c) 2017 Bryan Braun; Licensed MIT - */ -/* eslint-env amd, node */ - -// https://github.com/umdjs/umd/blob/master/templates/returnExports.js -(function (root, factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([], factory); - } else if (typeof module === 'object' && module.exports) { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like environments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals (root is window) - root.AnchorJS = factory(); - root.anchors = new root.AnchorJS(); - } -})(this, function () { - 'use strict'; - function AnchorJS(options) { - this.options = options || {}; - this.elements = []; - - /** - * Assigns options to the internal options object, and provides defaults. - * @param {Object} opts - Options object - */ - function _applyRemainingDefaultOptions(opts) { - opts.icon = opts.hasOwnProperty('icon') ? opts.icon : '\ue9cb'; // Accepts characters (and also URLs?), like '#', '¶', '❡', or '§'. - opts.visible = opts.hasOwnProperty('visible') ? opts.visible : 'hover'; // Also accepts 'always' & 'touch' - opts.placement = opts.hasOwnProperty('placement') - ? opts.placement - : 'right'; // Also accepts 'left' - opts.class = opts.hasOwnProperty('class') ? opts.class : ''; // Accepts any class name. - // Using Math.floor here will ensure the value is Number-cast and an integer. - opts.truncate = opts.hasOwnProperty('truncate') - ? Math.floor(opts.truncate) - : 64; // Accepts any value that can be typecast to a number. - } - - _applyRemainingDefaultOptions(this.options); - - /** - * Checks to see if this device supports touch. Uses criteria pulled from Modernizr: - * https://github.com/Modernizr/Modernizr/blob/da22eb27631fc4957f67607fe6042e85c0a84656/feature-detects/touchevents.js#L40 - * @returns {Boolean} - true if the current device supports touch. - */ - this.isTouchDevice = function () { - return !!( - 'ontouchstart' in window || - (window.DocumentTouch && document instanceof DocumentTouch) - ); - }; - - /** - * Add anchor links to page elements. - * @param {String|Array|Nodelist} selector - A CSS selector for targeting the elements you wish to add anchor links - * to. Also accepts an array or nodeList containing the relavant elements. - * @returns {this} - The AnchorJS object - */ - this.add = function (selector) { - var elements, - elsWithIds, - idList, - elementID, - i, - index, - count, - tidyText, - newTidyText, - readableID, - anchor, - visibleOptionToUse, - indexesToDrop = []; - - // We reapply options here because somebody may have overwritten the default options object when setting options. - // For example, this overwrites all options but visible: - // - // anchors.options = { visible: 'always'; } - _applyRemainingDefaultOptions(this.options); - - visibleOptionToUse = this.options.visible; - if (visibleOptionToUse === 'touch') { - visibleOptionToUse = this.isTouchDevice() ? 'always' : 'hover'; - } - - // Provide a sensible default selector, if none is given. - if (!selector) { - selector = 'h2, h3, h4, h5, h6'; - } - - elements = _getElements(selector); - - if (elements.length === 0) { - return this; - } - - _addBaselineStyles(); - - // We produce a list of existing IDs so we don't generate a duplicate. - elsWithIds = document.querySelectorAll('[id]'); - idList = [].map.call(elsWithIds, function assign(el) { - return el.id; - }); - - for (i = 0; i < elements.length; i++) { - if (this.hasAnchorJSLink(elements[i])) { - indexesToDrop.push(i); - continue; - } - - if (elements[i].hasAttribute('id')) { - elementID = elements[i].getAttribute('id'); - } else if (elements[i].hasAttribute('data-anchor-id')) { - elementID = elements[i].getAttribute('data-anchor-id'); - } else { - tidyText = this.urlify(elements[i].textContent); - - // Compare our generated ID to existing IDs (and increment it if needed) - // before we add it to the page. - newTidyText = tidyText; - count = 0; - do { - if (index !== undefined) { - newTidyText = tidyText + '-' + count; - } - - index = idList.indexOf(newTidyText); - count += 1; - } while (index !== -1); - index = undefined; - idList.push(newTidyText); - - elements[i].setAttribute('id', newTidyText); - elementID = newTidyText; - } - - readableID = elementID.replace(/-/g, ' '); - - // The following code builds the following DOM structure in a more effiecient (albeit opaque) way. - // ''; - anchor = document.createElement('a'); - anchor.className = 'anchorjs-link ' + this.options.class; - anchor.href = '#' + elementID; - anchor.setAttribute('aria-label', 'Anchor link for: ' + readableID); - anchor.setAttribute('data-anchorjs-icon', this.options.icon); - - if (visibleOptionToUse === 'always') { - anchor.style.opacity = '1'; - } - - if (this.options.icon === '\ue9cb') { - anchor.style.font = '1em/1 anchorjs-icons'; - - // We set lineHeight = 1 here because the `anchorjs-icons` font family could otherwise affect the - // height of the heading. This isn't the case for icons with `placement: left`, so we restore - // line-height: inherit in that case, ensuring they remain positioned correctly. For more info, - // see https://github.com/bryanbraun/anchorjs/issues/39. - if (this.options.placement === 'left') { - anchor.style.lineHeight = 'inherit'; - } - } - - if (this.options.placement === 'left') { - anchor.style.position = 'absolute'; - anchor.style.marginLeft = '-1em'; - anchor.style.paddingRight = '0.5em'; - elements[i].insertBefore(anchor, elements[i].firstChild); - } else { - // if the option provided is `right` (or anything else). - anchor.style.paddingLeft = '0.375em'; - elements[i].appendChild(anchor); - } - } - - for (i = 0; i < indexesToDrop.length; i++) { - elements.splice(indexesToDrop[i] - i, 1); - } - this.elements = this.elements.concat(elements); - - return this; - }; - - /** - * Removes all anchorjs-links from elements targed by the selector. - * @param {String|Array|Nodelist} selector - A CSS selector string targeting elements with anchor links, - * OR a nodeList / array containing the DOM elements. - * @returns {this} - The AnchorJS object - */ - this.remove = function (selector) { - var index, - domAnchor, - elements = _getElements(selector); - - for (var i = 0; i < elements.length; i++) { - domAnchor = elements[i].querySelector('.anchorjs-link'); - if (domAnchor) { - // Drop the element from our main list, if it's in there. - index = this.elements.indexOf(elements[i]); - if (index !== -1) { - this.elements.splice(index, 1); - } - // Remove the anchor from the DOM. - elements[i].removeChild(domAnchor); - } - } - return this; - }; - - /** - * Removes all anchorjs links. Mostly used for tests. - */ - this.removeAll = function () { - this.remove(this.elements); - }; - - /** - * Urlify - Refine text so it makes a good ID. - * - * To do this, we remove apostrophes, replace nonsafe characters with hyphens, - * remove extra hyphens, truncate, trim hyphens, and make lowercase. - * - * @param {String} text - Any text. Usually pulled from the webpage element we are linking to. - * @returns {String} - hyphen-delimited text for use in IDs and URLs. - */ - this.urlify = function (text) { - // Regex for finding the nonsafe URL characters (many need escaping): & +$,:;=?@"#{}|^~[`%!'<>]./()*\ - var nonsafeChars = /[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\]/g, - urlText; - - // The reason we include this _applyRemainingDefaultOptions is so urlify can be called independently, - // even after setting options. This can be useful for tests or other applications. - if (!this.options.truncate) { - _applyRemainingDefaultOptions(this.options); - } - - // Note: we trim hyphens after truncating because truncating can cause dangling hyphens. - // Example string: // " ⚡⚡ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." - urlText = text - .trim() // "⚡⚡ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." - .replace(/\'/gi, '') // "⚡⚡ Dont forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." - .replace(nonsafeChars, '-') // "⚡⚡-Dont-forget--URL-fragments-should-be-i18n-friendly--hyphenated--short--and-clean-" - .replace(/-{2,}/g, '-') // "⚡⚡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-short-and-clean-" - .substring(0, this.options.truncate) // "⚡⚡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-" - .replace(/^-+|-+$/gm, '') // "⚡⚡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated" - .toLowerCase(); // "⚡⚡-dont-forget-url-fragments-should-be-i18n-friendly-hyphenated" - - return urlText; - }; - - /** - * Determines if this element already has an AnchorJS link on it. - * Uses this technique: http://stackoverflow.com/a/5898748/1154642 - * @param {HTMLElemnt} el - a DOM node - * @returns {Boolean} true/false - */ - this.hasAnchorJSLink = function (el) { - var hasLeftAnchor = - el.firstChild && - (' ' + el.firstChild.className + ' ').indexOf(' anchorjs-link ') > -1, - hasRightAnchor = - el.lastChild && - (' ' + el.lastChild.className + ' ').indexOf(' anchorjs-link ') > -1; - - return hasLeftAnchor || hasRightAnchor || false; - }; - - /** - * Turns a selector, nodeList, or array of elements into an array of elements (so we can use array methods). - * It also throws errors on any other inputs. Used to handle inputs to .add and .remove. - * @param {String|Array|Nodelist} input - A CSS selector string targeting elements with anchor links, - * OR a nodeList / array containing the DOM elements. - * @returns {Array} - An array containing the elements we want. - */ - function _getElements(input) { - var elements; - if (typeof input === 'string' || input instanceof String) { - // See https://davidwalsh.name/nodelist-array for the technique transforming nodeList -> Array. - elements = [].slice.call(document.querySelectorAll(input)); - // I checked the 'input instanceof NodeList' test in IE9 and modern browsers and it worked for me. - } else if (Array.isArray(input) || input instanceof NodeList) { - elements = [].slice.call(input); - } else { - throw new Error('The selector provided to AnchorJS was invalid.'); - } - return elements; - } - - /** - * _addBaselineStyles - * Adds baseline styles to the page, used by all AnchorJS links irregardless of configuration. - */ - function _addBaselineStyles() { - // We don't want to add global baseline styles if they've been added before. - if (document.head.querySelector('style.anchorjs') !== null) { - return; - } - - var style = document.createElement('style'), - linkRule = - ' .anchorjs-link {' + - ' opacity: 0;' + - ' text-decoration: none;' + - ' -webkit-font-smoothing: antialiased;' + - ' -moz-osx-font-smoothing: grayscale;' + - ' }', - hoverRule = - ' *:hover > .anchorjs-link,' + - ' .anchorjs-link:focus {' + - ' opacity: 1;' + - ' }', - anchorjsLinkFontFace = - ' @font-face {' + - ' font-family: "anchorjs-icons";' + // Icon from icomoon; 10px wide & 10px tall; 2 empty below & 4 above - ' src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype");' + - ' }', - pseudoElContent = - ' [data-anchorjs-icon]::after {' + - ' content: attr(data-anchorjs-icon);' + - ' }', - firstStyleEl; - - style.className = 'anchorjs'; - style.appendChild(document.createTextNode('')); // Necessary for Webkit. - - // We place it in the head with the other style tags, if possible, so as to - // not look out of place. We insert before the others so these styles can be - // overridden if necessary. - firstStyleEl = document.head.querySelector('[rel="stylesheet"], style'); - if (firstStyleEl === undefined) { - document.head.appendChild(style); - } else { - document.head.insertBefore(style, firstStyleEl); - } - - style.sheet.insertRule(linkRule, style.sheet.cssRules.length); - style.sheet.insertRule(hoverRule, style.sheet.cssRules.length); - style.sheet.insertRule(pseudoElContent, style.sheet.cssRules.length); - style.sheet.insertRule(anchorjsLinkFontFace, style.sheet.cssRules.length); - } - } - - return AnchorJS; -}); diff --git a/docs/assets/bass-addons.css b/docs/assets/bass-addons.css deleted file mode 100644 index c27e96d..0000000 --- a/docs/assets/bass-addons.css +++ /dev/null @@ -1,12 +0,0 @@ -.input { - font-family: inherit; - display: block; - width: 100%; - height: 2rem; - padding: .5rem; - margin-bottom: 1rem; - border: 1px solid #ccc; - font-size: .875rem; - border-radius: 3px; - box-sizing: border-box; -} diff --git a/docs/assets/bass.css b/docs/assets/bass.css deleted file mode 100644 index 2d860c5..0000000 --- a/docs/assets/bass.css +++ /dev/null @@ -1,544 +0,0 @@ -/*! Basscss | http://basscss.com | MIT License */ - -.h1{ font-size: 2rem } -.h2{ font-size: 1.5rem } -.h3{ font-size: 1.25rem } -.h4{ font-size: 1rem } -.h5{ font-size: .875rem } -.h6{ font-size: .75rem } - -.font-family-inherit{ font-family:inherit } -.font-size-inherit{ font-size:inherit } -.text-decoration-none{ text-decoration:none } - -.bold{ font-weight: bold; font-weight: bold } -.regular{ font-weight:normal } -.italic{ font-style:italic } -.caps{ text-transform:uppercase; letter-spacing: .2em; } - -.left-align{ text-align:left } -.center{ text-align:center } -.right-align{ text-align:right } -.justify{ text-align:justify } - -.nowrap{ white-space:nowrap } -.break-word{ word-wrap:break-word } - -.line-height-1{ line-height: 1 } -.line-height-2{ line-height: 1.125 } -.line-height-3{ line-height: 1.25 } -.line-height-4{ line-height: 1.5 } - -.list-style-none{ list-style:none } -.underline{ text-decoration:underline } - -.truncate{ - max-width:100%; - overflow:hidden; - text-overflow:ellipsis; - white-space:nowrap; -} - -.list-reset{ - list-style:none; - padding-left:0; -} - -.inline{ display:inline } -.block{ display:block } -.inline-block{ display:inline-block } -.table{ display:table } -.table-cell{ display:table-cell } - -.overflow-hidden{ overflow:hidden } -.overflow-scroll{ overflow:scroll } -.overflow-auto{ overflow:auto } - -.clearfix:before, -.clearfix:after{ - content:" "; - display:table -} -.clearfix:after{ clear:both } - -.left{ float:left } -.right{ float:right } - -.fit{ max-width:100% } - -.max-width-1{ max-width: 24rem } -.max-width-2{ max-width: 32rem } -.max-width-3{ max-width: 48rem } -.max-width-4{ max-width: 64rem } - -.border-box{ box-sizing:border-box } - -.align-baseline{ vertical-align:baseline } -.align-top{ vertical-align:top } -.align-middle{ vertical-align:middle } -.align-bottom{ vertical-align:bottom } - -.m0{ margin:0 } -.mt0{ margin-top:0 } -.mr0{ margin-right:0 } -.mb0{ margin-bottom:0 } -.ml0{ margin-left:0 } -.mx0{ margin-left:0; margin-right:0 } -.my0{ margin-top:0; margin-bottom:0 } - -.m1{ margin: .5rem } -.mt1{ margin-top: .5rem } -.mr1{ margin-right: .5rem } -.mb1{ margin-bottom: .5rem } -.ml1{ margin-left: .5rem } -.mx1{ margin-left: .5rem; margin-right: .5rem } -.my1{ margin-top: .5rem; margin-bottom: .5rem } - -.m2{ margin: 1rem } -.mt2{ margin-top: 1rem } -.mr2{ margin-right: 1rem } -.mb2{ margin-bottom: 1rem } -.ml2{ margin-left: 1rem } -.mx2{ margin-left: 1rem; margin-right: 1rem } -.my2{ margin-top: 1rem; margin-bottom: 1rem } - -.m3{ margin: 2rem } -.mt3{ margin-top: 2rem } -.mr3{ margin-right: 2rem } -.mb3{ margin-bottom: 2rem } -.ml3{ margin-left: 2rem } -.mx3{ margin-left: 2rem; margin-right: 2rem } -.my3{ margin-top: 2rem; margin-bottom: 2rem } - -.m4{ margin: 4rem } -.mt4{ margin-top: 4rem } -.mr4{ margin-right: 4rem } -.mb4{ margin-bottom: 4rem } -.ml4{ margin-left: 4rem } -.mx4{ margin-left: 4rem; margin-right: 4rem } -.my4{ margin-top: 4rem; margin-bottom: 4rem } - -.mxn1{ margin-left: -.5rem; margin-right: -.5rem; } -.mxn2{ margin-left: -1rem; margin-right: -1rem; } -.mxn3{ margin-left: -2rem; margin-right: -2rem; } -.mxn4{ margin-left: -4rem; margin-right: -4rem; } - -.ml-auto{ margin-left:auto } -.mr-auto{ margin-right:auto } -.mx-auto{ margin-left:auto; margin-right:auto; } - -.p0{ padding:0 } -.pt0{ padding-top:0 } -.pr0{ padding-right:0 } -.pb0{ padding-bottom:0 } -.pl0{ padding-left:0 } -.px0{ padding-left:0; padding-right:0 } -.py0{ padding-top:0; padding-bottom:0 } - -.p1{ padding: .5rem } -.pt1{ padding-top: .5rem } -.pr1{ padding-right: .5rem } -.pb1{ padding-bottom: .5rem } -.pl1{ padding-left: .5rem } -.py1{ padding-top: .5rem; padding-bottom: .5rem } -.px1{ padding-left: .5rem; padding-right: .5rem } - -.p2{ padding: 1rem } -.pt2{ padding-top: 1rem } -.pr2{ padding-right: 1rem } -.pb2{ padding-bottom: 1rem } -.pl2{ padding-left: 1rem } -.py2{ padding-top: 1rem; padding-bottom: 1rem } -.px2{ padding-left: 1rem; padding-right: 1rem } - -.p3{ padding: 2rem } -.pt3{ padding-top: 2rem } -.pr3{ padding-right: 2rem } -.pb3{ padding-bottom: 2rem } -.pl3{ padding-left: 2rem } -.py3{ padding-top: 2rem; padding-bottom: 2rem } -.px3{ padding-left: 2rem; padding-right: 2rem } - -.p4{ padding: 4rem } -.pt4{ padding-top: 4rem } -.pr4{ padding-right: 4rem } -.pb4{ padding-bottom: 4rem } -.pl4{ padding-left: 4rem } -.py4{ padding-top: 4rem; padding-bottom: 4rem } -.px4{ padding-left: 4rem; padding-right: 4rem } - -.col{ - float:left; - box-sizing:border-box; -} - -.col-right{ - float:right; - box-sizing:border-box; -} - -.col-1{ - width:8.33333%; -} - -.col-2{ - width:16.66667%; -} - -.col-3{ - width:25%; -} - -.col-4{ - width:33.33333%; -} - -.col-5{ - width:41.66667%; -} - -.col-6{ - width:50%; -} - -.col-7{ - width:58.33333%; -} - -.col-8{ - width:66.66667%; -} - -.col-9{ - width:75%; -} - -.col-10{ - width:83.33333%; -} - -.col-11{ - width:91.66667%; -} - -.col-12{ - width:100%; -} -@media (min-width: 40em){ - - .sm-col{ - float:left; - box-sizing:border-box; - } - - .sm-col-right{ - float:right; - box-sizing:border-box; - } - - .sm-col-1{ - width:8.33333%; - } - - .sm-col-2{ - width:16.66667%; - } - - .sm-col-3{ - width:25%; - } - - .sm-col-4{ - width:33.33333%; - } - - .sm-col-5{ - width:41.66667%; - } - - .sm-col-6{ - width:50%; - } - - .sm-col-7{ - width:58.33333%; - } - - .sm-col-8{ - width:66.66667%; - } - - .sm-col-9{ - width:75%; - } - - .sm-col-10{ - width:83.33333%; - } - - .sm-col-11{ - width:91.66667%; - } - - .sm-col-12{ - width:100%; - } - -} -@media (min-width: 52em){ - - .md-col{ - float:left; - box-sizing:border-box; - } - - .md-col-right{ - float:right; - box-sizing:border-box; - } - - .md-col-1{ - width:8.33333%; - } - - .md-col-2{ - width:16.66667%; - } - - .md-col-3{ - width:25%; - } - - .md-col-4{ - width:33.33333%; - } - - .md-col-5{ - width:41.66667%; - } - - .md-col-6{ - width:50%; - } - - .md-col-7{ - width:58.33333%; - } - - .md-col-8{ - width:66.66667%; - } - - .md-col-9{ - width:75%; - } - - .md-col-10{ - width:83.33333%; - } - - .md-col-11{ - width:91.66667%; - } - - .md-col-12{ - width:100%; - } - -} -@media (min-width: 64em){ - - .lg-col{ - float:left; - box-sizing:border-box; - } - - .lg-col-right{ - float:right; - box-sizing:border-box; - } - - .lg-col-1{ - width:8.33333%; - } - - .lg-col-2{ - width:16.66667%; - } - - .lg-col-3{ - width:25%; - } - - .lg-col-4{ - width:33.33333%; - } - - .lg-col-5{ - width:41.66667%; - } - - .lg-col-6{ - width:50%; - } - - .lg-col-7{ - width:58.33333%; - } - - .lg-col-8{ - width:66.66667%; - } - - .lg-col-9{ - width:75%; - } - - .lg-col-10{ - width:83.33333%; - } - - .lg-col-11{ - width:91.66667%; - } - - .lg-col-12{ - width:100%; - } - -} -.flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } - -@media (min-width: 40em){ - .sm-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } -} - -@media (min-width: 52em){ - .md-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } -} - -@media (min-width: 64em){ - .lg-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } -} - -.flex-column{ -webkit-box-orient:vertical; -webkit-box-direction:normal; -webkit-flex-direction:column; -ms-flex-direction:column; flex-direction:column } -.flex-wrap{ -webkit-flex-wrap:wrap; -ms-flex-wrap:wrap; flex-wrap:wrap } - -.items-start{ -webkit-box-align:start; -webkit-align-items:flex-start; -ms-flex-align:start; -ms-grid-row-align:flex-start; align-items:flex-start } -.items-end{ -webkit-box-align:end; -webkit-align-items:flex-end; -ms-flex-align:end; -ms-grid-row-align:flex-end; align-items:flex-end } -.items-center{ -webkit-box-align:center; -webkit-align-items:center; -ms-flex-align:center; -ms-grid-row-align:center; align-items:center } -.items-baseline{ -webkit-box-align:baseline; -webkit-align-items:baseline; -ms-flex-align:baseline; -ms-grid-row-align:baseline; align-items:baseline } -.items-stretch{ -webkit-box-align:stretch; -webkit-align-items:stretch; -ms-flex-align:stretch; -ms-grid-row-align:stretch; align-items:stretch } - -.self-start{ -webkit-align-self:flex-start; -ms-flex-item-align:start; align-self:flex-start } -.self-end{ -webkit-align-self:flex-end; -ms-flex-item-align:end; align-self:flex-end } -.self-center{ -webkit-align-self:center; -ms-flex-item-align:center; align-self:center } -.self-baseline{ -webkit-align-self:baseline; -ms-flex-item-align:baseline; align-self:baseline } -.self-stretch{ -webkit-align-self:stretch; -ms-flex-item-align:stretch; align-self:stretch } - -.justify-start{ -webkit-box-pack:start; -webkit-justify-content:flex-start; -ms-flex-pack:start; justify-content:flex-start } -.justify-end{ -webkit-box-pack:end; -webkit-justify-content:flex-end; -ms-flex-pack:end; justify-content:flex-end } -.justify-center{ -webkit-box-pack:center; -webkit-justify-content:center; -ms-flex-pack:center; justify-content:center } -.justify-between{ -webkit-box-pack:justify; -webkit-justify-content:space-between; -ms-flex-pack:justify; justify-content:space-between } -.justify-around{ -webkit-justify-content:space-around; -ms-flex-pack:distribute; justify-content:space-around } - -.content-start{ -webkit-align-content:flex-start; -ms-flex-line-pack:start; align-content:flex-start } -.content-end{ -webkit-align-content:flex-end; -ms-flex-line-pack:end; align-content:flex-end } -.content-center{ -webkit-align-content:center; -ms-flex-line-pack:center; align-content:center } -.content-between{ -webkit-align-content:space-between; -ms-flex-line-pack:justify; align-content:space-between } -.content-around{ -webkit-align-content:space-around; -ms-flex-line-pack:distribute; align-content:space-around } -.content-stretch{ -webkit-align-content:stretch; -ms-flex-line-pack:stretch; align-content:stretch } -.flex-auto{ - -webkit-box-flex:1; - -webkit-flex:1 1 auto; - -ms-flex:1 1 auto; - flex:1 1 auto; - min-width:0; - min-height:0; -} -.flex-none{ -webkit-box-flex:0; -webkit-flex:none; -ms-flex:none; flex:none } -.fs0{ flex-shrink: 0 } - -.order-0{ -webkit-box-ordinal-group:1; -webkit-order:0; -ms-flex-order:0; order:0 } -.order-1{ -webkit-box-ordinal-group:2; -webkit-order:1; -ms-flex-order:1; order:1 } -.order-2{ -webkit-box-ordinal-group:3; -webkit-order:2; -ms-flex-order:2; order:2 } -.order-3{ -webkit-box-ordinal-group:4; -webkit-order:3; -ms-flex-order:3; order:3 } -.order-last{ -webkit-box-ordinal-group:100000; -webkit-order:99999; -ms-flex-order:99999; order:99999 } - -.relative{ position:relative } -.absolute{ position:absolute } -.fixed{ position:fixed } - -.top-0{ top:0 } -.right-0{ right:0 } -.bottom-0{ bottom:0 } -.left-0{ left:0 } - -.z1{ z-index: 1 } -.z2{ z-index: 2 } -.z3{ z-index: 3 } -.z4{ z-index: 4 } - -.border{ - border-style:solid; - border-width: 1px; -} - -.border-top{ - border-top-style:solid; - border-top-width: 1px; -} - -.border-right{ - border-right-style:solid; - border-right-width: 1px; -} - -.border-bottom{ - border-bottom-style:solid; - border-bottom-width: 1px; -} - -.border-left{ - border-left-style:solid; - border-left-width: 1px; -} - -.border-none{ border:0 } - -.rounded{ border-radius: 3px } -.circle{ border-radius:50% } - -.rounded-top{ border-radius: 3px 3px 0 0 } -.rounded-right{ border-radius: 0 3px 3px 0 } -.rounded-bottom{ border-radius: 0 0 3px 3px } -.rounded-left{ border-radius: 3px 0 0 3px } - -.not-rounded{ border-radius:0 } - -.hide{ - position:absolute !important; - height:1px; - width:1px; - overflow:hidden; - clip:rect(1px, 1px, 1px, 1px); -} - -@media (max-width: 40em){ - .xs-hide{ display:none !important } -} - -@media (min-width: 40em) and (max-width: 52em){ - .sm-hide{ display:none !important } -} - -@media (min-width: 52em) and (max-width: 64em){ - .md-hide{ display:none !important } -} - -@media (min-width: 64em){ - .lg-hide{ display:none !important } -} - -.display-none{ display:none !important } - diff --git a/docs/assets/fonts/EOT/SourceCodePro-Bold.eot b/docs/assets/fonts/EOT/SourceCodePro-Bold.eot deleted file mode 100755 index d24cc39..0000000 Binary files a/docs/assets/fonts/EOT/SourceCodePro-Bold.eot and /dev/null differ diff --git a/docs/assets/fonts/EOT/SourceCodePro-Regular.eot b/docs/assets/fonts/EOT/SourceCodePro-Regular.eot deleted file mode 100755 index 09e9473..0000000 Binary files a/docs/assets/fonts/EOT/SourceCodePro-Regular.eot and /dev/null differ diff --git a/docs/assets/fonts/LICENSE.txt b/docs/assets/fonts/LICENSE.txt deleted file mode 100755 index d154618..0000000 --- a/docs/assets/fonts/LICENSE.txt +++ /dev/null @@ -1,93 +0,0 @@ -Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. - -This Font Software is licensed under the SIL Open Font License, Version 1.1. - -This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/assets/fonts/OTF/SourceCodePro-Bold.otf b/docs/assets/fonts/OTF/SourceCodePro-Bold.otf deleted file mode 100755 index f4e576c..0000000 Binary files a/docs/assets/fonts/OTF/SourceCodePro-Bold.otf and /dev/null differ diff --git a/docs/assets/fonts/OTF/SourceCodePro-Regular.otf b/docs/assets/fonts/OTF/SourceCodePro-Regular.otf deleted file mode 100755 index 4e3b9d0..0000000 Binary files a/docs/assets/fonts/OTF/SourceCodePro-Regular.otf and /dev/null differ diff --git a/docs/assets/fonts/TTF/SourceCodePro-Bold.ttf b/docs/assets/fonts/TTF/SourceCodePro-Bold.ttf deleted file mode 100755 index e0c576f..0000000 Binary files a/docs/assets/fonts/TTF/SourceCodePro-Bold.ttf and /dev/null differ diff --git a/docs/assets/fonts/TTF/SourceCodePro-Regular.ttf b/docs/assets/fonts/TTF/SourceCodePro-Regular.ttf deleted file mode 100755 index 437f472..0000000 Binary files a/docs/assets/fonts/TTF/SourceCodePro-Regular.ttf and /dev/null differ diff --git a/docs/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff b/docs/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff deleted file mode 100755 index cf96099..0000000 Binary files a/docs/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff and /dev/null differ diff --git a/docs/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff b/docs/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff deleted file mode 100755 index 395436e..0000000 Binary files a/docs/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff and /dev/null differ diff --git a/docs/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff b/docs/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff deleted file mode 100755 index c65ba84..0000000 Binary files a/docs/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff and /dev/null differ diff --git a/docs/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff b/docs/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff deleted file mode 100755 index 0af792a..0000000 Binary files a/docs/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff and /dev/null differ diff --git a/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 b/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 deleted file mode 100755 index cbe3835..0000000 Binary files a/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 and /dev/null differ diff --git a/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 b/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 deleted file mode 100755 index 65cd591..0000000 Binary files a/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 and /dev/null differ diff --git a/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 b/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 deleted file mode 100755 index b78d523..0000000 Binary files a/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 and /dev/null differ diff --git a/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 b/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 deleted file mode 100755 index 18d2199..0000000 Binary files a/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 and /dev/null differ diff --git a/docs/assets/fonts/source-code-pro.css b/docs/assets/fonts/source-code-pro.css deleted file mode 100755 index 3abb4f0..0000000 --- a/docs/assets/fonts/source-code-pro.css +++ /dev/null @@ -1,23 +0,0 @@ -@font-face{ - font-family: 'Source Code Pro'; - font-weight: 400; - font-style: normal; - font-stretch: normal; - src: url('EOT/SourceCodePro-Regular.eot') format('embedded-opentype'), - url('WOFF2/TTF/SourceCodePro-Regular.ttf.woff2') format('woff2'), - url('WOFF/OTF/SourceCodePro-Regular.otf.woff') format('woff'), - url('OTF/SourceCodePro-Regular.otf') format('opentype'), - url('TTF/SourceCodePro-Regular.ttf') format('truetype'); -} - -@font-face{ - font-family: 'Source Code Pro'; - font-weight: 700; - font-style: normal; - font-stretch: normal; - src: url('EOT/SourceCodePro-Bold.eot') format('embedded-opentype'), - url('WOFF2/TTF/SourceCodePro-Bold.ttf.woff2') format('woff2'), - url('WOFF/OTF/SourceCodePro-Bold.otf.woff') format('woff'), - url('OTF/SourceCodePro-Bold.otf') format('opentype'), - url('TTF/SourceCodePro-Bold.ttf') format('truetype'); -} diff --git a/docs/assets/github.css b/docs/assets/github.css deleted file mode 100644 index 8852abb..0000000 --- a/docs/assets/github.css +++ /dev/null @@ -1,123 +0,0 @@ -/* - -github.com style (c) Vasily Polovnyov - -*/ - -.hljs { - display: block; - overflow-x: auto; - padding: 0.5em; - color: #333; - background: #f8f8f8; - -webkit-text-size-adjust: none; -} - -.hljs-comment, -.diff .hljs-header, -.hljs-javadoc { - color: #998; - font-style: italic; -} - -.hljs-keyword, -.css .rule .hljs-keyword, -.hljs-winutils, -.nginx .hljs-title, -.hljs-subst, -.hljs-request, -.hljs-status { - color: #1184CE; -} - -.hljs-number, -.hljs-hexcolor, -.ruby .hljs-constant { - color: #ed225d; -} - -.hljs-string, -.hljs-tag .hljs-value, -.hljs-phpdoc, -.hljs-dartdoc, -.tex .hljs-formula { - color: #ed225d; -} - -.hljs-title, -.hljs-id, -.scss .hljs-preprocessor { - color: #900; - font-weight: bold; -} - -.hljs-list .hljs-keyword, -.hljs-subst { - font-weight: normal; -} - -.hljs-class .hljs-title, -.hljs-type, -.vhdl .hljs-literal, -.tex .hljs-command { - color: #458; - font-weight: bold; -} - -.hljs-tag, -.hljs-tag .hljs-title, -.hljs-rules .hljs-property, -.django .hljs-tag .hljs-keyword { - color: #000080; - font-weight: normal; -} - -.hljs-attribute, -.hljs-variable, -.lisp .hljs-body { - color: #008080; -} - -.hljs-regexp { - color: #009926; -} - -.hljs-symbol, -.ruby .hljs-symbol .hljs-string, -.lisp .hljs-keyword, -.clojure .hljs-keyword, -.scheme .hljs-keyword, -.tex .hljs-special, -.hljs-prompt { - color: #990073; -} - -.hljs-built_in { - color: #0086b3; -} - -.hljs-preprocessor, -.hljs-pragma, -.hljs-pi, -.hljs-doctype, -.hljs-shebang, -.hljs-cdata { - color: #999; - font-weight: bold; -} - -.hljs-deletion { - background: #fdd; -} - -.hljs-addition { - background: #dfd; -} - -.diff .hljs-change { - background: #0086b3; -} - -.hljs-chunk { - color: #aaa; -} diff --git a/docs/assets/site.js b/docs/assets/site.js deleted file mode 100644 index a624be7..0000000 --- a/docs/assets/site.js +++ /dev/null @@ -1,168 +0,0 @@ -/* global anchors */ - -// add anchor links to headers -anchors.options.placement = 'left'; -anchors.add('h3'); - -// Filter UI -var tocElements = document.getElementById('toc').getElementsByTagName('li'); - -document.getElementById('filter-input').addEventListener('keyup', function (e) { - var i, element, children; - - // enter key - if (e.keyCode === 13) { - // go to the first displayed item in the toc - for (i = 0; i < tocElements.length; i++) { - element = tocElements[i]; - if (!element.classList.contains('display-none')) { - location.replace(element.firstChild.href); - return e.preventDefault(); - } - } - } - - var match = function () { - return true; - }; - - var value = this.value.toLowerCase(); - - if (!value.match(/^\s*$/)) { - match = function (element) { - var html = element.firstChild.innerHTML; - return html && html.toLowerCase().indexOf(value) !== -1; - }; - } - - for (i = 0; i < tocElements.length; i++) { - element = tocElements[i]; - children = Array.from(element.getElementsByTagName('li')); - if (match(element) || children.some(match)) { - element.classList.remove('display-none'); - } else { - element.classList.add('display-none'); - } - } -}); - -var items = document.getElementsByClassName('toggle-sibling'); -for (var j = 0; j < items.length; j++) { - items[j].addEventListener('click', toggleSibling); -} - -function toggleSibling() { - var stepSibling = this.parentNode.getElementsByClassName('toggle-target')[0]; - var icon = this.getElementsByClassName('icon')[0]; - var klass = 'display-none'; - if (stepSibling.classList.contains(klass)) { - stepSibling.classList.remove(klass); - icon.innerHTML = '▾'; - } else { - stepSibling.classList.add(klass); - icon.innerHTML = '▸'; - } -} - -function showHashTarget(targetId) { - if (targetId) { - var hashTarget = document.getElementById(targetId); - // new target is hidden - if ( - hashTarget && - hashTarget.offsetHeight === 0 && - hashTarget.parentNode.parentNode.classList.contains('display-none') - ) { - hashTarget.parentNode.parentNode.classList.remove('display-none'); - } - } -} - -function scrollIntoView(targetId) { - // Only scroll to element if we don't have a stored scroll position. - if (targetId && !history.state) { - var hashTarget = document.getElementById(targetId); - if (hashTarget) { - hashTarget.scrollIntoView(); - } - } -} - -function gotoCurrentTarget() { - showHashTarget(location.hash.substring(1)); - scrollIntoView(location.hash.substring(1)); -} - -window.addEventListener('hashchange', gotoCurrentTarget); -gotoCurrentTarget(); - -var toclinks = document.getElementsByClassName('pre-open'); -for (var k = 0; k < toclinks.length; k++) { - toclinks[k].addEventListener('mousedown', preOpen, false); -} - -function preOpen() { - showHashTarget(this.hash.substring(1)); -} - -var split_left = document.querySelector('#split-left'); -var split_right = document.querySelector('#split-right'); -var split_parent = split_left.parentNode; -var cw_with_sb = split_left.clientWidth; -split_left.style.overflow = 'hidden'; -var cw_without_sb = split_left.clientWidth; -split_left.style.overflow = ''; - -Split(['#split-left', '#split-right'], { - elementStyle: function (dimension, size, gutterSize) { - return { - 'flex-basis': 'calc(' + size + '% - ' + gutterSize + 'px)' - }; - }, - gutterStyle: function (dimension, gutterSize) { - return { - 'flex-basis': gutterSize + 'px' - }; - }, - gutterSize: 20, - sizes: [33, 67] -}); - -// Chrome doesn't remember scroll position properly so do it ourselves. -// Also works on Firefox and Edge. - -function updateState() { - history.replaceState( - { - left_top: split_left.scrollTop, - right_top: split_right.scrollTop - }, - document.title - ); -} - -function loadState(ev) { - if (ev) { - // Edge doesn't replace change history.state on popstate. - history.replaceState(ev.state, document.title); - } - if (history.state) { - split_left.scrollTop = history.state.left_top; - split_right.scrollTop = history.state.right_top; - } -} - -window.addEventListener('load', function () { - // Restore after Firefox scrolls to hash. - setTimeout(function () { - loadState(); - // Update with initial scroll position. - updateState(); - // Update scroll positions only after we've loaded because Firefox - // emits an initial scroll event with 0. - split_left.addEventListener('scroll', updateState); - split_right.addEventListener('scroll', updateState); - }, 1); -}); - -window.addEventListener('popstate', loadState); diff --git a/docs/assets/split.css b/docs/assets/split.css deleted file mode 100644 index 2d7779e..0000000 --- a/docs/assets/split.css +++ /dev/null @@ -1,15 +0,0 @@ -.gutter { - background-color: #f5f5f5; - background-repeat: no-repeat; - background-position: 50%; -} - -.gutter.gutter-vertical { - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAFAQMAAABo7865AAAABlBMVEVHcEzMzMzyAv2sAAAAAXRSTlMAQObYZgAAABBJREFUeF5jOAMEEAIEEFwAn3kMwcB6I2AAAAAASUVORK5CYII='); - cursor: ns-resize; -} - -.gutter.gutter-horizontal { - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAIklEQVQoU2M4c+bMfxAGAgYYmwGrIIiDjrELjpo5aiZeMwF+yNnOs5KSvgAAAABJRU5ErkJggg=='); - cursor: ew-resize; -} diff --git a/docs/assets/split.js b/docs/assets/split.js deleted file mode 100644 index 71f9a60..0000000 --- a/docs/assets/split.js +++ /dev/null @@ -1,782 +0,0 @@ -/*! Split.js - v1.5.11 */ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.Split = factory()); -}(this, (function () { 'use strict'; - - // The programming goals of Split.js are to deliver readable, understandable and - // maintainable code, while at the same time manually optimizing for tiny minified file size, - // browser compatibility without additional requirements, graceful fallback (IE8 is supported) - // and very few assumptions about the user's page layout. - var global = window; - var document = global.document; - - // Save a couple long function names that are used frequently. - // This optimization saves around 400 bytes. - var addEventListener = 'addEventListener'; - var removeEventListener = 'removeEventListener'; - var getBoundingClientRect = 'getBoundingClientRect'; - var gutterStartDragging = '_a'; - var aGutterSize = '_b'; - var bGutterSize = '_c'; - var HORIZONTAL = 'horizontal'; - var NOOP = function () { return false; }; - - // Figure out if we're in IE8 or not. IE8 will still render correctly, - // but will be static instead of draggable. - var isIE8 = global.attachEvent && !global[addEventListener]; - - // Helper function determines which prefixes of CSS calc we need. - // We only need to do this once on startup, when this anonymous function is called. - // - // Tests -webkit, -moz and -o prefixes. Modified from StackOverflow: - // http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167 - var calc = (['', '-webkit-', '-moz-', '-o-'] - .filter(function (prefix) { - var el = document.createElement('div'); - el.style.cssText = "width:" + prefix + "calc(9px)"; - - return !!el.style.length - }) - .shift()) + "calc"; - - // Helper function checks if its argument is a string-like type - var isString = function (v) { return typeof v === 'string' || v instanceof String; }; - - // Helper function allows elements and string selectors to be used - // interchangeably. In either case an element is returned. This allows us to - // do `Split([elem1, elem2])` as well as `Split(['#id1', '#id2'])`. - var elementOrSelector = function (el) { - if (isString(el)) { - var ele = document.querySelector(el); - if (!ele) { - throw new Error(("Selector " + el + " did not match a DOM element")) - } - return ele - } - - return el - }; - - // Helper function gets a property from the properties object, with a default fallback - var getOption = function (options, propName, def) { - var value = options[propName]; - if (value !== undefined) { - return value - } - return def - }; - - var getGutterSize = function (gutterSize, isFirst, isLast, gutterAlign) { - if (isFirst) { - if (gutterAlign === 'end') { - return 0 - } - if (gutterAlign === 'center') { - return gutterSize / 2 - } - } else if (isLast) { - if (gutterAlign === 'start') { - return 0 - } - if (gutterAlign === 'center') { - return gutterSize / 2 - } - } - - return gutterSize - }; - - // Default options - var defaultGutterFn = function (i, gutterDirection) { - var gut = document.createElement('div'); - gut.className = "gutter gutter-" + gutterDirection; - return gut - }; - - var defaultElementStyleFn = function (dim, size, gutSize) { - var style = {}; - - if (!isString(size)) { - if (!isIE8) { - style[dim] = calc + "(" + size + "% - " + gutSize + "px)"; - } else { - style[dim] = size + "%"; - } - } else { - style[dim] = size; - } - - return style - }; - - var defaultGutterStyleFn = function (dim, gutSize) { - var obj; - - return (( obj = {}, obj[dim] = (gutSize + "px"), obj )); - }; - - // The main function to initialize a split. Split.js thinks about each pair - // of elements as an independant pair. Dragging the gutter between two elements - // only changes the dimensions of elements in that pair. This is key to understanding - // how the following functions operate, since each function is bound to a pair. - // - // A pair object is shaped like this: - // - // { - // a: DOM element, - // b: DOM element, - // aMin: Number, - // bMin: Number, - // dragging: Boolean, - // parent: DOM element, - // direction: 'horizontal' | 'vertical' - // } - // - // The basic sequence: - // - // 1. Set defaults to something sane. `options` doesn't have to be passed at all. - // 2. Initialize a bunch of strings based on the direction we're splitting. - // A lot of the behavior in the rest of the library is paramatized down to - // rely on CSS strings and classes. - // 3. Define the dragging helper functions, and a few helpers to go with them. - // 4. Loop through the elements while pairing them off. Every pair gets an - // `pair` object and a gutter. - // 5. Actually size the pair elements, insert gutters and attach event listeners. - var Split = function (idsOption, options) { - if ( options === void 0 ) options = {}; - - var ids = idsOption; - var dimension; - var clientAxis; - var position; - var positionEnd; - var clientSize; - var elements; - - // Allow HTMLCollection to be used as an argument when supported - if (Array.from) { - ids = Array.from(ids); - } - - // All DOM elements in the split should have a common parent. We can grab - // the first elements parent and hope users read the docs because the - // behavior will be whacky otherwise. - var firstElement = elementOrSelector(ids[0]); - var parent = firstElement.parentNode; - var parentStyle = getComputedStyle ? getComputedStyle(parent) : null; - var parentFlexDirection = parentStyle ? parentStyle.flexDirection : null; - - // Set default options.sizes to equal percentages of the parent element. - var sizes = getOption(options, 'sizes') || ids.map(function () { return 100 / ids.length; }); - - // Standardize minSize to an array if it isn't already. This allows minSize - // to be passed as a number. - var minSize = getOption(options, 'minSize', 100); - var minSizes = Array.isArray(minSize) ? minSize : ids.map(function () { return minSize; }); - - // Get other options - var expandToMin = getOption(options, 'expandToMin', false); - var gutterSize = getOption(options, 'gutterSize', 10); - var gutterAlign = getOption(options, 'gutterAlign', 'center'); - var snapOffset = getOption(options, 'snapOffset', 30); - var dragInterval = getOption(options, 'dragInterval', 1); - var direction = getOption(options, 'direction', HORIZONTAL); - var cursor = getOption( - options, - 'cursor', - direction === HORIZONTAL ? 'col-resize' : 'row-resize' - ); - var gutter = getOption(options, 'gutter', defaultGutterFn); - var elementStyle = getOption( - options, - 'elementStyle', - defaultElementStyleFn - ); - var gutterStyle = getOption(options, 'gutterStyle', defaultGutterStyleFn); - - // 2. Initialize a bunch of strings based on the direction we're splitting. - // A lot of the behavior in the rest of the library is paramatized down to - // rely on CSS strings and classes. - if (direction === HORIZONTAL) { - dimension = 'width'; - clientAxis = 'clientX'; - position = 'left'; - positionEnd = 'right'; - clientSize = 'clientWidth'; - } else if (direction === 'vertical') { - dimension = 'height'; - clientAxis = 'clientY'; - position = 'top'; - positionEnd = 'bottom'; - clientSize = 'clientHeight'; - } - - // 3. Define the dragging helper functions, and a few helpers to go with them. - // Each helper is bound to a pair object that contains its metadata. This - // also makes it easy to store references to listeners that that will be - // added and removed. - // - // Even though there are no other functions contained in them, aliasing - // this to self saves 50 bytes or so since it's used so frequently. - // - // The pair object saves metadata like dragging state, position and - // event listener references. - - function setElementSize(el, size, gutSize, i) { - // Split.js allows setting sizes via numbers (ideally), or if you must, - // by string, like '300px'. This is less than ideal, because it breaks - // the fluid layout that `calc(% - px)` provides. You're on your own if you do that, - // make sure you calculate the gutter size by hand. - var style = elementStyle(dimension, size, gutSize, i); - - Object.keys(style).forEach(function (prop) { - // eslint-disable-next-line no-param-reassign - el.style[prop] = style[prop]; - }); - } - - function setGutterSize(gutterElement, gutSize, i) { - var style = gutterStyle(dimension, gutSize, i); - - Object.keys(style).forEach(function (prop) { - // eslint-disable-next-line no-param-reassign - gutterElement.style[prop] = style[prop]; - }); - } - - function getSizes() { - return elements.map(function (element) { return element.size; }) - } - - // Supports touch events, but not multitouch, so only the first - // finger `touches[0]` is counted. - function getMousePosition(e) { - if ('touches' in e) { return e.touches[0][clientAxis] } - return e[clientAxis] - } - - // Actually adjust the size of elements `a` and `b` to `offset` while dragging. - // calc is used to allow calc(percentage + gutterpx) on the whole split instance, - // which allows the viewport to be resized without additional logic. - // Element a's size is the same as offset. b's size is total size - a size. - // Both sizes are calculated from the initial parent percentage, - // then the gutter size is subtracted. - function adjust(offset) { - var a = elements[this.a]; - var b = elements[this.b]; - var percentage = a.size + b.size; - - a.size = (offset / this.size) * percentage; - b.size = percentage - (offset / this.size) * percentage; - - setElementSize(a.element, a.size, this[aGutterSize], a.i); - setElementSize(b.element, b.size, this[bGutterSize], b.i); - } - - // drag, where all the magic happens. The logic is really quite simple: - // - // 1. Ignore if the pair is not dragging. - // 2. Get the offset of the event. - // 3. Snap offset to min if within snappable range (within min + snapOffset). - // 4. Actually adjust each element in the pair to offset. - // - // --------------------------------------------------------------------- - // | | <- a.minSize || b.minSize -> | | - // | | | <- this.snapOffset || this.snapOffset -> | | | - // | | | || | | | - // | | | || | | | - // --------------------------------------------------------------------- - // | <- this.start this.size -> | - function drag(e) { - var offset; - var a = elements[this.a]; - var b = elements[this.b]; - - if (!this.dragging) { return } - - // Get the offset of the event from the first side of the - // pair `this.start`. Then offset by the initial position of the - // mouse compared to the gutter size. - offset = - getMousePosition(e) - - this.start + - (this[aGutterSize] - this.dragOffset); - - if (dragInterval > 1) { - offset = Math.round(offset / dragInterval) * dragInterval; - } - - // If within snapOffset of min or max, set offset to min or max. - // snapOffset buffers a.minSize and b.minSize, so logic is opposite for both. - // Include the appropriate gutter sizes to prevent overflows. - if (offset <= a.minSize + snapOffset + this[aGutterSize]) { - offset = a.minSize + this[aGutterSize]; - } else if ( - offset >= - this.size - (b.minSize + snapOffset + this[bGutterSize]) - ) { - offset = this.size - (b.minSize + this[bGutterSize]); - } - - // Actually adjust the size. - adjust.call(this, offset); - - // Call the drag callback continously. Don't do anything too intensive - // in this callback. - getOption(options, 'onDrag', NOOP)(); - } - - // Cache some important sizes when drag starts, so we don't have to do that - // continously: - // - // `size`: The total size of the pair. First + second + first gutter + second gutter. - // `start`: The leading side of the first element. - // - // ------------------------------------------------ - // | aGutterSize -> ||| | - // | ||| | - // | ||| | - // | ||| <- bGutterSize | - // ------------------------------------------------ - // | <- start size -> | - function calculateSizes() { - // Figure out the parent size minus padding. - var a = elements[this.a].element; - var b = elements[this.b].element; - - var aBounds = a[getBoundingClientRect](); - var bBounds = b[getBoundingClientRect](); - - this.size = - aBounds[dimension] + - bBounds[dimension] + - this[aGutterSize] + - this[bGutterSize]; - this.start = aBounds[position]; - this.end = aBounds[positionEnd]; - } - - function innerSize(element) { - // Return nothing if getComputedStyle is not supported (< IE9) - // Or if parent element has no layout yet - if (!getComputedStyle) { return null } - - var computedStyle = getComputedStyle(element); - - if (!computedStyle) { return null } - - var size = element[clientSize]; - - if (size === 0) { return null } - - if (direction === HORIZONTAL) { - size -= - parseFloat(computedStyle.paddingLeft) + - parseFloat(computedStyle.paddingRight); - } else { - size -= - parseFloat(computedStyle.paddingTop) + - parseFloat(computedStyle.paddingBottom); - } - - return size - } - - // When specifying percentage sizes that are less than the computed - // size of the element minus the gutter, the lesser percentages must be increased - // (and decreased from the other elements) to make space for the pixels - // subtracted by the gutters. - function trimToMin(sizesToTrim) { - // Try to get inner size of parent element. - // If it's no supported, return original sizes. - var parentSize = innerSize(parent); - if (parentSize === null) { - return sizesToTrim - } - - if (minSizes.reduce(function (a, b) { return a + b; }, 0) > parentSize) { - return sizesToTrim - } - - // Keep track of the excess pixels, the amount of pixels over the desired percentage - // Also keep track of the elements with pixels to spare, to decrease after if needed - var excessPixels = 0; - var toSpare = []; - - var pixelSizes = sizesToTrim.map(function (size, i) { - // Convert requested percentages to pixel sizes - var pixelSize = (parentSize * size) / 100; - var elementGutterSize = getGutterSize( - gutterSize, - i === 0, - i === sizesToTrim.length - 1, - gutterAlign - ); - var elementMinSize = minSizes[i] + elementGutterSize; - - // If element is too smal, increase excess pixels by the difference - // and mark that it has no pixels to spare - if (pixelSize < elementMinSize) { - excessPixels += elementMinSize - pixelSize; - toSpare.push(0); - return elementMinSize - } - - // Otherwise, mark the pixels it has to spare and return it's original size - toSpare.push(pixelSize - elementMinSize); - return pixelSize - }); - - // If nothing was adjusted, return the original sizes - if (excessPixels === 0) { - return sizesToTrim - } - - return pixelSizes.map(function (pixelSize, i) { - var newPixelSize = pixelSize; - - // While there's still pixels to take, and there's enough pixels to spare, - // take as many as possible up to the total excess pixels - if (excessPixels > 0 && toSpare[i] - excessPixels > 0) { - var takenPixels = Math.min( - excessPixels, - toSpare[i] - excessPixels - ); - - // Subtract the amount taken for the next iteration - excessPixels -= takenPixels; - newPixelSize = pixelSize - takenPixels; - } - - // Return the pixel size adjusted as a percentage - return (newPixelSize / parentSize) * 100 - }) - } - - // stopDragging is very similar to startDragging in reverse. - function stopDragging() { - var self = this; - var a = elements[self.a].element; - var b = elements[self.b].element; - - if (self.dragging) { - getOption(options, 'onDragEnd', NOOP)(getSizes()); - } - - self.dragging = false; - - // Remove the stored event listeners. This is why we store them. - global[removeEventListener]('mouseup', self.stop); - global[removeEventListener]('touchend', self.stop); - global[removeEventListener]('touchcancel', self.stop); - global[removeEventListener]('mousemove', self.move); - global[removeEventListener]('touchmove', self.move); - - // Clear bound function references - self.stop = null; - self.move = null; - - a[removeEventListener]('selectstart', NOOP); - a[removeEventListener]('dragstart', NOOP); - b[removeEventListener]('selectstart', NOOP); - b[removeEventListener]('dragstart', NOOP); - - a.style.userSelect = ''; - a.style.webkitUserSelect = ''; - a.style.MozUserSelect = ''; - a.style.pointerEvents = ''; - - b.style.userSelect = ''; - b.style.webkitUserSelect = ''; - b.style.MozUserSelect = ''; - b.style.pointerEvents = ''; - - self.gutter.style.cursor = ''; - self.parent.style.cursor = ''; - document.body.style.cursor = ''; - } - - // startDragging calls `calculateSizes` to store the inital size in the pair object. - // It also adds event listeners for mouse/touch events, - // and prevents selection while dragging so avoid the selecting text. - function startDragging(e) { - // Right-clicking can't start dragging. - if ('button' in e && e.button !== 0) { - return - } - - // Alias frequently used variables to save space. 200 bytes. - var self = this; - var a = elements[self.a].element; - var b = elements[self.b].element; - - // Call the onDragStart callback. - if (!self.dragging) { - getOption(options, 'onDragStart', NOOP)(getSizes()); - } - - // Don't actually drag the element. We emulate that in the drag function. - e.preventDefault(); - - // Set the dragging property of the pair object. - self.dragging = true; - - // Create two event listeners bound to the same pair object and store - // them in the pair object. - self.move = drag.bind(self); - self.stop = stopDragging.bind(self); - - // All the binding. `window` gets the stop events in case we drag out of the elements. - global[addEventListener]('mouseup', self.stop); - global[addEventListener]('touchend', self.stop); - global[addEventListener]('touchcancel', self.stop); - global[addEventListener]('mousemove', self.move); - global[addEventListener]('touchmove', self.move); - - // Disable selection. Disable! - a[addEventListener]('selectstart', NOOP); - a[addEventListener]('dragstart', NOOP); - b[addEventListener]('selectstart', NOOP); - b[addEventListener]('dragstart', NOOP); - - a.style.userSelect = 'none'; - a.style.webkitUserSelect = 'none'; - a.style.MozUserSelect = 'none'; - a.style.pointerEvents = 'none'; - - b.style.userSelect = 'none'; - b.style.webkitUserSelect = 'none'; - b.style.MozUserSelect = 'none'; - b.style.pointerEvents = 'none'; - - // Set the cursor at multiple levels - self.gutter.style.cursor = cursor; - self.parent.style.cursor = cursor; - document.body.style.cursor = cursor; - - // Cache the initial sizes of the pair. - calculateSizes.call(self); - - // Determine the position of the mouse compared to the gutter - self.dragOffset = getMousePosition(e) - self.end; - } - - // adjust sizes to ensure percentage is within min size and gutter. - sizes = trimToMin(sizes); - - // 5. Create pair and element objects. Each pair has an index reference to - // elements `a` and `b` of the pair (first and second elements). - // Loop through the elements while pairing them off. Every pair gets a - // `pair` object and a gutter. - // - // Basic logic: - // - // - Starting with the second element `i > 0`, create `pair` objects with - // `a = i - 1` and `b = i` - // - Set gutter sizes based on the _pair_ being first/last. The first and last - // pair have gutterSize / 2, since they only have one half gutter, and not two. - // - Create gutter elements and add event listeners. - // - Set the size of the elements, minus the gutter sizes. - // - // ----------------------------------------------------------------------- - // | i=0 | i=1 | i=2 | i=3 | - // | | | | | - // | pair 0 pair 1 pair 2 | - // | | | | | - // ----------------------------------------------------------------------- - var pairs = []; - elements = ids.map(function (id, i) { - // Create the element object. - var element = { - element: elementOrSelector(id), - size: sizes[i], - minSize: minSizes[i], - i: i, - }; - - var pair; - - if (i > 0) { - // Create the pair object with its metadata. - pair = { - a: i - 1, - b: i, - dragging: false, - direction: direction, - parent: parent, - }; - - pair[aGutterSize] = getGutterSize( - gutterSize, - i - 1 === 0, - false, - gutterAlign - ); - pair[bGutterSize] = getGutterSize( - gutterSize, - false, - i === ids.length - 1, - gutterAlign - ); - - // if the parent has a reverse flex-direction, switch the pair elements. - if ( - parentFlexDirection === 'row-reverse' || - parentFlexDirection === 'column-reverse' - ) { - var temp = pair.a; - pair.a = pair.b; - pair.b = temp; - } - } - - // Determine the size of the current element. IE8 is supported by - // staticly assigning sizes without draggable gutters. Assigns a string - // to `size`. - // - // IE9 and above - if (!isIE8) { - // Create gutter elements for each pair. - if (i > 0) { - var gutterElement = gutter(i, direction, element.element); - setGutterSize(gutterElement, gutterSize, i); - - // Save bound event listener for removal later - pair[gutterStartDragging] = startDragging.bind(pair); - - // Attach bound event listener - gutterElement[addEventListener]( - 'mousedown', - pair[gutterStartDragging] - ); - gutterElement[addEventListener]( - 'touchstart', - pair[gutterStartDragging] - ); - - parent.insertBefore(gutterElement, element.element); - - pair.gutter = gutterElement; - } - } - - setElementSize( - element.element, - element.size, - getGutterSize( - gutterSize, - i === 0, - i === ids.length - 1, - gutterAlign - ), - i - ); - - // After the first iteration, and we have a pair object, append it to the - // list of pairs. - if (i > 0) { - pairs.push(pair); - } - - return element - }); - - function adjustToMin(element) { - var isLast = element.i === pairs.length; - var pair = isLast ? pairs[element.i - 1] : pairs[element.i]; - - calculateSizes.call(pair); - - var size = isLast - ? pair.size - element.minSize - pair[bGutterSize] - : element.minSize + pair[aGutterSize]; - - adjust.call(pair, size); - } - - elements.forEach(function (element) { - var computedSize = element.element[getBoundingClientRect]()[dimension]; - - if (computedSize < element.minSize) { - if (expandToMin) { - adjustToMin(element); - } else { - // eslint-disable-next-line no-param-reassign - element.minSize = computedSize; - } - } - }); - - function setSizes(newSizes) { - var trimmed = trimToMin(newSizes); - trimmed.forEach(function (newSize, i) { - if (i > 0) { - var pair = pairs[i - 1]; - - var a = elements[pair.a]; - var b = elements[pair.b]; - - a.size = trimmed[i - 1]; - b.size = newSize; - - setElementSize(a.element, a.size, pair[aGutterSize], a.i); - setElementSize(b.element, b.size, pair[bGutterSize], b.i); - } - }); - } - - function destroy(preserveStyles, preserveGutter) { - pairs.forEach(function (pair) { - if (preserveGutter !== true) { - pair.parent.removeChild(pair.gutter); - } else { - pair.gutter[removeEventListener]( - 'mousedown', - pair[gutterStartDragging] - ); - pair.gutter[removeEventListener]( - 'touchstart', - pair[gutterStartDragging] - ); - } - - if (preserveStyles !== true) { - var style = elementStyle( - dimension, - pair.a.size, - pair[aGutterSize] - ); - - Object.keys(style).forEach(function (prop) { - elements[pair.a].element.style[prop] = ''; - elements[pair.b].element.style[prop] = ''; - }); - } - }); - } - - if (isIE8) { - return { - setSizes: setSizes, - destroy: destroy, - } - } - - return { - setSizes: setSizes, - getSizes: getSizes, - collapse: function collapse(i) { - adjustToMin(elements[i]); - }, - destroy: destroy, - parent: parent, - pairs: pairs, - } - }; - - return Split; - -}))); diff --git a/docs/assets/style.css b/docs/assets/style.css deleted file mode 100644 index 0618f43..0000000 --- a/docs/assets/style.css +++ /dev/null @@ -1,147 +0,0 @@ -.documentation { - font-family: Helvetica, sans-serif; - color: #666; - line-height: 1.5; - background: #f5f5f5; -} - -.black { - color: #666; -} - -.bg-white { - background-color: #fff; -} - -h4 { - margin: 20px 0 10px 0; -} - -.documentation h3 { - color: #000; -} - -.border-bottom { - border-color: #ddd; -} - -a { - color: #1184ce; - text-decoration: none; -} - -.documentation a[href]:hover { - text-decoration: underline; -} - -a:hover { - cursor: pointer; -} - -.py1-ul li { - padding: 5px 0; -} - -.max-height-100 { - max-height: 100%; -} - -.height-viewport-100 { - height: 100vh; -} - -section:target h3 { - font-weight: 700; -} - -.documentation td, -.documentation th { - padding: 0.25rem 0.25rem; -} - -h1:hover .anchorjs-link, -h2:hover .anchorjs-link, -h3:hover .anchorjs-link, -h4:hover .anchorjs-link { - opacity: 1; -} - -.fix-3 { - width: 25%; - max-width: 244px; -} - -.fix-3 { - width: 25%; - max-width: 244px; -} - -@media (min-width: 52em) { - .fix-margin-3 { - margin-left: 25%; - } -} - -.pre, -pre, -code, -.code { - font-family: Source Code Pro, Menlo, Consolas, Liberation Mono, monospace; - font-size: 14px; -} - -.fill-light { - background: #f9f9f9; -} - -.width2 { - width: 1rem; -} - -.input { - font-family: inherit; - display: block; - width: 100%; - height: 2rem; - padding: 0.5rem; - margin-bottom: 1rem; - border: 1px solid #ccc; - font-size: 0.875rem; - border-radius: 3px; - box-sizing: border-box; -} - -table { - border-collapse: collapse; -} - -.prose table th, -.prose table td { - text-align: left; - padding: 8px; - border: 1px solid #ddd; -} - -.prose table th:nth-child(1) { - border-right: none; -} -.prose table th:nth-child(2) { - border-left: none; -} - -.prose table { - border: 1px solid #ddd; -} - -.prose-big { - font-size: 18px; - line-height: 30px; -} - -.quiet { - opacity: 0.7; -} - -.minishadow { - box-shadow: 2px 2px 10px #f3f3f3; -} diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index d9fc1a4..0000000 --- a/docs/index.html +++ /dev/null @@ -1,2395 +0,0 @@ - - - - - @openaddresses/deploy 5.3.1 | Documentation - - - - - - - -
-
-
-

@openaddresses/deploy

-
5.3.1
- -
- -
- -
-
-
- - -
- - -
- -

- GH -

- - -
- - - -
new GH(creds: Credentials)
- - - - - - - - - - - -
Parameters
-
- -
-
- creds (Credentials) - Credentials object - -
- -
- -
- - - - - - - - - - - - - - - -
Instance Members
-
- -
-
-
- - deployment(stack, success) -
-
- -
- -
-
-
- - deployment_update(stack, success) -
-
- -
- -
-
-
- - deployment_delete() -
-
- -
- -
- - - - - - -
- - - - -
- - -
- -

- Credentials -

- - -
- - -

Store all credentials required for deploy functionality

- -
new Credentials(argv: Object, opts: Object)
- - - - - - - - - - - -
Parameters
-
- -
-
- argv (Object) - Command Line Arguments - -
- -
- -
-
- opts (Object) - Options Object - -
- -
- -
- - - -
Properties
-
- -
- repo (string) - : Git Repository Name - - -
- -
- sha (string) - : Current Git Commit Sha - - -
- -
- name (string) - : Git Repository Name Override - - -
- -
- stack (string) - - -
- -
- subname (string) - - -
- -
- github (string) - : Github API token if provided - - -
- -
- user (string) - : Name of the current git user - - -
- -
- user (string) - : Name of the github repo owner - - -
- -
- origin (string) - : Name of the origin repo - - -
- -
- template (string) - : path to cloudformation template - - -
- -
- profile (string) - - -
- -
- dotdeploy (Object) - - -
- -
- profiles (Object) - - -
- -
- tags (Array) - - -
- -
- region (string) - - -
- -
- accountId (string) - - -
- -
- accessKeyId (string) - - -
- -
- secretAccessKey (string) - - -
- -
- - - - - - - - - - - -
Static Members
-
- -
-
-
- - dot_deploy() -
-
- -
- -
-
-
- - gitroot() -
-
- -
- -
-
-
- - gitrepo() -
-
- -
- -
-
-
- - gituser() -
-
- -
- -
-
-
- - gitowner() -
-
- -
- -
-
-
- - gitsha() -
-
- -
- -
- - - - - - - - -
- - - - -
- - -
- -

- check -

- - -
- - -

Check if desired artifacts are present before deploying

- -
check(creds: Credentials)
- - - - - - - - - - - -
Parameters
-
- -
-
- creds (Credentials) - Credentials - -
- -
- -
- - - - - - - - - - - - - - - - - - - -
- - - - -
- - -
- -

- check -

- - -
- - -

Ensure docker artifacts are present before deploy

- -
check(creds: Credentials)
- - - - - - - - - - - -
Parameters
-
- -
-
- creds (Credentials) - Credentials - -
- -
- -
- - - - - - - - - - - - - - - - - - - -
- - - - -
- - -
- -

- check -

- - -
- - -

Ensure lambda artifacts are present before deploy

- -
check(creds: Credentials)
- - - - - - - - - - - -
Parameters
-
- -
-
- creds (Credentials) - Credentials - -
- -
- -
- - - - - - - - - - - - - - - - - - - -
- - - - -
- - -
- -

- tagger -

- - -
- - -

Add additional global tags

- -
tagger(template: any, tags: any): Object
- - - - - - - - - - - -
Parameters
-
- -
-
- template (any) - -
- -
- -
-
- tags (any) - -
- -
- -
- - - - - - -
Returns
- Object: - template - - - -
Returns
- Array: - tags - - - - - - - - - - - - - - - - - - -
- - - - -
- - -
- -

- Env -

- - -
- - - -
new Env()
- - - - - - - - - - - - - - - - - - - - - - - -
Static Members
-
- -
-
-
- - help() -
-
- -
- -
-
-
- - main(creds) -
-
- -
- -
- - - - - - - - -
- - - - -
- - -
- -

- List -

- - -
- - - -
new List()
- - - - - - - - - - - - - - - - - - - - - - - -
Static Members
-
- -
-
-
- - help() -
-
- -
- -
-
-
- - main(creds, argv) -
-
- -
- -
- - - - - - - - -
- - - - -
- - -
- -

- Init -

- - -
- - - -
new Init()
- - - - - - - - - - - - - - - - - - - - - - - -
Static Members
-
- -
-
-
- - help() -
-
- -
- -
-
-
- - main() -
-
- -
- -
-
-
- - bucket(creds) -
-
- -
- -
- - - - - - - - -
- - - - -
- - -
- -

- Info -

- - -
- - - -
new Info()
- - - - - - - - - - - - - - - - - - - - - - - -
Static Members
-
- -
-
-
- - help() -
-
- -
- -
-
-
- - main(creds, argv) -
-
- -
- -
-
-
- - table(name, kv) -
-
- -
- -
- - - - - - - - -
- - - - -
- - -
- -

- Json -

- - -
- - - -
new Json()
- - - - - - - - - - - - - - - - - - - - - - - -
Static Members
-
- -
-
-
- - help() -
-
- -
- -
-
-
- - main(creds) -
-
- -
- -
- - - - - - - - -
- - - -
-
- - - - - diff --git a/eslint.config.js b/eslint.config.js index c9ffcae..ce3d313 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,39 +1,15 @@ -import js from "@eslint/js"; -import nodePlugin from "eslint-plugin-n"; +import eslint from '@eslint/js'; +import tseslint from 'typescript-eslint'; -export default [ - js.configs.recommended, - nodePlugin.configs["flat/recommended-module"], +export default tseslint.config( + { + ignores: ['dist/**', 'docs/**', 'coverage/**'] + }, + eslint.configs.recommended, + ...tseslint.configs.recommended, { "rules": { - "n/no-process-exit": "warn", - "no-console": 0, - "arrow-parens": [ "error", "always" ], - "no-var": "error", - "prefer-const": "error", - "array-bracket-spacing": [ "error", "never" ], - "comma-dangle": [ "error", "never" ], - "computed-property-spacing": [ "error", "never" ], - "eol-last": "error", - "eqeqeq": [ "error", "smart" ], - "indent": [ "error", 4, { "SwitchCase": 1 } ], - "no-confusing-arrow": [ "error", { "allowParens": false } ], - "no-extend-native": "error", - "no-mixed-spaces-and-tabs": "error", - "func-call-spacing": [ "error", "never" ], - "no-trailing-spaces": "error", - "no-unused-vars": "error", - "no-use-before-define": [ "error", "nofunc" ], - "object-curly-spacing": [ "error", "always" ], - "prefer-arrow-callback": "error", - "quotes": [ "error", "single", "avoid-escape" ], - "semi": [ "error", "always" ], - "space-infix-ops": "error", - "spaced-comment": [ "error", "always" ], - "keyword-spacing": [ "error", { "before": true, "after": true } ], - "template-curly-spacing": [ "error", "never" ], - "semi-spacing": "error", - "strict": "error", + "@typescript-eslint/no-explicit-any": "warn" } } -] +); diff --git a/lib/artifacts.js b/lib/artifacts.js deleted file mode 100644 index 6d9a5ac..0000000 --- a/lib/artifacts.js +++ /dev/null @@ -1,15 +0,0 @@ -import docker from './artifacts/docker.js'; -import s3 from './artifacts/s3.js'; - -/** - * Check if desired artifacts are present before deploying - * - * @param {Context} context Context - */ -export default async function check(context) { - await docker(context); - await s3(context); - - return true; -} - diff --git a/lib/artifacts.ts b/lib/artifacts.ts new file mode 100644 index 0000000..04c2cdb --- /dev/null +++ b/lib/artifacts.ts @@ -0,0 +1,10 @@ +import docker from './artifacts/docker.js'; +import s3 from './artifacts/s3.js'; +import type { DeployContext } from './types.js'; + +export default async function check(context: DeployContext): Promise { + await docker(context); + await s3(context); + + return true; +} diff --git a/lib/artifacts/docker.js b/lib/artifacts/docker.js deleted file mode 100644 index 385b6ee..0000000 --- a/lib/artifacts/docker.js +++ /dev/null @@ -1,104 +0,0 @@ -import { ECRClient, BatchGetImageCommand } from '@aws-sdk/client-ecr'; -import fs from 'fs'; -import ora from 'ora'; -import Handlebars from 'handlebars'; - -const retries = {}; -const MAX_RETRIES = 60; - -/** - * Ensure docker artifacts are present before deploy - * - * @param {Credentials} creds Credentials - */ -export default async function check(creds) { - const images = []; - - // docker check explicitly disabled - if ( - creds.dotdeploy.artifacts - && creds.dotdeploy.artifacts.docker === false - ) { - return; - } else if ( - !creds.dotdeploy.artifacts - || !creds.dotdeploy.artifacts.docker - ) { - // No dotdeploy or docker file found - try { - fs.accessSync('./Dockerfile'); - } catch (err) { - return; - } - - images.push('{{project}}:{{gitsha}}'); - } else if ( - creds.dotdeploy.artifacts - && creds.dotdeploy.artifacts.docker - ) { - if (typeof creds.dotdeploy.artifacts.docker === 'string') { - images.push(creds.dotdeploy.artifacts.docker); - } else { - creds.dotdeploy.artifacts.docker.forEach((image) => { - images.push(image); - }); - } - } - - for (const image of images) { - await single(creds, image); - } - - return true; -} - -function single(creds, image) { - return new Promise((resolve, reject) => { - const ecr = new ECRClient({ - credentials: creds.aws, - region: creds.region - }); - - image = Handlebars.compile(image)({ - rootStackName: `${creds.repo}-${creds.stack}`, - fullStackName: `${creds.repo}-${creds.name}`, - accountId: creds._accountId, - stack: creds.stack, - region: creds.region, - project: creds.repo, - gitsha: creds.sha - }); - - const progress = ora(`Docker Image: AWS::ECR:${image}`).start(); - - retries[image] = 0; - - if (image.split(':').length !== 2) { - return reject(new Error('docker artifact must be in format :')); - } - - checkecr(); - - async function checkecr() { - try { - const data = await ecr.send(new BatchGetImageCommand({ - imageIds: [{ imageTag: image.split(':')[1] }], - repositoryName: image.split(':')[0] - })); - - if (data && data.images.length) { - progress.succeed(); - return resolve(image); - } else if (retries[image] < MAX_RETRIES) { - retries[image] += 1; - setTimeout(checkecr, 5000); - } else { - progress.fail(); - return reject(new Error(`No image found for: ${image}`)); - } - } catch (err) { - return reject(err); - } - } - }); -} diff --git a/lib/artifacts/docker.ts b/lib/artifacts/docker.ts new file mode 100644 index 0000000..dc67e4c --- /dev/null +++ b/lib/artifacts/docker.ts @@ -0,0 +1,97 @@ +import fs from 'node:fs'; +import Handlebars from 'handlebars'; +import ora from 'ora'; +import { BatchGetImageCommand, ECRClient } from '@aws-sdk/client-ecr'; +import type { DeployContext } from '../types.js'; + +const retries = new Map(); +const MAX_RETRIES = 60; + +export default async function check(creds: DeployContext): Promise { + const images: string[] = []; + const dockerArtifacts = creds.dotdeploy.artifacts?.docker; + + if (dockerArtifacts === false) { + return; + } + + if (!dockerArtifacts) { + try { + fs.accessSync('./Dockerfile'); + } catch { + return; + } + + images.push('{{project}}:{{gitsha}}'); + } else if (typeof dockerArtifacts === 'string') { + images.push(dockerArtifacts); + } else { + images.push(...dockerArtifacts); + } + + for (const image of images) { + await single(creds, image); + } + + return true; +} + +async function single(creds: DeployContext, imageTemplate: string): Promise { + const ecr = new ECRClient({ + credentials: creds.aws, + region: creds.region + }); + + const image = Handlebars.compile(imageTemplate)({ + rootStackName: `${creds.repo}-${creds.stack}`, + fullStackName: `${creds.repo}-${creds.name}`, + accountId: creds._accountId ?? await creds.accountId(), + stack: creds.stack, + region: creds.region, + project: creds.repo, + gitsha: creds.sha + }) as string; + + const progress = ora(`Docker Image: AWS::ECR:${image}`).start(); + retries.set(image, 0); + + if (image.split(':').length !== 2) { + progress.fail(); + throw new Error('docker artifact must be in format :'); + } + + return await new Promise((resolve, reject) => { + const checkEcr = async (): Promise => { + try { + const [repositoryName, imageTag] = image.split(':'); + const data = await ecr.send(new BatchGetImageCommand({ + imageIds: [{ imageTag }], + repositoryName + })); + + if ((data.images?.length ?? 0) > 0) { + progress.succeed(); + resolve(image); + return; + } + + const attempt = retries.get(image) ?? 0; + if (attempt < MAX_RETRIES) { + retries.set(image, attempt + 1); + setTimeout(() => { + void checkEcr(); + }, 5000); + return; + } + + progress.fail(); + reject(new Error(`No image found for: ${image}`)); + } catch (error) { + progress.fail(); + reject(error); + } + }; + + void checkEcr(); + }); +} diff --git a/lib/artifacts/s3.js b/lib/artifacts/s3.js deleted file mode 100644 index d39705c..0000000 --- a/lib/artifacts/s3.js +++ /dev/null @@ -1,88 +0,0 @@ -import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; -import Handlebars from 'handlebars'; -import ora from 'ora'; - -const retries = {}; -const MAX_RETRIES = 60; - -/** - * Ensure lambda artifacts are present before deploy - * - * @param {Credentials} creds Credentials - */ -export default async function check(creds) { - const objects = []; - - if ( - creds.dotdeploy.artifacts - && creds.dotdeploy.artifacts.s3 === false - ) { - return; - } else if ( - creds.dotdeploy.artifacts - && creds.dotdeploy.artifacts.s3 - ) { - if (typeof creds.dotdeploy.artifacts.s3 === 'string') { - objects.push(creds.dotdeploy.artifacts.s3); - } else { - creds.dotdeploy.artifacts.s3.forEach((l) => { - objects.push(l); - }); - } - } - - for (const object of objects) { - await single(creds, object); - } - - return true; -} - -function single(creds, object) { - return new Promise((resolve, reject) => { - const s3 = new S3Client({ - credentials: creds.aws, - region: creds.region - }); - - object = Handlebars.compile(object)({ - rootStackName: `${creds.repo}-${creds.stack}`, - fullStackName: `${creds.repo}-${creds.name}`, - accountId: creds._accountId, - stack: creds.stack, - region: creds.region, - project: creds.repo, - gitsha: creds.sha - }); - - const progress = ora(`S3 Object: AWS::S3:${object}`).start(); - - retries[object] = 0; - - checks3(); - - async function checks3() { - try { - const data = await s3.send(new HeadObjectCommand({ - Bucket: object.split('/')[0], - Key: object.split('/').splice(1).join('/') - })); - - if (data && data.ContentLength) { - progress.succeed(); - return resolve(object); - } else { - progress.fail(); - return reject(new Error(`No object found for: ${object}`)); - } - } catch (err) { - if (err && String(err).includes('NotFound') && retries[object] < MAX_RETRIES) { - retries[object] += 1; - setTimeout(checks3, 5000); - } else { - return reject(err); - } - } - } - }); -} diff --git a/lib/artifacts/s3.ts b/lib/artifacts/s3.ts new file mode 100644 index 0000000..dc4b5ce --- /dev/null +++ b/lib/artifacts/s3.ts @@ -0,0 +1,83 @@ +import Handlebars from 'handlebars'; +import ora from 'ora'; +import { HeadObjectCommand, S3Client } from '@aws-sdk/client-s3'; +import type { DeployContext } from '../types.js'; + +const retries = new Map(); +const MAX_RETRIES = 60; + +export default async function check(creds: DeployContext): Promise { + const objects: string[] = []; + const s3Artifacts = creds.dotdeploy.artifacts?.s3; + + if (s3Artifacts === false || !s3Artifacts) { + return; + } + + if (typeof s3Artifacts === 'string') { + objects.push(s3Artifacts); + } else { + objects.push(...s3Artifacts); + } + + for (const object of objects) { + await single(creds, object); + } + + return true; +} + +async function single(creds: DeployContext, objectTemplate: string): Promise { + const s3 = new S3Client({ + credentials: creds.aws, + region: creds.region + }); + + const object = Handlebars.compile(objectTemplate)({ + rootStackName: `${creds.repo}-${creds.stack}`, + fullStackName: `${creds.repo}-${creds.name}`, + accountId: creds._accountId ?? await creds.accountId(), + stack: creds.stack, + region: creds.region, + project: creds.repo, + gitsha: creds.sha + }) as string; + + const progress = ora(`S3 Object: AWS::S3:${object}`).start(); + retries.set(object, 0); + + return await new Promise((resolve, reject) => { + const checkS3 = async (): Promise => { + try { + const [bucket, ...keyParts] = object.split('/'); + const data = await s3.send(new HeadObjectCommand({ + Bucket: bucket, + Key: keyParts.join('/') + })); + + if ((data.ContentLength ?? 0) > 0) { + progress.succeed(); + resolve(object); + return; + } + + progress.fail(); + reject(new Error(`No object found for: ${object}`)); + } catch (error) { + const attempt = retries.get(object) ?? 0; + if (String(error).includes('NotFound') && attempt < MAX_RETRIES) { + retries.set(object, attempt + 1); + setTimeout(() => { + void checkS3(); + }, 5000); + return; + } + + progress.fail(); + reject(error); + } + }; + + void checkS3(); + }); +} diff --git a/lib/cancel.js b/lib/cancel.ts similarity index 72% rename from lib/cancel.js rename to lib/cancel.ts index dc63134..c4eb9bb 100644 --- a/lib/cancel.js +++ b/lib/cancel.ts @@ -1,15 +1,9 @@ -/** - * @class - */ export default class Cancel { static short = 'Cancel a stack update, rolling it back'; - /** - * Print help documentation to the screen - */ - static help() { + static help(): void { console.log(); - console.log('Cancel a deploy to an stack, rolling it back'); + console.log('Cancel a deploy to a stack, rolling it back'); console.log(); console.log('Usage: deploy cancel [--help]'); console.log(); diff --git a/lib/commands.js b/lib/commands.ts similarity index 71% rename from lib/commands.js rename to lib/commands.ts index 3cebc64..eab7644 100644 --- a/lib/commands.js +++ b/lib/commands.ts @@ -1,15 +1,16 @@ -import env from './env.js'; -import list from './list.js'; import cancel from './cancel.js'; -import init from './init.js'; -import info from './info.js'; -import json from './json.js'; import create from './create.js'; import del from './delete.js'; -import update from './json.js'; +import env from './env.js'; import exec from './exec.js'; +import info from './info.js'; +import init from './init.js'; +import json from './json.js'; +import list from './list.js'; +import update from './update.js'; +import type { CommandModule } from './types.js'; -export default { +const commands: Record = { delete: del, create, update, @@ -21,3 +22,5 @@ export default { cancel, exec }; + +export default commands; diff --git a/lib/context.js b/lib/context.js deleted file mode 100644 index dfc5ca8..0000000 --- a/lib/context.js +++ /dev/null @@ -1,251 +0,0 @@ -import fs from 'fs'; -import path from 'path'; -import Git from './git.js'; -import AJV from 'ajv'; -import CFN from '@openaddresses/cfn-config'; -import { fromIni } from '@aws-sdk/credential-providers'; -import { STSClient, GetCallerIdentityCommand } from '@aws-sdk/client-sts'; - -const ajv = new AJV({ - allErrors: true -}); - -// Only these keys are allowed to overwrite Credentials keys -// when loaded from a .deployrc.json file -const PROFILE_KEYS = ['region', 'github']; - -/** - * Store all credentials required for deploy functionality - * - * @class - * - * @param {Object} argv Command Line Arguments - * - * @prop {string} repo Git Repository Name - * @prop {string} sha Current Git Commit Sha - * @prop {string} name Git Repository Name Override - * @prop {string} stack - * @prop {string} subname - * @prop {string} github Github API token if provided - * @prop {string} user Name of the current git user - * @prop {string} user Name of the github repo owner - * @prop {string} origin Name of the origin repo - * @prop {string} template path to cloudformation template - * @prop {string} profile - * @prop {Object} dotdeploy - * @prop {Object} profiles - * @prop {Array} tags - * @prop {string} region - * @prop {object} aws AWS Credentials - */ -export default class Credentials { - static async generate(argv) { - const creds = new Credentials(); - creds.user = Git.user(); - creds.owner = Git.owner(); - - creds.repo = Git.repo(); - creds.sha = Git.sha(); - - if (!creds.repo) throw new Error('No Git Repo detected! Are you in the correct directory? Or did you download a static non-git copy of the repo?'); - if (!creds.sha) throw new Error('Could not determine git sha'); - - // If GH deployment has been requested, store ID here - creds.deployment = false; - - creds.name = false; - creds.stack = (argv._[3] || '').replace(new RegExp(`^${this.repo}-`), ''); - creds.subname = false; - creds.template = false; - creds.profile = false; - creds.dotdeploy = {}; - creds.profiles = {}; - creds.tags = []; - - creds.region = 'us-east-1'; - - creds.github = false; - creds.force = argv.force || false; - - creds.dotdeploy = Credentials.dot_deploy(); - - let readcreds; - try { - readcreds = JSON.parse(fs.readFileSync(path.resolve(process.env.HOME, '.deployrc.json'))); - } catch (err) { - readcreds = {}; - } - - const validate = ajv.compile(JSON.parse(fs.readFileSync(new URL('../data/rc_schema.json', import.meta.url)))); - - if (!validate(readcreds)) { - console.error(JSON.stringify(validate.errors, null, 4)); - throw new Error('~/.deployrc.json does not conform to schema'); - } - - Object.keys(readcreds).forEach((key) => { - if (readcreds[key] !== undefined) { - creds.profiles[key] = readcreds[key]; - } - }); - - if (argv.template) { - creds.subname = path.parse(argv.template).name.replace(/\.template/, '') + '-'; - creds.template = argv.template; - } else if (argv.template === false) { - creds.subname = null; - creds.template = null; - } else { - creds.subname = ''; - - const cf_base = `${creds.repo}.template`; - let cf_path = false; - for (const file of fs.readdirSync(path.resolve('./cloudformation/'))) { - if (file.indexOf(cf_base) === -1) continue; - - if ( - path.parse(file).name === creds.repo + '.template' - && ( - path.parse(file).ext === '.js' - || path.parse(file).ext === '.json' - ) - ) { - cf_path = path.resolve('./cloudformation/', file); - break; - } - } - - if (!cf_path) { - throw new Error(`Could not find CF Template in cloudformation/${creds.repo}.template.js(on)`); - } - - creds.template = cf_path; - } - - if (creds.dotdeploy.name) { - creds.repo = creds.dotdeploy.name; - } - - if (argv.profile) { - creds.profile = argv.profile; - } else if (creds.dotdeploy.profile) { - creds.profile = creds.dotdeploy.profile; - } else if (Object.keys(creds.profiles).length > 1) { - throw new Error('Multiple deploy profiles found. Deploy with --profile or set a .deploy file'); - } else { - creds.profile = Object.keys(creds.profiles)[0]; - } - - if (!creds.profiles[creds.profile]) creds.profiles[creds.profile] = {}; - - PROFILE_KEYS.forEach((key) => { - if (creds.profiles[creds.profile][key] !== undefined) { - creds[key] = creds.profiles[creds.profile][key]; - } - }); - - // CLI Params override config - if (argv.region) { - creds.region = argv.region; - } else if (creds.dotdeploy.region) { - creds.region = creds.dotdeploy.region; - } - - if (argv.name) { - creds.name = argv.name.replace(new RegExp(`^${creds.repo}-`, '')); - } else { - creds.name = (creds.subname || '') + creds.stack; - } - - if (!readcreds[creds.profile]) { - readcreds[creds.profile] = {}; - } - - if (readcreds[creds.profile].tags) { - creds.tags = creds.tags.concat(readcreds[creds.profile].tags); - } - - if (creds.dotdeploy.tags) { - creds.tags = creds.tags.concat(creds.dotdeploy.tags || []); - } - - // Load GitHub polling configuration - creds.githubPolling = { - timeout: 30 * 60 * 1000, // 30 minutes default - interval: 30 * 1000 // 30 seconds default - }; - - creds.aws = {}; - - try { - creds.aws = await (await fromIni({ - profile: creds.profile - })()); - } catch (err) { - throw new Error('creds not set: run deploy init'); - } - - creds.cfn = new CFN({ - region: creds.region, - credentials: creds.aws - },{ - tags: creds.tags, - name: creds.repo, - configBucket: `cfn-config-active-${await creds.accountId()}-${creds.region}`, - templateBucket: `cfn-config-templates-${await creds.accountId()}-${creds.region}` - }); - - - return creds; - } - - /** - * Attempt to read a dot deploy file - * - * @returns {Object} Dot Deploy Object - */ - static dot_deploy() { - const attempts = [ - path.resolve('./.deploy'), - path.resolve(Git.root(), '.deploy') - ]; - - let dotdeploy = false; - - - const validate = ajv.compile(JSON.parse(fs.readFileSync(new URL('../data/schema.json', import.meta.url)))); - - for (const attempt of attempts) { - try { - dotdeploy = JSON.parse(fs.readFileSync(attempt)); - - if (!validate(dotdeploy)) { - console.error(JSON.stringify(validate.errors, null, 4)); - throw new Error(`${attempt} does not conform to schema`); - } - } catch (err) { - if (err.name === 'SyntaxError') { - throw new Error(`Invalid JSON in ${attempt} file`); - } - - continue; - } - } - - return dotdeploy; - } - - async accountId() { - if (this._accountId) return this._accountId; - - const sts = new STSClient({ - credentials: this.aws, - region: this.region - }); - - const account = await sts.send(new GetCallerIdentityCommand()); - this._accountId = account.Account; - - return this._accountId; - } -} diff --git a/lib/context.ts b/lib/context.ts new file mode 100644 index 0000000..934ffbe --- /dev/null +++ b/lib/context.ts @@ -0,0 +1,242 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import AjvModule from 'ajv'; +import CFN from '@openaddresses/cfn-config'; +import { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts'; +import { fromIni } from '@aws-sdk/credential-providers'; +import Git from './git.js'; +import type { AwsCredentials, DeployArgv, ConfigTag, DeployProfile, DotDeployConfig, GitHubPollingConfig, DeployTag } from './types.js'; + +const AjvConstructor = ((AjvModule as unknown as { default?: unknown }).default ?? AjvModule) as new (options?: object) => { + compile: (schema: object) => { + (data: unknown): boolean; + errors?: unknown; + }; +}; + +const ajv = new AjvConstructor({ + allErrors: true +}); + +const PROFILE_KEYS = ['region', 'github'] as const; + +export default class Credentials { + user = ''; + owner: string | false = false; + repo = ''; + sha = ''; + deployment: number | false = false; + name = ''; + stack = ''; + subname: string | null = ''; + template: string | null = null; + profile = ''; + dotdeploy: DotDeployConfig = {}; + profiles: Record = {}; + tags: ConfigTag[] = []; + region = 'us-east-1'; + github: string | false = false; + githubPolling: GitHubPollingConfig = { + timeout: 30 * 60 * 1000, + interval: 30 * 1000 + }; + force = false; + aws!: AwsCredentials; + cfn!: CFN; + _accountId?: string; + + static async generate(argv: DeployArgv): Promise { + const creds = new Credentials(); + creds.user = Git.user(); + creds.owner = Git.owner(); + creds.repo = Git.repo(); + creds.sha = Git.sha(); + + if (!creds.repo) { + throw new Error('No Git Repo detected! Are you in the correct directory? Or did you download a static non-git copy of the repo?'); + } + + if (!creds.sha) { + throw new Error('Could not determine git sha'); + } + + creds.stack = String(argv._[1] ?? '').replace(new RegExp(`^${creds.repo}-`), ''); + creds.force = argv.force ?? false; + creds.dotdeploy = Credentials.dot_deploy() || {}; + + const readcreds = Credentials.readProfiles(); + + Object.keys(readcreds).forEach((key) => { + if (readcreds[key] !== undefined) { + creds.profiles[key] = readcreds[key] as DeployProfile; + } + }); + + if (typeof argv.template === 'string') { + creds.subname = `${path.parse(argv.template).name.replace(/\.template/, '')}-`; + creds.template = argv.template; + } else if (argv.template === false) { + creds.subname = null; + creds.template = null; + } else { + creds.subname = ''; + creds.template = Credentials.findTemplatePath(creds.repo); + } + + if (creds.dotdeploy.name) { + creds.repo = creds.dotdeploy.name; + } + + if (argv.profile) { + creds.profile = argv.profile; + } else if (creds.dotdeploy.profile) { + creds.profile = creds.dotdeploy.profile; + } else if (Object.keys(creds.profiles).length > 1) { + throw new Error('Multiple deploy profiles found. Deploy with --profile or set a .deploy file'); + } else { + creds.profile = Object.keys(creds.profiles)[0] ?? 'default'; + } + + if (!creds.profiles[creds.profile]) { + creds.profiles[creds.profile] = {}; + } + + PROFILE_KEYS.forEach((key) => { + const value = creds.profiles[creds.profile][key]; + if (value !== undefined) { + creds[key] = value; + } + }); + + if (argv.region) { + creds.region = argv.region; + } else if (creds.dotdeploy.region) { + creds.region = creds.dotdeploy.region; + } + + if (argv.name) { + creds.name = argv.name.replace(new RegExp(`^${creds.repo}-`), ''); + } else { + creds.name = `${creds.subname ?? ''}${creds.stack}`; + } + + const profileConfig = readcreds[creds.profile] ?? {}; + if (profileConfig.tags) { + creds.tags = creds.tags.concat(profileConfig.tags); + } + + if (creds.dotdeploy.tags) { + creds.tags = creds.tags.concat(creds.dotdeploy.tags); + } + + try { + creds.aws = await (await fromIni({ + profile: creds.profile + })()) as Credentials['aws']; + } catch { + throw new Error('creds not set: run deploy init'); + } + + const accountId = await creds.accountId(); + creds.cfn = new CFN({ + region: creds.region, + credentials: creds.aws + }, { + tags: creds.tags.filter((t): t is DeployTag => typeof t !== 'string'), + name: creds.repo, + configBucket: `cfn-config-active-${accountId}-${creds.region}`, + templateBucket: `cfn-config-templates-${accountId}-${creds.region}` + }); + + return creds; + } + + static dot_deploy(): DotDeployConfig | false { + const attempts = Array.from(new Set([ + path.resolve('./.deploy'), + path.resolve(Git.root(), '.deploy') + ])); + + const validate = ajv.compile(JSON.parse(fs.readFileSync(new URL('../data/schema.json', import.meta.url), 'utf8')) as object); + + for (const attempt of attempts) { + if (!fs.existsSync(attempt)) { + continue; + } + + let dotdeploy: DotDeployConfig; + try { + dotdeploy = JSON.parse(fs.readFileSync(attempt, 'utf8')) as DotDeployConfig; + } catch (error) { + if (error instanceof SyntaxError) { + throw new Error(`Invalid JSON in ${attempt} file`, { cause: error }); + } + + throw error; + } + + if (!validate(dotdeploy)) { + console.error(JSON.stringify(validate.errors, null, 4)); + throw new Error(`${attempt} does not conform to schema`); + } + + return dotdeploy; + } + + return false; + } + + async accountId(): Promise { + if (this._accountId) { + return this._accountId; + } + + const sts = new STSClient({ + credentials: this.aws, + region: this.region + }); + + const account = await sts.send(new GetCallerIdentityCommand({})); + if (!account.Account) { + throw new Error('Unable to determine AWS account ID'); + } + + this._accountId = account.Account; + return this._accountId; + } + + private static readProfiles(): Record { + let readcreds: Record; + try { + const raw = fs.readFileSync(path.resolve(process.env.HOME ?? '', '.deployrc.json'), 'utf8'); + readcreds = JSON.parse(raw) as Record; + } catch { + readcreds = {}; + } + + const validate = ajv.compile(JSON.parse(fs.readFileSync(new URL('../data/rc_schema.json', import.meta.url), 'utf8')) as object); + if (!validate(readcreds)) { + console.error(JSON.stringify(validate.errors, null, 4)); + throw new Error('~/.deployrc.json does not conform to schema'); + } + + return readcreds; + } + + private static findTemplatePath(repo: string): string { + const baseName = `${repo}.template`; + const cloudformationDir = path.resolve('./cloudformation/'); + for (const file of fs.readdirSync(cloudformationDir)) { + if (!file.includes(baseName)) { + continue; + } + + const parsed = path.parse(file); + if (parsed.name === baseName && (parsed.ext === '.js' || parsed.ext === '.json')) { + return path.resolve(cloudformationDir, file); + } + } + + throw new Error(`Could not find CF Template in cloudformation/${repo}.template.js(on)`); + } +} diff --git a/lib/create.js b/lib/create.ts similarity index 83% rename from lib/create.js rename to lib/create.ts index 1bd5b80..401f287 100644 --- a/lib/create.js +++ b/lib/create.ts @@ -1,13 +1,7 @@ -/** - * @class - */ export default class Create { static short = 'Create a new stack of the current repo'; - /** - * Print help documentation to the screen - */ - static help() { + static help(): void { console.log(); console.log('Create a new CloudFormation stack'); console.log(); diff --git a/lib/delete.js b/lib/delete.ts similarity index 83% rename from lib/delete.js rename to lib/delete.ts index 0fe7a69..18f3d4b 100644 --- a/lib/delete.js +++ b/lib/delete.ts @@ -1,13 +1,7 @@ -/** - * @class - */ export default class Delete { static short = 'Delete an existing stack of the current repo'; - /** - * Print help documentation to the screen - */ - static help() { + static help(): void { console.log(); console.log('Delete a CloudFormation stack'); console.log(); diff --git a/lib/env.js b/lib/env.ts similarity index 65% rename from lib/env.js rename to lib/env.ts index 4603611..a0fd1e3 100644 --- a/lib/env.js +++ b/lib/env.ts @@ -1,13 +1,9 @@ -/** - * @class - */ +import type { DeployContext } from './types.js'; + export default class Env { static short = 'Setup AWS env vars in current shell'; - /** - * Print help documentation to the screen - */ - static help() { + static help(): void { console.log(); console.log('Usage: deploy env'); console.log(); @@ -15,17 +11,15 @@ export default class Env { console.log(); } - /** - * Export environment variables into the shell - * - * @param {Context} context Context - */ - static async main(context) { + static async main(context: DeployContext): Promise { console.log(`export AWS_ACCOUNT_ID=${await context.accountId()}`); console.log(`export AWS_REGION=${context.region}`); console.log(`export AWS_ACCESS_KEY_ID=${context.aws.accessKeyId}`); console.log(`export AWS_SECRET_ACCESS_KEY=${context.aws.secretAccessKey}`); - if (context.aws.sessionToken) console.log(`export AWS_SESSION_TOKEN=${context.aws.sessionToken}`); + + if (context.aws.sessionToken) { + console.log(`export AWS_SESSION_TOKEN=${context.aws.sessionToken}`); + } console.error(`ok - [${context.profile}] environment configured`); } diff --git a/lib/exec.js b/lib/exec.js deleted file mode 100644 index 33d9c8d..0000000 --- a/lib/exec.js +++ /dev/null @@ -1,135 +0,0 @@ -import inquirer from 'inquirer'; -import { - ECSClient, - ListClustersCommand, - ListServicesCommand, - DescribeServicesCommand, - DescribeTasksCommand, - ListTasksCommand -} from '@aws-sdk/client-ecs'; -import minimist from 'minimist'; - -/** - * @class - */ -export default class Exec { - static short = 'SSH into a fargate container'; - - /** - * Print help documentation to the screen - */ - static help() { - console.log(); - console.log('Usage: deploy exec'); - console.log(); - console.log('Run a command on a FARGATE service'); - console.log(); - console.log('[options]:'); - console.log(' --region Override default region to perform operations in'); - console.log(' --cluster Set cluster to perform operation in'); - console.log(' --task Set TaskId to perform operation in'); - console.log(' --command Set command to run - defaults to /bin/bash'); - console.log(); - } - - /** - * List current stacks deployed to a given profile - * - * @param {Context} context - * @param {Object} argv - */ - static async main(context, argv) { - argv = minimist(argv, { - string: ['region', 'cluster', 'task', 'command'] - }); - - if (!argv) { - argv.region = context.region; - } - - const ecs = new ECSClient({ - credentials: context.aws, - region: context.region - }); - - if (!argv.cluster) { - const res = await ecs.send(new ListClustersCommand({})); - - Object.assign(argv, await inquirer.prompt({ - type: 'list', - name: 'cluster', - message: 'ECS Cluster', - choices: res.clusterArns.map((cluster) => { - return cluster.split('/').pop(); - }).sort() - })); - } - - if (!argv.task) { - const res = await ecs.send(new ListServicesCommand({ - cluster: argv.cluster - })); - - Object.assign(argv, await inquirer.prompt({ - type: 'list', - name: 'service', - message: 'ECS Service', - choices: res.serviceArns.map((service) => { - return service.split('/').pop(); - }).sort() - })); - - const service = await ecs.send(new DescribeServicesCommand({ - cluster: argv.cluster, - services: [argv.service] - })); - - if (!service.services[0].enableExecuteCommand) { - throw new Error('Service does not have enableExecuteCommand set to true - exec is disabled'); - } - - const tasks = await ecs.send(new ListTasksCommand({ - cluster: argv.cluster, - serviceName: argv.service - })); - - Object.assign(argv, await inquirer.prompt({ - type: 'list', - name: 'task', - message: 'ECS TASK', - choices: tasks.taskArns.map((task) => { - return task.split('/').pop(); - }).sort() - })); - } - - if (!argv.container) { - const tasks = await ecs.send(new DescribeTasksCommand({ - cluster: argv.cluster, - tasks: [argv.task] - })); - - Object.assign(argv, await inquirer.prompt({ - type: 'list', - name: 'container', - message: 'ECS Container', - choices: tasks.tasks[0].containers.map((container) => { - return container.name; - }).sort() - })); - } - - console.log(`aws ecs execute-command --cluster ${argv.cluster} --task ${argv.task} --container ${argv.container} --command ${argv.command || '/bin/bash'} --interactive`); - - /** TODO Eventually support executing directly - const exec = await ecs.send(new ExecuteCommandCommand({ - interactive: true, - cluster: argv.cluster, - task: argv.task, - container: argv.container, - command: argv.command || '/bin/bash' - })); - - */ - } -} diff --git a/lib/exec.ts b/lib/exec.ts new file mode 100644 index 0000000..01b3d9f --- /dev/null +++ b/lib/exec.ts @@ -0,0 +1,140 @@ +import inquirer from 'inquirer'; +import { parseArgs } from 'node:util'; +import { + DescribeServicesCommand, + DescribeTasksCommand, + ECSClient, + ListClustersCommand, + ListServicesCommand, + ListTasksCommand +} from '@aws-sdk/client-ecs'; +import type { DeployArgv, DeployContext } from './types.js'; + +export default class Exec { + static short = 'SSH into a fargate container'; + + static help(): void { + console.log(); + console.log('Usage: deploy exec'); + console.log(); + console.log('Run a command on a FARGATE service'); + console.log(); + console.log('[options]:'); + console.log(' --region Override default region to perform operations in'); + console.log(' --cluster Set cluster to perform operation in'); + console.log(' --task Set TaskId to perform operation in'); + console.log(' --command Set command to run - defaults to /bin/bash'); + console.log(); + } + + static async main(context: DeployContext, argvInput: string[]): Promise { + const { values } = parseArgs({ + args: argvInput, + options: { + region: { type: 'string' }, + cluster: { type: 'string' }, + task: { type: 'string' }, + command: { type: 'string' }, + container: { type: 'string' } + }, + allowPositionals: true, + strict: false + }); + const argv = { ...values, _: [] } as DeployArgv; + + if (!argv.region) { + argv.region = context.region; + } + + const ecs = new ECSClient({ + credentials: context.aws, + region: argv.region + }); + + if (!argv.cluster) { + const response = await ecs.send(new ListClustersCommand({})); + const choices = (response.clusterArns ?? []).map((cluster) => cluster.split('/').pop() ?? cluster).sort(); + + if (choices.length === 0) { + throw new Error('No ECS clusters found'); + } + + const answer = await inquirer.prompt<{ cluster: string }>({ + type: 'list', + name: 'cluster', + message: 'ECS Cluster', + choices + }); + argv.cluster = answer.cluster; + } + + if (!argv.task) { + const servicesResponse = await ecs.send(new ListServicesCommand({ + cluster: argv.cluster + })); + const serviceChoices = (servicesResponse.serviceArns ?? []).map((service) => service.split('/').pop() ?? service).sort(); + + if (serviceChoices.length === 0) { + throw new Error(`No ECS services found for cluster ${argv.cluster}`); + } + + const serviceAnswer = await inquirer.prompt<{ service: string }>({ + type: 'list', + name: 'service', + message: 'ECS Service', + choices: serviceChoices + }); + argv.service = serviceAnswer.service; + + const service = await ecs.send(new DescribeServicesCommand({ + cluster: argv.cluster, + services: [argv.service] + })); + const selectedService = service.services?.[0]; + + if (!selectedService?.enableExecuteCommand) { + throw new Error('Service does not have enableExecuteCommand set to true - exec is disabled'); + } + + const tasks = await ecs.send(new ListTasksCommand({ + cluster: argv.cluster, + serviceName: argv.service + })); + const taskChoices = (tasks.taskArns ?? []).map((task) => task.split('/').pop() ?? task).sort(); + + if (taskChoices.length === 0) { + throw new Error(`No ECS tasks found for service ${argv.service}`); + } + + const taskAnswer = await inquirer.prompt<{ task: string }>({ + type: 'list', + name: 'task', + message: 'ECS Task', + choices: taskChoices + }); + argv.task = taskAnswer.task; + } + + if (!argv.container) { + const tasks = await ecs.send(new DescribeTasksCommand({ + cluster: argv.cluster, + tasks: [argv.task ?? ''] + })); + const containerChoices = (tasks.tasks?.[0]?.containers ?? []).map((container) => container.name ?? '').filter(Boolean).sort(); + + if (containerChoices.length === 0) { + throw new Error(`No containers found for task ${argv.task}`); + } + + const containerAnswer = await inquirer.prompt<{ container: string }>({ + type: 'list', + name: 'container', + message: 'ECS Container', + choices: containerChoices + }); + argv.container = containerAnswer.container; + } + + console.log(`aws ecs execute-command --cluster ${argv.cluster} --task ${argv.task} --container ${argv.container} --command ${argv.command || '/bin/bash'} --interactive`); + } +} diff --git a/lib/gh.js b/lib/gh.js deleted file mode 100644 index 704e59e..0000000 --- a/lib/gh.js +++ /dev/null @@ -1,249 +0,0 @@ -import fs from 'node:fs'; -import ora from 'ora'; -import Git from './git.js'; - -/** - * @class - */ -export default class GH { - /** - * Create a new github API object - * - * @constructor - * @param {Context} context Context object - */ - constructor(context) { - this.url = 'https://api.github.com'; - const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url))); - - this.repo = Git.repo(); - - this.enabled = context.github; - - this.headers = { - Accept: 'application/vnd.github.v3+json', - Authorization: `Bearer ${context.github}`, - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': `openaddresses-deploy@${pkg.version}`, - 'Content-Type': 'application/json' - }; - - this.context = context; - } - - /** - * Create or update a deploy status on github.com - * - * @param {string} stack The stackname to update - * @param {boolean} success Was the deployment successful - */ - async deployment(stack, success) { - if (!this.enabled) return; - - if (success === undefined) { - success = 'pending'; - } else if (success) { - success = 'success'; - } else if (!success) { - success = 'failed'; - } - - // Poll GitHub status checks before proceeding with deployment - if (this.context.force !== true) { - try { - await this.pollStatusChecks(this.context.githubPolling); - } catch (err) { - console.error(`Status Check Polling Failed: ${err.message}`); - process.exit(1); - } - } - - if (this.context.deployment) { - return await this.deployment_update(stack, success); - } else { - const deploy_id = await this.deployment_list(stack); - - if (!deploy_id) { - await this.deployment_create(stack); - } else { - this.context.deployment = deploy_id; - - await this.deployment_update(stack, success); - } - } - } - - async status() { - const res = await fetch(this.url + `/repos/${this.context.owner}/${this.repo}/commits/${this.context.sha}/check-runs`, { - method: 'GET', - headers: this.headers - }); - - const body = await res.json(); - - if (!res.ok) { - if (this.context.force) { - console.log('warn - Error in Github Status, skipping due to --force'); - } else { - console.error(body); - throw new Error('Could not list status checks'); - } - } - - return body; - } - - /** - * Poll GitHub status checks until they pass or fail - * - * @param {Object} options - Polling options - * @param {number} options.timeout - Timeout in milliseconds (default: 30 minutes) - * @param {number} options.interval - Poll interval in milliseconds (default: 30 seconds) - * @returns {Promise} - True if checks pass, throws error if they fail - */ - async pollStatusChecks(options = {}) { - const timeout = options.timeout || 30 * 60 * 1000; // 30 minutes default - const interval = options.interval || 30 * 1000; // 30 seconds default - const startTime = Date.now(); - - const progress = ora(`GitHub Status Checks: ${this.context.sha}`).start(); - - try { - while (Date.now() - startTime < timeout) { - try { - const status = await this.status(); - - progress.text = `GitHub Status Checks: (${status.check_runs?.length || 0} checks)`; - - const completed = status.check_runs?.filter((s) => s.status === 'completed') || []; - - if (completed.length === status.check_runs?.length) { - progress.succeed(); - return; - }; - - await new Promise((resolve) => setTimeout(resolve, interval)); - } catch (error) { - if (error.message.includes('Status checks failed') || error.message.includes('encountered errors')) { - throw error; // Re-throw status check failures - } - - progress.text = `GitHub Status Checks: Error - ${error.message}`; - await new Promise((resolve) => setTimeout(resolve, interval)); - } - } - - progress.fail(`GitHub Status Checks: Timeout after ${timeout / 1000 / 60} minutes`); - throw new Error(`❌ Timeout waiting for status checks to complete after ${timeout / 1000 / 60} minutes`); - } catch (error) { - // Ensure we clean up the spinner if it's still running - if (progress.isSpinning) { - progress.fail('GitHub Status Checks: Failed'); - } - throw error; - } - } - - async deployment_list(stack) { - const url = new URL(this.url + `/repos/${this.context.owner}/${this.repo}/deployments`); - url.searchParams.append('sha', this.context.sha); - url.searchParams.append('task', 'deploy'); - url.searchParams.append('environment', stack); - - const res = await fetch(url, { - method: 'GET', - headers: this.headers - }); - - const body = await res.json(); - - if (!res.ok) { - if (this.context.force) { - console.log('warn - Error in Github Deployment List, skipping due to --force'); - } else { - console.error(body); - throw new Error('Could not list deployments'); - } - } else { - if (body.length > 0) return body[0].id; - return false; - } - } - - async deployment_create(stack) { - const res = await fetch(this.url + `/repos/${this.context.owner}/${this.repo}/deployments`, { - method: 'POST', - headers: this.headers, - body: JSON.stringify({ - ref: this.context.sha, - task: 'deploy', - environment: stack, - production_environment: ['prod', 'production'].includes(stack) - }) - }); - - const body = await res.json(); - - if (!res.ok) { - if (this.context.force) { - console.log('warn - Error in Github Deployment Creation, skipping due to --force'); - } else { - console.error(body); - throw new Error('Could not create deployment'); - } - } else { - this.context.deployment = body.id; - return true; - } - } - - /** - * Create or update a deploy status on github.com - * - * @param {string} stack The stackname to update - */ - async deployment_update(stack, success) { - const res = await fetch(this.url + `/repos/${this.context.owner}/${this.repo}/deployments/${this.context.deployment}/statuses`, { - method: 'POST', - headers: this.headers, - body: JSON.stringify({ - state: success - }) - }); - - const body = await res.json(); - - if (!res.ok) { - if (this.context.force) { - console.log('warn - Error in Github Deployment Update, skipping due to --force'); - } else { - console.error(body); - throw new Error('Could not create deployment'); - } - } else { - return body; - } - } - - /** - * delete a deployment on github.com - */ - async deployment_delete() { - const res = await fetch(this.url + `/repos/${this.context.owner}/${this.repo}/deployments/${this.context.deployment}`, { - method: 'DELETE', - headers: this.headers - }); - - const body = await res.json(); - if (!res.ok) { - if (this.context.force) { - console.log('warn - Error in Github Deployment Deletion skipping due to --force'); - } else { - console.error(body); - throw new Error('Could not delete deployment'); - } - } else { - return body; - } - } -} diff --git a/lib/gh.ts b/lib/gh.ts new file mode 100644 index 0000000..17c66c3 --- /dev/null +++ b/lib/gh.ts @@ -0,0 +1,246 @@ +import fs from 'node:fs'; +import ora from 'ora'; +import Git from './git.js'; +import type { DeployContext, GitHubPollingConfig } from './types.js'; + +type DeploymentState = 'pending' | 'success' | 'failure'; + +interface GitHubCheckRun { + name?: string; + status?: string; + conclusion?: string | null; +} + +interface GitHubCheckRunsResponse { + check_runs?: GitHubCheckRun[]; +} + +interface GitHubDeployment { + id: number; +} + +export default class GH { + readonly url = 'https://api.github.com'; + readonly repo: string; + readonly enabled: boolean; + readonly headers: Record; + readonly context: DeployContext; + + constructor(context: DeployContext) { + const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }; + + this.repo = Git.repo(); + this.enabled = Boolean(context.github); + this.headers = { + Accept: 'application/vnd.github.v3+json', + Authorization: `Bearer ${context.github ?? ''}`, + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': `openaddresses-deploy@${pkg.version}`, + 'Content-Type': 'application/json' + }; + this.context = context; + } + + async deployment(stack: string, success?: boolean): Promise { + if (!this.enabled) { + return; + } + + const state = this.deploymentState(success); + + if (state === 'pending' && this.context.force !== true) { + try { + await this.pollStatusChecks(this.context.githubPolling); + } catch (error) { + const err = asError(error); + console.error(`Status Check Polling Failed: ${err.message}`); + process.exit(1); + } + } + + if (this.context.deployment) { + await this.deployment_update(stack, state); + return; + } + + const deploymentId = await this.deployment_list(stack); + if (!deploymentId) { + await this.deployment_create(stack); + if (state !== 'pending') { + await this.deployment_update(stack, state); + } + return; + } + + this.context.deployment = deploymentId; + await this.deployment_update(stack, state); + } + + async status(): Promise { + const response = await fetch(`${this.url}/repos/${this.context.owner}/${this.repo}/commits/${this.context.sha}/check-runs`, { + method: 'GET', + headers: this.headers + }); + + const body = await response.json() as GitHubCheckRunsResponse; + if (!response.ok) { + if (this.context.force) { + console.log('warn - Error in Github Status, skipping due to --force'); + return { check_runs: [] }; + } + + console.error(body); + throw new Error('Could not list status checks'); + } + + return body; + } + + async pollStatusChecks(options: Partial = {}): Promise { + const timeout = options.timeout ?? 30 * 60 * 1000; + const interval = options.interval ?? 30 * 1000; + const startTime = Date.now(); + const progress = ora(`GitHub Status Checks: ${this.context.sha}`).start(); + + try { + while (Date.now() - startTime < timeout) { + const status = await this.status(); + const checks = status.check_runs ?? []; + const completed = checks.filter((check) => check.status === 'completed'); + const failed = completed.filter((check) => { + const conclusion = check.conclusion ?? ''; + return !['success', 'neutral', 'skipped'].includes(conclusion); + }); + + progress.text = `GitHub Status Checks: (${checks.length} checks)`; + + if (failed.length > 0) { + const names = failed.map((check) => check.name ?? 'unknown').join(', '); + throw new Error(`Status checks failed: ${names}`); + } + + if (checks.length > 0 && completed.length === checks.length) { + progress.succeed(); + return; + } + + await new Promise((resolve) => setTimeout(resolve, interval)); + } + + progress.fail(`GitHub Status Checks: Timeout after ${timeout / 1000 / 60} minutes`); + throw new Error(`Timeout waiting for status checks to complete after ${timeout / 1000 / 60} minutes`); + } catch (error) { + if (progress.isSpinning) { + progress.fail('GitHub Status Checks: Failed'); + } + + throw error; + } + } + + async deployment_list(stack: string): Promise { + const url = new URL(`${this.url}/repos/${this.context.owner}/${this.repo}/deployments`); + url.searchParams.append('sha', this.context.sha); + url.searchParams.append('task', 'deploy'); + url.searchParams.append('environment', stack); + + const response = await fetch(url, { + method: 'GET', + headers: this.headers + }); + const body = await response.json() as GitHubDeployment[]; + + if (!response.ok) { + if (this.context.force) { + console.log('warn - Error in Github Deployment List, skipping due to --force'); + return false; + } + + console.error(body); + throw new Error('Could not list deployments'); + } + + return body.length > 0 ? body[0].id : false; + } + + async deployment_create(stack: string): Promise { + const response = await fetch(`${this.url}/repos/${this.context.owner}/${this.repo}/deployments`, { + method: 'POST', + headers: this.headers, + body: JSON.stringify({ + ref: this.context.sha, + task: 'deploy', + environment: stack, + production_environment: ['prod', 'production'].includes(stack) + }) + }); + const body = await response.json() as GitHubDeployment; + + if (!response.ok) { + if (this.context.force) { + console.log('warn - Error in Github Deployment Creation, skipping due to --force'); + return; + } + + console.error(body); + throw new Error('Could not create deployment'); + } + + this.context.deployment = body.id; + } + + async deployment_update(_stack: string, success: DeploymentState): Promise { + const response = await fetch(`${this.url}/repos/${this.context.owner}/${this.repo}/deployments/${this.context.deployment}/statuses`, { + method: 'POST', + headers: this.headers, + body: JSON.stringify({ + state: success + }) + }); + const body = await response.json() as unknown; + + if (!response.ok) { + if (this.context.force) { + console.log('warn - Error in Github Deployment Update, skipping due to --force'); + return body; + } + + console.error(body); + throw new Error('Could not create deployment'); + } + + return body; + } + + async deployment_delete(): Promise { + const response = await fetch(`${this.url}/repos/${this.context.owner}/${this.repo}/deployments/${this.context.deployment}`, { + method: 'DELETE', + headers: this.headers + }); + const body = await response.json() as unknown; + + if (!response.ok) { + if (this.context.force) { + console.log('warn - Error in Github Deployment Deletion skipping due to --force'); + return body; + } + + console.error(body); + throw new Error('Could not delete deployment'); + } + + return body; + } + + private deploymentState(success?: boolean): DeploymentState { + if (success === undefined) { + return 'pending'; + } + + return success ? 'success' : 'failure'; + } +} + +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} diff --git a/lib/git.js b/lib/git.js deleted file mode 100644 index 4d23360..0000000 --- a/lib/git.js +++ /dev/null @@ -1,114 +0,0 @@ -import path from 'path'; -import cp from 'child_process'; - -/** - * @class - */ -export default class Git { - /** - * Return top level dir of a git repo - * @return {string} - */ - static root() { - const git = cp.spawnSync('git', [ - 'rev-parse', '--show-toplevel' - ]); - - if (!git.stdout) return (new Error('Is this a git repo? Could not determine Git Root Directory')); - return String(git.stdout).replace(/\n/g, ''); - } - - /** - * Get the name of the current GitRepo - * @return {string} - */ - static repo() { - return path.parse(this.root()).name; - } - - /** - * Get the name of the current git user - * @return {string} - */ - static user() { - const git = cp.spawnSync('git', [ - 'config', 'user.name' - ]); - - if (!git.stdout) return (new Error('Is this a git repo? Could not determine GitSha')); - return String(git.stdout).replace(/\n/g, ''); - } - - /** - * Get the name of the upstream git owner - * @return {string} - */ - static owner() { - const git = cp.spawnSync('git', [ - 'config', '--get', 'remote.origin.url' - ]); - - if (!String(git.stdout)) return false; - - const owner = String(git.stdout).replace(/\n/g, ''); - - if (owner.includes('git@github.com')) { - return owner - .replace(/.*git@github.com:/, '') - .replace(/\/.*/, ''); - } else if (owner.match('https://.*github.com')) { - const giturl = new URL(owner); - - return giturl.pathname - .replace('.git', '') - .slice(1) - .replace(/\/.*/, ''); - } else { - throw new Error('only origins of format: git@github.com or https://github.com are supported'); - } - } - - /** - * Get the current GitSha - * - * @returns {String} - */ - static sha() { - const git = cp.spawnSync('git', [ - '--git-dir', path.resolve(this.root(), '.git'), - 'rev-parse', 'HEAD' - ]); - - if (!git.stdout) return (new Error('Is this a git repo? Could not determine GitSha')); - return String(git.stdout).replace(/\n/g, ''); - - } - - /** - * Determine if there are uncommitted changes in the repo - * - * @returns {Boolean} - */ - static uncommitted() { - const git = cp.spawnSync('git', [ - '--git-dir', path.resolve(this.root(), '.git'), - 'status', '-s' - ]); - - return !!String(git.stdout); - } - - /** - * Determine if all commits have been pushed to remote - * - * @returns {Boolean} - */ - static pushed() { - const git = cp.spawnSync('git', [ - '--git-dir', path.resolve(this.root(), '.git'), - 'status' - ]); - - return !String(git.stdout).match(/Your branch is ahead of/); - } -} diff --git a/lib/git.ts b/lib/git.ts new file mode 100644 index 0000000..80904ab --- /dev/null +++ b/lib/git.ts @@ -0,0 +1,76 @@ +import cp from 'node:child_process'; +import path from 'node:path'; + +export default class Git { + static root(): string { + const git = cp.spawnSync('git', ['rev-parse', '--show-toplevel']); + const stdout = String(git.stdout ?? '').trim(); + + if (!stdout) { + throw new Error('Is this a git repo? Could not determine Git root directory'); + } + + return stdout; + } + + static repo(): string { + return path.parse(this.root()).name; + } + + static user(): string { + const git = cp.spawnSync('git', ['config', 'user.name']); + const stdout = String(git.stdout ?? '').trim(); + + if (!stdout) { + throw new Error('Is this a git repo? Could not determine git user'); + } + + return stdout; + } + + static owner(): string | false { + const git = cp.spawnSync('git', ['config', '--get', 'remote.origin.url']); + const stdout = String(git.stdout ?? '').trim(); + + if (!stdout) { + return false; + } + + if (stdout.includes('git@github.com')) { + return stdout + .replace(/.*git@github.com:/, '') + .replace(/\/.*/, ''); + } + + if (/https:\/\/.*github.com/.test(stdout)) { + const remoteUrl = new URL(stdout); + return remoteUrl.pathname + .replace('.git', '') + .slice(1) + .replace(/\/.*/, ''); + } + + throw new Error('only origins of format: git@github.com or https://github.com are supported'); + } + + static sha(): string { + const git = cp.spawnSync('git', ['--git-dir', path.resolve(this.root(), '.git'), 'rev-parse', 'HEAD']); + const stdout = String(git.stdout ?? '').trim(); + + if (!stdout) { + throw new Error('Is this a git repo? Could not determine GitSha'); + } + + return stdout; + } + + static uncommitted(): boolean { + const git = cp.spawnSync('git', ['--git-dir', path.resolve(this.root(), '.git'), 'status', '-s']); + return Boolean(String(git.stdout ?? '').trim()); + } + + static pushed(): boolean { + const git = cp.spawnSync('git', ['--git-dir', path.resolve(this.root(), '.git'), 'status']); + return !/Your branch is ahead of/.test(String(git.stdout ?? '')); + } +} diff --git a/lib/help.js b/lib/help.ts old mode 100755 new mode 100644 similarity index 79% rename from lib/help.js rename to lib/help.ts index bedb48f..80eea05 --- a/lib/help.js +++ b/lib/help.ts @@ -1,18 +1,17 @@ import mode from './commands.js'; -/** - * @class - */ -export default class help { - static main() { +export default class Help { + static main(): never { console.log(); console.log('Usage: deploy [--profile ] [--template ]'); console.log(' [--version] [--help]'); console.log(); - console.log('Create, manage and delete Cloudformation Resouces from the CLI'); + console.log('Create, manage and delete CloudFormation resources from the CLI'); console.log(); console.log('Subcommands:'); - for (const m in mode) console.log(` ${m.padEnd(12)} [--help] ${mode[m].short}`); + for (const name of Object.keys(mode)) { + console.log(` ${name.padEnd(12)} [--help] ${mode[name].short}`); + } console.log(); console.log('[options]:'); console.log(' --region Override default region to perform operations in'); @@ -20,7 +19,7 @@ export default class help { console.log(' with must be defined either via a .deploy file or via this flag'); console.log(' --name Override the default naming conventions of substacks'); console.log(' --template The master template should be found at "cloudformation/.template.js(on)"'); - console.log(' if the project has multiple CF Templates, they can be deployed by specifying'); + console.log(' if the project has multiple CF templates, they can be deployed by specifying'); console.log(' their location with this flag. The stack will be named:'); console.log(' --