diff --git a/.eslintrc.js b/.eslintrc.js index 23d8ff0..183fa50 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -22,4 +22,4 @@ module.exports = { }, }, ], -} +}; diff --git a/.prettierrc b/.prettierrc index bc613e4..78c2a69 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,6 +1,5 @@ { "singleQuote": true, - "semi": false, "printWidth": 100, "arrowParens": "avoid" } diff --git a/generate-local.js b/generate-local.js index 2829eed..c538aab 100644 --- a/generate-local.js +++ b/generate-local.js @@ -1,99 +1,99 @@ -import chalk from 'chalk' -import commandExists from 'command-exists' -import execa from 'execa' -import { copyFileSync, ensureFileSync, existsSync, removeSync } from 'fs-extra' -import minimist from 'minimist' -import path from 'path' +import chalk from 'chalk'; +import commandExists from 'command-exists'; +import execa from 'execa'; +import { copyFileSync, ensureFileSync, existsSync, removeSync } from 'fs-extra'; +import minimist from 'minimist'; +import path from 'path'; -const docsPath = '../ember-api-docs-data' +const docsPath = '../ember-api-docs-data'; -const argv = minimist(process.argv.slice(2)) +const argv = minimist(process.argv.slice(2)); -const { project, version, install } = argv +const { project, version, install } = argv; const exit = function exit() { - console.log(...arguments) - process.exit(1) -} + console.log(...arguments); + process.exit(1); +}; async function runCmd(cmd, path, args = []) { - console.log(chalk.underline(`Running '${chalk.green(cmd)}' in ${path}`)) - const executedCmd = await execa(cmd, args, { cwd: path, shell: true, stdio: 'inherit' }) + console.log(chalk.underline(`Running '${chalk.green(cmd)}' in ${path}`)); + const executedCmd = await execa(cmd, args, { cwd: path, shell: true, stdio: 'inherit' }); if (executedCmd.failed) { - console.error(executedCmd.stdout) - console.error(executedCmd.stderr) - process.exit(1) + console.error(executedCmd.stdout); + console.error(executedCmd.stderr); + process.exit(1); } - console.log(executedCmd.stdout + '\n') + console.log(executedCmd.stdout + '\n'); } -;(async () => { +(async () => { if (!project || !version) { exit( chalk.red('Both project and version args are required.\n'), chalk.yellow(' e.g., yarn gen --project ember --version 3.10.1'), - ) + ); } if (!['ember', 'ember-data'].includes(project)) { - exit(chalk.red(`Project has to be either 'ember' or 'ember-data'. (was given ${project})\n`)) + exit(chalk.red(`Project has to be either 'ember' or 'ember-data'. (was given ${project})\n`)); } try { - await commandExists('yarn') + await commandExists('yarn'); } catch (e) { - exit(chalk.red('We need yarn installed globally for this script to work')) + exit(chalk.red('We need yarn installed globally for this script to work')); } - let emberProjectPath = path.join(__dirname, '../', 'ember.js') - let emberDataProjectPath = path.join(__dirname, '../', 'data') + let emberProjectPath = path.join(__dirname, '../', 'ember.js'); + let emberDataProjectPath = path.join(__dirname, '../', 'data'); let checkIfProjectDirExists = dirPath => { if (!existsSync(dirPath)) { - exit(chalk.yellow(`Please checkout the ${project} project at ${dirPath}`)) + exit(chalk.yellow(`Please checkout the ${project} project at ${dirPath}`)); } - } + }; let buildDocs = async projDirPath => { - checkIfProjectDirExists(projDirPath) + checkIfProjectDirExists(projDirPath); if (project === 'ember') { - await runCmd('volta', projDirPath, ['run', 'yarn']) + await runCmd('volta', projDirPath, ['run', 'yarn']); } else { - await runCmd('corepack', projDirPath, ['pnpm', 'install']) + await runCmd('corepack', projDirPath, ['pnpm', 'install']); } if (install) { - await runCmd(project === 'ember' ? 'yarn' : 'pnpm install', projDirPath) - console.log('\n\n') + await runCmd(project === 'ember' ? 'yarn' : 'pnpm install', projDirPath); + console.log('\n\n'); } await runCmd( project === 'ember' ? 'volta run yarn docs' : 'corepack pnpm run build:docs', projDirPath, - ) + ); - let destination = `${docsPath}/s3-docs/v${version}/${project}-docs.json` - ensureFileSync(destination) - const projYuiDocFile = destination - removeSync(projYuiDocFile) - removeSync(`${docsPath}/json-docs/${project}/${version}`) + let destination = `${docsPath}/s3-docs/v${version}/${project}-docs.json`; + ensureFileSync(destination); + const projYuiDocFile = destination; + removeSync(projYuiDocFile); + removeSync(`${docsPath}/json-docs/${project}/${version}`); const yuiDocFile = path.join( projDirPath, project === 'ember' ? 'docs/data.json' : 'packages/-ember-data/dist/docs/data.json', - ) - copyFileSync(yuiDocFile, projYuiDocFile) - } + ); + copyFileSync(yuiDocFile, projYuiDocFile); + }; let dirMap = { ember: emberProjectPath, 'ember-data': emberDataProjectPath, - } + }; - await buildDocs(dirMap[project]) + await buildDocs(dirMap[project]); await execa('volta', [ 'run', @@ -104,5 +104,5 @@ async function runCmd(cmd, path, args = []) { '--version', version, '--no-sync', - ]).stdout.pipe(process.stdout) -})() + ]).stdout.pipe(process.stdout); +})(); diff --git a/index.js b/index.js index 19e0254..25fdf93 100644 --- a/index.js +++ b/index.js @@ -1,15 +1,15 @@ // eslint-disable-next-line require = require('esm')(module /*, options*/) -const argv = require('minimist')(process.argv.slice(2)) +const argv = require('minimist')(process.argv.slice(2)); -let possibleProjects = ['ember', 'ember-data'] +let possibleProjects = ['ember', 'ember-data']; let projects = - argv.project && possibleProjects.includes(argv.project) ? [argv.project] : possibleProjects -let specificDocsVersion = argv.version ? argv.version : '' + argv.project && possibleProjects.includes(argv.project) ? [argv.project] : possibleProjects; +let specificDocsVersion = argv.version ? argv.version : ''; -let runClean = !!argv.clean -let noSync = !argv.sync +let runClean = !!argv.clean; +let noSync = !argv.sync; -const { apiDocsProcessor } = require('./main.js') -apiDocsProcessor(projects, specificDocsVersion, runClean, noSync) +const { apiDocsProcessor } = require('./main.js'); +apiDocsProcessor(projects, specificDocsVersion, runClean, noSync); diff --git a/lib/add-inherited-items.js b/lib/add-inherited-items.js index 208eca8..a06de96 100644 --- a/lib/add-inherited-items.js +++ b/lib/add-inherited-items.js @@ -1,50 +1,50 @@ -import _ from 'lodash' +import _ from 'lodash'; export default function addInheritedItems(docSets) { docSets.forEach(versionData => { - let data = versionData.data - let classes = _.values(data.classes).filter(klass => klass && klass.name) - classes = classes.filter(removeLongDocsBecauseEmber1HasWeirdDocs) - let classItems = data.classitems.filter(({ itemtype }) => itemtype) + let data = versionData.data; + let classes = _.values(data.classes).filter(klass => klass && klass.name); + classes = classes.filter(removeLongDocsBecauseEmber1HasWeirdDocs); + let classItems = data.classitems.filter(({ itemtype }) => itemtype); classes.forEach(klass => { - let parents = getParents(klass, classes) + let parents = getParents(klass, classes); for (let i = 0; i < parents.length; ++i) { - parents = parents.concat(getParents(parents[i], classes)) + parents = parents.concat(getParents(parents[i], classes)); } parents.forEach(parent => { - if (!parent) return - let parentItems = classItems.filter(item => item.class === parent.name) + if (!parent) return; + let parentItems = classItems.filter(item => item.class === parent.name); parentItems = parentItems.map(item => { - item = _.clone(item) - item.inherited = true - item.inheritedFrom = item.class - item.class = klass.name - return item - }) - data.classitems = data.classitems.concat(parentItems) - }) - }) - }) + item = _.clone(item); + item.inherited = true; + item.inheritedFrom = item.class; + item.class = klass.name; + return item; + }); + data.classitems = data.classitems.concat(parentItems); + }); + }); + }); - return Promise.resolve(docSets) + return Promise.resolve(docSets); } function getParents(klass, classes) { - let parents = [] + let parents = []; if (klass.extends) { - parents = parents.concat([klass.extends]) + parents = parents.concat([klass.extends]); } if (klass.uses && klass.uses.length) { - parents = parents.concat(klass.uses.reverse()) + parents = parents.concat(klass.uses.reverse()); } return parents .map(parent => _.find(classes, ({ name }) => name === parent)) - .filter(parent => parent) + .filter(parent => parent); } function removeLongDocsBecauseEmber1HasWeirdDocs({ name }) { - let str = 'A Suite can' - return !name.includes(str) + let str = 'A Suite can'; + return !name.includes(str); } diff --git a/lib/add-since-tags.js b/lib/add-since-tags.js index dc68e70..ee36a0f 100644 --- a/lib/add-since-tags.js +++ b/lib/add-since-tags.js @@ -1,37 +1,37 @@ -import _ from 'lodash' +import _ from 'lodash'; export default function addSinceTags(docSets) { - let versionIndex = Object.create(null) + let versionIndex = Object.create(null); docSets.forEach(versionData => { - let data = versionData.data - let version = (versionData.version = versionData.version.replace('v', '')) - let classItems = data.classitems.filter(({ itemtype }) => itemtype) + let data = versionData.data; + let version = (versionData.version = versionData.version.replace('v', '')); + let classItems = data.classitems.filter(({ itemtype }) => itemtype); classItems.forEach(classItem => { - let classItemName = `${classItem.class}#${classItem.name}` - classItem.version = version - createMethodEntry(versionIndex, classItemName, classItem.itemtype, version) - }) + let classItemName = `${classItem.class}#${classItem.name}`; + classItem.version = version; + createMethodEntry(versionIndex, classItemName, classItem.itemtype, version); + }); - let classes = _.values(data.classes) + let classes = _.values(data.classes); classes.forEach(klass => { - klass.version = version - createMethodEntry(versionIndex, klass.name, 'class', version) - }) - }) + klass.version = version; + createMethodEntry(versionIndex, klass.name, 'class', version); + }); + }); - sortVersionIndex(versionIndex) + sortVersionIndex(versionIndex); - let classItems = classItemsWithItemType(docSets) + let classItems = classItemsWithItemType(docSets); classItems.forEach(classItem => { - let classItemName = `${classItem.class}#${classItem.name}` - let version = versionIndex[classItem.itemtype][classItemName][0] + let classItemName = `${classItem.class}#${classItem.name}`; + let version = versionIndex[classItem.itemtype][classItemName][0]; - classItem.since = version - }) + classItem.since = version; + }); let classes = _.chain(docSets) .map('data') @@ -39,29 +39,29 @@ export default function addSinceTags(docSets) { .flatten() .map(klassSet => _.values(klassSet)) .flatten() - .value() + .value(); - classes.forEach(klass => (klass.since = versionIndex['class'][klass.name][0])) + classes.forEach(klass => (klass.since = versionIndex['class'][klass.name][0])); - return Promise.resolve(docSets) + return Promise.resolve(docSets); } function sortVersionIndex(versionIndex) { - let keys = Object.keys(versionIndex) + let keys = Object.keys(versionIndex); keys.forEach(key => Object.keys(versionIndex[key]).forEach(item => versionIndex[key][item].sort()), - ) + ); } const createMethodEntry = (versionIndex, method, itemType, version) => { - versionIndex[itemType] = versionIndex[itemType] || Object.create(null) - versionIndex[itemType][method] = versionIndex[itemType][method] || [] - versionIndex[itemType][method].push(version) -} + versionIndex[itemType] = versionIndex[itemType] || Object.create(null); + versionIndex[itemType][method] = versionIndex[itemType][method] || []; + versionIndex[itemType][method].push(version); +}; const classItemsWithItemType = versions => versions.reduce( (memo, { data }) => memo.concat(data.classitems.filter(({ itemtype }) => itemtype)), [], - ) + ); diff --git a/lib/create-classes.js b/lib/create-classes.js index 690e9ac..7de934f 100644 --- a/lib/create-classes.js +++ b/lib/create-classes.js @@ -1,21 +1,21 @@ -import saveDoc from './save-document.js' +import saveDoc from './save-document.js'; export default async function (document, projectName, projectVersion) { - let things = document.data + let things = document.data; for (const klass of things) { if (!klass.id) { - console.log(klass) - console.log(new Error('WHAT').stack) - process.exit(1) + console.log(klass); + console.log(new Error('WHAT').stack); + process.exit(1); } const doc = { data: klass, - } + }; - console.log(`Creating ${klass.id} in ${projectName}-${projectVersion}`) - await saveDoc(doc, projectName, projectVersion) + console.log(`Creating ${klass.id} in ${projectName}-${projectVersion}`); + await saveDoc(doc, projectName, projectVersion); } - return document + return document; } diff --git a/lib/create-project-versions.js b/lib/create-project-versions.js index 191b092..c79edf9 100644 --- a/lib/create-project-versions.js +++ b/lib/create-project-versions.js @@ -1,12 +1,12 @@ // eslint-disable-next-line n/no-missing-import -import tojsonapi from 'yuidoc-to-jsonapi/lib/converter' -import saveDoc from './save-document.js' -import updateIDs from './update-with-versions-and-project.js' +import tojsonapi from 'yuidoc-to-jsonapi/lib/converter'; +import saveDoc from './save-document.js'; +import updateIDs from './update-with-versions-and-project.js'; export default async function createProjectVersions(versions, projectName) { - const results = [] + const results = []; for (const version of versions) { - let jsonapidoc = updateIDs(tojsonapi(version.data), version.version) + let jsonapidoc = updateIDs(tojsonapi(version.data), version.version); let projectData = { type: 'project', @@ -15,7 +15,7 @@ export default async function createProjectVersions(versions, projectName) { name: projectName, github: 'https://github.com/emberjs/ember.js', }, - } + }; let versionDocument = { data: { @@ -49,10 +49,10 @@ export default async function createProjectVersions(versions, projectName) { }, }, included: [projectData], - } + }; - const result = await saveDoc(versionDocument, projectName, version.version) - results.push(result) + const result = await saveDoc(versionDocument, projectName, version.version); + results.push(result); } - return results + return results; } diff --git a/lib/filter-jsonapi-doc.js b/lib/filter-jsonapi-doc.js index df9c945..13a1abb 100644 --- a/lib/filter-jsonapi-doc.js +++ b/lib/filter-jsonapi-doc.js @@ -1,30 +1,30 @@ -import _ from 'lodash' +import _ from 'lodash'; function byType(document, type) { - return _.filter(totalData(document), ['type', type]) + return _.filter(totalData(document), ['type', type]); } function totalData({ data, included }) { - return data.concat(included || []) + return data.concat(included || []); } function hasBelongsTo(document, relationshipName, relationshipValue) { return _.filter(totalData(document), [ `relationships.${relationshipName}.data.id`, relationshipValue, - ]) + ]); } function classWithIncluded(document, klass) { - let classDocument = _.filter(byType(document, 'class'), ['id', klass])[0] + let classDocument = _.filter(byType(document, 'class'), ['id', klass])[0]; - let related = hasBelongsTo(document, 'class', klass) + let related = hasBelongsTo(document, 'class', klass); return { data: classDocument, included: related, - } + }; } -export { byType } -export { classWithIncluded } +export { byType }; +export { classWithIncluded }; diff --git a/lib/fix-borked-yuidoc-files.js b/lib/fix-borked-yuidoc-files.js index 8628e5e..627de8d 100644 --- a/lib/fix-borked-yuidoc-files.js +++ b/lib/fix-borked-yuidoc-files.js @@ -1,8 +1,8 @@ -import fs from 'fs-extra' -import semverCompare from 'semver-compare' -import { normalizeYuiDocClassItem } from './yuidoc-fixer/normalize-yui-doc-class-item.js' -import { yuiDocClassItemKeys } from './yuidoc-fixer/yui-doc-class-item-keys.js' -import { normalizeYuiDocClass } from './yuidoc-fixer/normalize-yui-doc-class.js' +import fs from 'fs-extra'; +import semverCompare from 'semver-compare'; +import { normalizeYuiDocClassItem } from './yuidoc-fixer/normalize-yui-doc-class-item.js'; +import { yuiDocClassItemKeys } from './yuidoc-fixer/yui-doc-class-item-keys.js'; +import { normalizeYuiDocClass } from './yuidoc-fixer/normalize-yui-doc-class.js'; /** * In ember 3.10 and above we introduced decorators. @@ -14,56 +14,56 @@ import { normalizeYuiDocClass } from './yuidoc-fixer/normalize-yui-doc-class.js' * @param {*} file */ -const docsPath = '../ember-api-docs-data' +const docsPath = '../ember-api-docs-data'; export default async function fixBorkedYuidocFiles(file) { if (!file) { - return + return; } const version = file .replace(`${docsPath}/s3-docs/v`, '') .replace('/ember-docs.json', '') - .replace('/ember-data-docs.json', '') + .replace('/ember-data-docs.json', ''); if (semverCompare(version, '3.10.0') === -1) { - return file + return file; } - console.log(`\n\n\nProcessing ${file} for broken decorators usage in code samples`) + console.log(`\n\n\nProcessing ${file} for broken decorators usage in code samples`); - const doc = await fs.readJson(file) + const doc = await fs.readJson(file); let normalizedClasses = Object.keys(doc.classes).reduce((result, klass) => { - result[klass] = normalizeYuiDocClass(doc.classes[klass]) - return result - }, {}) + result[klass] = normalizeYuiDocClass(doc.classes[klass]); + return result; + }, {}); let normalizedClassItems = doc.classitems.map(item => { - let keys = Object.keys(item) - let locationOfDescriptionField = keys.indexOf('description') + let keys = Object.keys(item); + let locationOfDescriptionField = keys.indexOf('description'); if ( locationOfDescriptionField === -1 || yuiDocClassItemKeys.includes(keys[locationOfDescriptionField + 1]) ) { - return item + return item; } - return normalizeYuiDocClassItem(item) - }) + return normalizeYuiDocClassItem(item); + }); - let newDoc = {} + let newDoc = {}; Object.keys(doc).forEach(key => { if (key === 'classitems') { - newDoc[key] = normalizedClassItems + newDoc[key] = normalizedClassItems; } else if (key === 'classes') { - newDoc[key] = normalizedClasses + newDoc[key] = normalizedClasses; } else { - newDoc[key] = doc[key] + newDoc[key] = doc[key]; } - }) + }); - await fs.writeJson(file, newDoc, { spaces: 2 }) + await fs.writeJson(file, newDoc, { spaces: 2 }); } diff --git a/lib/get-latest-patch-versions.js b/lib/get-latest-patch-versions.js index a4f520e..61aa1c4 100644 --- a/lib/get-latest-patch-versions.js +++ b/lib/get-latest-patch-versions.js @@ -1,11 +1,11 @@ -import { groupBy } from 'lodash' -import semverCompare from 'semver-compare' -import semverUtils from 'semver-utils' +import { groupBy } from 'lodash'; +import semverCompare from 'semver-compare'; +import semverUtils from 'semver-utils'; export function getLatestPatchVersions(versions) { let groupedVersions = groupBy( versions.sort(semverCompare).map(semverUtils.parse), v => `${v.major}.${v.minor}`, - ) - return Object.values(groupedVersions).map(verGroup => verGroup.pop().version) + ); + return Object.values(groupedVersions).map(verGroup => verGroup.pop().version); } diff --git a/lib/get-version-index.js b/lib/get-version-index.js index 4ab93a6..b040d4a 100644 --- a/lib/get-version-index.js +++ b/lib/get-version-index.js @@ -1,4 +1,4 @@ -import { byType } from './filter-jsonapi-doc.js' +import { byType } from './filter-jsonapi-doc.js'; export default function getVersionIndex(doc, projectName) { return { @@ -14,10 +14,10 @@ export default function getVersionIndex(doc, projectName) { return { id, type, - } + }; }), }, }, }, - } + }; } diff --git a/lib/markup.js b/lib/markup.js index 2bde8ea..1337b44 100644 --- a/lib/markup.js +++ b/lib/markup.js @@ -1,89 +1,89 @@ -import { marked } from 'marked' -import hljs from 'highlight.js' -import cheerio from 'cheerio' +import { marked } from 'marked'; +import hljs from 'highlight.js'; +import cheerio from 'cheerio'; marked.setOptions({ highlight: code => hljs.highlightAuto(code).value, -}) +}); export default function (doc) { - console.log('transforming markup for document') + console.log('transforming markup for document'); for (const data of doc.data) { - const { id, attributes } = data - console.log(`\tGenerating markup for ${id}`) + const { id, attributes } = data; + console.log(`\tGenerating markup for ${id}`); try { - const description = attributes.description + const description = attributes.description; if (description) { - attributes.description = highlight(description) + attributes.description = highlight(description); } // console.log('\tcompleted highlighting') - replaceDescriptionFor(attributes.methods) - replaceDescriptionFor(attributes.properties) - replaceDescriptionFor(attributes.events) + replaceDescriptionFor(attributes.methods); + replaceDescriptionFor(attributes.properties); + replaceDescriptionFor(attributes.events); // console.log(`\tMarkup Generated for ${id}\n`) } catch (e) { - console.log(`Error generating markup for ${id}`) - console.log(e) - process.exit(1) + console.log(`Error generating markup for ${id}`); + console.log(e); + process.exit(1); } } - console.log('completed markup transformation for document') - return doc + console.log('completed markup transformation for document'); + return doc; } function replaceDescriptionFor(items) { if (items) { items.forEach(item => { - let itemDescription = item.description + let itemDescription = item.description; if (itemDescription) { - item.description = highlight(itemDescription) + item.description = highlight(itemDescription); } - }) + }); } } function highlight(description) { if (description) { description = description.replace(/&#(\d+);/g, function (match, dec) { - return String.fromCharCode(dec) - }) + return String.fromCharCode(dec); + }); } - let markedup = removeHLJSPrefix(marked.parse(description)) - let $ = cheerio.load(markedup) + let markedup = removeHLJSPrefix(marked.parse(description)); + let $ = cheerio.load(markedup); - let codeBlocks = $('pre code') + let codeBlocks = $('pre code'); codeBlocks.each((i, el) => { - let element = $(el) - let klass = element.attr('class') - let lang = '' - let tableHeader = '' + let element = $(el); + let klass = element.attr('class'); + let lang = ''; + let tableHeader = ''; if (klass) { - let type = klass.split('-').pop() + let type = klass.split('-').pop(); if (isFile(type)) { tableHeader = ` ${type} - ` + `; } - lang = determineLanguage(type) + lang = determineLanguage(type); } - let lines = element.html().split('\n') + let lines = element.html().split('\n'); // get rid of empty blank line if (lines[lines.length - 1].trim() === '') { - lines.pop() + lines.pop(); } - let wrappedLines = `
${lines.join('\n')}
` - let lineNumbers = lines.map((_, i) => `${i + 1}\n`).join('') + let wrappedLines = `
${lines.join('\n')}
`; + let lineNumbers = lines.map((_, i) => `${i + 1}\n`).join(''); element.parent().after(`
@@ -98,33 +98,33 @@ function highlight(description) {
- `) + `); - element.parent().remove() - }) + element.parent().remove(); + }); - return $.html() + return $.html(); } function determineLanguage(maybeFileName) { - const lang = maybeFileName.split('.').pop() + const lang = maybeFileName.split('.').pop(); switch (lang) { case 'js': case 'javascript': - return 'javascript' + return 'javascript'; case 'ts': - return 'typescript' + return 'typescript'; case 'hbs': - return 'handlebars' + return 'handlebars'; default: - return lang + return lang; } } function removeHLJSPrefix(string) { - return string.replace(/hljs-/g, '') + return string.replace(/hljs-/g, ''); } function isFile(string) { - return /\./.test(string) + return /\./.test(string); } diff --git a/lib/modules-transform.js b/lib/modules-transform.js index fea4ca3..c508bde 100644 --- a/lib/modules-transform.js +++ b/lib/modules-transform.js @@ -1,7 +1,7 @@ -import _ from 'lodash' +import _ from 'lodash'; function addSubModulesParentAttribute(moduleObj) { - moduleObj.parent = moduleObj.is_submodule ? moduleObj.module : null + moduleObj.parent = moduleObj.is_submodule ? moduleObj.module : null; } function filterStaticAndDerived(classes, className) { @@ -9,76 +9,76 @@ function filterStaticAndDerived(classes, className) { (_.has(classes, className) && !_.has(classes[className], 'static') && _.has(classes[className], 'file')) || - !_.has(classes, className) - return included + !_.has(classes, className); + return included; } function addPrivatePublicClassesAttributes(module, classes) { - let classNames = Object.keys(module.classes) - let applicableClassNames = _.filter(classNames, _.curry(filterStaticAndDerived)(classes)) + let classNames = Object.keys(module.classes); + let applicableClassNames = _.filter(classNames, _.curry(filterStaticAndDerived)(classes)); let [privateclasses, publicclasses] = _.partition(applicableClassNames, className => { - return classes[className].access === 'private' || classes[className].deprecated === true - }) - module.publicclasses = publicclasses - module.privateclasses = privateclasses - delete module.classes + return classes[className].access === 'private' || classes[className].deprecated === true; + }); + module.publicclasses = publicclasses; + module.privateclasses = privateclasses; + delete module.classes; } function isPublicStaticMethod(item) { - return item.itemtype === 'method' && item.access === 'public' && item.static === 1 + return item.itemtype === 'method' && item.access === 'public' && item.static === 1; } function isStaticMethod(item) { - return item.itemtype === 'method' && item.static === 1 + return item.itemtype === 'method' && item.static === 1; } function separateByClassName(result, value) { - ;(result[value.class] || (result[value.class] = [])).push(value) - return result + (result[value.class] || (result[value.class] = [])).push(value); + return result; } function sortByName(items) { - return _.sortBy(items, 'name') + return _.sortBy(items, 'name'); } function separateFunctions(moduleName, classitems, accessFilter) { - let matchesModule = ({ module }) => module === moduleName + let matchesModule = ({ module }) => module === moduleName; return _.flow([ _.curryRight(_.filter)(matchesModule), _.curryRight(_.filter)(accessFilter), sortByName, _.curryRight(_.reduce)(separateByClassName, {}), - ])(classitems) + ])(classitems); } function cleanUpSubmodules({ submodules }) { return _.flow([ _.curryRight(_.filter)(item => item !== 'undefined'), _.curryRight(_.reduce)((result, value) => { - result[value] = 1 - return result + result[value] = 1; + return result; }, {}), - ])(Object.keys(submodules)) + ])(Object.keys(submodules)); } export default function transformModules(docSets) { try { docSets.forEach(({ data }) => { - let modules = _.values(data.modules) - let classes = data.classes - let classitems = data.classitems + let modules = _.values(data.modules); + let classes = data.classes; + let classitems = data.classitems; modules.forEach(mod => { - addSubModulesParentAttribute(mod) - addPrivatePublicClassesAttributes(mod, classes) - mod.staticfunctions = separateFunctions(mod.name, classitems, isPublicStaticMethod) - mod.allstaticfunctions = separateFunctions(mod.name, classitems, isStaticMethod) - mod.submodules = cleanUpSubmodules(mod) - }) - }) + addSubModulesParentAttribute(mod); + addPrivatePublicClassesAttributes(mod, classes); + mod.staticfunctions = separateFunctions(mod.name, classitems, isPublicStaticMethod); + mod.allstaticfunctions = separateFunctions(mod.name, classitems, isStaticMethod); + mod.submodules = cleanUpSubmodules(mod); + }); + }); } catch (e) { - return Promise.reject(e) + return Promise.reject(e); } - return Promise.resolve(docSets) + return Promise.resolve(docSets); } diff --git a/lib/normalize-ember-dependencies.js b/lib/normalize-ember-dependencies.js index fd402a7..9eeddeb 100644 --- a/lib/normalize-ember-dependencies.js +++ b/lib/normalize-ember-dependencies.js @@ -1,5 +1,5 @@ -import _ from 'lodash' -import { byType } from './filter-jsonapi-doc.js' +import _ from 'lodash'; +import { byType } from './filter-jsonapi-doc.js'; const missingDoc = ({ id, version }) => { return { @@ -9,80 +9,80 @@ const missingDoc = ({ id, version }) => { name: id, version, }, - } -} + }; +}; export default giantDocument => { return new Promise(resolve => { - let nonEmberDocs = giantDocument.data.filter(({ relationships }) => relationships) + let nonEmberDocs = giantDocument.data.filter(({ relationships }) => relationships); nonEmberDocs.forEach(({ relationships, attributes }) => { _.forIn(relationships, ({ data }, relationshipName) => { if (Array.isArray(data)) { relationships[relationshipName].data = _.map(data, d => { - return fixEmberRelationship(d, attributes.version) - }) + return fixEmberRelationship(d, attributes.version); + }); } else if (data) { - relationships[relationshipName].data = fixEmberRelationship(data, attributes.version) + relationships[relationshipName].data = fixEmberRelationship(data, attributes.version); } - }) - }) + }); + }); let missing = nonEmberDocs.map(({ relationships }) => { - let missing = [] + let missing = []; _.forIn(relationships, ({ data }) => { if (Array.isArray(data)) { missing = missing .concat(data.filter(({ type }) => type === 'missing')) - .map(m => missingDoc(m)) + .map(m => missingDoc(m)); } else if (data) { if (data.type === 'missing') { - missing.push(missingDoc(data)) + missing.push(missingDoc(data)); } } - }) + }); - return missing - }) + return missing; + }); - missing = _.flatten(missing) + missing = _.flatten(missing); - giantDocument.data = giantDocument.data.concat(missing) + giantDocument.data = giantDocument.data.concat(missing); function fixEmberRelationship(relationship, version) { - let type = relationship.type - let id = relationship.id + let type = relationship.type; + let id = relationship.id; - let doc = giantDocument.data.find(model => model.id === id) + let doc = giantDocument.data.find(model => model.id === id); if (doc || type === 'project-version' || type === 'project') { - return relationship + return relationship; } else { - let nonVersionedID = id.split('-').pop() - let matchingDocuments = byType(giantDocument, type) + let nonVersionedID = id.split('-').pop(); + let matchingDocuments = byType(giantDocument, type); let latest = _(matchingDocuments) .filter(({ name }) => name === nonVersionedID) .sortBy(({ relationships }) => relationships['project-version'].data.id) .reverse() - .value()[0] + .value()[0]; if (latest) { return { id: latest.id, type: latest.type, version, - } + }; } else { return { id: id.split('-').pop(), type: 'missing', version, - } + }; } } } - resolve(giantDocument) - }) -} + resolve(giantDocument); + }); +}; diff --git a/lib/normalize-ids.js b/lib/normalize-ids.js index ffdcde6..a734528 100644 --- a/lib/normalize-ids.js +++ b/lib/normalize-ids.js @@ -1,31 +1,31 @@ -import _ from 'lodash' -import saveDoc from './save-document.js' -import tojsonapi from 'yuidoc-to-jsonapi/lib/converter.js' -import updateIDs from './update-with-versions-and-project.js' -import { byType as findType } from './filter-jsonapi-doc.js' +import _ from 'lodash'; +import saveDoc from './save-document.js'; +import tojsonapi from 'yuidoc-to-jsonapi/lib/converter.js'; +import updateIDs from './update-with-versions-and-project.js'; +import { byType as findType } from './filter-jsonapi-doc.js'; function removeLongDocsBecauseEmber1HasWeirdDocs({ id }) { - let str = 'A Suite can' - return !id.includes(str) + let str = 'A Suite can'; + return !id.includes(str); } function extractRelationship({ id, type }) { - return { id, type } + return { id, type }; } function filterForVersion(version) { return ({ relationships }) => { - const projectVersion = relationships['project-version'].data.id.split('-').pop() - return version.version === projectVersion - } + const projectVersion = relationships['project-version'].data.id.split('-').pop(); + return version.version === projectVersion; + }; } function isPrivate({ attributes }) { - return attributes.access === 'private' || attributes.deprecated === true + return attributes.access === 'private' || attributes.deprecated === true; } function isPublic({ attributes }) { - return attributes.access !== 'private' && attributes.deprecated !== true + return attributes.access !== 'private' && attributes.deprecated !== true; } /** @@ -34,41 +34,41 @@ function isPublic({ attributes }) { * Therefore we filter it out of the module list here. */ function filter176(project, version, { attributes }) { - return project !== 'ember' || parseInt(version.split('.')[1]) < 16 || attributes.name !== 'ember' + return project !== 'ember' || parseInt(version.split('.')[1]) < 16 || attributes.name !== 'ember'; } async function normalizeIDs(pVersions, projectName) { let jsonapidocs = pVersions.map(({ data, version }) => { Object.keys(data.modules).forEach(k => { - let modWithVer = data.modules[k] - modWithVer.version = version - data.modules[k] = modWithVer - }) - let doc = tojsonapi(data) - return updateIDs(doc, projectName, version) - }) + let modWithVer = data.modules[k]; + modWithVer.version = version; + data.modules[k] = modWithVer; + }); + let doc = tojsonapi(data); + return updateIDs(doc, projectName, version); + }); let jsonapidoc = { data: _.flatten(jsonapidocs.map(({ data }) => data)), - } + }; - jsonapidoc.data = jsonapidoc.data.filter(removeLongDocsBecauseEmber1HasWeirdDocs) + jsonapidoc.data = jsonapidoc.data.filter(removeLongDocsBecauseEmber1HasWeirdDocs); let projectVersions = pVersions.map(version => { let classes = findType(jsonapidoc, 'class') .filter(filterForVersion(version)) - .filter(removeLongDocsBecauseEmber1HasWeirdDocs) + .filter(removeLongDocsBecauseEmber1HasWeirdDocs); - let namespaces = classes.filter(({ attributes }) => attributes.static === 1) + let namespaces = classes.filter(({ attributes }) => attributes.static === 1); classes = classes.filter( ({ attributes }) => attributes.static !== 1 && _.has(attributes, 'file'), - ) + ); - namespaces.forEach(ns => (ns.type = 'namespace')) + namespaces.forEach(ns => (ns.type = 'namespace')); let modules = findType(jsonapidoc, 'module') .filter(filterForVersion(version)) - .filter(_.curry(filter176)(projectName, version.version)) + .filter(_.curry(filter176)(projectName, version.version)); return { id: `${projectName}-${version.version}`, @@ -111,18 +111,18 @@ async function normalizeIDs(pVersions, projectName) { data: modules.filter(isPublic).map(extractRelationship), }, }, - } - }) + }; + }); for (const projectVersion of projectVersions) { - let doc = { data: projectVersion } + let doc = { data: projectVersion }; - let version = projectVersion.attributes.version + let version = projectVersion.attributes.version; - await saveDoc(doc, projectName, version) + await saveDoc(doc, projectName, version); } - return { data: jsonapidoc.data.concat(projectVersions) } + return { data: jsonapidoc.data.concat(projectVersions) }; } -export default normalizeIDs +export default normalizeIDs; diff --git a/lib/read-docs.js b/lib/read-docs.js index 36704ee..5f70a79 100644 --- a/lib/read-docs.js +++ b/lib/read-docs.js @@ -1,66 +1,66 @@ -import fs from 'fs-extra' -import glob from 'glob' -import { dasherize } from 'inflected' -import { get as deepGet } from 'lodash' -import { getLatestPatchVersions } from './get-latest-patch-versions.js' +import fs from 'fs-extra'; +import glob from 'glob'; +import { dasherize } from 'inflected'; +import { get as deepGet } from 'lodash'; +import { getLatestPatchVersions } from './get-latest-patch-versions.js'; -const docsPath = '../ember-api-docs-data' +const docsPath = '../ember-api-docs-data'; export default function readDocs(projects, specificVersion = '', runClean = false) { return projects.reduce(async (prevPromise, projectName) => { - let prevValue = await prevPromise - let prevIndexedVersions = [] + let prevValue = await prevPromise; + let prevIndexedVersions = []; - let projectFile = `${docsPath}/json-docs/${projectName}/projects/${projectName}.json` + let projectFile = `${docsPath}/json-docs/${projectName}/projects/${projectName}.json`; - console.log(projectFile, await fs.pathExists(projectFile)) + console.log(projectFile, await fs.pathExists(projectFile)); if (await fs.pathExists(projectFile)) { - projectFile = await fs.readJson(projectFile) + projectFile = await fs.readJson(projectFile); prevIndexedVersions = deepGet(projectFile, 'data.relationships.project-versions.data').map( ({ id }) => id.replace(`${projectName}-`, ''), - ) + ); } let folders = glob.sync( `${docsPath}/s3-docs/v${specificVersion}*/${dasherize(projectName)}-docs.json`, - ) + ); let availableSourceVersions = folders.map(x => x.replace(`${docsPath}/s3-docs/v`, '').replace(`/${projectName}-docs.json`, ''), - ) + ); if (!runClean) { folders = folders.filter(f => { if (!prevIndexedVersions.includes(f)) { - return f + return f; } else { let version = f .replace(`${docsPath}/s3-docs/v`, '') - .replace(`/${projectName}-docs.json`, '') - console.log(`${projectName}-${version} has already been indexed in json-docs`) + .replace(`/${projectName}-docs.json`, ''); + console.log(`${projectName}-${version} has already been indexed in json-docs`); } - }) + }); } - availableSourceVersions = getLatestPatchVersions(availableSourceVersions) + availableSourceVersions = getLatestPatchVersions(availableSourceVersions); let docs = await Promise.all( availableSourceVersions.map(async version => { - let data + let data; try { - data = await fs.readJSON(`${docsPath}/s3-docs/v${version}/${projectName}-docs.json`) - return { project: projectName, version, data } + data = await fs.readJSON(`${docsPath}/s3-docs/v${version}/${projectName}-docs.json`); + return { project: projectName, version, data }; } catch (e) { - console.error(version) - console.error(e.stack) - process.exit(1) + console.error(version); + console.error(e.stack); + process.exit(1); } }), - ) + ); - return { ...prevValue, [projectName]: docs } - }, Promise.resolve({})) + return { ...prevValue, [projectName]: docs }; + }, Promise.resolve({})); } diff --git a/lib/rev-docs.js b/lib/rev-docs.js index a7faeed..077214a 100644 --- a/lib/rev-docs.js +++ b/lib/rev-docs.js @@ -1,62 +1,62 @@ -import fs from 'fs-extra' -import ora from 'ora' -import { basename as getFileName } from 'path' -import { singularize } from 'inflected' -import path from 'path' -const glob = require('glob') +import fs from 'fs-extra'; +import ora from 'ora'; +import { basename as getFileName } from 'path'; +import { singularize } from 'inflected'; +import path from 'path'; +const glob = require('glob'); -const docsPath = '../ember-api-docs-data' +const docsPath = '../ember-api-docs-data'; function revProjVersionFiles(project, ver) { - let opProgress = ora(`Revving ${project}:${ver} files`).start() - const projDocsDir = path.resolve(`${docsPath}/json-docs/${project}`) - const revIndexFolder = path.resolve(`${docsPath}/rev-index`) + let opProgress = ora(`Revving ${project}:${ver} files`).start(); + const projDocsDir = path.resolve(`${docsPath}/json-docs/${project}`); + const revIndexFolder = path.resolve(`${docsPath}/rev-index`); - fs.mkdirpSync(revIndexFolder) - const destination = `${revIndexFolder}/${project}-${ver}.json` + fs.mkdirpSync(revIndexFolder); + const destination = `${revIndexFolder}/${project}-${ver}.json`; - fs.copySync(`${projDocsDir}/${ver}/project-versions/${project}-${ver}.json`, destination) + fs.copySync(`${projDocsDir}/${ver}/project-versions/${project}-${ver}.json`, destination); - opProgress.text = `Revving ${project}:${ver}` + opProgress.text = `Revving ${project}:${ver}`; - const projVerRevFile = `${revIndexFolder}/${project}-${ver}.json` - let projVerRevContent = fs.readJsonSync(projVerRevFile) - projVerRevContent.meta = {} + const projVerRevFile = `${revIndexFolder}/${project}-${ver}.json`; + let projVerRevContent = fs.readJsonSync(projVerRevFile); + projVerRevContent.meta = {}; Object.keys(projVerRevContent.data.relationships).forEach(k => { if (Array.isArray(projVerRevContent.data.relationships[k].data)) { projVerRevContent.data.relationships[k].data.forEach(({ type, id }) => { if (!projVerRevContent.meta[type]) { - projVerRevContent.meta[type] = {} + projVerRevContent.meta[type] = {}; } - projVerRevContent.meta[type][id] = '' - }) + projVerRevContent.meta[type][id] = ''; + }); } else if (k !== 'project') { - let d = projVerRevContent.data.relationships[k].data + let d = projVerRevContent.data.relationships[k].data; if (!projVerRevContent.meta[d.type]) { - projVerRevContent.meta[d.type] = {} + projVerRevContent.meta[d.type] = {}; } - projVerRevContent.meta[d.type][d.id] = '' + projVerRevContent.meta[d.type][d.id] = ''; } - }) - projVerRevContent.meta['missing'] = {} + }); + projVerRevContent.meta['missing'] = {}; - const projVerDir = `${projDocsDir}/${ver}` + const projVerDir = `${projDocsDir}/${ver}`; glob .sync(`${projVerDir}/**/*.json`) .filter(f => !f.includes('project-versions')) .map(f => { - let fileShortName = f.replace(`${projVerDir}/`, '').replace('.json', '') - let [fileObjType, entityName] = fileShortName.split('/') + let fileShortName = f.replace(`${projVerDir}/`, '').replace('.json', ''); + let [fileObjType, entityName] = fileShortName.split('/'); projVerRevContent.meta[singularize(fileObjType)][entityName] = getFileName(f).replace( '.json', '', - ) - }) + ); + }); - fs.writeJsonSync(projVerRevFile, projVerRevContent) - opProgress.succeed('Revving done!') + fs.writeJsonSync(projVerRevFile, projVerRevContent); + opProgress.succeed('Revving done!'); } -export default revProjVersionFiles +export default revProjVersionFiles; diff --git a/lib/save-document.js b/lib/save-document.js index 77f226a..ae98afe 100644 --- a/lib/save-document.js +++ b/lib/save-document.js @@ -1,10 +1,10 @@ -import fs from 'fs-extra' -import path from 'path' -import mkdirp from 'mkdirp' -import { pluralize } from 'inflected' -import chalk from 'chalk' +import fs from 'fs-extra'; +import path from 'path'; +import mkdirp from 'mkdirp'; +import { pluralize } from 'inflected'; +import chalk from 'chalk'; -const docsPath = '../ember-api-docs-data' +const docsPath = '../ember-api-docs-data'; // updateOrCreate export default async function saveDoc(document, projectName, version = '') { @@ -15,9 +15,9 @@ export default async function saveDoc(document, projectName, version = '') { version, pluralize(document.data.type), encodeURIComponent(`${document.data.id}.json`), - ) + ); - let json = JSON.stringify(document, null, 2) + let json = JSON.stringify(document, null, 2); return new Promise((resolve, reject) => { if ((version.startsWith('1.') || version.startsWith('0.')) && document.data.id.length > 50) { @@ -27,19 +27,19 @@ export default async function saveDoc(document, projectName, version = '') { document.data.id, )} because it's too long\n\n`, ), - ) + ); // wtf ember 1.0 docs?? - return resolve() + return resolve(); } - mkdirp.sync(path.dirname(documentPath)) + mkdirp.sync(path.dirname(documentPath)); // console.log(`Saving ${documentPath}`) // good for debuggin return fs.writeFile(documentPath, json, err => { if (err) { - return reject(err) + return reject(err); } - resolve(documentPath) - }) - }) + resolve(documentPath); + }); + }); } diff --git a/lib/transform-yui-object.js b/lib/transform-yui-object.js index 106d269..f385660 100644 --- a/lib/transform-yui-object.js +++ b/lib/transform-yui-object.js @@ -1,15 +1,15 @@ -import transformModules from './modules-transform.js' -import addInheritedItems from './add-inherited-items.js' -import normalizeIDs from './normalize-ids.js' +import transformModules from './modules-transform.js'; +import addInheritedItems from './add-inherited-items.js'; +import normalizeIDs from './normalize-ids.js'; export default async function transformYuiObject(docs, projName) { - let d = await transformModules(docs) - console.log('\ttransformed yui object') - d = await addInheritedItems(d) - console.log('\tadded inherited') + let d = await transformModules(docs); + console.log('\ttransformed yui object'); + d = await addInheritedItems(d); + console.log('\tadded inherited'); - d = await normalizeIDs(d, projName) - console.log('\tnormalized ids') + d = await normalizeIDs(d, projName); + console.log('\tnormalized ids'); - return d + return d; } diff --git a/lib/update-with-versions-and-project.js b/lib/update-with-versions-and-project.js index 4823a3c..c4ce8d5 100644 --- a/lib/update-with-versions-and-project.js +++ b/lib/update-with-versions-and-project.js @@ -1,64 +1,64 @@ -import _ from 'lodash' +import _ from 'lodash'; function generateID(type, projectName, version, id) { if (!projectName) { throw new Error( `no project ! type: ${type} project name: ${projectName} version: ${version}, id: ${id}`, - ) + ); } - return `${projectName}-${version}-${id}` + return `${projectName}-${version}-${id}`; } function updateDocument(doc, projectName, version) { - let dup = _.cloneDeep(doc) + let dup = _.cloneDeep(doc); - dup.id = generateID(doc.type, projectName, version, dup.id) + dup.id = generateID(doc.type, projectName, version, dup.id); - dup.relationships = dup.relationships || {} + dup.relationships = dup.relationships || {}; Object.keys(dup.relationships).forEach(relationshipKey => { - let relationship = dup.relationships[relationshipKey] + let relationship = dup.relationships[relationshipKey]; if (relationship && relationship.data) { if (Array.isArray(relationship.data)) { relationship.data.forEach(data => { - data.id = generateID(data.type, projectName, version, data.id) - }) + data.id = generateID(data.type, projectName, version, data.id); + }); } else { relationship.data.id = generateID( relationship.data.type, projectName, version, relationship.data.id, - ) + ); } } - }) + }); dup.relationships['project-version'] = { data: { id: `${projectName}-${version}`, type: 'project-version', }, - } + }; - return dup + return dup; } export default function updateWithIDs(document, projectName, version) { - let dup = _.cloneDeep(document) + let dup = _.cloneDeep(document); if (Array.isArray(dup.data)) { dup.data = dup.data.map(data => { - return updateDocument(data, projectName, version) - }) + return updateDocument(data, projectName, version); + }); } else { - dup.data = updateDocument(dup.data, projectName, version) + dup.data = updateDocument(dup.data, projectName, version); } dup.included = (dup.included || []).map(included => { - return updateDocument(included, projectName, version) - }) + return updateDocument(included, projectName, version); + }); - return dup + return dup; } diff --git a/lib/yuidoc-fixer/emberKnownEntityNames.js b/lib/yuidoc-fixer/emberKnownEntityNames.js index 3b72138..2f28a3c 100644 --- a/lib/yuidoc-fixer/emberKnownEntityNames.js +++ b/lib/yuidoc-fixer/emberKnownEntityNames.js @@ -1,5 +1,5 @@ -import moduleData from 'ember-rfc176-data' -import keyfinder from 'keyfinder' -import { uniq } from 'lodash' +import moduleData from 'ember-rfc176-data'; +import keyfinder from 'keyfinder'; +import { uniq } from 'lodash'; -export const emberKnownEntityNames = uniq(keyfinder(moduleData, 'export')) +export const emberKnownEntityNames = uniq(keyfinder(moduleData, 'export')); diff --git a/lib/yuidoc-fixer/normalize-yui-doc-class-item.js b/lib/yuidoc-fixer/normalize-yui-doc-class-item.js index 06dd2c6..f69962c 100644 --- a/lib/yuidoc-fixer/normalize-yui-doc-class-item.js +++ b/lib/yuidoc-fixer/normalize-yui-doc-class-item.js @@ -1,60 +1,60 @@ -import { toLower } from 'lodash' -import { yuiDocClassItemKeys } from './yui-doc-class-item-keys.js' -import { emberKnownEntityNames } from './emberKnownEntityNames.js' +import { toLower } from 'lodash'; +import { yuiDocClassItemKeys } from './yui-doc-class-item-keys.js'; +import { emberKnownEntityNames } from './emberKnownEntityNames.js'; export const normalizeYuiDocClassItem = item => { - let normalizedItem = {} + let normalizedItem = {}; - let encounteredDescription = false - let finishedNormalization = false - let newDescription = '' - let faultyKeys = [] + let encounteredDescription = false; + let finishedNormalization = false; + let newDescription = ''; + let faultyKeys = []; Object.keys(item).forEach(key => { if (key === 'description') { - encounteredDescription = true + encounteredDescription = true; } if (!encounteredDescription || finishedNormalization) { - normalizedItem[key] = item[key] + normalizedItem[key] = item[key]; } else { if (key === 'description' || !yuiDocClassItemKeys.includes(key)) { - let content = item[key] + let content = item[key]; if (key === 'description') { - newDescription = content + '\n' + newDescription = content + '\n'; if (content.endsWith('}')) { - newDescription += '\n' + newDescription += '\n'; } - return + return; } // For cases where we have @decorator(args), other cases are @decorator x if (typeof content === 'string' && !content.startsWith('(')) { - content = ' ' + content + content = ' ' + content; } - let transformedKey = key + let transformedKey = key; if (emberKnownEntityNames.map(toLower).includes(key)) { transformedKey = emberKnownEntityNames.find( name => name.toLowerCase() === key.toLowerCase(), - ) + ); } - newDescription += ' @' + transformedKey + content + '\n' + newDescription += ' @' + transformedKey + content + '\n'; - faultyKeys.push(transformedKey) + faultyKeys.push(transformedKey); } else { - normalizedItem[key] = item[key] - finishedNormalization = true - normalizedItem.description = newDescription + normalizedItem[key] = item[key]; + finishedNormalization = true; + normalizedItem.description = newDescription; } } - }) + }); - console.log(`File name: ${item.file} | Line number: ${item.line} | Faulty keys: ${faultyKeys}`) + console.log(`File name: ${item.file} | Line number: ${item.line} | Faulty keys: ${faultyKeys}`); - return normalizedItem -} + return normalizedItem; +}; diff --git a/lib/yuidoc-fixer/normalize-yui-doc-class.js b/lib/yuidoc-fixer/normalize-yui-doc-class.js index 380d749..a3ac891 100644 --- a/lib/yuidoc-fixer/normalize-yui-doc-class.js +++ b/lib/yuidoc-fixer/normalize-yui-doc-class.js @@ -1,20 +1,20 @@ -import { normalizeYuiDocClassItem } from './normalize-yui-doc-class-item.js' -import { yuiDocClassItemKeys } from './yui-doc-class-item-keys.js' +import { normalizeYuiDocClassItem } from './normalize-yui-doc-class-item.js'; +import { yuiDocClassItemKeys } from './yui-doc-class-item-keys.js'; export const normalizeYuiDocClass = klass => { if (!klass.description) { - return klass + return klass; } - let keys = Object.keys(klass) - let locationOfDescriptionField = keys.indexOf('description') + let keys = Object.keys(klass); + let locationOfDescriptionField = keys.indexOf('description'); if ( locationOfDescriptionField === -1 || yuiDocClassItemKeys.includes(keys[locationOfDescriptionField + 1]) ) { - return klass + return klass; } - return normalizeYuiDocClassItem(klass) -} + return normalizeYuiDocClassItem(klass); +}; diff --git a/lib/yuidoc-fixer/yui-doc-class-item-keys.js b/lib/yuidoc-fixer/yui-doc-class-item-keys.js index 1a5d670..b76780d 100644 --- a/lib/yuidoc-fixer/yui-doc-class-item-keys.js +++ b/lib/yuidoc-fixer/yui-doc-class-item-keys.js @@ -1,4 +1,4 @@ -import { without } from 'lodash' +import { without } from 'lodash'; const originalYuiDocClassItemKeys = [ 'async', // bool, custom events can fire the listeners in a setTimeout @@ -74,7 +74,7 @@ const originalYuiDocClassItemKeys = [ 'uses', // 0..n compents mixed (usually, via augment) into the prototype 'value', // the value of a constant 'writeonce', // YUI attribute config -] +]; const additionalDocumentationKeywords = [ 'access', @@ -83,11 +83,11 @@ const additionalDocumentationKeywords = [ 'params', 'name', 'is_constructor', -] +]; -const keywordsInOurProjects = ['readonly'] +const keywordsInOurProjects = ['readonly']; export const yuiDocClassItemKeys = without( [...additionalDocumentationKeywords, ...originalYuiDocClassItemKeys], ...keywordsInOurProjects, -) +); diff --git a/main.js b/main.js index 1160712..04cb79c 100644 --- a/main.js +++ b/main.js @@ -1,131 +1,131 @@ -import fs from 'fs-extra' -import rimraf from 'rimraf' +import fs from 'fs-extra'; +import rimraf from 'rimraf'; -import markup from './lib/markup.js' -import readDocs from './lib/read-docs.js' -import createClassesOnDisk from './lib/create-classes.js' -import transformYuiObject from './lib/transform-yui-object.js' -import normalizeEmberDependencies from './lib/normalize-ember-dependencies.js' -import getVersionIndex from './lib/get-version-index.js' -import saveDoc from './lib/save-document.js' -import revProjVersionFiles from './lib/rev-docs.js' -import fixBorkedYuidocFiles from './lib/fix-borked-yuidoc-files.js' +import markup from './lib/markup.js'; +import readDocs from './lib/read-docs.js'; +import createClassesOnDisk from './lib/create-classes.js'; +import transformYuiObject from './lib/transform-yui-object.js'; +import normalizeEmberDependencies from './lib/normalize-ember-dependencies.js'; +import getVersionIndex from './lib/get-version-index.js'; +import saveDoc from './lib/save-document.js'; +import revProjVersionFiles from './lib/rev-docs.js'; +import fixBorkedYuidocFiles from './lib/fix-borked-yuidoc-files.js'; -const docsPath = '../ember-api-docs-data' +const docsPath = '../ember-api-docs-data'; async function transformObject(doc, projectName, docVersion) { try { - const object = await transformYuiObject([doc], projectName) - const { data } = markup(object) - const giantDocument = { data } - console.log('normalizing dependencies') - let transformed = await normalizeEmberDependencies(giantDocument) - transformed = await createClassesOnDisk(transformed, projectName, docVersion) - console.log(`Finished processing ${projectName}-${docVersion}`) - transformed = getVersionIndex(transformed, projectName) - revProjVersionFiles(projectName, docVersion) - return transformed + const object = await transformYuiObject([doc], projectName); + const { data } = markup(object); + const giantDocument = { data }; + console.log('normalizing dependencies'); + let transformed = await normalizeEmberDependencies(giantDocument); + transformed = await createClassesOnDisk(transformed, projectName, docVersion); + console.log(`Finished processing ${projectName}-${docVersion}`); + transformed = getVersionIndex(transformed, projectName); + revProjVersionFiles(projectName, docVersion); + return transformed; } catch (e) { - console.log(e) - throw e + console.log(e); + throw e; } } async function transformProject(project, projectName) { - const docs = [] + const docs = []; for (const doc of project) { - let docVersion = doc.version - console.log(`Starting to process ${projectName}-${docVersion}`) + let docVersion = doc.version; + console.log(`Starting to process ${projectName}-${docVersion}`); - const existingFolder = `${docsPath}/json-docs/${projectName}/${docVersion}` + const existingFolder = `${docsPath}/json-docs/${projectName}/${docVersion}`; if (fs.existsSync(existingFolder)) { - rimraf.sync(existingFolder) + rimraf.sync(existingFolder); } - const transformed = await transformObject(doc, projectName, docVersion) - docs.push(transformed) + const transformed = await transformObject(doc, projectName, docVersion); + docs.push(transformed); } - let [docToSave, ...remainingDocs] = docs.filter(({ data }) => data.id === projectName) + let [docToSave, ...remainingDocs] = docs.filter(({ data }) => data.id === projectName); if (!docToSave) { - return void 0 + return void 0; } - let existingDoc = `${docsPath}/json-docs/${projectName}/projects/${projectName}.json` + let existingDoc = `${docsPath}/json-docs/${projectName}/projects/${projectName}.json`; if (fs.existsSync(existingDoc)) { - existingDoc = fs.readJsonSync(existingDoc) - const newData = docToSave.data.relationships['project-versions'].data - const oldData = existingDoc.data.relationships['project-versions'].data - const updatedData = mergeById(newData, oldData) - docToSave.data.relationships['project-versions'].data = updatedData + existingDoc = fs.readJsonSync(existingDoc); + const newData = docToSave.data.relationships['project-versions'].data; + const oldData = existingDoc.data.relationships['project-versions'].data; + const updatedData = mergeById(newData, oldData); + docToSave.data.relationships['project-versions'].data = updatedData; } remainingDocs.forEach(({ data }) => { docToSave.data.relationships['project-versions'].data = docToSave.data.relationships[ 'project-versions' - ].data.concat(data.relationships['project-versions'].data) - }) - await saveDoc(docToSave, projectName) - return projectName + ].data.concat(data.relationships['project-versions'].data); + }); + await saveDoc(docToSave, projectName); + return projectName; } async function transformProjectsDeep(projects, docs) { - const built = [] + const built = []; for (const projectName of projects) { - const transformed = await transformProject(docs[projectName], projectName) - built.push(transformed) + const transformed = await transformProject(docs[projectName], projectName); + built.push(transformed); } - return built + return built; } export async function apiDocsProcessor(projects, specificDocsVersion, runClean) { let filesToProcess = projects.map(project => { - return `${docsPath}/s3-docs/v${specificDocsVersion}/${project}-docs.json` - }) - await Promise.all(filesToProcess.map(fixBorkedYuidocFiles)) + return `${docsPath}/s3-docs/v${specificDocsVersion}/${project}-docs.json`; + }); + await Promise.all(filesToProcess.map(fixBorkedYuidocFiles)); - const _transformProjectsDeep = transformProjectsDeep.bind(null, projects) + const _transformProjectsDeep = transformProjectsDeep.bind(null, projects); await readDocs(projects, specificDocsVersion, runClean) .then(_transformProjectsDeep) .then(() => projects.map(project => { - const projRevFile = `${docsPath}/rev-index/${project}.json` + const projRevFile = `${docsPath}/rev-index/${project}.json`; let projRevFileContent = fs.readJsonSync( `${docsPath}/json-docs/${project}/projects/${project}.json`, - ) - const availableVersions = [] + ); + const availableVersions = []; projRevFileContent.meta = { availableVersions, - } + }; projRevFileContent.data.relationships['project-versions'].data.forEach(({ id }) => availableVersions.push(id.replace(`${project}-`, '')), - ) - console.log({ project, availableVersions }) - fs.writeJsonSync(projRevFile, projRevFileContent, { spaces: 2 }) + ); + console.log({ project, availableVersions }); + fs.writeJsonSync(projRevFile, projRevFileContent, { spaces: 2 }); }), ) .then(() => { - console.log('\n\n\n') - console.log('Done!') - }) + console.log('\n\n\n'); + console.log('Done!'); + }); } function mergeById(arr1, arr2) { - const seen = new Set() - const result = [] - let maxLen = arr1.length > arr2.length ? arr1.length : arr2.length + const seen = new Set(); + const result = []; + let maxLen = arr1.length > arr2.length ? arr1.length : arr2.length; for (let i = 0; i < maxLen; i++) { if (i < arr1.length && !seen.has(arr1[i].id)) { - result.push(arr1[i]) - seen.add(arr1[i].id) + result.push(arr1[i]); + seen.add(arr1[i].id); } if (i < arr2.length && !seen.has(arr2[i].id)) { - result.push(arr2[i]) - seen.add(arr2[i].id) + result.push(arr2[i]); + seen.add(arr2[i].id); } } - return result + return result; } diff --git a/test/add-since-tag-test.js b/test/add-since-tag-test.js index ab37d7c..bd37f07 100644 --- a/test/add-since-tag-test.js +++ b/test/add-since-tag-test.js @@ -1,6 +1,6 @@ -import addSinceTags from '../lib/add-since-tags.js' -import { assert } from 'chai' -import _ from 'lodash' +import addSinceTags from '../lib/add-since-tags.js'; +import { assert } from 'chai'; +import _ from 'lodash'; describe('addSinceTags', () => { beforeEach(function () { @@ -21,14 +21,14 @@ describe('addSinceTags', () => { }, ], }, - } - }) - addSinceTags(this.yuiDocSets) - }) + }; + }); + addSinceTags(this.yuiDocSets); + }); it('adds a since tag to classitems', function () { this.yuiDocSets.forEach(({ data }) => { - data.classitems.forEach(({ since }) => assert.equal(since, '1.0.0')) - }) - }) -}) + data.classitems.forEach(({ since }) => assert.equal(since, '1.0.0')); + }); + }); +}); diff --git a/test/filter-jsonapi-doc-test.js b/test/filter-jsonapi-doc-test.js index fc40dc2..b63ddea 100644 --- a/test/filter-jsonapi-doc-test.js +++ b/test/filter-jsonapi-doc-test.js @@ -1,6 +1,6 @@ -import { assert } from 'chai' -import _ from 'lodash' -import { classWithIncluded } from '../lib/filter-jsonapi-doc.js' +import { assert } from 'chai'; +import _ from 'lodash'; +import { classWithIncluded } from '../lib/filter-jsonapi-doc.js'; describe('filter json api docs', () => { describe('#classWithIncluded', () => { @@ -30,21 +30,21 @@ describe('filter json api docs', () => { }, }, ], - } + }; - this.response = classWithIncluded(this.document, 'Ember.Butt') - }) + this.response = classWithIncluded(this.document, 'Ember.Butt'); + }); it('returns the class in the result', function () { - assert.typeOf(this.response.data, 'object') + assert.typeOf(this.response.data, 'object'); assert.deepEqual(this.response.data, { id: 'Ember.Butt', type: 'class', relationships: { methods: [{ id: 'Ember.Butt#Foo', type: 'method' }], }, - }) - }) + }); + }); it('returns associated methods', function () { assert.deepEqual(this.response.included, [ @@ -57,12 +57,12 @@ describe('filter json api docs', () => { }, }, }, - ]) - }) + ]); + }); it('does not return unassociated models', function () { - let unassociated = _.filter(this.response.included, ['type', 'yoloswag']) - assert.equal(unassociated.length, 0) - }) - }) -}) + let unassociated = _.filter(this.response.included, ['type', 'yoloswag']); + assert.equal(unassociated.length, 0); + }); + }); +}); diff --git a/test/markup-test.js b/test/markup-test.js index f576b0d..ec3f1a5 100644 --- a/test/markup-test.js +++ b/test/markup-test.js @@ -1,7 +1,7 @@ -import markup from '../lib/markup.js' -import { assert } from 'chai' -import fs from 'fs' -import { join } from 'path' +import markup from '../lib/markup.js'; +import { assert } from 'chai'; +import fs from 'fs'; +import { join } from 'path'; function desc(path) { return { @@ -12,48 +12,48 @@ function desc(path) { properties: [], events: [], }, - } + }; } function mark(path) { - let data = [desc(path)] - let result = markup({ data }) - let content = result.data[0].attributes.description - maybeWrite(content, path) - return content + let data = [desc(path)]; + let result = markup({ data }); + let content = result.data[0].attributes.description; + maybeWrite(content, path); + return content; } function maybeWrite(content, path) { - const fsPath = join(__dirname, `./mocks/description/${path}.html`) + const fsPath = join(__dirname, `./mocks/description/${path}.html`); if (fs.existsSync(fsPath)) { - return + return; } - fs.writeFileSync(fsPath, content, 'utf-8') + fs.writeFileSync(fsPath, content, 'utf-8'); } function snapshot(path) { - const fsPath = join(__dirname, `./mocks/description/${path}.html`) - return fs.readFileSync(fsPath, 'utf8') + const fsPath = join(__dirname, `./mocks/description/${path}.html`); + return fs.readFileSync(fsPath, 'utf8'); } describe('markup', () => { it('render correct syntax for handlebars with title', function () { - const caseName = 'handlebars-title' - assert.equal(mark(caseName), snapshot(caseName)) - }) + const caseName = 'handlebars-title'; + assert.equal(mark(caseName), snapshot(caseName)); + }); it('render correct syntax for handlebars without title', function () { - const caseName = 'handlebars' - assert.equal(mark(caseName), snapshot(caseName)) - }) + const caseName = 'handlebars'; + assert.equal(mark(caseName), snapshot(caseName)); + }); it('render correct syntax for javascript with title', function () { - const caseName = 'javascript-title' - assert.equal(mark(caseName), snapshot(caseName)) - }) + const caseName = 'javascript-title'; + assert.equal(mark(caseName), snapshot(caseName)); + }); it('render correct syntax for javascript without title', function () { - const caseName = 'javascript' - assert.equal(mark(caseName), snapshot(caseName)) - }) -}) + const caseName = 'javascript'; + assert.equal(mark(caseName), snapshot(caseName)); + }); +}); diff --git a/test/modules-transform-test.js b/test/modules-transform-test.js index c5f1c2a..d6ba887 100644 --- a/test/modules-transform-test.js +++ b/test/modules-transform-test.js @@ -1,6 +1,6 @@ -import transformModules from '../lib/modules-transform.js' -import { assert } from 'chai' -import _ from 'lodash' +import transformModules from '../lib/modules-transform.js'; +import { assert } from 'chai'; +import _ from 'lodash'; describe('transformModules', () => { beforeEach(function () { @@ -67,41 +67,41 @@ describe('transformModules', () => { }, }, }, - } - }) - transformModules(this.yuiDocSets) - }) + }; + }); + transformModules(this.yuiDocSets); + }); it('adds a parent attribute to sub modules', function () { this.yuiDocSets.forEach(({ data }) => { - let subModules = _.filter(data.modules, ({ is_submodule }) => is_submodule) + let subModules = _.filter(data.modules, ({ is_submodule }) => is_submodule); subModules.forEach(({ parent }) => { - assert.equal(parent, 'foo') - }) - }) - }) + assert.equal(parent, 'foo'); + }); + }); + }); it('publicclasses/privateclasses attributes are set correctly', function () { this.yuiDocSets.forEach(({ data }) => { - let modules = data.modules + let modules = data.modules; assert.deepEqual(modules[0].publicclasses, [ 'Testing.class.public-2', 'Testing.class.public-4', - ]) + ]); assert.deepEqual(modules[0].privateclasses, [ 'Testing.class.private-1', 'Testing.class.private-3', 'Testing.class.deprecated-3', - ]) - assert.isUndefined(modules[0].classes) + ]); + assert.isUndefined(modules[0].classes); - assert.deepEqual(modules[1].publicclasses, []) - assert.deepEqual(modules[1].privateclasses, ['Testing.class.private-1']) - assert.isUndefined(modules[1].classes) + assert.deepEqual(modules[1].publicclasses, []); + assert.deepEqual(modules[1].privateclasses, ['Testing.class.private-1']); + assert.isUndefined(modules[1].classes); - assert.deepEqual(modules[2].publicclasses, ['Testing.class.public-2']) - assert.deepEqual(modules[2].privateclasses, ['Testing.class.private-1']) - assert.isUndefined(modules[2].classes) - }) - }) -}) + assert.deepEqual(modules[2].publicclasses, ['Testing.class.public-2']); + assert.deepEqual(modules[2].privateclasses, ['Testing.class.private-1']); + assert.isUndefined(modules[2].classes); + }); + }); +}); diff --git a/test/update-ids-with-versions-and-project-test.js b/test/update-ids-with-versions-and-project-test.js index 4204a37..66875f9 100644 --- a/test/update-ids-with-versions-and-project-test.js +++ b/test/update-ids-with-versions-and-project-test.js @@ -1,5 +1,5 @@ -import updateWithIDs from '../lib/update-with-versions-and-project.js' -import { assert } from 'chai' +import updateWithIDs from '../lib/update-with-versions-and-project.js'; +import { assert } from 'chai'; describe('update with versions and project', () => { describe('`data` in jsonapi document is an object', () => { @@ -39,24 +39,24 @@ describe('update with versions and project', () => { }, }, ], - } + }; - this.converted = updateWithIDs(this.document, 'ember', '1.1.0') - }) + this.converted = updateWithIDs(this.document, 'ember', '1.1.0'); + }); it('adds the project name and version to the IDs', function () { - assert.equal(this.converted.data.id, 'ember-1.1.0-Ember.CoreView') - assert.equal(this.converted.included[0].id, 'ember-1.1.0-ember') + assert.equal(this.converted.data.id, 'ember-1.1.0-Ember.CoreView'); + assert.equal(this.converted.included[0].id, 'ember-1.1.0-ember'); assert.equal( this.converted.included[0].relationships.classes.data[0].id, 'ember-1.1.0-Ember.CoreView', - ) - }) + ); + }); it('adds the id to relationships', function () { - assert.equal(this.converted.data.relationships.module.data.id, 'ember-1.1.0-ember') - }) - }) + assert.equal(this.converted.data.relationships.module.data.id, 'ember-1.1.0-ember'); + }); + }); describe('when `data` is an array of objects in the jsonapi doc', () => { beforeEach(function () { @@ -97,22 +97,22 @@ describe('update with versions and project', () => { }, }, ], - } + }; - this.converted = updateWithIDs(this.document, 'ember', '1.1.0') - }) + this.converted = updateWithIDs(this.document, 'ember', '1.1.0'); + }); it('adds the project name and version to the IDs', function () { - assert.equal(this.converted.data[0].id, 'ember-1.1.0-Ember.CoreView') - assert.equal(this.converted.included[0].id, 'ember-1.1.0-ember') + assert.equal(this.converted.data[0].id, 'ember-1.1.0-Ember.CoreView'); + assert.equal(this.converted.included[0].id, 'ember-1.1.0-ember'); assert.equal( this.converted.included[0].relationships.classes.data[0].id, 'ember-1.1.0-Ember.CoreView', - ) - }) + ); + }); it('adds the id to relationships', function () { - assert.equal(this.converted.data[0].relationships.module.data.id, 'ember-1.1.0-ember') - }) - }) -}) + assert.equal(this.converted.data[0].relationships.module.data.id, 'ember-1.1.0-ember'); + }); + }); +});