summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSamy Pessé <samypesse@gmail.com>2016-09-05 12:32:25 +0200
committerSamy Pessé <samypesse@gmail.com>2016-09-05 12:32:25 +0200
commitb796069adeadd655ad34dc425ff7a05d7a54cd47 (patch)
tree30edaffa584e7d3db3f4c65f401f4a8f58f4eef9
parent839904a70419aaef1006be820ec092d978236a20 (diff)
downloadgitbook-b796069adeadd655ad34dc425ff7a05d7a54cd47.zip
gitbook-b796069adeadd655ad34dc425ff7a05d7a54cd47.tar.gz
gitbook-b796069adeadd655ad34dc425ff7a05d7a54cd47.tar.bz2
Move gitbook source code to es6 (linted)
-rw-r--r--package.json2
-rw-r--r--packages/gitbook/lib/cli/getBook.js23
-rw-r--r--packages/gitbook/lib/cli/getOutputFolder.js17
-rw-r--r--packages/gitbook/lib/cli/init.js17
-rw-r--r--packages/gitbook/lib/cli/server.js128
-rw-r--r--packages/gitbook/lib/constants/configDefault.js6
-rw-r--r--packages/gitbook/lib/json/encodeBook.js39
-rw-r--r--packages/gitbook/lib/output/createTemplateEngine.js45
-rw-r--r--packages/gitbook/lib/output/modifiers/__tests__/fetchRemoteImages.js40
-rw-r--r--packages/gitbook/lib/output/modifiers/__tests__/inlinePng.js25
-rw-r--r--packages/gitbook/lib/output/modifiers/__tests__/svgToImg.js25
-rw-r--r--packages/gitbook/lib/output/modifiers/__tests__/svgToPng.js33
-rw-r--r--packages/gitbook/lib/output/website/onFinish.js35
-rw-r--r--packages/gitbook/lib/plugins/__tests__/installPlugin.js29
-rw-r--r--packages/gitbook/lib/plugins/locateRootFolder.js22
-rw-r--r--packages/gitbook/lib/utils/git.js133
-rw-r--r--packages/gitbook/src/__tests__/gitbook.js (renamed from packages/gitbook/lib/__tests__/gitbook.js)2
-rw-r--r--packages/gitbook/src/__tests__/init.js (renamed from packages/gitbook/lib/__tests__/init.js)6
-rw-r--r--packages/gitbook/src/__tests__/module.js (renamed from packages/gitbook/lib/__tests__/module.js)0
-rw-r--r--packages/gitbook/src/api/decodeConfig.js (renamed from packages/gitbook/lib/api/decodeConfig.js)2
-rw-r--r--packages/gitbook/src/api/decodeGlobal.js (renamed from packages/gitbook/lib/api/decodeGlobal.js)6
-rw-r--r--packages/gitbook/src/api/decodePage.js (renamed from packages/gitbook/lib/api/decodePage.js)4
-rw-r--r--packages/gitbook/src/api/deprecate.js (renamed from packages/gitbook/lib/api/deprecate.js)20
-rw-r--r--packages/gitbook/src/api/encodeConfig.js (renamed from packages/gitbook/lib/api/encodeConfig.js)10
-rw-r--r--packages/gitbook/src/api/encodeGlobal.js (renamed from packages/gitbook/lib/api/encodeGlobal.js)94
-rw-r--r--packages/gitbook/src/api/encodeNavigation.js (renamed from packages/gitbook/lib/api/encodeNavigation.js)24
-rw-r--r--packages/gitbook/src/api/encodePage.js (renamed from packages/gitbook/lib/api/encodePage.js)16
-rw-r--r--packages/gitbook/src/api/encodeProgress.js (renamed from packages/gitbook/lib/api/encodeProgress.js)22
-rw-r--r--packages/gitbook/src/api/encodeSummary.js (renamed from packages/gitbook/lib/api/encodeSummary.js)21
-rw-r--r--packages/gitbook/src/api/index.js (renamed from packages/gitbook/lib/api/index.js)0
-rw-r--r--packages/gitbook/src/browser.js (renamed from packages/gitbook/lib/browser.js)2
-rw-r--r--packages/gitbook/src/cli/build.js (renamed from packages/gitbook/lib/cli/build.js)20
-rw-r--r--packages/gitbook/src/cli/buildEbook.js (renamed from packages/gitbook/lib/cli/buildEbook.js)40
-rw-r--r--packages/gitbook/src/cli/getBook.js23
-rw-r--r--packages/gitbook/src/cli/getOutputFolder.js17
-rw-r--r--packages/gitbook/src/cli/index.js (renamed from packages/gitbook/lib/cli/index.js)2
-rw-r--r--packages/gitbook/src/cli/init.js17
-rw-r--r--packages/gitbook/src/cli/install.js (renamed from packages/gitbook/lib/cli/install.js)12
-rw-r--r--packages/gitbook/src/cli/options.js (renamed from packages/gitbook/lib/cli/options.js)8
-rw-r--r--packages/gitbook/src/cli/parse.js (renamed from packages/gitbook/lib/cli/parse.js)40
-rw-r--r--packages/gitbook/src/cli/serve.js (renamed from packages/gitbook/lib/cli/serve.js)54
-rw-r--r--packages/gitbook/src/cli/server.js127
-rw-r--r--packages/gitbook/src/cli/watch.js (renamed from packages/gitbook/lib/cli/watch.js)16
-rw-r--r--packages/gitbook/src/constants/__tests__/configSchema.js (renamed from packages/gitbook/lib/constants/__tests__/configSchema.js)12
-rw-r--r--packages/gitbook/src/constants/configDefault.js6
-rw-r--r--packages/gitbook/src/constants/configFiles.js (renamed from packages/gitbook/lib/constants/configFiles.js)0
-rw-r--r--packages/gitbook/src/constants/configSchema.js (renamed from packages/gitbook/lib/constants/configSchema.js)2
-rw-r--r--packages/gitbook/src/constants/defaultBlocks.js (renamed from packages/gitbook/lib/constants/defaultBlocks.js)14
-rw-r--r--packages/gitbook/src/constants/defaultFilters.js (renamed from packages/gitbook/lib/constants/defaultFilters.js)8
-rw-r--r--packages/gitbook/src/constants/defaultPlugins.js (renamed from packages/gitbook/lib/constants/defaultPlugins.js)10
-rw-r--r--packages/gitbook/src/constants/extsAsciidoc.js (renamed from packages/gitbook/lib/constants/extsAsciidoc.js)0
-rw-r--r--packages/gitbook/src/constants/extsMarkdown.js (renamed from packages/gitbook/lib/constants/extsMarkdown.js)0
-rw-r--r--packages/gitbook/src/constants/ignoreFiles.js (renamed from packages/gitbook/lib/constants/ignoreFiles.js)0
-rw-r--r--packages/gitbook/src/constants/pluginAssetsFolder.js (renamed from packages/gitbook/lib/constants/pluginAssetsFolder.js)0
-rw-r--r--packages/gitbook/src/constants/pluginHooks.js (renamed from packages/gitbook/lib/constants/pluginHooks.js)0
-rw-r--r--packages/gitbook/src/constants/pluginPrefix.js (renamed from packages/gitbook/lib/constants/pluginPrefix.js)0
-rw-r--r--packages/gitbook/src/constants/pluginResources.js (renamed from packages/gitbook/lib/constants/pluginResources.js)2
-rw-r--r--packages/gitbook/src/constants/templatesFolder.js (renamed from packages/gitbook/lib/constants/templatesFolder.js)0
-rw-r--r--packages/gitbook/src/constants/themePrefix.js (renamed from packages/gitbook/lib/constants/themePrefix.js)2
-rw-r--r--packages/gitbook/src/fs/__tests__/mock.js (renamed from packages/gitbook/lib/fs/__tests__/mock.js)5
-rw-r--r--packages/gitbook/src/fs/mock.js (renamed from packages/gitbook/lib/fs/mock.js)34
-rw-r--r--packages/gitbook/src/fs/node.js (renamed from packages/gitbook/lib/fs/node.js)18
-rw-r--r--packages/gitbook/src/gitbook.js (renamed from packages/gitbook/lib/gitbook.js)14
-rw-r--r--packages/gitbook/src/index.js (renamed from packages/gitbook/lib/index.js)4
-rw-r--r--packages/gitbook/src/init.js (renamed from packages/gitbook/lib/init.js)42
-rw-r--r--packages/gitbook/src/json/encodeBook.js39
-rw-r--r--packages/gitbook/src/json/encodeBookWithPage.js (renamed from packages/gitbook/lib/json/encodeBookWithPage.js)10
-rw-r--r--packages/gitbook/src/json/encodeFile.js (renamed from packages/gitbook/lib/json/encodeFile.js)2
-rw-r--r--packages/gitbook/src/json/encodeGlossary.js (renamed from packages/gitbook/lib/json/encodeGlossary.js)8
-rw-r--r--packages/gitbook/src/json/encodeGlossaryEntry.js (renamed from packages/gitbook/lib/json/encodeGlossaryEntry.js)0
-rw-r--r--packages/gitbook/src/json/encodeLanguages.js (renamed from packages/gitbook/lib/json/encodeLanguages.js)6
-rw-r--r--packages/gitbook/src/json/encodeOutput.js (renamed from packages/gitbook/lib/json/encodeOutput.js)10
-rw-r--r--packages/gitbook/src/json/encodeOutputWithPage.js (renamed from packages/gitbook/lib/json/encodeOutputWithPage.js)12
-rw-r--r--packages/gitbook/src/json/encodePage.js (renamed from packages/gitbook/lib/json/encodePage.js)14
-rw-r--r--packages/gitbook/src/json/encodeReadme.js (renamed from packages/gitbook/lib/json/encodeReadme.js)4
-rw-r--r--packages/gitbook/src/json/encodeSummary.js (renamed from packages/gitbook/lib/json/encodeSummary.js)8
-rw-r--r--packages/gitbook/src/json/encodeSummaryArticle.js (renamed from packages/gitbook/lib/json/encodeSummaryArticle.js)4
-rw-r--r--packages/gitbook/src/json/encodeSummaryPart.js (renamed from packages/gitbook/lib/json/encodeSummaryPart.js)2
-rw-r--r--packages/gitbook/src/json/index.js (renamed from packages/gitbook/lib/json/index.js)0
-rw-r--r--packages/gitbook/src/models/__tests__/config.js (renamed from packages/gitbook/lib/models/__tests__/config.js)33
-rw-r--r--packages/gitbook/src/models/__tests__/glossary.js (renamed from packages/gitbook/lib/models/__tests__/glossary.js)15
-rw-r--r--packages/gitbook/src/models/__tests__/glossaryEntry.js (renamed from packages/gitbook/lib/models/__tests__/glossaryEntry.js)5
-rw-r--r--packages/gitbook/src/models/__tests__/page.js (renamed from packages/gitbook/lib/models/__tests__/page.js)9
-rw-r--r--packages/gitbook/src/models/__tests__/plugin.js (renamed from packages/gitbook/lib/models/__tests__/plugin.js)9
-rw-r--r--packages/gitbook/src/models/__tests__/pluginDependency.js (renamed from packages/gitbook/lib/models/__tests__/pluginDependency.js)22
-rw-r--r--packages/gitbook/src/models/__tests__/summary.js (renamed from packages/gitbook/lib/models/__tests__/summary.js)21
-rw-r--r--packages/gitbook/src/models/__tests__/summaryArticle.js (renamed from packages/gitbook/lib/models/__tests__/summaryArticle.js)21
-rw-r--r--packages/gitbook/src/models/__tests__/summaryPart.js (renamed from packages/gitbook/lib/models/__tests__/summaryPart.js)7
-rw-r--r--packages/gitbook/src/models/__tests__/templateBlock.js (renamed from packages/gitbook/lib/models/__tests__/templateBlock.js)74
-rw-r--r--packages/gitbook/src/models/__tests__/templateEngine.js (renamed from packages/gitbook/lib/models/__tests__/templateEngine.js)28
-rw-r--r--packages/gitbook/src/models/book.js (renamed from packages/gitbook/lib/models/book.js)70
-rw-r--r--packages/gitbook/src/models/config.js (renamed from packages/gitbook/lib/models/config.js)28
-rw-r--r--packages/gitbook/src/models/file.js (renamed from packages/gitbook/lib/models/file.js)10
-rw-r--r--packages/gitbook/src/models/fs.js (renamed from packages/gitbook/lib/models/fs.js)207
-rw-r--r--packages/gitbook/src/models/glossary.js (renamed from packages/gitbook/lib/models/glossary.js)34
-rw-r--r--packages/gitbook/src/models/glossaryEntry.js (renamed from packages/gitbook/lib/models/glossaryEntry.js)6
-rw-r--r--packages/gitbook/src/models/ignore.js (renamed from packages/gitbook/lib/models/ignore.js)12
-rw-r--r--packages/gitbook/src/models/language.js (renamed from packages/gitbook/lib/models/language.js)6
-rw-r--r--packages/gitbook/src/models/languages.js (renamed from packages/gitbook/lib/models/languages.js)14
-rw-r--r--packages/gitbook/src/models/output.js (renamed from packages/gitbook/lib/models/output.js)10
-rw-r--r--packages/gitbook/src/models/page.js (renamed from packages/gitbook/lib/models/page.js)16
-rw-r--r--packages/gitbook/src/models/parser.js (renamed from packages/gitbook/lib/models/parser.js)32
-rw-r--r--packages/gitbook/src/models/plugin.js (renamed from packages/gitbook/lib/models/plugin.js)28
-rw-r--r--packages/gitbook/src/models/pluginDependency.js (renamed from packages/gitbook/lib/models/pluginDependency.js)30
-rw-r--r--packages/gitbook/src/models/readme.js (renamed from packages/gitbook/lib/models/readme.js)8
-rw-r--r--packages/gitbook/src/models/summary.js (renamed from packages/gitbook/lib/models/summary.js)52
-rw-r--r--packages/gitbook/src/models/summaryArticle.js (renamed from packages/gitbook/lib/models/summaryArticle.js)36
-rw-r--r--packages/gitbook/src/models/summaryPart.js (renamed from packages/gitbook/lib/models/summaryPart.js)14
-rw-r--r--packages/gitbook/src/models/templateBlock.js (renamed from packages/gitbook/lib/models/templateBlock.js)93
-rw-r--r--packages/gitbook/src/models/templateEngine.js (renamed from packages/gitbook/lib/models/templateEngine.js)28
-rw-r--r--packages/gitbook/src/models/templateOutput.js (renamed from packages/gitbook/lib/models/templateOutput.js)6
-rw-r--r--packages/gitbook/src/models/templateShortcut.js (renamed from packages/gitbook/lib/models/templateShortcut.js)8
-rw-r--r--packages/gitbook/src/modifiers/config/__tests__/addPlugin.js (renamed from packages/gitbook/lib/modifiers/config/__tests__/addPlugin.js)15
-rw-r--r--packages/gitbook/src/modifiers/config/__tests__/removePlugin.js (renamed from packages/gitbook/lib/modifiers/config/__tests__/removePlugin.js)19
-rw-r--r--packages/gitbook/src/modifiers/config/__tests__/togglePlugin.js (renamed from packages/gitbook/lib/modifiers/config/__tests__/togglePlugin.js)15
-rw-r--r--packages/gitbook/src/modifiers/config/addPlugin.js (renamed from packages/gitbook/lib/modifiers/config/addPlugin.js)10
-rw-r--r--packages/gitbook/src/modifiers/config/editPlugin.js (renamed from packages/gitbook/lib/modifiers/config/editPlugin.js)2
-rw-r--r--packages/gitbook/src/modifiers/config/getPluginConfig.js (renamed from packages/gitbook/lib/modifiers/config/getPluginConfig.js)4
-rw-r--r--packages/gitbook/src/modifiers/config/hasPlugin.js (renamed from packages/gitbook/lib/modifiers/config/hasPlugin.js)0
-rw-r--r--packages/gitbook/src/modifiers/config/index.js (renamed from packages/gitbook/lib/modifiers/config/index.js)0
-rw-r--r--packages/gitbook/src/modifiers/config/isDefaultPlugin.js (renamed from packages/gitbook/lib/modifiers/config/isDefaultPlugin.js)4
-rw-r--r--packages/gitbook/src/modifiers/config/removePlugin.js (renamed from packages/gitbook/lib/modifiers/config/removePlugin.js)6
-rw-r--r--packages/gitbook/src/modifiers/config/togglePlugin.js (renamed from packages/gitbook/lib/modifiers/config/togglePlugin.js)8
-rw-r--r--packages/gitbook/src/modifiers/index.js (renamed from packages/gitbook/lib/modifiers/index.js)0
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/editArticle.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/editArticle.js)0
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/editPartTitle.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/editPartTitle.js)19
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/insertArticle.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/insertArticle.js)26
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/insertPart.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/insertPart.js)24
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/mergeAtLevel.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/mergeAtLevel.js)22
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/moveArticle.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/moveArticle.js)24
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/moveArticleAfter.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/moveArticleAfter.js)26
-rw-r--r--packages/gitbook/src/modifiers/summary/__tests__/removeArticle.js (renamed from packages/gitbook/lib/modifiers/summary/__tests__/removeArticle.js)14
-rw-r--r--packages/gitbook/src/modifiers/summary/editArticleRef.js (renamed from packages/gitbook/lib/modifiers/summary/editArticleRef.js)2
-rw-r--r--packages/gitbook/src/modifiers/summary/editArticleTitle.js (renamed from packages/gitbook/lib/modifiers/summary/editArticleTitle.js)2
-rw-r--r--packages/gitbook/src/modifiers/summary/editPartTitle.js (renamed from packages/gitbook/lib/modifiers/summary/editPartTitle.js)4
-rw-r--r--packages/gitbook/src/modifiers/summary/index.js (renamed from packages/gitbook/lib/modifiers/summary/index.js)0
-rw-r--r--packages/gitbook/src/modifiers/summary/indexArticleLevels.js (renamed from packages/gitbook/lib/modifiers/summary/indexArticleLevels.js)4
-rw-r--r--packages/gitbook/src/modifiers/summary/indexLevels.js (renamed from packages/gitbook/lib/modifiers/summary/indexLevels.js)4
-rw-r--r--packages/gitbook/src/modifiers/summary/indexPartLevels.js (renamed from packages/gitbook/lib/modifiers/summary/indexPartLevels.js)8
-rw-r--r--packages/gitbook/src/modifiers/summary/insertArticle.js (renamed from packages/gitbook/lib/modifiers/summary/insertArticle.js)18
-rw-r--r--packages/gitbook/src/modifiers/summary/insertPart.js (renamed from packages/gitbook/lib/modifiers/summary/insertPart.js)6
-rw-r--r--packages/gitbook/src/modifiers/summary/mergeAtLevel.js (renamed from packages/gitbook/lib/modifiers/summary/mergeAtLevel.js)16
-rw-r--r--packages/gitbook/src/modifiers/summary/moveArticle.js (renamed from packages/gitbook/lib/modifiers/summary/moveArticle.js)14
-rw-r--r--packages/gitbook/src/modifiers/summary/moveArticleAfter.js (renamed from packages/gitbook/lib/modifiers/summary/moveArticleAfter.js)20
-rw-r--r--packages/gitbook/src/modifiers/summary/removeArticle.js (renamed from packages/gitbook/lib/modifiers/summary/removeArticle.js)14
-rw-r--r--packages/gitbook/src/modifiers/summary/removePart.js (renamed from packages/gitbook/lib/modifiers/summary/removePart.js)4
-rw-r--r--packages/gitbook/src/modifiers/summary/unshiftArticle.js (renamed from packages/gitbook/lib/modifiers/summary/unshiftArticle.js)12
-rw-r--r--packages/gitbook/src/output/__tests__/createMock.js (renamed from packages/gitbook/lib/output/__tests__/createMock.js)22
-rw-r--r--packages/gitbook/src/output/__tests__/ebook.js (renamed from packages/gitbook/lib/output/__tests__/ebook.js)4
-rw-r--r--packages/gitbook/src/output/__tests__/generateMock.js (renamed from packages/gitbook/lib/output/__tests__/generateMock.js)18
-rw-r--r--packages/gitbook/src/output/__tests__/json.js (renamed from packages/gitbook/lib/output/__tests__/json.js)4
-rw-r--r--packages/gitbook/src/output/__tests__/website.js (renamed from packages/gitbook/lib/output/__tests__/website.js)14
-rw-r--r--packages/gitbook/src/output/callHook.js (renamed from packages/gitbook/lib/output/callHook.js)14
-rw-r--r--packages/gitbook/src/output/callPageHook.js (renamed from packages/gitbook/lib/output/callPageHook.js)4
-rw-r--r--packages/gitbook/src/output/createTemplateEngine.js45
-rw-r--r--packages/gitbook/src/output/ebook/getConvertOptions.js (renamed from packages/gitbook/lib/output/ebook/getConvertOptions.js)24
-rw-r--r--packages/gitbook/src/output/ebook/getCoverPath.js (renamed from packages/gitbook/lib/output/ebook/getCoverPath.js)14
-rw-r--r--packages/gitbook/src/output/ebook/getPDFTemplate.js (renamed from packages/gitbook/lib/output/ebook/getPDFTemplate.js)18
-rw-r--r--packages/gitbook/src/output/ebook/index.js (renamed from packages/gitbook/lib/output/ebook/index.js)4
-rw-r--r--packages/gitbook/src/output/ebook/onFinish.js (renamed from packages/gitbook/lib/output/ebook/onFinish.js)40
-rw-r--r--packages/gitbook/src/output/ebook/onPage.js (renamed from packages/gitbook/lib/output/ebook/onPage.js)6
-rw-r--r--packages/gitbook/src/output/ebook/options.js (renamed from packages/gitbook/lib/output/ebook/options.js)4
-rw-r--r--packages/gitbook/src/output/generateAssets.js (renamed from packages/gitbook/lib/output/generateAssets.js)6
-rw-r--r--packages/gitbook/src/output/generateBook.js (renamed from packages/gitbook/lib/output/generateBook.js)74
-rw-r--r--packages/gitbook/src/output/generatePage.js (renamed from packages/gitbook/lib/output/generatePage.js)32
-rw-r--r--packages/gitbook/src/output/generatePages.js (renamed from packages/gitbook/lib/output/generatePages.js)10
-rw-r--r--packages/gitbook/src/output/getModifiers.js (renamed from packages/gitbook/lib/output/getModifiers.js)38
-rw-r--r--packages/gitbook/src/output/helper/fileToOutput.js (renamed from packages/gitbook/lib/output/helper/fileToOutput.js)14
-rw-r--r--packages/gitbook/src/output/helper/fileToURL.js (renamed from packages/gitbook/lib/output/helper/fileToURL.js)10
-rw-r--r--packages/gitbook/src/output/helper/index.js (renamed from packages/gitbook/lib/output/helper/index.js)0
-rw-r--r--packages/gitbook/src/output/helper/resolveFileToURL.js (renamed from packages/gitbook/lib/output/helper/resolveFileToURL.js)6
-rw-r--r--packages/gitbook/src/output/helper/writeFile.js (renamed from packages/gitbook/lib/output/helper/writeFile.js)6
-rw-r--r--packages/gitbook/src/output/index.js (renamed from packages/gitbook/lib/output/index.js)6
-rw-r--r--packages/gitbook/src/output/json/index.js (renamed from packages/gitbook/lib/output/json/index.js)0
-rw-r--r--packages/gitbook/src/output/json/onFinish.js (renamed from packages/gitbook/lib/output/json/onFinish.js)18
-rw-r--r--packages/gitbook/src/output/json/onPage.js (renamed from packages/gitbook/lib/output/json/onPage.js)20
-rw-r--r--packages/gitbook/src/output/json/options.js (renamed from packages/gitbook/lib/output/json/options.js)4
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/addHeadingId.js (renamed from packages/gitbook/lib/output/modifiers/__tests__/addHeadingId.js)13
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/annotateText.js (renamed from packages/gitbook/lib/output/modifiers/__tests__/annotateText.js)23
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/fetchRemoteImages.js39
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/highlightCode.js (renamed from packages/gitbook/lib/output/modifiers/__tests__/highlightCode.js)23
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/inlinePng.js24
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/resolveLinks.js (renamed from packages/gitbook/lib/output/modifiers/__tests__/resolveLinks.js)44
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/svgToImg.js24
-rw-r--r--packages/gitbook/src/output/modifiers/__tests__/svgToPng.js32
-rw-r--r--packages/gitbook/src/output/modifiers/addHeadingId.js (renamed from packages/gitbook/lib/output/modifiers/addHeadingId.js)4
-rw-r--r--packages/gitbook/src/output/modifiers/annotateText.js (renamed from packages/gitbook/lib/output/modifiers/annotateText.js)45
-rw-r--r--packages/gitbook/src/output/modifiers/editHTMLElement.js (renamed from packages/gitbook/lib/output/modifiers/editHTMLElement.js)6
-rw-r--r--packages/gitbook/src/output/modifiers/fetchRemoteImages.js (renamed from packages/gitbook/lib/output/modifiers/fetchRemoteImages.js)22
-rw-r--r--packages/gitbook/src/output/modifiers/highlightCode.js (renamed from packages/gitbook/lib/output/modifiers/highlightCode.js)14
-rw-r--r--packages/gitbook/src/output/modifiers/index.js (renamed from packages/gitbook/lib/output/modifiers/index.js)0
-rw-r--r--packages/gitbook/src/output/modifiers/inlineAssets.js (renamed from packages/gitbook/lib/output/modifiers/inlineAssets.js)12
-rw-r--r--packages/gitbook/src/output/modifiers/inlinePng.js (renamed from packages/gitbook/lib/output/modifiers/inlinePng.js)22
-rw-r--r--packages/gitbook/src/output/modifiers/modifyHTML.js (renamed from packages/gitbook/lib/output/modifiers/modifyHTML.js)10
-rw-r--r--packages/gitbook/src/output/modifiers/resolveImages.js (renamed from packages/gitbook/lib/output/modifiers/resolveImages.js)10
-rw-r--r--packages/gitbook/src/output/modifiers/resolveLinks.js (renamed from packages/gitbook/lib/output/modifiers/resolveLinks.js)14
-rw-r--r--packages/gitbook/src/output/modifiers/svgToImg.js (renamed from packages/gitbook/lib/output/modifiers/svgToImg.js)26
-rw-r--r--packages/gitbook/src/output/modifiers/svgToPng.js (renamed from packages/gitbook/lib/output/modifiers/svgToPng.js)24
-rw-r--r--packages/gitbook/src/output/prepareAssets.js (renamed from packages/gitbook/lib/output/prepareAssets.js)8
-rw-r--r--packages/gitbook/src/output/preparePages.js (renamed from packages/gitbook/lib/output/preparePages.js)8
-rw-r--r--packages/gitbook/src/output/preparePlugins.js (renamed from packages/gitbook/lib/output/preparePlugins.js)8
-rw-r--r--packages/gitbook/src/output/website/__tests__/i18n.js (renamed from packages/gitbook/lib/output/website/__tests__/i18n.js)16
-rw-r--r--packages/gitbook/src/output/website/copyPluginAssets.js (renamed from packages/gitbook/lib/output/website/copyPluginAssets.js)44
-rw-r--r--packages/gitbook/src/output/website/createTemplateEngine.js (renamed from packages/gitbook/lib/output/website/createTemplateEngine.js)81
-rw-r--r--packages/gitbook/src/output/website/index.js (renamed from packages/gitbook/lib/output/website/index.js)0
-rw-r--r--packages/gitbook/src/output/website/listSearchPaths.js (renamed from packages/gitbook/lib/output/website/listSearchPaths.js)6
-rw-r--r--packages/gitbook/src/output/website/onAsset.js (renamed from packages/gitbook/lib/output/website/onAsset.js)14
-rw-r--r--packages/gitbook/src/output/website/onFinish.js35
-rw-r--r--packages/gitbook/src/output/website/onInit.js (renamed from packages/gitbook/lib/output/website/onInit.js)8
-rw-r--r--packages/gitbook/src/output/website/onPage.js (renamed from packages/gitbook/lib/output/website/onPage.js)50
-rw-r--r--packages/gitbook/src/output/website/options.js (renamed from packages/gitbook/lib/output/website/options.js)4
-rw-r--r--packages/gitbook/src/output/website/prepareI18n.js (renamed from packages/gitbook/lib/output/website/prepareI18n.js)16
-rw-r--r--packages/gitbook/src/output/website/prepareResources.js (renamed from packages/gitbook/lib/output/website/prepareResources.js)26
-rw-r--r--packages/gitbook/src/output/website/state.js (renamed from packages/gitbook/lib/output/website/state.js)6
-rw-r--r--packages/gitbook/src/parse/__tests__/listAssets.js (renamed from packages/gitbook/lib/parse/__tests__/listAssets.js)14
-rw-r--r--packages/gitbook/src/parse/__tests__/parseBook.js (renamed from packages/gitbook/lib/parse/__tests__/parseBook.js)38
-rw-r--r--packages/gitbook/src/parse/__tests__/parseGlossary.js (renamed from packages/gitbook/lib/parse/__tests__/parseGlossary.js)24
-rw-r--r--packages/gitbook/src/parse/__tests__/parseIgnore.js (renamed from packages/gitbook/lib/parse/__tests__/parseIgnore.js)10
-rw-r--r--packages/gitbook/src/parse/__tests__/parsePageFromString.js (renamed from packages/gitbook/lib/parse/__tests__/parsePageFromString.js)20
-rw-r--r--packages/gitbook/src/parse/__tests__/parseReadme.js (renamed from packages/gitbook/lib/parse/__tests__/parseReadme.js)20
-rw-r--r--packages/gitbook/src/parse/__tests__/parseSummary.js (renamed from packages/gitbook/lib/parse/__tests__/parseSummary.js)22
-rw-r--r--packages/gitbook/src/parse/findParsableFile.js (renamed from packages/gitbook/lib/parse/findParsableFile.js)18
-rw-r--r--packages/gitbook/src/parse/index.js (renamed from packages/gitbook/lib/parse/index.js)0
-rw-r--r--packages/gitbook/src/parse/listAssets.js (renamed from packages/gitbook/lib/parse/listAssets.js)20
-rw-r--r--packages/gitbook/src/parse/lookupStructureFile.js (renamed from packages/gitbook/lib/parse/lookupStructureFile.js)6
-rw-r--r--packages/gitbook/src/parse/parseBook.js (renamed from packages/gitbook/lib/parse/parseBook.js)28
-rw-r--r--packages/gitbook/src/parse/parseConfig.js (renamed from packages/gitbook/lib/parse/parseConfig.js)16
-rw-r--r--packages/gitbook/src/parse/parseGlossary.js (renamed from packages/gitbook/lib/parse/parseGlossary.js)8
-rw-r--r--packages/gitbook/src/parse/parseIgnore.js (renamed from packages/gitbook/lib/parse/parseIgnore.js)10
-rw-r--r--packages/gitbook/src/parse/parseLanguages.js (renamed from packages/gitbook/lib/parse/parseLanguages.js)8
-rw-r--r--packages/gitbook/src/parse/parsePage.js (renamed from packages/gitbook/lib/parse/parsePage.js)6
-rw-r--r--packages/gitbook/src/parse/parsePageFromString.js (renamed from packages/gitbook/lib/parse/parsePageFromString.js)8
-rw-r--r--packages/gitbook/src/parse/parsePagesList.js (renamed from packages/gitbook/lib/parse/parsePagesList.js)24
-rw-r--r--packages/gitbook/src/parse/parseReadme.js (renamed from packages/gitbook/lib/parse/parseReadme.js)10
-rw-r--r--packages/gitbook/src/parse/parseStructureFile.js (renamed from packages/gitbook/lib/parse/parseStructureFile.js)12
-rw-r--r--packages/gitbook/src/parse/parseSummary.js (renamed from packages/gitbook/lib/parse/parseSummary.js)16
-rw-r--r--packages/gitbook/src/parse/validateConfig.js (renamed from packages/gitbook/lib/parse/validateConfig.js)16
-rw-r--r--packages/gitbook/src/parse/walkSummary.js (renamed from packages/gitbook/lib/parse/walkSummary.js)4
-rw-r--r--packages/gitbook/src/parsers.js (renamed from packages/gitbook/lib/parsers.js)20
-rw-r--r--packages/gitbook/src/plugins/__tests__/findForBook.js (renamed from packages/gitbook/lib/plugins/__tests__/findForBook.js)12
-rw-r--r--packages/gitbook/src/plugins/__tests__/findInstalled.js (renamed from packages/gitbook/lib/plugins/__tests__/findInstalled.js)10
-rw-r--r--packages/gitbook/src/plugins/__tests__/installPlugin.js29
-rw-r--r--packages/gitbook/src/plugins/__tests__/installPlugins.js (renamed from packages/gitbook/lib/plugins/__tests__/installPlugins.js)16
-rw-r--r--packages/gitbook/src/plugins/__tests__/listDependencies.js (renamed from packages/gitbook/lib/plugins/__tests__/listDependencies.js)24
-rw-r--r--packages/gitbook/src/plugins/__tests__/locateRootFolder.js (renamed from packages/gitbook/lib/plugins/__tests__/locateRootFolder.js)4
-rw-r--r--packages/gitbook/src/plugins/__tests__/resolveVersion.js (renamed from packages/gitbook/lib/plugins/__tests__/resolveVersion.js)8
-rw-r--r--packages/gitbook/src/plugins/__tests__/sortDependencies.js (renamed from packages/gitbook/lib/plugins/__tests__/sortDependencies.js)20
-rw-r--r--packages/gitbook/src/plugins/__tests__/validatePlugin.js (renamed from packages/gitbook/lib/plugins/__tests__/validatePlugin.js)8
-rw-r--r--packages/gitbook/src/plugins/findForBook.js (renamed from packages/gitbook/lib/plugins/findForBook.js)10
-rw-r--r--packages/gitbook/src/plugins/findInstalled.js (renamed from packages/gitbook/lib/plugins/findInstalled.js)44
-rw-r--r--packages/gitbook/src/plugins/index.js (renamed from packages/gitbook/lib/plugins/index.js)0
-rw-r--r--packages/gitbook/src/plugins/installPlugin.js (renamed from packages/gitbook/lib/plugins/installPlugin.js)18
-rw-r--r--packages/gitbook/src/plugins/installPlugins.js (renamed from packages/gitbook/lib/plugins/installPlugins.js)16
-rw-r--r--packages/gitbook/src/plugins/listBlocks.js (renamed from packages/gitbook/lib/plugins/listBlocks.js)4
-rw-r--r--packages/gitbook/src/plugins/listDependencies.js (renamed from packages/gitbook/lib/plugins/listDependencies.js)6
-rw-r--r--packages/gitbook/src/plugins/listDepsForBook.js (renamed from packages/gitbook/lib/plugins/listDepsForBook.js)6
-rw-r--r--packages/gitbook/src/plugins/listFilters.js (renamed from packages/gitbook/lib/plugins/listFilters.js)2
-rw-r--r--packages/gitbook/src/plugins/listResources.js (renamed from packages/gitbook/lib/plugins/listResources.js)16
-rw-r--r--packages/gitbook/src/plugins/loadForBook.js (renamed from packages/gitbook/lib/plugins/loadForBook.js)24
-rw-r--r--packages/gitbook/src/plugins/loadPlugin.js (renamed from packages/gitbook/lib/plugins/loadPlugin.js)34
-rw-r--r--packages/gitbook/src/plugins/locateRootFolder.js22
-rw-r--r--packages/gitbook/src/plugins/resolveVersion.js (renamed from packages/gitbook/lib/plugins/resolveVersion.js)22
-rw-r--r--packages/gitbook/src/plugins/sortDependencies.js (renamed from packages/gitbook/lib/plugins/sortDependencies.js)14
-rw-r--r--packages/gitbook/src/plugins/toNames.js (renamed from packages/gitbook/lib/plugins/toNames.js)0
-rw-r--r--packages/gitbook/src/plugins/validateConfig.js (renamed from packages/gitbook/lib/plugins/validateConfig.js)28
-rw-r--r--packages/gitbook/src/plugins/validatePlugin.js (renamed from packages/gitbook/lib/plugins/validatePlugin.js)10
-rw-r--r--packages/gitbook/src/templating/__tests__/conrefsLoader.js (renamed from packages/gitbook/lib/templating/__tests__/conrefsLoader.js)18
-rw-r--r--packages/gitbook/src/templating/__tests__/include.md (renamed from packages/gitbook/lib/templating/__tests__/include.md)0
-rw-r--r--packages/gitbook/src/templating/__tests__/postRender.js (renamed from packages/gitbook/lib/templating/__tests__/postRender.js)14
-rw-r--r--packages/gitbook/src/templating/__tests__/replaceShortcuts.js (renamed from packages/gitbook/lib/templating/__tests__/replaceShortcuts.js)12
-rw-r--r--packages/gitbook/src/templating/conrefsLoader.js (renamed from packages/gitbook/lib/templating/conrefsLoader.js)30
-rw-r--r--packages/gitbook/src/templating/index.js (renamed from packages/gitbook/lib/templating/index.js)0
-rw-r--r--packages/gitbook/src/templating/listShortcuts.js (renamed from packages/gitbook/lib/templating/listShortcuts.js)6
-rw-r--r--packages/gitbook/src/templating/postRender.js (renamed from packages/gitbook/lib/templating/postRender.js)16
-rw-r--r--packages/gitbook/src/templating/render.js (renamed from packages/gitbook/lib/templating/render.js)12
-rw-r--r--packages/gitbook/src/templating/renderFile.js (renamed from packages/gitbook/lib/templating/renderFile.js)12
-rw-r--r--packages/gitbook/src/templating/replaceShortcuts.js (renamed from packages/gitbook/lib/templating/replaceShortcuts.js)16
-rw-r--r--packages/gitbook/src/templating/themesLoader.js (renamed from packages/gitbook/lib/templating/themesLoader.js)48
-rw-r--r--packages/gitbook/src/utils/__tests__/git.js (renamed from packages/gitbook/lib/utils/__tests__/git.js)14
-rw-r--r--packages/gitbook/src/utils/__tests__/location.js (renamed from packages/gitbook/lib/utils/__tests__/location.js)3
-rw-r--r--packages/gitbook/src/utils/__tests__/path.js (renamed from packages/gitbook/lib/utils/__tests__/path.js)4
-rw-r--r--packages/gitbook/src/utils/command.js (renamed from packages/gitbook/lib/utils/command.js)36
-rw-r--r--packages/gitbook/src/utils/error.js (renamed from packages/gitbook/lib/utils/error.js)48
-rw-r--r--packages/gitbook/src/utils/fs.js (renamed from packages/gitbook/lib/utils/fs.js)62
-rw-r--r--packages/gitbook/src/utils/genKey.js (renamed from packages/gitbook/lib/utils/genKey.js)4
-rw-r--r--packages/gitbook/src/utils/git.js135
-rw-r--r--packages/gitbook/src/utils/images.js (renamed from packages/gitbook/lib/utils/images.js)24
-rw-r--r--packages/gitbook/src/utils/location.js (renamed from packages/gitbook/lib/utils/location.js)40
-rw-r--r--packages/gitbook/src/utils/logger.js (renamed from packages/gitbook/lib/utils/logger.js)48
-rw-r--r--packages/gitbook/src/utils/mergeDefaults.js (renamed from packages/gitbook/lib/utils/mergeDefaults.js)6
-rw-r--r--packages/gitbook/src/utils/path.js (renamed from packages/gitbook/lib/utils/path.js)25
-rw-r--r--packages/gitbook/src/utils/promise.js (renamed from packages/gitbook/lib/utils/promise.js)14
-rw-r--r--packages/gitbook/src/utils/reducedObject.js (renamed from packages/gitbook/lib/utils/reducedObject.js)8
-rw-r--r--packages/gitbook/src/utils/timing.js (renamed from packages/gitbook/lib/utils/timing.js)34
294 files changed, 2775 insertions, 2813 deletions
diff --git a/package.json b/package.json
index 878eaa8..5940776 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"private": true,
"devDependencies": {
- "eslint": "2.10.2",
+ "eslint": "3.4.0",
"eslint-config-gitbook": "^1.2.0",
"expect": "^1.20.1",
"lerna": "2.0.0-beta.26",
diff --git a/packages/gitbook/lib/cli/getBook.js b/packages/gitbook/lib/cli/getBook.js
deleted file mode 100644
index ac82187..0000000
--- a/packages/gitbook/lib/cli/getBook.js
+++ /dev/null
@@ -1,23 +0,0 @@
-var path = require('path');
-var Book = require('../models/book');
-var createNodeFS = require('../fs/node');
-
-/**
- Return a book instance to work on from
- command line args/kwargs
-
- @param {Array} args
- @param {Object} kwargs
- @return {Book}
-*/
-function getBook(args, kwargs) {
- var input = path.resolve(args[0] || process.cwd());
- var logLevel = kwargs.log;
-
- var fs = createNodeFS(input);
- var book = Book.createForFS(fs);
-
- return book.setLogLevel(logLevel);
-}
-
-module.exports = getBook;
diff --git a/packages/gitbook/lib/cli/getOutputFolder.js b/packages/gitbook/lib/cli/getOutputFolder.js
deleted file mode 100644
index 272dff9..0000000
--- a/packages/gitbook/lib/cli/getOutputFolder.js
+++ /dev/null
@@ -1,17 +0,0 @@
-var path = require('path');
-
-/**
- Return path to output folder
-
- @param {Array} args
- @return {String}
-*/
-function getOutputFolder(args) {
- var bookRoot = path.resolve(args[0] || process.cwd());
- var defaultOutputRoot = path.join(bookRoot, '_book');
- var outputFolder = args[1]? path.resolve(process.cwd(), args[1]) : defaultOutputRoot;
-
- return outputFolder;
-}
-
-module.exports = getOutputFolder;
diff --git a/packages/gitbook/lib/cli/init.js b/packages/gitbook/lib/cli/init.js
deleted file mode 100644
index 55f1b15..0000000
--- a/packages/gitbook/lib/cli/init.js
+++ /dev/null
@@ -1,17 +0,0 @@
-var path = require('path');
-
-var options = require('./options');
-var initBook = require('../init');
-
-module.exports = {
- name: 'init [book]',
- description: 'setup and create files for chapters',
- options: [
- options.log
- ],
- exec: function(args, kwargs) {
- var bookRoot = path.resolve(process.cwd(), args[0] || './');
-
- return initBook(bookRoot);
- }
-};
diff --git a/packages/gitbook/lib/cli/server.js b/packages/gitbook/lib/cli/server.js
deleted file mode 100644
index 752f867..0000000
--- a/packages/gitbook/lib/cli/server.js
+++ /dev/null
@@ -1,128 +0,0 @@
-var events = require('events');
-var http = require('http');
-var send = require('send');
-var util = require('util');
-var url = require('url');
-
-var Promise = require('../utils/promise');
-
-function Server() {
- this.running = null;
- this.dir = null;
- this.port = 0;
- this.sockets = [];
-}
-util.inherits(Server, events.EventEmitter);
-
-/**
- Return true if the server is running
-
- @return {Boolean}
-*/
-Server.prototype.isRunning = function() {
- return !!this.running;
-};
-
-/**
- Stop the server
-
- @return {Promise}
-*/
-Server.prototype.stop = function() {
- var that = this;
- if (!this.isRunning()) return Promise();
-
- var d = Promise.defer();
- this.running.close(function(err) {
- that.running = null;
- that.emit('state', false);
-
- if (err) d.reject(err);
- else d.resolve();
- });
-
- for (var i = 0; i < this.sockets.length; i++) {
- this.sockets[i].destroy();
- }
-
- return d.promise;
-};
-
-/**
- Start the server
-
- @return {Promise}
-*/
-Server.prototype.start = function(dir, port) {
- var that = this, pre = Promise();
- port = port || 8004;
-
- if (that.isRunning()) pre = this.stop();
- return pre
- .then(function() {
- var d = Promise.defer();
-
- that.running = http.createServer(function(req, res){
- // Render error
- function error(err) {
- res.statusCode = err.status || 500;
- res.end(err.message);
- }
-
- // Redirect to directory's index.html
- function redirect() {
- var resultURL = urlTransform(req.url, function(parsed) {
- parsed.pathname += '/';
- return parsed;
- });
-
- res.statusCode = 301;
- res.setHeader('Location', resultURL);
- res.end('Redirecting to ' + resultURL);
- }
-
- res.setHeader('X-Current-Location', req.url);
-
- // Send file
- send(req, url.parse(req.url).pathname, {
- root: dir
- })
- .on('error', error)
- .on('directory', redirect)
- .pipe(res);
- });
-
- that.running.on('connection', function (socket) {
- that.sockets.push(socket);
- socket.setTimeout(4000);
- socket.on('close', function () {
- that.sockets.splice(that.sockets.indexOf(socket), 1);
- });
- });
-
- that.running.listen(port, function(err) {
- if (err) return d.reject(err);
-
- that.port = port;
- that.dir = dir;
- that.emit('state', true);
- d.resolve();
- });
-
- return d.promise;
- });
-};
-
-/**
- urlTransform is a helper function that allows a function to transform
- a url string in it's parsed form and returns the new url as a string
-
- @param {String} uri
- @param {Function} fn
- @return {String}
-*/
-function urlTransform(uri, fn) {
- return url.format(fn(url.parse(uri)));
-}
-
-module.exports = Server;
diff --git a/packages/gitbook/lib/constants/configDefault.js b/packages/gitbook/lib/constants/configDefault.js
deleted file mode 100644
index 0d95883..0000000
--- a/packages/gitbook/lib/constants/configDefault.js
+++ /dev/null
@@ -1,6 +0,0 @@
-var Immutable = require('immutable');
-var jsonSchemaDefaults = require('json-schema-defaults');
-
-var schema = require('./configSchema');
-
-module.exports = Immutable.fromJS(jsonSchemaDefaults(schema));
diff --git a/packages/gitbook/lib/json/encodeBook.js b/packages/gitbook/lib/json/encodeBook.js
deleted file mode 100644
index 9d7ec77..0000000
--- a/packages/gitbook/lib/json/encodeBook.js
+++ /dev/null
@@ -1,39 +0,0 @@
-var extend = require('extend');
-
-var gitbook = require('../gitbook');
-var encodeSummary = require('./encodeSummary');
-var encodeGlossary = require('./encodeGlossary');
-var encodeReadme = require('./encodeReadme');
-var encodeLanguages = require('./encodeLanguages');
-
-/**
- Encode a book to JSON
-
- @param {Book}
- @return {Object}
-*/
-function encodeBookToJson(book) {
- var config = book.getConfig();
- var language = book.getLanguage();
-
- var variables = config.getValue('variables', {});
-
- return {
- summary: encodeSummary(book.getSummary()),
- glossary: encodeGlossary(book.getGlossary()),
- readme: encodeReadme(book.getReadme()),
- config: book.getConfig().getValues().toJS(),
-
- languages: book.isMultilingual()? encodeLanguages(book.getLanguages()) : undefined,
-
- gitbook: {
- version: gitbook.version,
- time: gitbook.START_TIME
- },
- book: extend({
- language: language? language : undefined
- }, variables.toJS())
- };
-}
-
-module.exports = encodeBookToJson;
diff --git a/packages/gitbook/lib/output/createTemplateEngine.js b/packages/gitbook/lib/output/createTemplateEngine.js
deleted file mode 100644
index 8cf320e..0000000
--- a/packages/gitbook/lib/output/createTemplateEngine.js
+++ /dev/null
@@ -1,45 +0,0 @@
-var Templating = require('../templating');
-var TemplateEngine = require('../models/templateEngine');
-
-var Api = require('../api');
-var Plugins = require('../plugins');
-
-var defaultBlocks = require('../constants/defaultBlocks');
-var defaultFilters = require('../constants/defaultFilters');
-
-/**
- Create template engine for an output.
- It adds default filters/blocks, then add the ones from plugins
-
- @param {Output} output
- @return {TemplateEngine}
-*/
-function createTemplateEngine(output) {
- var plugins = output.getPlugins();
- var book = output.getBook();
- var rootFolder = book.getContentRoot();
- var logger = book.getLogger();
-
- var filters = Plugins.listFilters(plugins);
- var blocks = Plugins.listBlocks(plugins);
-
- // Extend with default
- blocks = defaultBlocks.merge(blocks);
- filters = defaultFilters.merge(filters);
-
- // Create loader
- var transformFn = Templating.replaceShortcuts.bind(null, blocks);
- var loader = new Templating.ConrefsLoader(rootFolder, transformFn, logger);
-
- // Create API context
- var context = Api.encodeGlobal(output);
-
- return new TemplateEngine({
- filters: filters,
- blocks: blocks,
- loader: loader,
- context: context
- });
-}
-
-module.exports = createTemplateEngine;
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/fetchRemoteImages.js b/packages/gitbook/lib/output/modifiers/__tests__/fetchRemoteImages.js
deleted file mode 100644
index bc1704d..0000000
--- a/packages/gitbook/lib/output/modifiers/__tests__/fetchRemoteImages.js
+++ /dev/null
@@ -1,40 +0,0 @@
-var cheerio = require('cheerio');
-var tmp = require('tmp');
-var path = require('path');
-
-var URL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/280px-PNG_transparency_demonstration_1.png';
-
-describe('fetchRemoteImages', function() {
- var dir;
- var fetchRemoteImages = require('../fetchRemoteImages');
-
- beforeEach(function() {
- dir = tmp.dirSync();
- });
-
- it('should download image file', function() {
- var $ = cheerio.load('<img src="' + URL + '" />');
-
- return fetchRemoteImages(dir.name, 'index.html', $)
- .then(function() {
- var $img = $('img');
- var src = $img.attr('src');
-
- expect(dir.name).toHaveFile(src);
- });
- });
-
- it('should download image file and replace with relative path', function() {
- var $ = cheerio.load('<img src="' + URL + '" />');
-
- return fetchRemoteImages(dir.name, 'test/index.html', $)
- .then(function() {
- var $img = $('img');
- var src = $img.attr('src');
-
- expect(dir.name).toHaveFile(path.join('test', src));
- });
- });
-});
-
-
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/inlinePng.js b/packages/gitbook/lib/output/modifiers/__tests__/inlinePng.js
deleted file mode 100644
index 0073cff..0000000
--- a/packages/gitbook/lib/output/modifiers/__tests__/inlinePng.js
+++ /dev/null
@@ -1,25 +0,0 @@
-var cheerio = require('cheerio');
-var tmp = require('tmp');
-var inlinePng = require('../inlinePng');
-
-describe('inlinePng', function() {
- var dir;
-
- beforeEach(function() {
- dir = tmp.dirSync();
- });
-
- it('should write an inline PNG using data URI as a file', function() {
- var $ = cheerio.load('<img alt="GitBook Logo 20x20" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUEAYAAADdGcFOAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsTAAALEwEAmpwYAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgpMwidZAAAF+klEQVRIDY3Wf5CVVR3H8c9z791fyI9dQwdQ4TTI7wEWnQZZAa/mJE4Z0OaKUuN1KoaykZxUGGHay+iIVFMoEYrUPhDCKEKW2ChT8dA0RCSxWi6EW3sYYpcfxq5C+4O9957O+7m7O/qHQ9/XzH1+nHuec57z8wkWTsKw0y6N/LxXN6KzTnEUHi8eP/l3YStSU/MdsYvBbGh8six2YXcbcgc++QkfTQkWz/81KtqDA0hlUoWnsX+5uxe5X365BB9my2bjrHNHccLk16BpS9CExjcmXMDbD6wehdyEjxbjz1uK1zn9qga6dcfnMLXeXY/qjuQqTF4W1MKke8ZgeNhjMCxMPIWSd4OF78C55CFI/1kF6WwXpMqjkAZ/CKniNDrCsmU4lE1YbPlgR2x7R39FF23D4mq3A1+Z35PGTNs1E1XhxcGQOh6HNPwXkK56BVJhOaRg/pvoHXNxHFw410B25EYE2RMvI0i/twFJvXcrFObykEa+DmnQGLwYqR0l2a6JqItaj8C/4E2QxtZCofkC8tF1t8HZc/fAZaLnIF2xEsoEtW1w7vBSSFtfhDTnCki9cSi81Ain1uko2Ld+Dmf2rkUq0/5t+PYbFtPQdkjzNiAXTWtDEF49FgkzJInAVPwNyhzcDOmrdZCm/Rn+ebWtcPs+/U24hmg2XL0rRkPPELh9R8fDtXR2oC/VuZbGaci79Ajkb6lZgfyYtyzy/X9s6T/pO/ZfN/RdNxxIwTWM2wbX8KVmuIaEqmKm6zEondwGpd0SyOy5DrJ//TFkX9kMhd3XQHbEVCSsm4OECV5HIv2p15CwfWPSntoHRbv2Q1HzSvSlSqZwATIuBxk/zZBOBbdB+u9hSKU3Q7pwAjInZkFm6U8hu7MSMqe/Dqn8fUj5GVCmpxK+4N/F1LMa0p5eSOPqIPP7NGSunAI/+R6GnzQzIBt8A1LC/QZ+6HwLst1rITv0n5CtXgSZ78yFTNkR+FdeDZneJkip3fAtsQ5Scilkek7CH9dAmjIWvkK7IXXOh6/IzZDNPQdZXR1TQmdjKv0ZfEu0YKDpNflpyG5aDtnRv8VAuu3dBV+huyBbvgdS97tQNLQc0mfugKy5Cb4BipPIXvsUpK5N8Mvao/Bd3QDZRH9Rrtj3Cl6FHwPFMLmNkKrj8BnHoT+XX6f2wl+XxFS4Ab7C72Dgf7bi+5DpTkNm8kQMpCs/BzIlz8LfPxnzLdh3EjwMX4GX4Ju4GNb9A1L7k/D3J8b6kv2LFCtmCmcgUzoJsr2z4MfwFsh87xikZefg188fYaAhpPUxm3ge/vFnYkoED0HqeQiyJYcwkNGWnoNv6s9C1p1Bf/389VYoCjohW7UfMms3wXdpBv7+FEiPLIHs4DIMNERUNhbSpY3wk6QOsqlCDVx2xCrInMpBmfNPQOnzKxBkkrugdOl9GKigSZZCUWIm/GqwDtLUI5D+WAOlb9wKP0YvQLbjZSjsaYaL/n0/FA3fDtnCGihK5UYjCK+ZDr+TDIKLdm2Fs1UOzo76F5wO74XSZj0S6d7RCMLkCshcXALZxaWQRjXDZQ62oRAdCeG/Ju5HELX2QFH3C0hkRy6GovyfwF58AoVbguOxyB2H7/I34Gf11yANnQSp7Vr4MbQH0vg7kbNNp5AM3UrIVDchnz56B1Jm573wW9gZSFVPwO/hefg5FsIvN09CchtQCIOFw/F5U8ii3CZn4cqo7C8YlXEPYkx9cacZl00+iwnprrtwVdj1Q/gXmAs/pu6LZc9XQOGgSvh19n2cDZN341g2EcfxTEGwH/RewqlMsUfbbWIGLjUG+j/j9nokD1beiOvLS5dhjr30Gu6ZnivgdtM/6VJvY1+6pBHbH+h9CX84vfMxNJtisYVFlys+WNCIZJNmIsjohlhNSQC3f8R55H+y/hjkN8GPR9ndCLJxT4/3n0Px51ay8XQnNrYfDJHf//Fc0oMrEZSeeQGJ7+Z+gKCgLbHNWgXnB9FlYt5JaN38JIINC95EakjtAqQeuUx21c5B6tEFf0fSfbEFQf28Z6D6y+X/H0jf40QQJhYwAAAAAElFTkSuQmCC"/>');
-
- return inlinePng(dir.name, 'index.html', $)
- .then(function() {
- var $img = $('img');
- var src = $img.attr('src');
-
- expect(dir.name).toHaveFile(src);
- });
- });
-});
-
-
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/svgToImg.js b/packages/gitbook/lib/output/modifiers/__tests__/svgToImg.js
deleted file mode 100644
index 5fe9796..0000000
--- a/packages/gitbook/lib/output/modifiers/__tests__/svgToImg.js
+++ /dev/null
@@ -1,25 +0,0 @@
-var cheerio = require('cheerio');
-var tmp = require('tmp');
-
-describe('svgToImg', function() {
- var dir;
- var svgToImg = require('../svgToImg');
-
- beforeEach(function() {
- dir = tmp.dirSync();
- });
-
- it('should write svg as a file', function() {
- var $ = cheerio.load('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" version="1.1"><rect width="200" height="100" stroke="black" stroke-width="6" fill="green"/></svg>');
-
- return svgToImg(dir.name, 'index.html', $)
- .then(function() {
- var $img = $('img');
- var src = $img.attr('src');
-
- expect(dir.name).toHaveFile(src);
- });
- });
-});
-
-
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/svgToPng.js b/packages/gitbook/lib/output/modifiers/__tests__/svgToPng.js
deleted file mode 100644
index dbb3502..0000000
--- a/packages/gitbook/lib/output/modifiers/__tests__/svgToPng.js
+++ /dev/null
@@ -1,33 +0,0 @@
-var cheerio = require('cheerio');
-var tmp = require('tmp');
-var path = require('path');
-
-var svgToImg = require('../svgToImg');
-var svgToPng = require('../svgToPng');
-
-describe('svgToPng', function() {
- var dir;
-
- beforeEach(function() {
- dir = tmp.dirSync();
- });
-
- it('should write svg as png file', function() {
- var $ = cheerio.load('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" version="1.1"><rect width="200" height="100" stroke="black" stroke-width="6" fill="green"/></svg>');
- var fileName = 'index.html';
-
- return svgToImg(dir.name, fileName, $)
- .then(function() {
- return svgToPng(dir.name, fileName, $);
- })
- .then(function() {
- var $img = $('img');
- var src = $img.attr('src');
-
- expect(dir.name).toHaveFile(src);
- expect(path.extname(src)).toBe('.png');
- });
- });
-});
-
-
diff --git a/packages/gitbook/lib/output/website/onFinish.js b/packages/gitbook/lib/output/website/onFinish.js
deleted file mode 100644
index 5267458..0000000
--- a/packages/gitbook/lib/output/website/onFinish.js
+++ /dev/null
@@ -1,35 +0,0 @@
-var Promise = require('../../utils/promise');
-var JSONUtils = require('../../json');
-var Templating = require('../../templating');
-var writeFile = require('../helper/writeFile');
-var createTemplateEngine = require('./createTemplateEngine');
-
-/**
- Finish the generation, write the languages index
-
- @param {Output}
- @return {Output}
-*/
-function onFinish(output) {
- var book = output.getBook();
- var options = output.getOptions();
- var prefix = options.get('prefix');
-
- if (!book.isMultilingual()) {
- return Promise(output);
- }
-
- var filePath = 'index.html';
- var engine = createTemplateEngine(output, filePath);
- var context = JSONUtils.encodeOutput(output);
-
- // Render the theme
- return Templating.renderFile(engine, prefix + '/languages.html', context)
-
- // Write it to the disk
- .then(function(tplOut) {
- return writeFile(output, filePath, tplOut.getContent());
- });
-}
-
-module.exports = onFinish;
diff --git a/packages/gitbook/lib/plugins/__tests__/installPlugin.js b/packages/gitbook/lib/plugins/__tests__/installPlugin.js
deleted file mode 100644
index 0c1a346..0000000
--- a/packages/gitbook/lib/plugins/__tests__/installPlugin.js
+++ /dev/null
@@ -1,29 +0,0 @@
-var path = require('path');
-
-var PluginDependency = require('../../models/pluginDependency');
-var Book = require('../../models/book');
-var NodeFS = require('../../fs/node');
-var installPlugin = require('../installPlugin');
-
-var Parse = require('../../parse');
-
-describe('installPlugin', function() {
- var book;
-
- this.timeout(30000);
-
- before(function() {
- var fs = NodeFS(path.resolve(__dirname, '../../../'));
- var baseBook = Book.createForFS(fs);
-
- return Parse.parseConfig(baseBook)
- .then(function(_book) {
- book = _book;
- });
- });
-
- it('must install a plugin from NPM', function() {
- var dep = PluginDependency.createFromString('ga');
- return installPlugin(book, dep);
- });
-});
diff --git a/packages/gitbook/lib/plugins/locateRootFolder.js b/packages/gitbook/lib/plugins/locateRootFolder.js
deleted file mode 100644
index 1139510..0000000
--- a/packages/gitbook/lib/plugins/locateRootFolder.js
+++ /dev/null
@@ -1,22 +0,0 @@
-var path = require('path');
-var resolve = require('resolve');
-
-var DEFAULT_PLUGINS = require('../constants/defaultPlugins');
-
-/**
- * Resolve the root folder containing for node_modules
- * since gitbook can be used as a library and dependency can be flattened.
- *
- * @return {String} folderPath
- */
-function locateRootFolder() {
- var firstDefaultPlugin = DEFAULT_PLUGINS.first();
- var pluginPath = resolve.sync(firstDefaultPlugin.getNpmID() + '/package.json', {
- basedir: __dirname
- });
- var nodeModules = path.resolve(pluginPath, '../../..');
-
- return nodeModules;
-}
-
-module.exports = locateRootFolder;
diff --git a/packages/gitbook/lib/utils/git.js b/packages/gitbook/lib/utils/git.js
deleted file mode 100644
index 6884b83..0000000
--- a/packages/gitbook/lib/utils/git.js
+++ /dev/null
@@ -1,133 +0,0 @@
-var is = require('is');
-var path = require('path');
-var crc = require('crc');
-var URI = require('urijs');
-
-var pathUtil = require('./path');
-var Promise = require('./promise');
-var command = require('./command');
-var fs = require('./fs');
-
-var GIT_PREFIX = 'git+';
-
-function Git() {
- this.tmpDir;
- this.cloned = {};
-}
-
-// Return an unique ID for a combinaison host/ref
-Git.prototype.repoID = function(host, ref) {
- return crc.crc32(host+'#'+(ref || '')).toString(16);
-};
-
-// Allocate a temporary folder for cloning repos in it
-Git.prototype.allocateDir = function() {
- var that = this;
-
- if (this.tmpDir) return Promise();
-
- return fs.tmpDir()
- .then(function(dir) {
- that.tmpDir = dir;
- });
-};
-
-// Clone a git repository if non existant
-Git.prototype.clone = function(host, ref) {
- var that = this;
-
- return this.allocateDir()
-
- // Return or clone the git repo
- .then(function() {
- // Unique ID for repo/ref combinaison
- var repoId = that.repoID(host, ref);
-
- // Absolute path to the folder
- var repoPath = path.join(that.tmpDir, repoId);
-
- if (that.cloned[repoId]) return repoPath;
-
- // Clone repo
- return command.exec('git clone '+host+' '+repoPath)
-
- // Checkout reference if specified
- .then(function() {
- that.cloned[repoId] = true;
-
- if (!ref) return;
- return command.exec('git checkout '+ref, { cwd: repoPath });
- })
- .thenResolve(repoPath);
- });
-};
-
-// Get file from a git repo
-Git.prototype.resolve = function(giturl) {
- // Path to a file in a git repo?
- if (!Git.isUrl(giturl)) {
- if (this.resolveRoot(giturl)) return Promise(giturl);
- return Promise(null);
- }
- if (is.string(giturl)) giturl = Git.parseUrl(giturl);
- if (!giturl) return Promise(null);
-
- // Clone or get from cache
- return this.clone(giturl.host, giturl.ref)
- .then(function(repo) {
- return path.resolve(repo, giturl.filepath);
- });
-};
-
-// Return root of git repo from a filepath
-Git.prototype.resolveRoot = function(filepath) {
- var relativeToGit, repoId;
-
- // No git repo cloned, or file is not in a git repository
- if (!this.tmpDir || !pathUtil.isInRoot(this.tmpDir, filepath)) return null;
-
- // Extract first directory (is the repo id)
- relativeToGit = path.relative(this.tmpDir, filepath);
- repoId = relativeToGit.split(path.sep)[0];
- if (!repoId) {
- return;
- }
-
- // Return an absolute file
- return path.resolve(this.tmpDir, repoId);
-};
-
-// Check if an url is a git dependency url
-Git.isUrl = function(giturl) {
- return (giturl.indexOf(GIT_PREFIX) === 0);
-};
-
-// Parse and extract infos
-Git.parseUrl = function(giturl) {
- var ref, uri, fileParts, filepath;
-
- if (!Git.isUrl(giturl)) return null;
- giturl = giturl.slice(GIT_PREFIX.length);
-
- uri = new URI(giturl);
- ref = uri.fragment() || null;
- uri.fragment(null);
-
- // Extract file inside the repo (after the .git)
- fileParts = uri.path().split('.git');
- filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
- if (filepath[0] == '/') {
- filepath = filepath.slice(1);
- }
-
- // Recreate pathname without the real filename
- uri.path(fileParts[0] + '.git');
-
- return {
- host: uri.toString(),
- ref: ref,
- filepath: filepath
- };
-};
-
-module.exports = Git;
diff --git a/packages/gitbook/lib/__tests__/gitbook.js b/packages/gitbook/src/__tests__/gitbook.js
index c3669bb..5292e01 100644
--- a/packages/gitbook/lib/__tests__/gitbook.js
+++ b/packages/gitbook/src/__tests__/gitbook.js
@@ -1,4 +1,4 @@
-var gitbook = require('../gitbook');
+const gitbook = require('../gitbook');
describe('satisfies', function() {
diff --git a/packages/gitbook/lib/__tests__/init.js b/packages/gitbook/src/__tests__/init.js
index 66188a3..d8e5398 100644
--- a/packages/gitbook/lib/__tests__/init.js
+++ b/packages/gitbook/src/__tests__/init.js
@@ -1,10 +1,10 @@
-var tmp = require('tmp');
-var initBook = require('../init');
+const tmp = require('tmp');
+const initBook = require('../init');
describe('initBook', function() {
it('should create a README and SUMMARY for empty book', function() {
- var dir = tmp.dirSync();
+ const dir = tmp.dirSync();
return initBook(dir.name)
.then(function() {
diff --git a/packages/gitbook/lib/__tests__/module.js b/packages/gitbook/src/__tests__/module.js
index d9220f5..d9220f5 100644
--- a/packages/gitbook/lib/__tests__/module.js
+++ b/packages/gitbook/src/__tests__/module.js
diff --git a/packages/gitbook/lib/api/decodeConfig.js b/packages/gitbook/src/api/decodeConfig.js
index 5e00df5..0c5ba66 100644
--- a/packages/gitbook/lib/api/decodeConfig.js
+++ b/packages/gitbook/src/api/decodeConfig.js
@@ -6,7 +6,7 @@
@return {Config}
*/
function decodeGlobal(config, result) {
- var values = result.values;
+ const values = result.values;
delete values.generator;
delete values.output;
diff --git a/packages/gitbook/lib/api/decodeGlobal.js b/packages/gitbook/src/api/decodeGlobal.js
index 118afb2..063683a 100644
--- a/packages/gitbook/lib/api/decodeGlobal.js
+++ b/packages/gitbook/src/api/decodeGlobal.js
@@ -1,4 +1,4 @@
-var decodeConfig = require('./decodeConfig');
+const decodeConfig = require('./decodeConfig');
/**
Decode changes from a JS API to a output object.
@@ -9,8 +9,8 @@ var decodeConfig = require('./decodeConfig');
@return {Output}
*/
function decodeGlobal(output, result) {
- var book = output.getBook();
- var config = book.getConfig();
+ let book = output.getBook();
+ let config = book.getConfig();
// Update config
config = decodeConfig(config, result.config);
diff --git a/packages/gitbook/lib/api/decodePage.js b/packages/gitbook/src/api/decodePage.js
index c85dd1b..4fd78af 100644
--- a/packages/gitbook/lib/api/decodePage.js
+++ b/packages/gitbook/src/api/decodePage.js
@@ -1,4 +1,4 @@
-var deprecate = require('./deprecate');
+const deprecate = require('./deprecate');
/**
Decode changes from a JS API to a page object.
@@ -10,7 +10,7 @@ var deprecate = require('./deprecate');
@return {Page}
*/
function decodePage(output, page, result) {
- var originalContent = page.getContent();
+ const originalContent = page.getContent();
// No returned value
// Existing content will be used
diff --git a/packages/gitbook/lib/api/deprecate.js b/packages/gitbook/src/api/deprecate.js
index 7a93a91..879355c 100644
--- a/packages/gitbook/lib/api/deprecate.js
+++ b/packages/gitbook/src/api/deprecate.js
@@ -1,8 +1,8 @@
-var is = require('is');
-var objectPath = require('object-path');
+const is = require('is');
+const objectPath = require('object-path');
-var logged = {};
-var disabled = {};
+const logged = {};
+const disabled = {};
/**
Log a deprecated notice
@@ -16,7 +16,7 @@ function logNotice(book, key, message) {
logged[key] = true;
- var logger = book.getLogger();
+ const logger = book.getLogger();
logger.warn.ln(message);
}
@@ -48,22 +48,22 @@ function deprecateMethod(book, key, fn, msg) {
@return {Function}
*/
function deprecateField(book, key, instance, property, value, msg) {
- var store = undefined;
+ let store = undefined;
- var prepare = function() {
+ const prepare = function() {
if (!is.undefined(store)) return;
if (is.fn(value)) store = value();
else store = value;
};
- var getter = function(){
+ const getter = function() {
prepare();
logNotice(book, key, msg);
return store;
};
- var setter = function(v) {
+ const setter = function(v) {
prepare();
logNotice(book, key, msg);
@@ -108,7 +108,7 @@ function disableDeprecation(key) {
*/
function deprecateRenamedMethod(book, key, instance, oldName, newName, msg) {
msg = msg || ('"' + oldName + '" is deprecated, use "' + newName + '()" instead');
- var fn = objectPath.get(instance, newName);
+ const fn = objectPath.get(instance, newName);
instance[oldName] = deprecateMethod(book, key, fn, msg);
}
diff --git a/packages/gitbook/lib/api/encodeConfig.js b/packages/gitbook/src/api/encodeConfig.js
index 2a05528..096f136 100644
--- a/packages/gitbook/lib/api/encodeConfig.js
+++ b/packages/gitbook/src/api/encodeConfig.js
@@ -1,5 +1,5 @@
-var objectPath = require('object-path');
-var deprecate = require('./deprecate');
+const objectPath = require('object-path');
+const deprecate = require('./deprecate');
/**
Encode a config object into a JS config api
@@ -9,14 +9,14 @@ var deprecate = require('./deprecate');
@return {Object}
*/
function encodeConfig(output, config) {
- var result = {
+ const result = {
values: config.getValues().toJS(),
- get: function(key, defaultValue) {
+ get(key, defaultValue) {
return objectPath.get(result.values, key, defaultValue);
},
- set: function(key, value) {
+ set(key, value) {
return objectPath.set(result.values, key, value);
}
};
diff --git a/packages/gitbook/lib/api/encodeGlobal.js b/packages/gitbook/src/api/encodeGlobal.js
index a366526..21a1e73 100644
--- a/packages/gitbook/lib/api/encodeGlobal.js
+++ b/packages/gitbook/src/api/encodeGlobal.js
@@ -1,19 +1,19 @@
-var path = require('path');
-var Promise = require('../utils/promise');
-var PathUtils = require('../utils/path');
-var fs = require('../utils/fs');
-
-var Plugins = require('../plugins');
-var deprecate = require('./deprecate');
-var fileToURL = require('../output/helper/fileToURL');
-var defaultBlocks = require('../constants/defaultBlocks');
-var gitbook = require('../gitbook');
-var parsers = require('../parsers');
-
-var encodeConfig = require('./encodeConfig');
-var encodeSummary = require('./encodeSummary');
-var encodeNavigation = require('./encodeNavigation');
-var encodePage = require('./encodePage');
+const path = require('path');
+const Promise = require('../utils/promise');
+const PathUtils = require('../utils/path');
+const fs = require('../utils/fs');
+
+const Plugins = require('../plugins');
+const deprecate = require('./deprecate');
+const fileToURL = require('../output/helper/fileToURL');
+const defaultBlocks = require('../constants/defaultBlocks');
+const gitbook = require('../gitbook');
+const parsers = require('../parsers');
+
+const encodeConfig = require('./encodeConfig');
+const encodeSummary = require('./encodeSummary');
+const encodeNavigation = require('./encodeNavigation');
+const encodePage = require('./encodePage');
/**
Encode a global context into a JS object
@@ -23,14 +23,14 @@ var encodePage = require('./encodePage');
@return {Object}
*/
function encodeGlobal(output) {
- var book = output.getBook();
- var bookFS = book.getContentFS();
- var logger = output.getLogger();
- var outputFolder = output.getRoot();
- var plugins = output.getPlugins();
- var blocks = Plugins.listBlocks(plugins);
-
- var result = {
+ const book = output.getBook();
+ const bookFS = book.getContentFS();
+ const logger = output.getLogger();
+ const outputFolder = output.getRoot();
+ const plugins = output.getPlugins();
+ const blocks = Plugins.listBlocks(plugins);
+
+ const result = {
log: logger,
config: encodeConfig(output, book.getConfig()),
summary: encodeSummary(output, book.getSummary()),
@@ -40,7 +40,7 @@ function encodeGlobal(output) {
@return {Boolean}
*/
- isMultilingual: function() {
+ isMultilingual() {
return book.isMultilingual();
},
@@ -49,7 +49,7 @@ function encodeGlobal(output) {
@return {Boolean}
*/
- isLanguageBook: function() {
+ isLanguageBook() {
return book.isLanguageBook();
},
@@ -59,7 +59,7 @@ function encodeGlobal(output) {
@param {String} fileName
@return {Promise<Buffer>}
*/
- readFile: function(fileName) {
+ readFile(fileName) {
return bookFS.read(fileName);
},
@@ -69,7 +69,7 @@ function encodeGlobal(output) {
@param {String} fileName
@return {Promise<String>}
*/
- readFileAsString: function(fileName) {
+ readFileAsString(fileName) {
return bookFS.readAsString(fileName);
},
@@ -79,7 +79,7 @@ function encodeGlobal(output) {
@param {String} fileName
@return {String}
*/
- resolve: function(fileName) {
+ resolve(fileName) {
return path.resolve(book.getContentRoot(), fileName);
},
@@ -89,8 +89,8 @@ function encodeGlobal(output) {
@param {String} filePath
@return {String}
*/
- getPageByPath: function(filePath) {
- var page = output.getPage(filePath);
+ getPageByPath(filePath) {
+ const page = output.getPage(filePath);
if (!page) return undefined;
return encodePage(output, page);
@@ -103,8 +103,8 @@ function encodeGlobal(output) {
@param {String} text
@return {Promise<String>}
*/
- renderBlock: function(type, text) {
- var parser = parsers.get(type);
+ renderBlock(type, text) {
+ const parser = parsers.get(type);
return parser.parsePage(text)
.get('content');
@@ -117,14 +117,15 @@ function encodeGlobal(output) {
@param {String} text
@return {Promise<String>}
*/
- renderInline: function(type, text) {
- var parser = parsers.get(type);
+ renderInline(type, text) {
+ const parser = parsers.get(type);
return parser.parseInline(text)
.get('content');
},
template: {
+
/**
Apply a templating block and returns its result
@@ -132,13 +133,14 @@ function encodeGlobal(output) {
@param {Object} blockData
@return {Promise|Object}
*/
- applyBlock: function(name, blockData) {
- var block = blocks.get(name) || defaultBlocks.get(name);
+ applyBlock(name, blockData) {
+ const block = blocks.get(name) || defaultBlocks.get(name);
return Promise(block.applyBlock(blockData, result));
}
},
output: {
+
/**
Name of the generator being used
{String}
@@ -149,7 +151,7 @@ function encodeGlobal(output) {
Return absolute path to the root folder of output
@return {String}
*/
- root: function() {
+ root() {
return outputFolder;
},
@@ -159,7 +161,7 @@ function encodeGlobal(output) {
@param {String} fileName
@return {String}
*/
- resolve: function(fileName) {
+ resolve(fileName) {
return path.resolve(outputFolder, fileName);
},
@@ -167,7 +169,7 @@ function encodeGlobal(output) {
Convert a filepath into an url
@return {String}
*/
- toURL: function(filePath) {
+ toURL(filePath) {
return fileToURL(output, filePath);
},
@@ -177,10 +179,10 @@ function encodeGlobal(output) {
@param {String} fileName
@return {Promise}
*/
- hasFile: function(fileName, content) {
+ hasFile(fileName, content) {
return Promise()
.then(function() {
- var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
+ const filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.exists(filePath);
});
@@ -194,10 +196,10 @@ function encodeGlobal(output) {
@param {Buffer} content
@return {Promise}
*/
- writeFile: function(fileName, content) {
+ writeFile(fileName, content) {
return Promise()
.then(function() {
- var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
+ const filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.ensureFile(filePath)
.then(function() {
@@ -215,10 +217,10 @@ function encodeGlobal(output) {
@param {Buffer} content
@return {Promise}
*/
- copyFile: function(inputFile, outputFile, content) {
+ copyFile(inputFile, outputFile, content) {
return Promise()
.then(function() {
- var outputFilePath = PathUtils.resolveInRoot(outputFolder, outputFile);
+ const outputFilePath = PathUtils.resolveInRoot(outputFolder, outputFile);
return fs.ensureFile(outputFilePath)
.then(function() {
diff --git a/packages/gitbook/lib/api/encodeNavigation.js b/packages/gitbook/src/api/encodeNavigation.js
index 8e329a1..d54239d 100644
--- a/packages/gitbook/lib/api/encodeNavigation.js
+++ b/packages/gitbook/src/api/encodeNavigation.js
@@ -1,4 +1,4 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
/**
Encode an article for next/prev
@@ -8,7 +8,7 @@ var Immutable = require('immutable');
@return {Object}
*/
function encodeArticle(pages, article) {
- var articlePath = article.getPath();
+ const articlePath = article.getPath();
return {
path: articlePath,
@@ -26,21 +26,21 @@ function encodeArticle(pages, article) {
@return {Object}
*/
function encodeNavigation(output) {
- var book = output.getBook();
- var pages = output.getPages();
- var summary = book.getSummary();
- var articles = summary.getArticlesAsList();
+ const book = output.getBook();
+ const pages = output.getPages();
+ const summary = book.getSummary();
+ const articles = summary.getArticlesAsList();
- var navigation = articles
+ const navigation = articles
.map(function(article, i) {
- var ref = article.getRef();
+ const ref = article.getRef();
if (!ref) {
return undefined;
}
- var prev = articles.get(i - 1);
- var next = articles.get(i + 1);
+ const prev = articles.get(i - 1);
+ const next = articles.get(i + 1);
return [
ref,
@@ -48,8 +48,8 @@ function encodeNavigation(output) {
index: i,
title: article.getTitle(),
introduction: (i === 0),
- prev: prev? encodeArticle(pages, prev) : undefined,
- next: next? encodeArticle(pages, next) : undefined,
+ prev: prev ? encodeArticle(pages, prev) : undefined,
+ next: next ? encodeArticle(pages, next) : undefined,
level: article.getLevel()
}
];
diff --git a/packages/gitbook/lib/api/encodePage.js b/packages/gitbook/src/api/encodePage.js
index 379d3d5..fb77fcd 100644
--- a/packages/gitbook/lib/api/encodePage.js
+++ b/packages/gitbook/src/api/encodePage.js
@@ -1,6 +1,6 @@
-var JSONUtils = require('../json');
-var deprecate = require('./deprecate');
-var encodeProgress = require('./encodeProgress');
+const JSONUtils = require('../json');
+const deprecate = require('./deprecate');
+const encodeProgress = require('./encodeProgress');
/**
Encode a page in a context to a JS API
@@ -10,13 +10,13 @@ var encodeProgress = require('./encodeProgress');
@return {Object}
*/
function encodePage(output, page) {
- var book = output.getBook();
- var summary = book.getSummary();
- var fs = book.getContentFS();
- var file = page.getFile();
+ const book = output.getBook();
+ const summary = book.getSummary();
+ const fs = book.getContentFS();
+ const file = page.getFile();
// JS Page is based on the JSON output
- var result = JSONUtils.encodePage(page, summary);
+ const result = JSONUtils.encodePage(page, summary);
result.type = file.getType();
result.path = file.getPath();
diff --git a/packages/gitbook/lib/api/encodeProgress.js b/packages/gitbook/src/api/encodeProgress.js
index afa0341..3224370 100644
--- a/packages/gitbook/lib/api/encodeProgress.js
+++ b/packages/gitbook/src/api/encodeProgress.js
@@ -1,5 +1,5 @@
-var Immutable = require('immutable');
-var encodeNavigation = require('./encodeNavigation');
+const Immutable = require('immutable');
+const encodeNavigation = require('./encodeNavigation');
/**
page.progress is a deprecated property from GitBook v2
@@ -9,15 +9,15 @@ var encodeNavigation = require('./encodeNavigation');
@return {Object}
*/
function encodeProgress(output, page) {
- var current = page.getPath();
- var navigation = encodeNavigation(output);
+ const current = page.getPath();
+ let navigation = encodeNavigation(output);
navigation = Immutable.Map(navigation);
- var n = navigation.size;
- var percent = 0, prevPercent = 0, currentChapter = null;
- var done = true;
+ const n = navigation.size;
+ let percent = 0, prevPercent = 0, currentChapter = null;
+ let done = true;
- var chapters = navigation
+ const chapters = navigation
.map(function(nav, chapterPath) {
nav.path = chapterPath;
return nav;
@@ -46,13 +46,13 @@ function encodeProgress(output, page) {
return {
// Previous percent
- prevPercent: prevPercent,
+ prevPercent,
// Current percent
- percent: percent,
+ percent,
// List of chapter with progress
- chapters: chapters,
+ chapters,
// Current chapter
current: currentChapter
diff --git a/packages/gitbook/lib/api/encodeSummary.js b/packages/gitbook/src/api/encodeSummary.js
index 0d66ded..323f5d4 100644
--- a/packages/gitbook/lib/api/encodeSummary.js
+++ b/packages/gitbook/src/api/encodeSummary.js
@@ -1,4 +1,4 @@
-var encodeSummaryArticle = require('../json/encodeSummaryArticle');
+const encodeSummaryArticle = require('../json/encodeSummaryArticle');
/**
Encode summary to provide an API to plugin
@@ -8,15 +8,16 @@ var encodeSummaryArticle = require('../json/encodeSummaryArticle');
@return {Object}
*/
function encodeSummary(output, summary) {
- var result = {
+ const result = {
+
/**
Iterate over the summary, it stops when the "iter" returns false
@param {Function} iter
*/
- walk: function (iter) {
+ walk(iter) {
summary.getArticle(function(article) {
- var jsonArticle = encodeSummaryArticle(article, false);
+ const jsonArticle = encodeSummaryArticle(article, false);
return iter(jsonArticle);
});
@@ -28,9 +29,9 @@ function encodeSummary(output, summary) {
@param {String} level
@return {Object}
*/
- getArticleByLevel: function(level) {
- var article = summary.getByLevel(level);
- return (article? encodeSummaryArticle(article) : undefined);
+ getArticleByLevel(level) {
+ const article = summary.getByLevel(level);
+ return (article ? encodeSummaryArticle(article) : undefined);
},
/**
@@ -39,9 +40,9 @@ function encodeSummary(output, summary) {
@param {String} level
@return {Object}
*/
- getArticleByPath: function(level) {
- var article = summary.getByPath(level);
- return (article? encodeSummaryArticle(article) : undefined);
+ getArticleByPath(level) {
+ const article = summary.getByPath(level);
+ return (article ? encodeSummaryArticle(article) : undefined);
}
};
diff --git a/packages/gitbook/lib/api/index.js b/packages/gitbook/src/api/index.js
index 5e67525..5e67525 100644
--- a/packages/gitbook/lib/api/index.js
+++ b/packages/gitbook/src/api/index.js
diff --git a/packages/gitbook/lib/browser.js b/packages/gitbook/src/browser.js
index 87a4dc4..771ecd5 100644
--- a/packages/gitbook/lib/browser.js
+++ b/packages/gitbook/src/browser.js
@@ -1,4 +1,4 @@
-var Modifiers = require('./modifiers');
+const Modifiers = require('./modifiers');
module.exports = {
Parse: require('./parse'),
diff --git a/packages/gitbook/lib/cli/build.js b/packages/gitbook/src/cli/build.js
index 023901e..3f5c937 100644
--- a/packages/gitbook/lib/cli/build.js
+++ b/packages/gitbook/src/cli/build.js
@@ -1,10 +1,10 @@
-var Parse = require('../parse');
-var Output = require('../output');
-var timing = require('../utils/timing');
+const Parse = require('../parse');
+const Output = require('../output');
+const timing = require('../utils/timing');
-var options = require('./options');
-var getBook = require('./getBook');
-var getOutputFolder = require('./getOutputFolder');
+const options = require('./options');
+const getBook = require('./getBook');
+const getOutputFolder = require('./getOutputFolder');
module.exports = {
@@ -15,11 +15,11 @@ module.exports = {
options.format,
options.timing
],
- exec: function(args, kwargs) {
- var book = getBook(args, kwargs);
- var outputFolder = getOutputFolder(args);
+ exec(args, kwargs) {
+ const book = getBook(args, kwargs);
+ const outputFolder = getOutputFolder(args);
- var Generator = Output.getGenerator(kwargs.format);
+ const Generator = Output.getGenerator(kwargs.format);
return Parse.parseBook(book)
.then(function(resultBook) {
diff --git a/packages/gitbook/lib/cli/buildEbook.js b/packages/gitbook/src/cli/buildEbook.js
index a87fac7..56e63f8 100644
--- a/packages/gitbook/lib/cli/buildEbook.js
+++ b/packages/gitbook/src/cli/buildEbook.js
@@ -1,13 +1,13 @@
-var path = require('path');
-var tmp = require('tmp');
+const path = require('path');
+const tmp = require('tmp');
-var Promise = require('../utils/promise');
-var fs = require('../utils/fs');
-var Parse = require('../parse');
-var Output = require('../output');
+const Promise = require('../utils/promise');
+const fs = require('../utils/fs');
+const Parse = require('../parse');
+const Output = require('../output');
-var options = require('./options');
-var getBook = require('./getBook');
+const options = require('./options');
+const getBook = require('./getBook');
module.exports = function(format) {
@@ -17,37 +17,37 @@ module.exports = function(format) {
options: [
options.log
],
- exec: function(args, kwargs) {
- var extension = '.' + format;
+ exec(args, kwargs) {
+ const extension = '.' + format;
// Output file will be stored in
- var outputFile = args[1] || ('book' + extension);
+ const outputFile = args[1] || ('book' + extension);
// Create temporary directory
- var outputFolder = tmp.dirSync().name;
+ const outputFolder = tmp.dirSync().name;
- var book = getBook(args, kwargs);
- var logger = book.getLogger();
- var Generator = Output.getGenerator('ebook');
+ const book = getBook(args, kwargs);
+ const logger = book.getLogger();
+ const Generator = Output.getGenerator('ebook');
return Parse.parseBook(book)
.then(function(resultBook) {
return Output.generate(Generator, resultBook, {
root: outputFolder,
- format: format
+ format
});
})
// Extract ebook file
.then(function(output) {
- var book = output.getBook();
- var languages = book.getLanguages();
+ const book = output.getBook();
+ const languages = book.getLanguages();
if (book.isMultilingual()) {
return Promise.forEach(languages.getList(), function(lang) {
- var langID = lang.getID();
+ const langID = lang.getID();
- var langOutputFile = path.join(
+ const langOutputFile = path.join(
path.dirname(outputFile),
path.basename(outputFile, extension) + '_' + langID + extension
);
diff --git a/packages/gitbook/src/cli/getBook.js b/packages/gitbook/src/cli/getBook.js
new file mode 100644
index 0000000..b37e49c
--- /dev/null
+++ b/packages/gitbook/src/cli/getBook.js
@@ -0,0 +1,23 @@
+const path = require('path');
+const Book = require('../models/book');
+const createNodeFS = require('../fs/node');
+
+/**
+ Return a book instance to work on from
+ command line args/kwargs
+
+ @param {Array} args
+ @param {Object} kwargs
+ @return {Book}
+*/
+function getBook(args, kwargs) {
+ const input = path.resolve(args[0] || process.cwd());
+ const logLevel = kwargs.log;
+
+ const fs = createNodeFS(input);
+ const book = Book.createForFS(fs);
+
+ return book.setLogLevel(logLevel);
+}
+
+module.exports = getBook;
diff --git a/packages/gitbook/src/cli/getOutputFolder.js b/packages/gitbook/src/cli/getOutputFolder.js
new file mode 100644
index 0000000..94f22da
--- /dev/null
+++ b/packages/gitbook/src/cli/getOutputFolder.js
@@ -0,0 +1,17 @@
+const path = require('path');
+
+/**
+ Return path to output folder
+
+ @param {Array} args
+ @return {String}
+*/
+function getOutputFolder(args) {
+ const bookRoot = path.resolve(args[0] || process.cwd());
+ const defaultOutputRoot = path.join(bookRoot, '_book');
+ const outputFolder = args[1] ? path.resolve(process.cwd(), args[1]) : defaultOutputRoot;
+
+ return outputFolder;
+}
+
+module.exports = getOutputFolder;
diff --git a/packages/gitbook/lib/cli/index.js b/packages/gitbook/src/cli/index.js
index f1fca1d..48ad117 100644
--- a/packages/gitbook/lib/cli/index.js
+++ b/packages/gitbook/src/cli/index.js
@@ -1,4 +1,4 @@
-var buildEbook = require('./buildEbook');
+const buildEbook = require('./buildEbook');
module.exports = [
require('./build'),
diff --git a/packages/gitbook/src/cli/init.js b/packages/gitbook/src/cli/init.js
new file mode 100644
index 0000000..51d6869
--- /dev/null
+++ b/packages/gitbook/src/cli/init.js
@@ -0,0 +1,17 @@
+const path = require('path');
+
+const options = require('./options');
+const initBook = require('../init');
+
+module.exports = {
+ name: 'init [book]',
+ description: 'setup and create files for chapters',
+ options: [
+ options.log
+ ],
+ exec(args, kwargs) {
+ const bookRoot = path.resolve(process.cwd(), args[0] || './');
+
+ return initBook(bookRoot);
+ }
+};
diff --git a/packages/gitbook/lib/cli/install.js b/packages/gitbook/src/cli/install.js
index c001711..6af4013 100644
--- a/packages/gitbook/lib/cli/install.js
+++ b/packages/gitbook/src/cli/install.js
@@ -1,8 +1,8 @@
-var options = require('./options');
-var getBook = require('./getBook');
+const options = require('./options');
+const getBook = require('./getBook');
-var Parse = require('../parse');
-var Plugins = require('../plugins');
+const Parse = require('../parse');
+const Plugins = require('../plugins');
module.exports = {
name: 'install [book]',
@@ -10,8 +10,8 @@ module.exports = {
options: [
options.log
],
- exec: function(args, kwargs) {
- var book = getBook(args, kwargs);
+ exec(args, kwargs) {
+ const book = getBook(args, kwargs);
return Parse.parseConfig(book)
.then(function(resultBook) {
diff --git a/packages/gitbook/lib/cli/options.js b/packages/gitbook/src/cli/options.js
index 72961ab..d643f91 100644
--- a/packages/gitbook/lib/cli/options.js
+++ b/packages/gitbook/src/cli/options.js
@@ -1,6 +1,6 @@
-var Logger = require('../utils/logger');
+const Logger = require('../utils/logger');
-var logOptions = {
+const logOptions = {
name: 'log',
description: 'Minimum log level to display',
values: Logger.LEVELS
@@ -11,14 +11,14 @@ var logOptions = {
defaults: 'info'
};
-var formatOption = {
+const formatOption = {
name: 'format',
description: 'Format to build to',
values: ['website', 'json', 'ebook'],
defaults: 'website'
};
-var timingOption = {
+const timingOption = {
name: 'timing',
description: 'Print timing debug information',
defaults: false
diff --git a/packages/gitbook/lib/cli/parse.js b/packages/gitbook/src/cli/parse.js
index 0fa509a..3d38fe7 100644
--- a/packages/gitbook/lib/cli/parse.js
+++ b/packages/gitbook/src/cli/parse.js
@@ -1,22 +1,22 @@
-var options = require('./options');
-var getBook = require('./getBook');
+const options = require('./options');
+const getBook = require('./getBook');
-var Parse = require('../parse');
+const Parse = require('../parse');
function printBook(book) {
- var logger = book.getLogger();
+ const logger = book.getLogger();
- var config = book.getConfig();
- var configFile = config.getFile();
+ const config = book.getConfig();
+ const configFile = config.getFile();
- var summary = book.getSummary();
- var summaryFile = summary.getFile();
+ const summary = book.getSummary();
+ const summaryFile = summary.getFile();
- var readme = book.getReadme();
- var readmeFile = readme.getFile();
+ const readme = book.getReadme();
+ const readmeFile = readme.getFile();
- var glossary = book.getGlossary();
- var glossaryFile = glossary.getFile();
+ const glossary = book.getGlossary();
+ const glossaryFile = glossary.getFile();
if (configFile.exists()) {
logger.info.ln('Configuration file is', configFile.getPath());
@@ -36,9 +36,9 @@ function printBook(book) {
}
function printMultingualBook(book) {
- var logger = book.getLogger();
- var languages = book.getLanguages();
- var books = book.getBooks();
+ const logger = book.getLogger();
+ const languages = book.getLanguages();
+ const books = book.getBooks();
logger.info.ln(languages.size + ' languages');
@@ -55,14 +55,14 @@ module.exports = {
options: [
options.log
],
- exec: function(args, kwargs) {
- var book = getBook(args, kwargs);
- var logger = book.getLogger();
+ exec(args, kwargs) {
+ const book = getBook(args, kwargs);
+ const logger = book.getLogger();
return Parse.parseBook(book)
.then(function(resultBook) {
- var rootFolder = book.getRoot();
- var contentFolder = book.getContentRoot();
+ const rootFolder = book.getRoot();
+ const contentFolder = book.getContentRoot();
logger.info.ln('Book located in:', rootFolder);
if (contentFolder != rootFolder) {
diff --git a/packages/gitbook/lib/cli/serve.js b/packages/gitbook/src/cli/serve.js
index 5340851..6397c2e 100644
--- a/packages/gitbook/lib/cli/serve.js
+++ b/packages/gitbook/src/cli/serve.js
@@ -1,24 +1,24 @@
/* eslint-disable no-console */
-var tinylr = require('tiny-lr');
-var open = require('open');
+const tinylr = require('tiny-lr');
+const open = require('open');
-var Parse = require('../parse');
-var Output = require('../output');
-var ConfigModifier = require('../modifiers').Config;
+const Parse = require('../parse');
+const Output = require('../output');
+const ConfigModifier = require('../modifiers').Config;
-var Promise = require('../utils/promise');
+const Promise = require('../utils/promise');
-var options = require('./options');
-var getBook = require('./getBook');
-var getOutputFolder = require('./getOutputFolder');
-var Server = require('./server');
-var watch = require('./watch');
+const options = require('./options');
+const getBook = require('./getBook');
+const getOutputFolder = require('./getOutputFolder');
+const Server = require('./server');
+const watch = require('./watch');
-var server, lrServer, lrPath;
+let server, lrServer, lrPath;
function waitForCtrlC() {
- var d = Promise.defer();
+ const d = Promise.defer();
process.on('SIGINT', function() {
d.resolve();
@@ -29,15 +29,15 @@ function waitForCtrlC() {
function generateBook(args, kwargs) {
- var port = kwargs.port;
- var outputFolder = getOutputFolder(args);
- var book = getBook(args, kwargs);
- var Generator = Output.getGenerator(kwargs.format);
- var browser = kwargs['browser'];
+ const port = kwargs.port;
+ const outputFolder = getOutputFolder(args);
+ const book = getBook(args, kwargs);
+ const Generator = Output.getGenerator(kwargs.format);
+ const browser = kwargs['browser'];
- var hasWatch = kwargs['watch'];
- var hasLiveReloading = kwargs['live'];
- var hasOpen = kwargs['open'];
+ const hasWatch = kwargs['watch'];
+ const hasLiveReloading = kwargs['live'];
+ const hasOpen = kwargs['open'];
// Stop server if running
if (server.isRunning()) console.log('Stopping server');
@@ -48,7 +48,7 @@ function generateBook(args, kwargs) {
.then(function(resultBook) {
if (hasLiveReloading) {
// Enable livereload plugin
- var config = resultBook.getConfig();
+ let config = resultBook.getConfig();
config = ConfigModifier.addPlugin(config, 'livereload');
resultBook = resultBook.set('config', config);
}
@@ -64,7 +64,7 @@ function generateBook(args, kwargs) {
return server.start(outputFolder, port);
})
.then(function() {
- console.log('Serving book on http://localhost:'+port);
+ console.log('Serving book on http://localhost:' + port);
if (lrPath && hasLiveReloading) {
// trigger livereload
@@ -76,7 +76,7 @@ function generateBook(args, kwargs) {
}
if (hasOpen) {
- open('http://localhost:'+port, browser);
+ open('http://localhost:' + port, browser);
}
})
.then(function() {
@@ -132,10 +132,10 @@ module.exports = {
options.log,
options.format
],
- exec: function(args, kwargs) {
+ exec(args, kwargs) {
server = new Server();
- var hasWatch = kwargs['watch'];
- var hasLiveReloading = kwargs['live'];
+ const hasWatch = kwargs['watch'];
+ const hasLiveReloading = kwargs['live'];
return Promise()
.then(function() {
diff --git a/packages/gitbook/src/cli/server.js b/packages/gitbook/src/cli/server.js
new file mode 100644
index 0000000..c494efc
--- /dev/null
+++ b/packages/gitbook/src/cli/server.js
@@ -0,0 +1,127 @@
+const events = require('events');
+const http = require('http');
+const send = require('send');
+const url = require('url');
+
+const Promise = require('../utils/promise');
+
+class Server extends events.EventEmitter {
+ constructor() {
+ super();
+ this.running = null;
+ this.dir = null;
+ this.port = 0;
+ this.sockets = [];
+ }
+
+ /**
+ * Return true if the server is running
+ * @return {Boolean}
+ */
+ isRunning() {
+ return !!this.running;
+ }
+
+ /**
+ * Stop the server
+ * @return {Promise}
+ */
+ stop() {
+ const that = this;
+ if (!this.isRunning()) return Promise();
+
+ const d = Promise.defer();
+ this.running.close(function(err) {
+ that.running = null;
+ that.emit('state', false);
+
+ if (err) d.reject(err);
+ else d.resolve();
+ });
+
+ for (let i = 0; i < this.sockets.length; i++) {
+ this.sockets[i].destroy();
+ }
+
+ return d.promise;
+ }
+
+ /**
+ * Start the server
+ * @return {Promise}
+ */
+ start(dir, port) {
+ const that = this;
+ let pre = Promise();
+ port = port || 8004;
+
+ if (that.isRunning()) pre = this.stop();
+ return pre
+ .then(function() {
+ const d = Promise.defer();
+
+ that.running = http.createServer(function(req, res) {
+ // Render error
+ function error(err) {
+ res.statusCode = err.status || 500;
+ res.end(err.message);
+ }
+
+ // Redirect to directory's index.html
+ function redirect() {
+ const resultURL = urlTransform(req.url, function(parsed) {
+ parsed.pathname += '/';
+ return parsed;
+ });
+
+ res.statusCode = 301;
+ res.setHeader('Location', resultURL);
+ res.end('Redirecting to ' + resultURL);
+ }
+
+ res.setHeader('X-Current-Location', req.url);
+
+ // Send file
+ send(req, url.parse(req.url).pathname, {
+ root: dir
+ })
+ .on('error', error)
+ .on('directory', redirect)
+ .pipe(res);
+ });
+
+ that.running.on('connection', function(socket) {
+ that.sockets.push(socket);
+ socket.setTimeout(4000);
+ socket.on('close', function() {
+ that.sockets.splice(that.sockets.indexOf(socket), 1);
+ });
+ });
+
+ that.running.listen(port, function(err) {
+ if (err) return d.reject(err);
+
+ that.port = port;
+ that.dir = dir;
+ that.emit('state', true);
+ d.resolve();
+ });
+
+ return d.promise;
+ });
+ }
+}
+
+/**
+ * urlTransform is a helper function that allows a function to transform
+ * a url string in it's parsed form and returns the new url as a string
+ *
+ * @param {String} uri
+ * @param {Function} fn
+ * @return {String}
+ */
+function urlTransform(uri, fn) {
+ return url.format(fn(url.parse(uri)));
+}
+
+module.exports = Server;
diff --git a/packages/gitbook/lib/cli/watch.js b/packages/gitbook/src/cli/watch.js
index 14434ab..e1d453c 100644
--- a/packages/gitbook/lib/cli/watch.js
+++ b/packages/gitbook/src/cli/watch.js
@@ -1,8 +1,8 @@
-var path = require('path');
-var chokidar = require('chokidar');
+const path = require('path');
+const chokidar = require('chokidar');
-var Promise = require('../utils/promise');
-var parsers = require('../parsers');
+const Promise = require('../utils/promise');
+const parsers = require('../parsers');
/**
Watch a folder and resolve promise once a file is modified
@@ -11,19 +11,19 @@ var parsers = require('../parsers');
@return {Promise}
*/
function watch(dir) {
- var d = Promise.defer();
+ const d = Promise.defer();
dir = path.resolve(dir);
- var toWatch = [
+ const toWatch = [
'book.json', 'book.js', '_layouts/**'
];
// Watch all parsable files
parsers.extensions.forEach(function(ext) {
- toWatch.push('**/*'+ext);
+ toWatch.push('**/*' + ext);
});
- var watcher = chokidar.watch(toWatch, {
+ const watcher = chokidar.watch(toWatch, {
cwd: dir,
ignored: '_book/**',
ignoreInitial: true
diff --git a/packages/gitbook/lib/constants/__tests__/configSchema.js b/packages/gitbook/src/constants/__tests__/configSchema.js
index efc99b9..df83680 100644
--- a/packages/gitbook/lib/constants/__tests__/configSchema.js
+++ b/packages/gitbook/src/constants/__tests__/configSchema.js
@@ -1,10 +1,10 @@
-var jsonschema = require('jsonschema');
-var schema = require('../configSchema');
+const jsonschema = require('jsonschema');
+const schema = require('../configSchema');
describe('configSchema', function() {
function validate(cfg) {
- var v = new jsonschema.Validator();
+ const v = new jsonschema.Validator();
return v.validate(cfg, schema, {
propertyName: 'config'
});
@@ -13,7 +13,7 @@ describe('configSchema', function() {
describe('structure', function() {
it('should accept dot in filename', function() {
- var result = validate({
+ const result = validate({
structure: {
readme: 'book-intro.adoc'
}
@@ -23,7 +23,7 @@ describe('configSchema', function() {
});
it('should accept uppercase in filename', function() {
- var result = validate({
+ const result = validate({
structure: {
readme: 'BOOK.adoc'
}
@@ -33,7 +33,7 @@ describe('configSchema', function() {
});
it('should not accept filepath', function() {
- var result = validate({
+ const result = validate({
structure: {
readme: 'folder/myFile.md'
}
diff --git a/packages/gitbook/src/constants/configDefault.js b/packages/gitbook/src/constants/configDefault.js
new file mode 100644
index 0000000..c384c6c
--- /dev/null
+++ b/packages/gitbook/src/constants/configDefault.js
@@ -0,0 +1,6 @@
+const Immutable = require('immutable');
+const jsonSchemaDefaults = require('json-schema-defaults');
+
+const schema = require('./configSchema');
+
+module.exports = Immutable.fromJS(jsonSchemaDefaults(schema));
diff --git a/packages/gitbook/lib/constants/configFiles.js b/packages/gitbook/src/constants/configFiles.js
index a67fd74..a67fd74 100644
--- a/packages/gitbook/lib/constants/configFiles.js
+++ b/packages/gitbook/src/constants/configFiles.js
diff --git a/packages/gitbook/lib/constants/configSchema.js b/packages/gitbook/src/constants/configSchema.js
index d2126c6..9aaf8cd 100644
--- a/packages/gitbook/lib/constants/configSchema.js
+++ b/packages/gitbook/src/constants/configSchema.js
@@ -1,4 +1,4 @@
-var FILENAME_REGEX = '^[a-zA-Z-._\d,\s]+$';
+const FILENAME_REGEX = '^[a-zA-Z-._\d,\s]+$';
module.exports = {
'$schema': 'http://json-schema.org/schema#',
diff --git a/packages/gitbook/lib/constants/defaultBlocks.js b/packages/gitbook/src/constants/defaultBlocks.js
index 74d1f1f..05c9b09 100644
--- a/packages/gitbook/lib/constants/defaultBlocks.js
+++ b/packages/gitbook/src/constants/defaultBlocks.js
@@ -1,17 +1,17 @@
-var Immutable = require('immutable');
-var TemplateBlock = require('../models/templateBlock');
+const Immutable = require('immutable');
+const TemplateBlock = require('../models/templateBlock');
module.exports = Immutable.Map({
html: TemplateBlock({
name: 'html',
- process: function(blk) {
+ process(blk) {
return blk;
}
}),
code: TemplateBlock({
name: 'code',
- process: function(blk) {
+ process(blk) {
return {
html: false,
body: blk.body
@@ -21,7 +21,7 @@ module.exports = Immutable.Map({
markdown: TemplateBlock({
name: 'markdown',
- process: function(blk) {
+ process(blk) {
return this.book.renderInline('markdown', blk.body)
.then(function(out) {
return { body: out };
@@ -31,7 +31,7 @@ module.exports = Immutable.Map({
asciidoc: TemplateBlock({
name: 'asciidoc',
- process: function(blk) {
+ process(blk) {
return this.book.renderInline('asciidoc', blk.body)
.then(function(out) {
return { body: out };
@@ -41,7 +41,7 @@ module.exports = Immutable.Map({
markup: TemplateBlock({
name: 'markup',
- process: function(blk) {
+ process(blk) {
return this.book.renderInline(this.ctx.file.type, blk.body)
.then(function(out) {
return { body: out };
diff --git a/packages/gitbook/lib/constants/defaultFilters.js b/packages/gitbook/src/constants/defaultFilters.js
index 35025cc..c9bffe1 100644
--- a/packages/gitbook/lib/constants/defaultFilters.js
+++ b/packages/gitbook/src/constants/defaultFilters.js
@@ -1,15 +1,15 @@
-var Immutable = require('immutable');
-var moment = require('moment');
+const Immutable = require('immutable');
+const moment = require('moment');
module.exports = Immutable.Map({
// Format a date
// ex: 'MMMM Do YYYY, h:mm:ss a
- date: function(time, format) {
+ date(time, format) {
return moment(time).format(format);
},
// Relative Time
- dateFromNow: function(time) {
+ dateFromNow(time) {
return moment(time).fromNow();
}
});
diff --git a/packages/gitbook/lib/constants/defaultPlugins.js b/packages/gitbook/src/constants/defaultPlugins.js
index 6d15971..cd1c0c8 100644
--- a/packages/gitbook/lib/constants/defaultPlugins.js
+++ b/packages/gitbook/src/constants/defaultPlugins.js
@@ -1,7 +1,7 @@
-var Immutable = require('immutable');
-var PluginDependency = require('../models/pluginDependency');
+const Immutable = require('immutable');
+const PluginDependency = require('../models/pluginDependency');
-var pkg = require('../../package.json');
+const pkg = require('../../package.json');
/**
* Create a PluginDependency from a dependency of gitbook
@@ -9,8 +9,8 @@ var pkg = require('../../package.json');
* @return {PluginDependency}
*/
function createFromDependency(pluginName) {
- var npmID = PluginDependency.nameToNpmID(pluginName);
- var version = pkg.dependencies[npmID];
+ const npmID = PluginDependency.nameToNpmID(pluginName);
+ const version = pkg.dependencies[npmID];
return PluginDependency.create(pluginName, version);
}
diff --git a/packages/gitbook/lib/constants/extsAsciidoc.js b/packages/gitbook/src/constants/extsAsciidoc.js
index b2f4ce4..b2f4ce4 100644
--- a/packages/gitbook/lib/constants/extsAsciidoc.js
+++ b/packages/gitbook/src/constants/extsAsciidoc.js
diff --git a/packages/gitbook/lib/constants/extsMarkdown.js b/packages/gitbook/src/constants/extsMarkdown.js
index 44bf36b..44bf36b 100644
--- a/packages/gitbook/lib/constants/extsMarkdown.js
+++ b/packages/gitbook/src/constants/extsMarkdown.js
diff --git a/packages/gitbook/lib/constants/ignoreFiles.js b/packages/gitbook/src/constants/ignoreFiles.js
index aac225e..aac225e 100644
--- a/packages/gitbook/lib/constants/ignoreFiles.js
+++ b/packages/gitbook/src/constants/ignoreFiles.js
diff --git a/packages/gitbook/lib/constants/pluginAssetsFolder.js b/packages/gitbook/src/constants/pluginAssetsFolder.js
index cd44722..cd44722 100644
--- a/packages/gitbook/lib/constants/pluginAssetsFolder.js
+++ b/packages/gitbook/src/constants/pluginAssetsFolder.js
diff --git a/packages/gitbook/lib/constants/pluginHooks.js b/packages/gitbook/src/constants/pluginHooks.js
index 2d5dcaa..2d5dcaa 100644
--- a/packages/gitbook/lib/constants/pluginHooks.js
+++ b/packages/gitbook/src/constants/pluginHooks.js
diff --git a/packages/gitbook/lib/constants/pluginPrefix.js b/packages/gitbook/src/constants/pluginPrefix.js
index c7f2dd0..c7f2dd0 100644
--- a/packages/gitbook/lib/constants/pluginPrefix.js
+++ b/packages/gitbook/src/constants/pluginPrefix.js
diff --git a/packages/gitbook/lib/constants/pluginResources.js b/packages/gitbook/src/constants/pluginResources.js
index ae283bf..cc9d134 100644
--- a/packages/gitbook/lib/constants/pluginResources.js
+++ b/packages/gitbook/src/constants/pluginResources.js
@@ -1,4 +1,4 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
module.exports = Immutable.List([
'js',
diff --git a/packages/gitbook/lib/constants/templatesFolder.js b/packages/gitbook/src/constants/templatesFolder.js
index aad6a72..aad6a72 100644
--- a/packages/gitbook/lib/constants/templatesFolder.js
+++ b/packages/gitbook/src/constants/templatesFolder.js
diff --git a/packages/gitbook/lib/constants/themePrefix.js b/packages/gitbook/src/constants/themePrefix.js
index 99428de..621e85c 100644
--- a/packages/gitbook/lib/constants/themePrefix.js
+++ b/packages/gitbook/src/constants/themePrefix.js
@@ -1,4 +1,4 @@
/*
All GitBook themes plugins name start with this prefix once shorted.
*/
-module.exports = 'theme-'; \ No newline at end of file
+module.exports = 'theme-';
diff --git a/packages/gitbook/lib/fs/__tests__/mock.js b/packages/gitbook/src/fs/__tests__/mock.js
index 04bd46a..7d1ea48 100644
--- a/packages/gitbook/lib/fs/__tests__/mock.js
+++ b/packages/gitbook/src/fs/__tests__/mock.js
@@ -1,7 +1,7 @@
-var createMockFS = require('../mock');
+const createMockFS = require('../mock');
describe('MockFS', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'README.md': 'Hello World',
'SUMMARY.md': '# Summary',
'folder': {
@@ -79,4 +79,3 @@ describe('MockFS', function() {
});
});
-
diff --git a/packages/gitbook/lib/fs/mock.js b/packages/gitbook/src/fs/mock.js
index 784c533..91f3bd6 100644
--- a/packages/gitbook/lib/fs/mock.js
+++ b/packages/gitbook/src/fs/mock.js
@@ -1,10 +1,10 @@
-var path = require('path');
-var is = require('is');
-var Buffer = require('buffer').Buffer;
-var Immutable = require('immutable');
+const path = require('path');
+const is = require('is');
+const Buffer = require('buffer').Buffer;
+const Immutable = require('immutable');
-var FS = require('../models/fs');
-var error = require('../utils/error');
+const FS = require('../models/fs');
+const error = require('../utils/error');
/**
Create a fake filesystem for unit testing GitBook.
@@ -13,14 +13,14 @@ var error = require('../utils/error');
*/
function createMockFS(files) {
files = Immutable.fromJS(files);
- var mtime = new Date();
+ const mtime = new Date();
function getFile(filePath) {
- var parts = path.normalize(filePath).split(path.sep);
+ const parts = path.normalize(filePath).split(path.sep);
return parts.reduce(function(list, part, i) {
if (!list) return null;
- var file;
+ let file;
if (!part || part === '.') file = list;
else file = list.get(part);
@@ -41,7 +41,7 @@ function createMockFS(files) {
}
function fsReadFile(filePath) {
- var file = getFile(filePath);
+ const file = getFile(filePath);
if (!is.string(file)) {
throw error.FileNotFoundError({
filename: filePath
@@ -52,7 +52,7 @@ function createMockFS(files) {
}
function fsStatFile(filePath) {
- var file = getFile(filePath);
+ const file = getFile(filePath);
if (!file) {
throw error.FileNotFoundError({
filename: filePath
@@ -60,12 +60,12 @@ function createMockFS(files) {
}
return {
- mtime: mtime
+ mtime
};
}
function fsReadDir(filePath) {
- var dir = getFile(filePath);
+ const dir = getFile(filePath);
if (!dir || is.string(dir)) {
throw error.FileNotFoundError({
filename: filePath
@@ -85,10 +85,10 @@ function createMockFS(files) {
return FS.create({
root: '',
- fsExists: fsExists,
- fsReadFile: fsReadFile,
- fsStatFile: fsStatFile,
- fsReadDir: fsReadDir
+ fsExists,
+ fsReadFile,
+ fsStatFile,
+ fsReadDir
});
}
diff --git a/packages/gitbook/lib/fs/node.js b/packages/gitbook/src/fs/node.js
index dfe9fae..6e28daf 100644
--- a/packages/gitbook/lib/fs/node.js
+++ b/packages/gitbook/src/fs/node.js
@@ -1,9 +1,9 @@
-var path = require('path');
-var Immutable = require('immutable');
-var fresh = require('fresh-require');
+const path = require('path');
+const Immutable = require('immutable');
+const fresh = require('fresh-require');
-var fs = require('../utils/fs');
-var FS = require('../models/fs');
+const fs = require('../utils/fs');
+const FS = require('../models/fs');
function fsReadDir(folder) {
return fs.readdir(folder)
@@ -14,7 +14,7 @@ function fsReadDir(folder) {
.map(function(file) {
if (file == '.' || file == '..') return;
- var stat = fs.statSync(path.join(folder, file));
+ const stat = fs.statSync(path.join(folder, file));
if (stat.isDirectory()) file = file + path.sep;
return file;
})
@@ -30,13 +30,13 @@ function fsLoadObject(filename) {
module.exports = function createNodeFS(root) {
return FS.create({
- root: root,
+ root,
fsExists: fs.exists,
fsReadFile: fs.readFile,
fsStatFile: fs.stat,
- fsReadDir: fsReadDir,
- fsLoadObject: fsLoadObject,
+ fsReadDir,
+ fsLoadObject,
fsReadAsStream: fs.readStream
});
};
diff --git a/packages/gitbook/lib/gitbook.js b/packages/gitbook/src/gitbook.js
index bafd3b8..5786e68 100644
--- a/packages/gitbook/lib/gitbook.js
+++ b/packages/gitbook/src/gitbook.js
@@ -1,10 +1,10 @@
-var semver = require('semver');
-var pkg = require('../package.json');
+const semver = require('semver');
+const pkg = require('../package.json');
-var VERSION = pkg.version;
-var VERSION_STABLE = VERSION.replace(/\-(\S+)/g, '');
+const VERSION = pkg.version;
+const VERSION_STABLE = VERSION.replace(/\-(\S+)/g, '');
-var START_TIME = new Date();
+const START_TIME = new Date();
/**
Verify that this gitbook version satisfies a requirement
@@ -23,6 +23,6 @@ function satisfies(condition) {
module.exports = {
version: pkg.version,
- satisfies: satisfies,
- START_TIME: START_TIME
+ satisfies,
+ START_TIME
};
diff --git a/packages/gitbook/lib/index.js b/packages/gitbook/src/index.js
index 1f683e2..7919000 100644
--- a/packages/gitbook/lib/index.js
+++ b/packages/gitbook/src/index.js
@@ -1,6 +1,6 @@
-var extend = require('extend');
+const extend = require('extend');
-var common = require('./browser');
+const common = require('./browser');
module.exports = extend({
initBook: require('./init'),
diff --git a/packages/gitbook/lib/init.js b/packages/gitbook/src/init.js
index c112d4d..bbd5f90 100644
--- a/packages/gitbook/lib/init.js
+++ b/packages/gitbook/src/init.js
@@ -1,12 +1,12 @@
-var path = require('path');
+const path = require('path');
-var createNodeFS = require('./fs/node');
-var fs = require('./utils/fs');
-var Promise = require('./utils/promise');
-var File = require('./models/file');
-var Readme = require('./models/readme');
-var Book = require('./models/book');
-var Parse = require('./parse');
+const createNodeFS = require('./fs/node');
+const fs = require('./utils/fs');
+const Promise = require('./utils/promise');
+const File = require('./models/file');
+const Readme = require('./models/readme');
+const Book = require('./models/book');
+const Parse = require('./parse');
/**
Initialize folder structure for a book
@@ -17,38 +17,38 @@ var Parse = require('./parse');
@return {Promise}
*/
function initBook(rootFolder) {
- var extension = '.md';
+ const extension = '.md';
return fs.mkdirp(rootFolder)
// Parse the summary and readme
.then(function() {
- var fs = createNodeFS(rootFolder);
- var book = Book.createForFS(fs);
+ const bookFS = createNodeFS(rootFolder);
+ const book = Book.createForFS(bookFS);
return Parse.parseReadme(book)
// Setup default readme if doesn't found one
.fail(function() {
- var readmeFile = File.createWithFilepath('README' + extension);
- var readme = Readme.create(readmeFile);
+ const readmeFile = File.createWithFilepath('README' + extension);
+ const readme = Readme.create(readmeFile);
return book.setReadme(readme);
});
})
.then(Parse.parseSummary)
.then(function(book) {
- var logger = book.getLogger();
- var summary = book.getSummary();
- var summaryFile = summary.getFile();
- var summaryFilename = summaryFile.getPath() || ('SUMMARY' + extension);
+ const logger = book.getLogger();
+ const summary = book.getSummary();
+ const summaryFile = summary.getFile();
+ const summaryFilename = summaryFile.getPath() || ('SUMMARY' + extension);
- var articles = summary.getArticlesAsList();
+ const articles = summary.getArticlesAsList();
// Write pages
return Promise.forEach(articles, function(article) {
- var articlePath = article.getPath();
- var filePath = articlePath? path.join(rootFolder, articlePath) : null;
+ const articlePath = article.getPath();
+ const filePath = articlePath ? path.join(rootFolder, articlePath) : null;
if (!filePath) {
return;
}
@@ -64,7 +64,7 @@ function initBook(rootFolder) {
// Write summary
.then(function() {
- var filePath = path.join(rootFolder, summaryFilename);
+ const filePath = path.join(rootFolder, summaryFilename);
return fs.ensureFile(filePath)
.then(function() {
diff --git a/packages/gitbook/src/json/encodeBook.js b/packages/gitbook/src/json/encodeBook.js
new file mode 100644
index 0000000..0b259a9
--- /dev/null
+++ b/packages/gitbook/src/json/encodeBook.js
@@ -0,0 +1,39 @@
+const extend = require('extend');
+
+const gitbook = require('../gitbook');
+const encodeSummary = require('./encodeSummary');
+const encodeGlossary = require('./encodeGlossary');
+const encodeReadme = require('./encodeReadme');
+const encodeLanguages = require('./encodeLanguages');
+
+/**
+ Encode a book to JSON
+
+ @param {Book}
+ @return {Object}
+*/
+function encodeBookToJson(book) {
+ const config = book.getConfig();
+ const language = book.getLanguage();
+
+ const variables = config.getValue('variables', {});
+
+ return {
+ summary: encodeSummary(book.getSummary()),
+ glossary: encodeGlossary(book.getGlossary()),
+ readme: encodeReadme(book.getReadme()),
+ config: book.getConfig().getValues().toJS(),
+
+ languages: book.isMultilingual() ? encodeLanguages(book.getLanguages()) : undefined,
+
+ gitbook: {
+ version: gitbook.version,
+ time: gitbook.START_TIME
+ },
+ book: extend({
+ language: language ? language : undefined
+ }, variables.toJS())
+ };
+}
+
+module.exports = encodeBookToJson;
diff --git a/packages/gitbook/lib/json/encodeBookWithPage.js b/packages/gitbook/src/json/encodeBookWithPage.js
index 1c5c7a3..f593af2 100644
--- a/packages/gitbook/lib/json/encodeBookWithPage.js
+++ b/packages/gitbook/src/json/encodeBookWithPage.js
@@ -1,6 +1,6 @@
-var encodeBook = require('./encodeBook');
-var encodePage = require('./encodePage');
-var encodeFile = require('./encodeFile');
+const encodeBook = require('./encodeBook');
+const encodePage = require('./encodePage');
+const encodeFile = require('./encodeFile');
/**
* Return a JSON representation of a book with a specific file
@@ -10,9 +10,9 @@ var encodeFile = require('./encodeFile');
* @return {Object}
*/
function encodeBookWithPage(book, page) {
- var file = page.getFile();
+ const file = page.getFile();
- var result = encodeBook(book);
+ const result = encodeBook(book);
result.page = encodePage(page, book.getSummary());
result.file = encodeFile(file);
diff --git a/packages/gitbook/lib/json/encodeFile.js b/packages/gitbook/src/json/encodeFile.js
index d2c9e8a..487a74c 100644
--- a/packages/gitbook/lib/json/encodeFile.js
+++ b/packages/gitbook/src/json/encodeFile.js
@@ -6,7 +6,7 @@
@return {Object}
*/
function encodeFileToJson(file) {
- var filePath = file.getPath();
+ const filePath = file.getPath();
if (!filePath) {
return undefined;
}
diff --git a/packages/gitbook/lib/json/encodeGlossary.js b/packages/gitbook/src/json/encodeGlossary.js
index e9bcfc9..6bdd683 100644
--- a/packages/gitbook/lib/json/encodeGlossary.js
+++ b/packages/gitbook/src/json/encodeGlossary.js
@@ -1,5 +1,5 @@
-var encodeFile = require('./encodeFile');
-var encodeGlossaryEntry = require('./encodeGlossaryEntry');
+const encodeFile = require('./encodeFile');
+const encodeGlossaryEntry = require('./encodeGlossaryEntry');
/**
Encode a glossary to JSON
@@ -8,8 +8,8 @@ var encodeGlossaryEntry = require('./encodeGlossaryEntry');
@return {Object}
*/
function encodeGlossary(glossary) {
- var file = glossary.getFile();
- var entries = glossary.getEntries();
+ const file = glossary.getFile();
+ const entries = glossary.getEntries();
return {
file: encodeFile(file),
diff --git a/packages/gitbook/lib/json/encodeGlossaryEntry.js b/packages/gitbook/src/json/encodeGlossaryEntry.js
index d163f45..d163f45 100644
--- a/packages/gitbook/lib/json/encodeGlossaryEntry.js
+++ b/packages/gitbook/src/json/encodeGlossaryEntry.js
diff --git a/packages/gitbook/lib/json/encodeLanguages.js b/packages/gitbook/src/json/encodeLanguages.js
index 8447e80..fc7487b 100644
--- a/packages/gitbook/lib/json/encodeLanguages.js
+++ b/packages/gitbook/src/json/encodeLanguages.js
@@ -1,4 +1,4 @@
-var encodeFile = require('./encodeFile');
+const encodeFile = require('./encodeFile');
/**
Encode a languages listing to JSON
@@ -7,8 +7,8 @@ var encodeFile = require('./encodeFile');
@return {Object}
*/
function encodeLanguages(languages) {
- var file = languages.getFile();
- var list = languages.getList();
+ const file = languages.getFile();
+ const list = languages.getList();
return {
file: encodeFile(file),
diff --git a/packages/gitbook/lib/json/encodeOutput.js b/packages/gitbook/src/json/encodeOutput.js
index 7347e57..31e5757 100644
--- a/packages/gitbook/lib/json/encodeOutput.js
+++ b/packages/gitbook/src/json/encodeOutput.js
@@ -1,4 +1,4 @@
-var encodeBook = require('./encodeBook');
+const encodeBook = require('./encodeBook');
/**
* Encode an output to JSON
@@ -7,11 +7,11 @@ var encodeBook = require('./encodeBook');
* @return {Object}
*/
function encodeOutputToJson(output) {
- var book = output.getBook();
- var generator = output.getGenerator();
- var options = output.getOptions();
+ const book = output.getBook();
+ const generator = output.getGenerator();
+ const options = output.getOptions();
- var result = encodeBook(book);
+ const result = encodeBook(book);
result.output = {
name: generator
diff --git a/packages/gitbook/lib/json/encodeOutputWithPage.js b/packages/gitbook/src/json/encodeOutputWithPage.js
index 8b21e3d..58db070 100644
--- a/packages/gitbook/lib/json/encodeOutputWithPage.js
+++ b/packages/gitbook/src/json/encodeOutputWithPage.js
@@ -1,6 +1,6 @@
-var encodeOutput = require('./encodeOutput');
-var encodePage = require('./encodePage');
-var encodeFile = require('./encodeFile');
+const encodeOutput = require('./encodeOutput');
+const encodePage = require('./encodePage');
+const encodeFile = require('./encodeFile');
/**
* Return a JSON representation of a book with a specific file
@@ -10,10 +10,10 @@ var encodeFile = require('./encodeFile');
* @return {Object}
*/
function encodeOutputWithPage(output, page) {
- var file = page.getFile();
- var book = output.getBook();
+ const file = page.getFile();
+ const book = output.getBook();
- var result = encodeOutput(output);
+ const result = encodeOutput(output);
result.page = encodePage(page, book.getSummary());
result.file = encodeFile(file);
diff --git a/packages/gitbook/lib/json/encodePage.js b/packages/gitbook/src/json/encodePage.js
index be92117..b20a40c 100644
--- a/packages/gitbook/lib/json/encodePage.js
+++ b/packages/gitbook/src/json/encodePage.js
@@ -1,4 +1,4 @@
-var encodeSummaryArticle = require('./encodeSummaryArticle');
+const encodeSummaryArticle = require('./encodeSummaryArticle');
/**
Return a JSON representation of a page
@@ -8,23 +8,23 @@ var encodeSummaryArticle = require('./encodeSummaryArticle');
@return {Object}
*/
function encodePage(page, summary) {
- var file = page.getFile();
- var attributes = page.getAttributes();
- var article = summary.getByPath(file.getPath());
+ const file = page.getFile();
+ const attributes = page.getAttributes();
+ const article = summary.getByPath(file.getPath());
- var result = attributes.toJS();
+ const result = attributes.toJS();
if (article) {
result.title = article.getTitle();
result.level = article.getLevel();
result.depth = article.getDepth();
- var nextArticle = summary.getNextArticle(article);
+ const nextArticle = summary.getNextArticle(article);
if (nextArticle) {
result.next = encodeSummaryArticle(nextArticle);
}
- var prevArticle = summary.getPrevArticle(article);
+ const prevArticle = summary.getPrevArticle(article);
if (prevArticle) {
result.previous = encodeSummaryArticle(prevArticle);
}
diff --git a/packages/gitbook/lib/json/encodeReadme.js b/packages/gitbook/src/json/encodeReadme.js
index 96176a3..cc71bcb 100644
--- a/packages/gitbook/lib/json/encodeReadme.js
+++ b/packages/gitbook/src/json/encodeReadme.js
@@ -1,4 +1,4 @@
-var encodeFile = require('./encodeFile');
+const encodeFile = require('./encodeFile');
/**
Encode a readme to JSON
@@ -7,7 +7,7 @@ var encodeFile = require('./encodeFile');
@return {Object}
*/
function encodeReadme(readme) {
- var file = readme.getFile();
+ const file = readme.getFile();
return {
file: encodeFile(file)
diff --git a/packages/gitbook/lib/json/encodeSummary.js b/packages/gitbook/src/json/encodeSummary.js
index 97db910..9a07da4 100644
--- a/packages/gitbook/lib/json/encodeSummary.js
+++ b/packages/gitbook/src/json/encodeSummary.js
@@ -1,5 +1,5 @@
-var encodeFile = require('./encodeFile');
-var encodeSummaryPart = require('./encodeSummaryPart');
+const encodeFile = require('./encodeFile');
+const encodeSummaryPart = require('./encodeSummaryPart');
/**
Encode a summary to JSON
@@ -8,8 +8,8 @@ var encodeSummaryPart = require('./encodeSummaryPart');
@return {Object}
*/
function encodeSummary(summary) {
- var file = summary.getFile();
- var parts = summary.getParts();
+ const file = summary.getFile();
+ const parts = summary.getParts();
return {
file: encodeFile(file),
diff --git a/packages/gitbook/lib/json/encodeSummaryArticle.js b/packages/gitbook/src/json/encodeSummaryArticle.js
index 2fc5144..0b9461c 100644
--- a/packages/gitbook/lib/json/encodeSummaryArticle.js
+++ b/packages/gitbook/src/json/encodeSummaryArticle.js
@@ -6,7 +6,7 @@
@return {Object}
*/
function encodeSummaryArticle(article, recursive) {
- var articles = undefined;
+ let articles = undefined;
if (recursive !== false) {
articles = article.getArticles()
.map(encodeSummaryArticle)
@@ -21,7 +21,7 @@ function encodeSummaryArticle(article, recursive) {
url: article.getUrl(),
path: article.getPath(),
ref: article.getRef(),
- articles: articles
+ articles
};
}
diff --git a/packages/gitbook/lib/json/encodeSummaryPart.js b/packages/gitbook/src/json/encodeSummaryPart.js
index a5e7218..eb16719 100644
--- a/packages/gitbook/lib/json/encodeSummaryPart.js
+++ b/packages/gitbook/src/json/encodeSummaryPart.js
@@ -1,4 +1,4 @@
-var encodeSummaryArticle = require('./encodeSummaryArticle');
+const encodeSummaryArticle = require('./encodeSummaryArticle');
/**
Encode a SummaryPart to JSON
diff --git a/packages/gitbook/lib/json/index.js b/packages/gitbook/src/json/index.js
index 3b68f5e..3b68f5e 100644
--- a/packages/gitbook/lib/json/index.js
+++ b/packages/gitbook/src/json/index.js
diff --git a/packages/gitbook/lib/models/__tests__/config.js b/packages/gitbook/src/models/__tests__/config.js
index abad754..a865f96 100644
--- a/packages/gitbook/lib/models/__tests__/config.js
+++ b/packages/gitbook/src/models/__tests__/config.js
@@ -1,8 +1,8 @@
-var Immutable = require('immutable');
-var Config = require('../config');
+const Immutable = require('immutable');
+const Config = require('../config');
describe('Config', function() {
- var config = Config.createWithValues({
+ const config = Config.createWithValues({
hello: {
world: 1,
test: 'Hello',
@@ -12,32 +12,32 @@ describe('Config', function() {
describe('getValue', function() {
it('must return value as immutable', function() {
- var value = config.getValue('hello');
+ const value = config.getValue('hello');
expect(Immutable.Map.isMap(value)).toBeTruthy();
});
it('must return deep value', function() {
- var value = config.getValue('hello.world');
+ const value = config.getValue('hello.world');
expect(value).toBe(1);
});
it('must return default value if non existant', function() {
- var value = config.getValue('hello.nonExistant', 'defaultValue');
+ const value = config.getValue('hello.nonExistant', 'defaultValue');
expect(value).toBe('defaultValue');
});
it('must not return default value for falsy values', function() {
- var value = config.getValue('hello.isFalse', 'defaultValue');
+ const value = config.getValue('hello.isFalse', 'defaultValue');
expect(value).toBe(false);
});
});
describe('setValue', function() {
it('must set value as immutable', function() {
- var testConfig = config.setValue('hello', {
+ const testConfig = config.setValue('hello', {
'cool': 1
});
- var value = testConfig.getValue('hello');
+ const value = testConfig.getValue('hello');
expect(Immutable.Map.isMap(value)).toBeTruthy();
expect(value.size).toBe(1);
@@ -45,9 +45,9 @@ describe('Config', function() {
});
it('must set deep value', function() {
- var testConfig = config.setValue('hello.world', 2);
- var hello = testConfig.getValue('hello');
- var world = testConfig.getValue('hello.world');
+ const testConfig = config.setValue('hello.world', 2);
+ const hello = testConfig.getValue('hello');
+ const world = testConfig.getValue('hello.world');
expect(Immutable.Map.isMap(hello)).toBeTruthy();
expect(hello.size).toBe(3);
@@ -58,11 +58,11 @@ describe('Config', function() {
describe('toReducedVersion', function() {
it('must only return diffs for simple values', function() {
- var _config = Config.createWithValues({
+ const _config = Config.createWithValues({
gitbook: '3.0.0'
});
- var reducedVersion = _config.toReducedVersion();
+ const reducedVersion = _config.toReducedVersion();
expect(reducedVersion.toJS()).toEqual({
gitbook: '3.0.0'
@@ -70,13 +70,13 @@ describe('Config', function() {
});
it('must only return diffs for deep values', function() {
- var _config = Config.createWithValues({
+ const _config = Config.createWithValues({
structure: {
readme: 'intro.md'
}
});
- var reducedVersion = _config.toReducedVersion();
+ const reducedVersion = _config.toReducedVersion();
expect(reducedVersion.toJS()).toEqual({
structure: {
@@ -87,4 +87,3 @@ describe('Config', function() {
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/glossary.js b/packages/gitbook/src/models/__tests__/glossary.js
index 5bf64dc..b50338a 100644
--- a/packages/gitbook/lib/models/__tests__/glossary.js
+++ b/packages/gitbook/src/models/__tests__/glossary.js
@@ -1,9 +1,9 @@
-var File = require('../file');
-var Glossary = require('../glossary');
-var GlossaryEntry = require('../glossaryEntry');
+const File = require('../file');
+const Glossary = require('../glossary');
+const GlossaryEntry = require('../glossaryEntry');
describe('Glossary', function() {
- var glossary = Glossary.createFromEntries(File(), [
+ const glossary = Glossary.createFromEntries(File(), [
{
name: 'Hello World',
description: 'Awesome!'
@@ -16,13 +16,13 @@ describe('Glossary', function() {
describe('createFromEntries', function() {
it('must add all entries', function() {
- var entries = glossary.getEntries();
+ const entries = glossary.getEntries();
expect(entries.size).toBe(2);
});
it('must add entries as GlossaryEntries', function() {
- var entries = glossary.getEntries();
- var entry = entries.get('hello-world');
+ const entries = glossary.getEntries();
+ const entry = entries.get('hello-world');
expect(entry instanceof GlossaryEntry).toBeTruthy();
});
});
@@ -37,4 +37,3 @@ describe('Glossary', function() {
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/glossaryEntry.js b/packages/gitbook/src/models/__tests__/glossaryEntry.js
index 833115d..66ddab4 100644
--- a/packages/gitbook/lib/models/__tests__/glossaryEntry.js
+++ b/packages/gitbook/src/models/__tests__/glossaryEntry.js
@@ -1,9 +1,9 @@
-var GlossaryEntry = require('../glossaryEntry');
+const GlossaryEntry = require('../glossaryEntry');
describe('GlossaryEntry', function() {
describe('getID', function() {
it('must return a normalized ID', function() {
- var entry = new GlossaryEntry({
+ const entry = new GlossaryEntry({
name: 'Hello World'
});
@@ -12,4 +12,3 @@ describe('GlossaryEntry', function() {
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/page.js b/packages/gitbook/src/models/__tests__/page.js
index 479d276..ad9420e 100644
--- a/packages/gitbook/lib/models/__tests__/page.js
+++ b/packages/gitbook/src/models/__tests__/page.js
@@ -1,11 +1,11 @@
-var Immutable = require('immutable');
-var Page = require('../page');
+const Immutable = require('immutable');
+const Page = require('../page');
describe('Page', function() {
describe('toText', function() {
it('must not prepend frontmatter if no attributes', function() {
- var page = Page().merge({
+ const page = Page().merge({
content: 'Hello World'
});
@@ -13,7 +13,7 @@ describe('Page', function() {
});
it('must prepend frontmatter if attributes', function() {
- var page = Page().merge({
+ const page = Page().merge({
content: 'Hello World',
attributes: Immutable.fromJS({
hello: 'world'
@@ -25,4 +25,3 @@ describe('Page', function() {
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/plugin.js b/packages/gitbook/src/models/__tests__/plugin.js
index b229664..63cb58c 100644
--- a/packages/gitbook/lib/models/__tests__/plugin.js
+++ b/packages/gitbook/src/models/__tests__/plugin.js
@@ -1,15 +1,15 @@
describe('Plugin', function() {
- var Plugin = require('../plugin');
+ const Plugin = require('../plugin');
describe('createFromString', function() {
it('must parse name', function() {
- var plugin = Plugin.createFromString('hello');
+ const plugin = Plugin.createFromString('hello');
expect(plugin.getName()).toBe('hello');
expect(plugin.getVersion()).toBe('*');
});
it('must parse version', function() {
- var plugin = Plugin.createFromString('hello@1.0.0');
+ const plugin = Plugin.createFromString('hello@1.0.0');
expect(plugin.getName()).toBe('hello');
expect(plugin.getVersion()).toBe('1.0.0');
});
@@ -17,11 +17,10 @@ describe('Plugin', function() {
describe('isLoaded', function() {
it('must return false for empty plugin', function() {
- var plugin = Plugin.createFromString('hello');
+ const plugin = Plugin.createFromString('hello');
expect(plugin.isLoaded()).toBe(false);
});
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/pluginDependency.js b/packages/gitbook/src/models/__tests__/pluginDependency.js
index cb04cf2..cda0cc2 100644
--- a/packages/gitbook/lib/models/__tests__/pluginDependency.js
+++ b/packages/gitbook/src/models/__tests__/pluginDependency.js
@@ -1,29 +1,29 @@
-var Immutable = require('immutable');
-var PluginDependency = require('../pluginDependency');
+const Immutable = require('immutable');
+const PluginDependency = require('../pluginDependency');
describe('PluginDependency', function() {
describe('createFromString', function() {
it('must parse name', function() {
- var plugin = PluginDependency.createFromString('hello');
+ const plugin = PluginDependency.createFromString('hello');
expect(plugin.getName()).toBe('hello');
expect(plugin.getVersion()).toBe('*');
});
it('must parse state', function() {
- var plugin = PluginDependency.createFromString('-hello');
+ const plugin = PluginDependency.createFromString('-hello');
expect(plugin.getName()).toBe('hello');
expect(plugin.isEnabled()).toBe(false);
});
describe('Version', function() {
it('must parse version', function() {
- var plugin = PluginDependency.createFromString('hello@1.0.0');
+ const plugin = PluginDependency.createFromString('hello@1.0.0');
expect(plugin.getName()).toBe('hello');
expect(plugin.getVersion()).toBe('1.0.0');
});
it('must parse semver', function() {
- var plugin = PluginDependency.createFromString('hello@>=4.0.0');
+ const plugin = PluginDependency.createFromString('hello@>=4.0.0');
expect(plugin.getName()).toBe('hello');
expect(plugin.getVersion()).toBe('>=4.0.0');
});
@@ -31,13 +31,13 @@ describe('PluginDependency', function() {
describe('GIT Version', function() {
it('must handle HTTPS urls', function() {
- var plugin = PluginDependency.createFromString('hello@git+https://github.com/GitbookIO/plugin-ga.git');
+ const plugin = PluginDependency.createFromString('hello@git+https://github.com/GitbookIO/plugin-ga.git');
expect(plugin.getName()).toBe('hello');
expect(plugin.getVersion()).toBe('git+https://github.com/GitbookIO/plugin-ga.git');
});
it('must handle SSH urls', function() {
- var plugin = PluginDependency.createFromString('hello@git+ssh://samy@github.com/GitbookIO/plugin-ga.git');
+ const plugin = PluginDependency.createFromString('hello@git+ssh://samy@github.com/GitbookIO/plugin-ga.git');
expect(plugin.getName()).toBe('hello');
expect(plugin.getVersion()).toBe('git+ssh://samy@github.com/GitbookIO/plugin-ga.git');
});
@@ -45,7 +45,7 @@ describe('PluginDependency', function() {
describe('listToArray', function() {
it('must create an array from a list of plugin dependencies', function() {
- var list = PluginDependency.listToArray(Immutable.List([
+ const list = PluginDependency.listToArray(Immutable.List([
PluginDependency.createFromString('hello@1.0.0'),
PluginDependency.createFromString('noversion'),
PluginDependency.createFromString('-disabled')
@@ -61,14 +61,14 @@ describe('PluginDependency', function() {
describe('listFromArray', function() {
it('must create an array from a list of plugin dependencies', function() {
- var arr = Immutable.fromJS([
+ const arr = Immutable.fromJS([
'hello@1.0.0',
{
'name': 'plugin-ga',
'version': 'git+ssh://samy@github.com/GitbookIO/plugin-ga.git'
}
]);
- var list = PluginDependency.listFromArray(arr);
+ const list = PluginDependency.listFromArray(arr);
expect(list.first().getName()).toBe('hello');
expect(list.first().getVersion()).toBe('1.0.0');
diff --git a/packages/gitbook/lib/models/__tests__/summary.js b/packages/gitbook/src/models/__tests__/summary.js
index 29c9330..49ed9b1 100644
--- a/packages/gitbook/lib/models/__tests__/summary.js
+++ b/packages/gitbook/src/models/__tests__/summary.js
@@ -1,9 +1,9 @@
describe('Summary', function() {
- var File = require('../file');
- var Summary = require('../summary');
+ const File = require('../file');
+ const Summary = require('../summary');
- var summary = Summary.createFromParts(File(), [
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -30,21 +30,21 @@ describe('Summary', function() {
describe('createFromEntries', function() {
it('must add all parts', function() {
- var parts = summary.getParts();
+ const parts = summary.getParts();
expect(parts.size).toBe(2);
});
});
describe('getByLevel', function() {
it('can return a Part', function() {
- var part = summary.getByLevel('1');
+ const part = summary.getByLevel('1');
expect(part).toBeDefined();
expect(part.getArticles().size).toBe(4);
});
it('can return a Part (2)', function() {
- var part = summary.getByLevel('2');
+ const part = summary.getByLevel('2');
expect(part).toBeDefined();
expect(part.getTitle()).toBe('Test');
@@ -52,7 +52,7 @@ describe('Summary', function() {
});
it('can return an Article', function() {
- var article = summary.getByLevel('1.1');
+ const article = summary.getByLevel('1.1');
expect(article).toBeDefined();
expect(article.getTitle()).toBe('My First Article');
@@ -61,21 +61,21 @@ describe('Summary', function() {
describe('getByPath', function() {
it('return correct article', function() {
- var article = summary.getByPath('README.md');
+ const article = summary.getByPath('README.md');
expect(article).toBeDefined();
expect(article.getTitle()).toBe('My First Article');
});
it('return correct article', function() {
- var article = summary.getByPath('article.md');
+ const article = summary.getByPath('article.md');
expect(article).toBeDefined();
expect(article.getTitle()).toBe('My Second Article');
});
it('return undefined if not found', function() {
- var article = summary.getByPath('NOT_EXISTING.md');
+ const article = summary.getByPath('NOT_EXISTING.md');
expect(article).toBeFalsy();
});
@@ -91,4 +91,3 @@ describe('Summary', function() {
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/summaryArticle.js b/packages/gitbook/src/models/__tests__/summaryArticle.js
index 22a7a20..506d481 100644
--- a/packages/gitbook/lib/models/__tests__/summaryArticle.js
+++ b/packages/gitbook/src/models/__tests__/summaryArticle.js
@@ -1,15 +1,15 @@
-var SummaryArticle = require('../summaryArticle');
-var File = require('../file');
+const SummaryArticle = require('../summaryArticle');
+const File = require('../file');
describe('SummaryArticle', function() {
describe('createChildLevel', function() {
it('must create the right level', function() {
- var article = SummaryArticle.create({}, '1.1');
+ const article = SummaryArticle.create({}, '1.1');
expect(article.createChildLevel()).toBe('1.1.1');
});
it('must create the right level when has articles', function() {
- var article = SummaryArticle.create({
+ const article = SummaryArticle.create({
articles: [
{
title: 'Test'
@@ -22,32 +22,31 @@ describe('SummaryArticle', function() {
describe('isFile', function() {
it('must return true when exactly the file', function() {
- var article = SummaryArticle.create({
+ const article = SummaryArticle.create({
ref: 'hello.md'
}, '1.1');
- var file = File.createWithFilepath('hello.md');
+ const file = File.createWithFilepath('hello.md');
expect(article.isFile(file)).toBe(true);
});
it('must return true when path is not normalized', function() {
- var article = SummaryArticle.create({
+ const article = SummaryArticle.create({
ref: '/hello.md'
}, '1.1');
- var file = File.createWithFilepath('hello.md');
+ const file = File.createWithFilepath('hello.md');
expect(article.isFile(file)).toBe(true);
});
it('must return false when has anchor', function() {
- var article = SummaryArticle.create({
+ const article = SummaryArticle.create({
ref: 'hello.md#world'
}, '1.1');
- var file = File.createWithFilepath('hello.md');
+ const file = File.createWithFilepath('hello.md');
expect(article.isFile(file)).toBe(false);
});
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/summaryPart.js b/packages/gitbook/src/models/__tests__/summaryPart.js
index 8ee50b6..fc9e8b5 100644
--- a/packages/gitbook/lib/models/__tests__/summaryPart.js
+++ b/packages/gitbook/src/models/__tests__/summaryPart.js
@@ -1,14 +1,14 @@
-var SummaryPart = require('../summaryPart');
+const SummaryPart = require('../summaryPart');
describe('SummaryPart', function() {
describe('createChildLevel', function() {
it('must create the right level', function() {
- var article = SummaryPart.create({}, '1');
+ const article = SummaryPart.create({}, '1');
expect(article.createChildLevel()).toBe('1.1');
});
it('must create the right level when has articles', function() {
- var article = SummaryPart.create({
+ const article = SummaryPart.create({
articles: [
{
title: 'Test'
@@ -20,4 +20,3 @@ describe('SummaryPart', function() {
});
});
-
diff --git a/packages/gitbook/lib/models/__tests__/templateBlock.js b/packages/gitbook/src/models/__tests__/templateBlock.js
index e5f7666..20511be 100644
--- a/packages/gitbook/lib/models/__tests__/templateBlock.js
+++ b/packages/gitbook/src/models/__tests__/templateBlock.js
@@ -1,13 +1,13 @@
-var nunjucks = require('nunjucks');
-var Immutable = require('immutable');
-var Promise = require('../../utils/promise');
+const nunjucks = require('nunjucks');
+const Immutable = require('immutable');
+const Promise = require('../../utils/promise');
describe('TemplateBlock', function() {
- var TemplateBlock = require('../templateBlock');
+ const TemplateBlock = require('../templateBlock');
describe('create', function() {
it('must initialize a simple TemplateBlock from a function', function() {
- var templateBlock = TemplateBlock.create('sayhello', function(block) {
+ const templateBlock = TemplateBlock.create('sayhello', function(block) {
return {
body: '<p>Hello, World!</p>',
parse: true
@@ -34,7 +34,7 @@ describe('TemplateBlock', function() {
describe('getShortcuts', function() {
it('must return undefined if no shortcuts', function() {
- var templateBlock = TemplateBlock.create('sayhello', function(block) {
+ const templateBlock = TemplateBlock.create('sayhello', function(block) {
return {
body: '<p>Hello, World!</p>',
parse: true
@@ -45,8 +45,8 @@ describe('TemplateBlock', function() {
});
it('must return complete shortcut', function() {
- var templateBlock = TemplateBlock.create('sayhello', {
- process: function(block) {
+ const templateBlock = TemplateBlock.create('sayhello', {
+ process(block) {
return '<p>Hello, World!</p>';
},
shortcuts: {
@@ -56,7 +56,7 @@ describe('TemplateBlock', function() {
}
});
- var shortcut = templateBlock.getShortcuts();
+ const shortcut = templateBlock.getShortcuts();
expect(shortcut).toBeDefined();
expect(shortcut.getStart()).toEqual('$');
@@ -68,28 +68,28 @@ describe('TemplateBlock', function() {
describe('toNunjucksExt()', function() {
it('should replace by block anchor', function() {
- var templateBlock = TemplateBlock.create('sayhello', function(block) {
+ const templateBlock = TemplateBlock.create('sayhello', function(block) {
return 'Hello';
});
- var blocks = {};
+ let blocks = {};
// Create a fresh Nunjucks environment
- var env = new nunjucks.Environment(null, { autoescape: false });
+ const env = new nunjucks.Environment(null, { autoescape: false });
// Add template block to environement
- var Ext = templateBlock.toNunjucksExt({}, blocks);
+ const Ext = templateBlock.toNunjucksExt({}, blocks);
env.addExtension(templateBlock.getExtensionName(), new Ext());
// Render a template using the block
- var src = '{% sayhello %}{% endsayhello %}';
+ const src = '{% sayhello %}{% endsayhello %}';
return Promise.nfcall(env.renderString.bind(env), src)
.then(function(res) {
blocks = Immutable.fromJS(blocks);
expect(blocks.size).toBe(1);
- var blockId = blocks.keySeq().get(0);
- var block = blocks.get(blockId);
+ const blockId = blocks.keySeq().get(0);
+ const block = blocks.get(blockId);
expect(res).toBe('{{-%' + blockId + '%-}}');
expect(block.get('body')).toBe('Hello');
@@ -98,7 +98,7 @@ describe('TemplateBlock', function() {
});
it('must create a valid nunjucks extension', function() {
- var templateBlock = TemplateBlock.create('sayhello', function(block) {
+ const templateBlock = TemplateBlock.create('sayhello', function(block) {
return {
body: '<p>Hello, World!</p>',
parse: true
@@ -106,14 +106,14 @@ describe('TemplateBlock', function() {
});
// Create a fresh Nunjucks environment
- var env = new nunjucks.Environment(null, { autoescape: false });
+ const env = new nunjucks.Environment(null, { autoescape: false });
// Add template block to environement
- var Ext = templateBlock.toNunjucksExt();
+ const Ext = templateBlock.toNunjucksExt();
env.addExtension(templateBlock.getExtensionName(), new Ext());
// Render a template using the block
- var src = '{% sayhello %}{% endsayhello %}';
+ const src = '{% sayhello %}{% endsayhello %}';
return Promise.nfcall(env.renderString.bind(env), src)
.then(function(res) {
expect(res).toBe('<p>Hello, World!</p>');
@@ -121,22 +121,22 @@ describe('TemplateBlock', function() {
});
it('must apply block arguments correctly', function() {
- var templateBlock = TemplateBlock.create('sayhello', function(block) {
+ const templateBlock = TemplateBlock.create('sayhello', function(block) {
return {
- body: '<'+block.kwargs.tag+'>Hello, '+block.kwargs.name+'!</'+block.kwargs.tag+'>',
+ body: '<' + block.kwargs.tag + '>Hello, ' + block.kwargs.name + '!</' + block.kwargs.tag + '>',
parse: true
};
});
// Create a fresh Nunjucks environment
- var env = new nunjucks.Environment(null, { autoescape: false });
+ const env = new nunjucks.Environment(null, { autoescape: false });
// Add template block to environement
- var Ext = templateBlock.toNunjucksExt();
+ const Ext = templateBlock.toNunjucksExt();
env.addExtension(templateBlock.getExtensionName(), new Ext());
// Render a template using the block
- var src = '{% sayhello name="Samy", tag="p" %}{% endsayhello %}';
+ const src = '{% sayhello name="Samy", tag="p" %}{% endsayhello %}';
return Promise.nfcall(env.renderString.bind(env), src)
.then(function(res) {
expect(res).toBe('<p>Hello, Samy!</p>');
@@ -144,7 +144,7 @@ describe('TemplateBlock', function() {
});
it('must accept an async function', function() {
- var templateBlock = TemplateBlock.create('sayhello', function(block) {
+ const templateBlock = TemplateBlock.create('sayhello', function(block) {
return Promise()
.then(function() {
return {
@@ -155,14 +155,14 @@ describe('TemplateBlock', function() {
});
// Create a fresh Nunjucks environment
- var env = new nunjucks.Environment(null, { autoescape: false });
+ const env = new nunjucks.Environment(null, { autoescape: false });
// Add template block to environement
- var Ext = templateBlock.toNunjucksExt();
+ const Ext = templateBlock.toNunjucksExt();
env.addExtension(templateBlock.getExtensionName(), new Ext());
// Render a template using the block
- var src = '{% sayhello %}Samy{% endsayhello %}';
+ const src = '{% sayhello %}Samy{% endsayhello %}';
return Promise.nfcall(env.renderString.bind(env), src)
.then(function(res) {
expect(res).toBe('Hello Samy');
@@ -170,36 +170,36 @@ describe('TemplateBlock', function() {
});
it('must handle nested blocks', function() {
- var templateBlock = new TemplateBlock({
+ const templateBlock = new TemplateBlock({
name: 'yoda',
blocks: Immutable.List(['start', 'end']),
- process: function(block) {
- var nested = {};
+ process(block) {
+ const nested = {};
block.blocks.forEach(function(blk) {
nested[blk.name] = blk.body.trim();
});
return {
- body: '<p class="yoda">'+nested.end+' '+nested.start+'</p>',
+ body: '<p class="yoda">' + nested.end + ' ' + nested.start + '</p>',
parse: true
};
}
});
// Create a fresh Nunjucks environment
- var env = new nunjucks.Environment(null, { autoescape: false });
+ const env = new nunjucks.Environment(null, { autoescape: false });
// Add template block to environement
- var Ext = templateBlock.toNunjucksExt();
+ const Ext = templateBlock.toNunjucksExt();
env.addExtension(templateBlock.getExtensionName(), new Ext());
// Render a template using the block
- var src = '{% yoda %}{% start %}this sentence should be{% end %}inverted{% endyoda %}';
+ const src = '{% yoda %}{% start %}this sentence should be{% end %}inverted{% endyoda %}';
return Promise.nfcall(env.renderString.bind(env), src)
.then(function(res) {
expect(res).toBe('<p class="yoda">inverted this sentence should be</p>');
});
});
});
-}); \ No newline at end of file
+});
diff --git a/packages/gitbook/lib/models/__tests__/templateEngine.js b/packages/gitbook/src/models/__tests__/templateEngine.js
index 6f18b18..30cd543 100644
--- a/packages/gitbook/lib/models/__tests__/templateEngine.js
+++ b/packages/gitbook/src/models/__tests__/templateEngine.js
@@ -1,40 +1,40 @@
describe('TemplateBlock', function() {
- var TemplateEngine = require('../templateEngine');
+ const TemplateEngine = require('../templateEngine');
describe('create', function() {
it('must initialize with a list of filters', function() {
- var engine = TemplateEngine.create({
+ const engine = TemplateEngine.create({
filters: {
- hello: function(name) {
+ hello(name) {
return 'Hello ' + name + '!';
}
}
});
- var env = engine.toNunjucks();
- var res = env.renderString('{{ "Luke"|hello }}');
+ const env = engine.toNunjucks();
+ const res = env.renderString('{{ "Luke"|hello }}');
expect(res).toBe('Hello Luke!');
});
it('must initialize with a list of globals', function() {
- var engine = TemplateEngine.create({
+ const engine = TemplateEngine.create({
globals: {
- hello: function(name) {
+ hello(name) {
return 'Hello ' + name + '!';
}
}
});
- var env = engine.toNunjucks();
- var res = env.renderString('{{ hello("Luke") }}');
+ const env = engine.toNunjucks();
+ const res = env.renderString('{{ hello("Luke") }}');
expect(res).toBe('Hello Luke!');
});
it('must pass context to filters and blocks', function() {
- var engine = TemplateEngine.create({
+ const engine = TemplateEngine.create({
filters: {
- hello: function(name) {
+ hello(name) {
return 'Hello ' + name + ' ' + this.lastName + '!';
}
},
@@ -42,10 +42,10 @@ describe('TemplateBlock', function() {
lastName: 'Skywalker'
}
});
- var env = engine.toNunjucks();
- var res = env.renderString('{{ "Luke"|hello }}');
+ const env = engine.toNunjucks();
+ const res = env.renderString('{{ "Luke"|hello }}');
expect(res).toBe('Hello Luke Skywalker!');
});
});
-}); \ No newline at end of file
+});
diff --git a/packages/gitbook/lib/models/book.js b/packages/gitbook/src/models/book.js
index f774ee8..4164536 100644
--- a/packages/gitbook/lib/models/book.js
+++ b/packages/gitbook/src/models/book.js
@@ -1,17 +1,17 @@
-var path = require('path');
-var Immutable = require('immutable');
+const path = require('path');
+const Immutable = require('immutable');
-var Logger = require('../utils/logger');
+const Logger = require('../utils/logger');
-var FS = require('./fs');
-var Config = require('./config');
-var Readme = require('./readme');
-var Summary = require('./summary');
-var Glossary = require('./glossary');
-var Languages = require('./languages');
-var Ignore = require('./ignore');
+const FS = require('./fs');
+const Config = require('./config');
+const Readme = require('./readme');
+const Summary = require('./summary');
+const Glossary = require('./glossary');
+const Languages = require('./languages');
+const Ignore = require('./ignore');
-var Book = Immutable.Record({
+const Book = Immutable.Record({
// Logger for outptu message
logger: Logger(),
@@ -81,9 +81,9 @@ Book.prototype.getLanguage = function() {
@return {FS}
*/
Book.prototype.getContentFS = function() {
- var fs = this.getFS();
- var config = this.getConfig();
- var rootFolder = config.getValue('root');
+ const fs = this.getFS();
+ const config = this.getConfig();
+ const rootFolder = config.getValue('root');
if (rootFolder) {
return FS.reduceScope(fs, rootFolder);
@@ -98,7 +98,7 @@ Book.prototype.getContentFS = function() {
@return {String}
*/
Book.prototype.getRoot = function() {
- var fs = this.getFS();
+ const fs = this.getFS();
return fs.getRoot();
};
@@ -108,7 +108,7 @@ Book.prototype.getRoot = function() {
@return {String}
*/
Book.prototype.getContentRoot = function() {
- var fs = this.getContentFS();
+ const fs = this.getContentFS();
return fs.getRoot();
};
@@ -119,8 +119,8 @@ Book.prototype.getContentRoot = function() {
@return {Page|undefined}
*/
Book.prototype.isFileIgnored = function(filename) {
- var ignore = this.getIgnore();
- var language = this.getLanguage();
+ const ignore = this.getIgnore();
+ const language = this.getLanguage();
// Ignore is always relative to the root of the main book
if (language) {
@@ -137,8 +137,8 @@ Book.prototype.isFileIgnored = function(filename) {
@return {Page|undefined}
*/
Book.prototype.isContentFileIgnored = function(filename) {
- var config = this.getConfig();
- var rootFolder = config.getValue('root');
+ const config = this.getConfig();
+ const rootFolder = config.getValue('root');
if (rootFolder) {
filename = path.join(rootFolder, filename);
@@ -182,7 +182,7 @@ Book.prototype.isLanguageBook = function() {
@return {Book}
*/
Book.prototype.getLanguageBook = function(language) {
- var books = this.getBooks();
+ const books = this.getBooks();
return books.get(language);
};
@@ -194,7 +194,7 @@ Book.prototype.getLanguageBook = function(language) {
@return {Book}
*/
Book.prototype.addLanguageBook = function(language, book) {
- var books = this.getBooks();
+ let books = this.getBooks();
books = books.set(language, book);
return this.set('books', books);
@@ -259,7 +259,7 @@ Book.prototype.setLogLevel = function(level) {
*/
Book.createForFS = function createForFS(fs) {
return new Book({
- fs: fs
+ fs
});
};
@@ -269,15 +269,15 @@ Book.createForFS = function createForFS(fs) {
*/
Book.prototype.getDefaultExt = function() {
// Inferring sources
- var clues = [
+ const clues = [
this.getReadme(),
this.getSummary(),
this.getGlossary()
];
// List their extensions
- var exts = clues.map(function (clue) {
- var file = clue.getFile();
+ const exts = clues.map(function(clue) {
+ const file = clue.getFile();
if (file.exists()) {
return file.getParser().getExtensions().first();
} else {
@@ -288,7 +288,7 @@ Book.prototype.getDefaultExt = function() {
exts.push('.md');
// Choose the first non null
- return exts.find(function (e) { return e !== null; });
+ return exts.find(function(e) { return e !== null; });
};
/**
@@ -298,7 +298,7 @@ Book.prototype.getDefaultExt = function() {
@return {String}
*/
Book.prototype.getDefaultReadmePath = function(absolute) {
- var defaultPath = 'README'+this.getDefaultExt();
+ const defaultPath = 'README' + this.getDefaultExt();
if (absolute) {
return path.join(this.getContentRoot(), defaultPath);
} else {
@@ -313,7 +313,7 @@ Book.prototype.getDefaultReadmePath = function(absolute) {
@return {String}
*/
Book.prototype.getDefaultSummaryPath = function(absolute) {
- var defaultPath = 'SUMMARY'+this.getDefaultExt();
+ const defaultPath = 'SUMMARY' + this.getDefaultExt();
if (absolute) {
return path.join(this.getContentRoot(), defaultPath);
} else {
@@ -328,7 +328,7 @@ Book.prototype.getDefaultSummaryPath = function(absolute) {
@return {String}
*/
Book.prototype.getDefaultGlossaryPath = function(absolute) {
- var defaultPath = 'GLOSSARY'+this.getDefaultExt();
+ const defaultPath = 'GLOSSARY' + this.getDefaultExt();
if (absolute) {
return path.join(this.getContentRoot(), defaultPath);
} else {
@@ -344,8 +344,8 @@ Book.prototype.getDefaultGlossaryPath = function(absolute) {
@return {Book}
*/
Book.createFromParent = function createFromParent(parent, language) {
- var ignore = parent.getIgnore();
- var config = parent.getConfig();
+ const ignore = parent.getIgnore();
+ let config = parent.getConfig();
// Set language in configuration
config = config.setValue('language', language);
@@ -353,10 +353,10 @@ Book.createFromParent = function createFromParent(parent, language) {
return new Book({
// Inherits config. logegr and list of ignored files
logger: parent.getLogger(),
- config: config,
- ignore: ignore,
+ config,
+ ignore,
- language: language,
+ language,
fs: FS.reduceScope(parent.getContentFS(), language)
});
};
diff --git a/packages/gitbook/lib/models/config.js b/packages/gitbook/src/models/config.js
index 6de52f9..6a0be5e 100644
--- a/packages/gitbook/lib/models/config.js
+++ b/packages/gitbook/src/models/config.js
@@ -1,12 +1,12 @@
-var is = require('is');
-var Immutable = require('immutable');
+const is = require('is');
+const Immutable = require('immutable');
-var File = require('./file');
-var PluginDependency = require('./pluginDependency');
-var configDefault = require('../constants/configDefault');
-var reducedObject = require('../utils/reducedObject');
+const File = require('./file');
+const PluginDependency = require('./pluginDependency');
+const configDefault = require('../constants/configDefault');
+const reducedObject = require('../utils/reducedObject');
-var Config = Immutable.Record({
+const Config = Immutable.Record({
file: File(),
values: configDefault
}, 'Config');
@@ -51,7 +51,7 @@ Config.prototype.setFile = function(file) {
* @return {Mixed}
*/
Config.prototype.getValue = function(keyPath, def) {
- var values = this.getValues();
+ const values = this.getValues();
keyPath = Config.keyToKeyPath(keyPath);
if (!values.hasIn(keyPath)) {
@@ -72,7 +72,7 @@ Config.prototype.setValue = function(keyPath, value) {
value = Immutable.fromJS(value);
- var values = this.getValues();
+ let values = this.getValues();
values = values.setIn(keyPath, value);
return this.set('values', values);
@@ -83,7 +83,7 @@ Config.prototype.setValue = function(keyPath, value) {
* @return {List<PluginDependency>}
*/
Config.prototype.getPluginDependencies = function() {
- var plugins = this.getValue('plugins');
+ const plugins = this.getValue('plugins');
if (is.string(plugins)) {
return PluginDependency.listFromString(plugins);
@@ -98,7 +98,7 @@ Config.prototype.getPluginDependencies = function() {
* @return {PluginDependency}
*/
Config.prototype.getPluginDependency = function(name) {
- var plugins = this.getPluginDependencies();
+ const plugins = this.getPluginDependencies();
return plugins.find(function(dep) {
return dep.getName() === name;
@@ -111,7 +111,7 @@ Config.prototype.getPluginDependency = function(name) {
* @return {Config}
*/
Config.prototype.setPluginDependencies = function(deps) {
- var plugins = PluginDependency.listToArray(deps);
+ const plugins = PluginDependency.listToArray(deps);
return this.setValue('plugins', plugins);
};
@@ -135,7 +135,7 @@ Config.prototype.updateValues = function(values) {
* @returns {Config}
*/
Config.prototype.mergeValues = function(values) {
- var currentValues = this.getValues();
+ let currentValues = this.getValues();
values = Immutable.fromJS(values);
currentValues = currentValues.mergeDeep(values);
@@ -151,7 +151,7 @@ Config.prototype.mergeValues = function(values) {
*/
Config.create = function(file, values) {
return new Config({
- file: file,
+ file,
values: Immutable.fromJS(values)
});
};
diff --git a/packages/gitbook/lib/models/file.js b/packages/gitbook/src/models/file.js
index 8ddd4af..84828ce 100644
--- a/packages/gitbook/lib/models/file.js
+++ b/packages/gitbook/src/models/file.js
@@ -1,9 +1,9 @@
-var path = require('path');
-var Immutable = require('immutable');
+const path = require('path');
+const Immutable = require('immutable');
-var parsers = require('../parsers');
+const parsers = require('../parsers');
-var File = Immutable.Record({
+const File = Immutable.Record({
// Path of the file, relative to the FS
path: String(),
@@ -34,7 +34,7 @@ File.prototype.exists = function() {
@return {String}
*/
File.prototype.getType = function() {
- var parser = this.getParser();
+ const parser = this.getParser();
if (parser) {
return parser.getName();
} else {
diff --git a/packages/gitbook/lib/models/fs.js b/packages/gitbook/src/models/fs.js
index 16bd4ea..7afbfbd 100644
--- a/packages/gitbook/lib/models/fs.js
+++ b/packages/gitbook/src/models/fs.js
@@ -1,13 +1,13 @@
-var path = require('path');
-var Immutable = require('immutable');
-var stream = require('stream');
+const path = require('path');
+const Immutable = require('immutable');
+const stream = require('stream');
-var File = require('./file');
-var Promise = require('../utils/promise');
-var error = require('../utils/error');
-var PathUtil = require('../utils/path');
+const File = require('./file');
+const Promise = require('../utils/promise');
+const error = require('../utils/error');
+const PathUtil = require('../utils/path');
-var FS = Immutable.Record({
+const FS = Immutable.Record({
root: String(),
fsExists: Function(),
@@ -35,27 +35,25 @@ FS.prototype.getRoot = function() {
@return {Boolean}
*/
FS.prototype.isInScope = function(filename) {
- var rootPath = this.getRoot();
+ const rootPath = this.getRoot();
filename = path.join(rootPath, filename);
return PathUtil.isInRoot(rootPath, filename);
};
/**
- Resolve a file in this FS
-
- @param {String}
- @return {String}
-*/
-FS.prototype.resolve = function() {
- var rootPath = this.getRoot();
- var args = Array.prototype.slice.call(arguments);
- var filename = path.join.apply(path, [rootPath].concat(args));
+ * Resolve a file in this FS
+ * @param {String}
+ * @return {String}
+ */
+FS.prototype.resolve = function(...args) {
+ const rootPath = this.getRoot();
+ let filename = path.join(rootPath, ...args);
filename = path.normalize(filename);
if (!this.isInScope(filename)) {
throw error.FileOutOfScopeError({
- filename: filename,
+ filename,
root: this.root
});
}
@@ -64,47 +62,44 @@ FS.prototype.resolve = function() {
};
/**
- Check if a file exists, run a Promise(true) if that's the case, Promise(false) otherwise
-
- @param {String} filename
- @return {Promise<Boolean>}
-*/
+ * Check if a file exists, run a Promise(true) if that's the case, Promise(false) otherwise
+ * @param {String} filename
+ * @return {Promise<Boolean>}
+ */
FS.prototype.exists = function(filename) {
- var that = this;
+ const that = this;
return Promise()
.then(function() {
filename = that.resolve(filename);
- var exists = that.get('fsExists');
+ const exists = that.get('fsExists');
return exists(filename);
});
};
/**
- Read a file and returns a promise with the content as a buffer
-
- @param {String} filename
- @return {Promise<Buffer>}
-*/
+ * Read a file and returns a promise with the content as a buffer
+ * @param {String} filename
+ * @return {Promise<Buffer>}
+ */
FS.prototype.read = function(filename) {
- var that = this;
+ const that = this;
return Promise()
.then(function() {
filename = that.resolve(filename);
- var read = that.get('fsReadFile');
+ const read = that.get('fsReadFile');
return read(filename);
});
};
/**
- Read a file as a string (utf-8)
-
- @param {String} filename
- @return {Promise<String>}
-*/
+ * Read a file as a string (utf-8)
+ * @param {String} filename
+ * @return {Promise<String>}
+ */
FS.prototype.readAsString = function(filename, encoding) {
encoding = encoding || 'utf8';
@@ -115,15 +110,14 @@ FS.prototype.readAsString = function(filename, encoding) {
};
/**
- Read file as a stream
-
- @param {String} filename
- @return {Promise<Stream>}
-*/
+ * Read file as a stream
+ * @param {String} filename
+ * @return {Promise<Stream>}
+ */
FS.prototype.readAsStream = function(filename) {
- var that = this;
- var filepath = that.resolve(filename);
- var fsReadAsStream = this.get('fsReadAsStream');
+ const that = this;
+ const filepath = that.resolve(filename);
+ const fsReadAsStream = this.get('fsReadAsStream');
if (fsReadAsStream) {
return Promise(fsReadAsStream(filepath));
@@ -131,7 +125,7 @@ FS.prototype.readAsStream = function(filename) {
return this.read(filename)
.then(function(buf) {
- var bufferStream = new stream.PassThrough();
+ const bufferStream = new stream.PassThrough();
bufferStream.end(buf);
return bufferStream;
@@ -139,18 +133,17 @@ FS.prototype.readAsStream = function(filename) {
};
/**
- Read stat infos about a file
-
- @param {String} filename
- @return {Promise<File>}
-*/
+ * Read stat infos about a file
+ * @param {String} filename
+ * @return {Promise<File>}
+ */
FS.prototype.statFile = function(filename) {
- var that = this;
+ const that = this;
return Promise()
.then(function() {
- var filepath = that.resolve(filename);
- var stat = that.get('fsStatFile');
+ const filepath = that.resolve(filename);
+ const stat = that.get('fsStatFile');
return stat(filepath);
})
@@ -160,19 +153,19 @@ FS.prototype.statFile = function(filename) {
};
/**
- List files/directories in a directory.
- Directories ends with '/'
+ * List files/directories in a directory.
+ * Directories ends with '/'
- @param {String} dirname
- @return {Promise<List<String>>}
-*/
+ * @param {String} dirname
+ * @return {Promise<List<String>>}
+ */
FS.prototype.readDir = function(dirname) {
- var that = this;
+ const that = this;
return Promise()
.then(function() {
- var dirpath = that.resolve(dirname);
- var readDir = that.get('fsReadDir');
+ const dirpath = that.resolve(dirname);
+ const readDir = that.get('fsReadDir');
return readDir(dirpath);
})
@@ -182,12 +175,12 @@ FS.prototype.readDir = function(dirname) {
};
/**
- List only files in a diretcory
- Directories ends with '/'
-
- @param {String} dirname
- @return {Promise<List<String>>}
-*/
+ * List only files in a diretcory
+ * Directories ends with '/'
+ *
+ * @param {String} dirname
+ * @return {Promise<List<String>>}
+ */
FS.prototype.listFiles = function(dirname) {
return this.readDir(dirname)
.then(function(files) {
@@ -196,21 +189,21 @@ FS.prototype.listFiles = function(dirname) {
};
/**
- List all files in a directory
-
- @param {String} dirName
- @param {Function(dirName)} filterFn: call it for each file/directory to test if it should stop iterating
- @return {Promise<List<String>>}
-*/
+ * List all files in a directory
+ *
+ * @param {String} dirName
+ * @param {Function(dirName)} filterFn: call it for each file/directory to test if it should stop iterating
+ * @return {Promise<List<String>>}
+ */
FS.prototype.listAllFiles = function(dirName, filterFn) {
- var that = this;
+ const that = this;
dirName = dirName || '.';
return this.readDir(dirName)
.then(function(files) {
return Promise.reduce(files, function(out, file) {
- var isDirectory = pathIsFolder(file);
- var newDirName = path.join(dirName, file);
+ const isDirectory = pathIsFolder(file);
+ const newDirName = path.join(dirName, file);
if (filterFn && filterFn(newDirName) === false) {
return out;
@@ -229,13 +222,13 @@ FS.prototype.listAllFiles = function(dirName, filterFn) {
};
/**
- Find a file in a folder (case insensitive)
- Return the found filename
-
- @param {String} dirname
- @param {String} filename
- @return {Promise<String>}
-*/
+ * Find a file in a folder (case insensitive)
+ * Return the found filename
+ *
+ * @param {String} dirname
+ * @param {String} filename
+ * @return {Promise<String>}
+ */
FS.prototype.findFile = function(dirname, filename) {
return this.listFiles(dirname)
.then(function(files) {
@@ -246,20 +239,20 @@ FS.prototype.findFile = function(dirname, filename) {
};
/**
- Load a JSON file
- By default, fs only supports JSON
-
- @param {String} filename
- @return {Promise<Object>}
-*/
+ * Load a JSON file
+ * By default, fs only supports JSON
+ *
+ * @param {String} filename
+ * @return {Promise<Object>}
+ */
FS.prototype.loadAsObject = function(filename) {
- var that = this;
- var fsLoadObject = this.get('fsLoadObject');
+ const that = this;
+ const fsLoadObject = this.get('fsLoadObject');
return this.exists(filename)
.then(function(exists) {
if (!exists) {
- var err = new Error('Module doesn\'t exist');
+ const err = new Error('Module doesn\'t exist');
err.code = 'MODULE_NOT_FOUND';
throw err;
@@ -277,22 +270,22 @@ FS.prototype.loadAsObject = function(filename) {
};
/**
- Create a FS instance
-
- @param {Object} def
- @return {FS}
-*/
+ * Create a FS instance
+ *
+ * @param {Object} def
+ * @return {FS}
+ */
FS.create = function create(def) {
return new FS(def);
};
/**
- Create a new FS instance with a reduced scope
-
- @param {FS} fs
- @param {String} scope
- @return {FS}
-*/
+ * Create a new FS instance with a reduced scope
+ *
+ * @param {FS} fs
+ * @param {String} scope
+ * @return {FS}
+ */
FS.reduceScope = function reduceScope(fs, scope) {
return fs.set('root', path.join(fs.getRoot(), scope));
};
@@ -300,8 +293,8 @@ FS.reduceScope = function reduceScope(fs, scope) {
// .readdir return files/folder as a list of string, folder ending with '/'
function pathIsFolder(filename) {
- var lastChar = filename[filename.length - 1];
+ const lastChar = filename[filename.length - 1];
return lastChar == '/' || lastChar == '\\';
}
-module.exports = FS; \ No newline at end of file
+module.exports = FS;
diff --git a/packages/gitbook/lib/models/glossary.js b/packages/gitbook/src/models/glossary.js
index 0033248..e269b14 100644
--- a/packages/gitbook/lib/models/glossary.js
+++ b/packages/gitbook/src/models/glossary.js
@@ -1,11 +1,11 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var error = require('../utils/error');
-var File = require('./file');
-var GlossaryEntry = require('./glossaryEntry');
-var parsers = require('../parsers');
+const error = require('../utils/error');
+const File = require('./file');
+const GlossaryEntry = require('./glossaryEntry');
+const parsers = require('../parsers');
-var Glossary = Immutable.Record({
+const Glossary = Immutable.Record({
file: File(),
entries: Immutable.OrderedMap()
});
@@ -25,8 +25,8 @@ Glossary.prototype.getEntries = function() {
@return {GlossaryEntry}
*/
Glossary.prototype.getEntry = function(name) {
- var entries = this.getEntries();
- var id = GlossaryEntry.nameToID(name);
+ const entries = this.getEntries();
+ const id = GlossaryEntry.nameToID(name);
return entries.get(id);
};
@@ -37,10 +37,10 @@ Glossary.prototype.getEntry = function(name) {
@return {Promise<String>}
*/
Glossary.prototype.toText = function(parser) {
- var file = this.getFile();
- var entries = this.getEntries();
+ const file = this.getFile();
+ const entries = this.getEntries();
- parser = parser? parsers.getByExt(parser) : file.getParser();
+ parser = parser ? parsers.getByExt(parser) : file.getParser();
if (!parser) {
throw error.FileNotParsableError({
@@ -60,8 +60,8 @@ Glossary.prototype.toText = function(parser) {
@return {Glossary}
*/
Glossary.addEntry = function addEntry(glossary, entry) {
- var id = entry.getID();
- var entries = glossary.getEntries();
+ const id = entry.getID();
+ let entries = glossary.getEntries();
entries = entries.set(id, entry);
return glossary.set('entries', entries);
@@ -75,9 +75,9 @@ Glossary.addEntry = function addEntry(glossary, entry) {
@return {Glossary}
*/
Glossary.addEntryByName = function addEntryByName(glossary, name, description) {
- var entry = new GlossaryEntry({
- name: name,
- description: description
+ const entry = new GlossaryEntry({
+ name,
+ description
});
return Glossary.addEntry(glossary, entry);
@@ -100,7 +100,7 @@ Glossary.createFromEntries = function createFromEntries(file, entries) {
});
return new Glossary({
- file: file,
+ file,
entries: Immutable.OrderedMap(entries)
});
};
diff --git a/packages/gitbook/lib/models/glossaryEntry.js b/packages/gitbook/src/models/glossaryEntry.js
index 10791db..b36b276 100644
--- a/packages/gitbook/lib/models/glossaryEntry.js
+++ b/packages/gitbook/src/models/glossaryEntry.js
@@ -1,11 +1,11 @@
-var Immutable = require('immutable');
-var slug = require('github-slugid');
+const Immutable = require('immutable');
+const slug = require('github-slugid');
/*
A definition represents an entry in the glossary
*/
-var GlossaryEntry = Immutable.Record({
+const GlossaryEntry = Immutable.Record({
name: String(),
description: String()
});
diff --git a/packages/gitbook/lib/models/ignore.js b/packages/gitbook/src/models/ignore.js
index 499195e..99ade9a 100644
--- a/packages/gitbook/lib/models/ignore.js
+++ b/packages/gitbook/src/models/ignore.js
@@ -1,10 +1,10 @@
-var Immutable = require('immutable');
-var IgnoreMutable = require('ignore');
+const Immutable = require('immutable');
+const IgnoreMutable = require('ignore');
/*
Immutable version of node-ignore
*/
-var Ignore = Immutable.Record({
+const Ignore = Immutable.Record({
ignore: new IgnoreMutable()
}, 'Ignore');
@@ -19,7 +19,7 @@ Ignore.prototype.getIgnore = function() {
@return {Boolean}
*/
Ignore.prototype.isFileIgnored = function(filename) {
- var ignore = this.getIgnore();
+ const ignore = this.getIgnore();
return ignore.filter([filename]).length == 0;
};
@@ -30,8 +30,8 @@ Ignore.prototype.isFileIgnored = function(filename) {
@return {Ignore}
*/
Ignore.prototype.add = function(rule) {
- var ignore = this.getIgnore();
- var newIgnore = new IgnoreMutable();
+ const ignore = this.getIgnore();
+ const newIgnore = new IgnoreMutable();
newIgnore.add(ignore);
newIgnore.add(rule);
diff --git a/packages/gitbook/lib/models/language.js b/packages/gitbook/src/models/language.js
index dcefbf6..1413091 100644
--- a/packages/gitbook/lib/models/language.js
+++ b/packages/gitbook/src/models/language.js
@@ -1,7 +1,7 @@
-var path = require('path');
-var Immutable = require('immutable');
+const path = require('path');
+const Immutable = require('immutable');
-var Language = Immutable.Record({
+const Language = Immutable.Record({
title: String(),
path: String()
});
diff --git a/packages/gitbook/lib/models/languages.js b/packages/gitbook/src/models/languages.js
index 42f05f9..9540546 100644
--- a/packages/gitbook/lib/models/languages.js
+++ b/packages/gitbook/src/models/languages.js
@@ -1,9 +1,9 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var File = require('./file');
-var Language = require('./language');
+const File = require('./file');
+const Language = require('./language');
-var Languages = Immutable.Record({
+const Languages = Immutable.Record({
file: File(),
list: Immutable.OrderedMap()
});
@@ -52,7 +52,7 @@ Languages.prototype.getCount = function() {
@return {Language}
*/
Languages.createFromList = function(file, langs) {
- var list = Immutable.OrderedMap();
+ let list = Immutable.OrderedMap();
langs.forEach(function(lang) {
lang = Language({
@@ -63,8 +63,8 @@ Languages.createFromList = function(file, langs) {
});
return Languages({
- file: file,
- list: list
+ file,
+ list
});
};
diff --git a/packages/gitbook/lib/models/output.js b/packages/gitbook/src/models/output.js
index 0f008ec..55d83a4 100644
--- a/packages/gitbook/lib/models/output.js
+++ b/packages/gitbook/src/models/output.js
@@ -1,9 +1,9 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Book = require('./book');
-var LocationUtils = require('../utils/location');
+const Book = require('./book');
+const LocationUtils = require('../utils/location');
-var Output = Immutable.Record({
+const Output = Immutable.Record({
book: Book(),
// Name of the generator being used
@@ -62,7 +62,7 @@ Output.prototype.getState = function() {
Output.prototype.getPage = function(filePath) {
filePath = LocationUtils.normalize(filePath);
- var pages = this.getPages();
+ const pages = this.getPages();
return pages.get(filePath);
};
diff --git a/packages/gitbook/lib/models/page.js b/packages/gitbook/src/models/page.js
index 275a034..dd60298 100644
--- a/packages/gitbook/lib/models/page.js
+++ b/packages/gitbook/src/models/page.js
@@ -1,9 +1,9 @@
-var Immutable = require('immutable');
-var yaml = require('js-yaml');
+const Immutable = require('immutable');
+const yaml = require('js-yaml');
-var File = require('./file');
+const File = require('./file');
-var Page = Immutable.Record({
+const Page = Immutable.Record({
file: File(),
// Attributes extracted from the YAML header
@@ -37,14 +37,14 @@ Page.prototype.getDir = function() {
* @return {String}
*/
Page.prototype.toText = function() {
- var attrs = this.getAttributes();
- var content = this.getContent();
+ const attrs = this.getAttributes();
+ const content = this.getContent();
if (attrs.size === 0) {
return content;
}
- var frontMatter = '---\n' + yaml.safeDump(attrs.toJS(), { skipInvalid: true }) + '---\n\n';
+ const frontMatter = '---\n' + yaml.safeDump(attrs.toJS(), { skipInvalid: true }) + '---\n\n';
return (frontMatter + content);
};
@@ -63,7 +63,7 @@ Page.prototype.getPath = function() {
*/
Page.createForFile = function(file) {
return new Page({
- file: file
+ file
});
};
diff --git a/packages/gitbook/lib/models/parser.js b/packages/gitbook/src/models/parser.js
index d64542f..3769dd3 100644
--- a/packages/gitbook/lib/models/parser.js
+++ b/packages/gitbook/src/models/parser.js
@@ -1,7 +1,7 @@
-var Immutable = require('immutable');
-var Promise = require('../utils/promise');
+const Immutable = require('immutable');
+const Promise = require('../utils/promise');
-var Parser = Immutable.Record({
+const Parser = Immutable.Record({
name: String(),
// List of extensions that can be processed using this parser
@@ -27,22 +27,22 @@ Parser.prototype.getExtensions = function() {
// PARSE
Parser.prototype.parseReadme = function(content) {
- var readme = this.get('readme');
+ const readme = this.get('readme');
return Promise(readme(content));
};
Parser.prototype.parseSummary = function(content) {
- var summary = this.get('summary');
+ const summary = this.get('summary');
return Promise(summary(content));
};
Parser.prototype.parseGlossary = function(content) {
- var glossary = this.get('glossary');
+ const glossary = this.get('glossary');
return Promise(glossary(content));
};
Parser.prototype.preparePage = function(content) {
- var page = this.get('page');
+ const page = this.get('page');
if (!page.prepare) {
return Promise(content);
}
@@ -51,39 +51,39 @@ Parser.prototype.preparePage = function(content) {
};
Parser.prototype.parsePage = function(content) {
- var page = this.get('page');
+ const page = this.get('page');
return Promise(page(content));
};
Parser.prototype.parseInline = function(content) {
- var inline = this.get('inline');
+ const inline = this.get('inline');
return Promise(inline(content));
};
Parser.prototype.parseLanguages = function(content) {
- var langs = this.get('langs');
+ const langs = this.get('langs');
return Promise(langs(content));
};
Parser.prototype.parseInline = function(content) {
- var inline = this.get('inline');
+ const inline = this.get('inline');
return Promise(inline(content));
};
// TO TEXT
Parser.prototype.renderLanguages = function(content) {
- var langs = this.get('langs');
+ const langs = this.get('langs');
return Promise(langs.toText(content));
};
Parser.prototype.renderSummary = function(content) {
- var summary = this.get('summary');
+ const summary = this.get('summary');
return Promise(summary.toText(content));
};
Parser.prototype.renderGlossary = function(content) {
- var glossary = this.get('glossary');
+ const glossary = this.get('glossary');
return Promise(glossary.toText(content));
};
@@ -94,7 +94,7 @@ Parser.prototype.renderGlossary = function(content) {
@return {Boolean}
*/
Parser.prototype.matchExtension = function(ext) {
- var exts = this.getExtensions();
+ const exts = this.getExtensions();
return exts.includes(ext.toLowerCase());
};
@@ -108,7 +108,7 @@ Parser.prototype.matchExtension = function(ext) {
*/
Parser.create = function(name, extensions, module) {
return new Parser({
- name: name,
+ name,
extensions: Immutable.List(extensions),
readme: module.readme,
langs: module.langs,
diff --git a/packages/gitbook/lib/models/plugin.js b/packages/gitbook/src/models/plugin.js
index acabba9..0e4c774 100644
--- a/packages/gitbook/lib/models/plugin.js
+++ b/packages/gitbook/src/models/plugin.js
@@ -1,12 +1,12 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var TemplateBlock = require('./templateBlock');
-var PluginDependency = require('./pluginDependency');
-var THEME_PREFIX = require('../constants/themePrefix');
+const TemplateBlock = require('./templateBlock');
+const PluginDependency = require('./pluginDependency');
+const THEME_PREFIX = require('../constants/themePrefix');
-var DEFAULT_VERSION = '*';
+const DEFAULT_VERSION = '*';
-var Plugin = Immutable.Record({
+const Plugin = Immutable.Record({
name: String(),
// Requirement version (ex: ">1.0.0")
@@ -77,7 +77,7 @@ Plugin.prototype.isLoaded = function() {
* @return {Boolean}
*/
Plugin.prototype.isTheme = function() {
- var name = this.getName();
+ const name = this.getName();
return (name && name.indexOf(THEME_PREFIX) === 0);
};
@@ -99,9 +99,9 @@ Plugin.prototype.getResources = function(type) {
throw new Error('Invalid assets type ' + type);
}
- var content = this.getContent();
+ const content = this.getContent();
return (content.get(type)
- || (type == 'website'? content.get('book') : null)
+ || (type == 'website' ? content.get('book') : null)
|| Immutable.Map());
};
@@ -118,7 +118,7 @@ Plugin.prototype.getFilters = function() {
* @return {Map<String:TemplateBlock>}
*/
Plugin.prototype.getBlocks = function() {
- var blocks = this.getContent().get('blocks');
+ let blocks = this.getContent().get('blocks');
blocks = blocks || Immutable.Map();
return blocks
@@ -142,12 +142,12 @@ Plugin.prototype.getHook = function(name) {
* @return {Plugin}
*/
Plugin.createFromString = function(s) {
- var parts = s.split('@');
- var name = parts[0];
- var version = parts.slice(1).join('@');
+ const parts = s.split('@');
+ const name = parts[0];
+ const version = parts.slice(1).join('@');
return new Plugin({
- name: name,
+ name,
version: version || DEFAULT_VERSION
});
};
diff --git a/packages/gitbook/lib/models/pluginDependency.js b/packages/gitbook/src/models/pluginDependency.js
index 8866294..4e5d464 100644
--- a/packages/gitbook/lib/models/pluginDependency.js
+++ b/packages/gitbook/src/models/pluginDependency.js
@@ -1,15 +1,15 @@
-var is = require('is');
-var semver = require('semver');
-var Immutable = require('immutable');
+const is = require('is');
+const semver = require('semver');
+const Immutable = require('immutable');
-var PREFIX = require('../constants/pluginPrefix');
-var DEFAULT_VERSION = '*';
+const PREFIX = require('../constants/pluginPrefix');
+const DEFAULT_VERSION = '*';
/*
* PluginDependency represents the informations about a plugin
* stored in config.plugins
*/
-var PluginDependency = Immutable.Record({
+const PluginDependency = Immutable.Record({
name: String(),
// Requirement version (ex: ">1.0.0")
@@ -71,7 +71,7 @@ PluginDependency.create = function(name, version, enabled) {
}
return new PluginDependency({
- name: name,
+ name,
version: version || DEFAULT_VERSION,
enabled: Boolean(enabled)
});
@@ -83,10 +83,10 @@ PluginDependency.create = function(name, version, enabled) {
* @return {Plugin|undefined}
*/
PluginDependency.createFromString = function(s) {
- var parts = s.split('@');
- var name = parts[0];
- var version = parts.slice(1).join('@');
- var enabled = true;
+ const parts = s.split('@');
+ let name = parts[0];
+ const version = parts.slice(1).join('@');
+ let enabled = true;
if (name[0] === '-') {
enabled = false;
@@ -94,9 +94,9 @@ PluginDependency.createFromString = function(s) {
}
return new PluginDependency({
- name: name,
+ name,
version: version || DEFAULT_VERSION,
- enabled: enabled
+ enabled
});
};
@@ -106,7 +106,7 @@ PluginDependency.createFromString = function(s) {
* @return {List<PluginDependency>}
*/
PluginDependency.listFromString = function(s) {
- var parts = s.split(',');
+ const parts = s.split(',');
return PluginDependency.listFromArray(parts);
};
@@ -140,7 +140,7 @@ PluginDependency.listFromArray = function(arr) {
PluginDependency.listToArray = function(list) {
return list
.map(function(dep) {
- var result = '';
+ let result = '';
if (!dep.isEnabled()) {
result += '-';
diff --git a/packages/gitbook/lib/models/readme.js b/packages/gitbook/src/models/readme.js
index c655c82..0fb52b4 100644
--- a/packages/gitbook/lib/models/readme.js
+++ b/packages/gitbook/src/models/readme.js
@@ -1,8 +1,8 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var File = require('./file');
+const File = require('./file');
-var Readme = Immutable.Record({
+const Readme = Immutable.Record({
file: File(),
title: String(),
description: String()
@@ -31,7 +31,7 @@ Readme.create = function(file, def) {
def = def || {};
return new Readme({
- file: file,
+ file,
title: def.title || '',
description: def.description || ''
});
diff --git a/packages/gitbook/lib/models/summary.js b/packages/gitbook/src/models/summary.js
index 70f0535..edc202e 100644
--- a/packages/gitbook/lib/models/summary.js
+++ b/packages/gitbook/src/models/summary.js
@@ -1,14 +1,14 @@
-var is = require('is');
-var Immutable = require('immutable');
+const is = require('is');
+const Immutable = require('immutable');
-var error = require('../utils/error');
-var LocationUtils = require('../utils/location');
-var File = require('./file');
-var SummaryPart = require('./summaryPart');
-var SummaryArticle = require('./summaryArticle');
-var parsers = require('../parsers');
+const error = require('../utils/error');
+const LocationUtils = require('../utils/location');
+const File = require('./file');
+const SummaryPart = require('./summaryPart');
+const SummaryArticle = require('./summaryArticle');
+const parsers = require('../parsers');
-var Summary = Immutable.Record({
+const Summary = Immutable.Record({
file: File(),
parts: Immutable.List()
}, 'Summary');
@@ -28,7 +28,7 @@ Summary.prototype.getParts = function() {
@return {Part}
*/
Summary.prototype.getPart = function(i) {
- var parts = this.getParts();
+ const parts = this.getParts();
return parts.get(i);
};
@@ -41,7 +41,7 @@ Summary.prototype.getPart = function(i) {
@return {Article|Part}
*/
Summary.prototype.getArticle = function(iter, partIter) {
- var parts = this.getParts();
+ const parts = this.getParts();
return parts.reduce(function(result, part) {
if (result) return result;
@@ -74,7 +74,7 @@ Summary.prototype.getByLevel = function(level) {
*/
Summary.prototype.getByPath = function(filePath) {
return this.getArticle(function(article) {
- var articlePath = article.getPath();
+ const articlePath = article.getPath();
return (
articlePath &&
@@ -101,8 +101,8 @@ Summary.prototype.getFirstArticle = function() {
@return {Article}
*/
Summary.prototype.getNextArticle = function(current) {
- var level = is.string(current)? current : current.getLevel();
- var wasPrev = false;
+ const level = is.string(current) ? current : current.getLevel();
+ let wasPrev = false;
return this.getArticle(function(article) {
if (wasPrev) return true;
@@ -119,8 +119,8 @@ Summary.prototype.getNextArticle = function(current) {
@return {Article}
*/
Summary.prototype.getPrevArticle = function(current) {
- var level = is.string(current)? current : current.getLevel();
- var prev = undefined;
+ const level = is.string(current) ? current : current.getLevel();
+ let prev = undefined;
this.getArticle(function(article) {
if (article.getLevel() == level) {
@@ -140,18 +140,18 @@ Summary.prototype.getPrevArticle = function(current) {
@param {String|Article} current
@return {Article|Part|Null}
*/
-Summary.prototype.getParent = function (level) {
+Summary.prototype.getParent = function(level) {
// Coerce to level
- level = is.string(level)? level : level.getLevel();
+ level = is.string(level) ? level : level.getLevel();
// Get parent level
- var parentLevel = getParentLevel(level);
+ const parentLevel = getParentLevel(level);
if (!parentLevel) {
return null;
}
// Get parent of the position
- var parentArticle = this.getByLevel(parentLevel);
+ const parentArticle = this.getByLevel(parentLevel);
return parentArticle || null;
};
@@ -162,10 +162,10 @@ Summary.prototype.getParent = function (level) {
@return {Promise<String>}
*/
Summary.prototype.toText = function(parseExt) {
- var file = this.getFile();
- var parts = this.getParts();
+ const file = this.getFile();
+ const parts = this.getParts();
- var parser = parseExt? parsers.getByExt(parseExt) : file.getParser();
+ const parser = parseExt ? parsers.getByExt(parseExt) : file.getParser();
if (!parser) {
throw error.FileNotParsableError({
@@ -184,7 +184,7 @@ Summary.prototype.toText = function(parseExt) {
@return {List<Article>}
*/
Summary.prototype.getArticlesAsList = function() {
- var accu = [];
+ const accu = [];
this.getArticle(function(article) {
accu.push(article);
@@ -209,7 +209,7 @@ Summary.createFromParts = function createFromParts(file, parts) {
});
return new Summary({
- file: file,
+ file,
parts: new Immutable.List(parts)
});
};
@@ -221,7 +221,7 @@ Summary.createFromParts = function createFromParts(file, parts) {
@return {String}
*/
function getParentLevel(level) {
- var parts = level.split('.');
+ const parts = level.split('.');
return parts.slice(0, -1).join('.');
}
diff --git a/packages/gitbook/lib/models/summaryArticle.js b/packages/gitbook/src/models/summaryArticle.js
index 6da8d1d..919e6b9 100644
--- a/packages/gitbook/lib/models/summaryArticle.js
+++ b/packages/gitbook/src/models/summaryArticle.js
@@ -1,12 +1,12 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var location = require('../utils/location');
+const location = require('../utils/location');
/*
An article represents an entry in the Summary / table of Contents
*/
-var SummaryArticle = Immutable.Record({
+const SummaryArticle = Immutable.Record({
level: String(),
title: String(),
ref: String(),
@@ -50,14 +50,14 @@ SummaryArticle.prototype.getPath = function() {
return undefined;
}
- var ref = this.getRef();
+ const ref = this.getRef();
if (!ref) {
return undefined;
}
- var parts = ref.split('#');
+ const parts = ref.split('#');
- var pathname = (parts.length > 1? parts.slice(0, -1).join('#') : ref);
+ const pathname = (parts.length > 1 ? parts.slice(0, -1).join('#') : ref);
// Normalize path to remove ('./', '/...', etc)
return location.flatten(pathname);
@@ -69,7 +69,7 @@ SummaryArticle.prototype.getPath = function() {
* @return {String}
*/
SummaryArticle.prototype.getUrl = function() {
- return this.isExternal()? this.getRef() : undefined;
+ return this.isExternal() ? this.getRef() : undefined;
};
/**
@@ -78,10 +78,10 @@ SummaryArticle.prototype.getUrl = function() {
* @return {String}
*/
SummaryArticle.prototype.getAnchor = function() {
- var ref = this.getRef();
- var parts = ref.split('#');
+ const ref = this.getRef();
+ const parts = ref.split('#');
- var anchor = (parts.length > 1? '#' + parts[parts.length - 1] : undefined);
+ const anchor = (parts.length > 1 ? '#' + parts[parts.length - 1] : undefined);
return anchor;
};
@@ -91,9 +91,9 @@ SummaryArticle.prototype.getAnchor = function() {
* @return {String}
*/
SummaryArticle.prototype.createChildLevel = function() {
- var level = this.getLevel();
- var subArticles = this.getArticles();
- var childLevel = level + '.' + (subArticles.size + 1);
+ const level = this.getLevel();
+ const subArticles = this.getArticles();
+ const childLevel = level + '.' + (subArticles.size + 1);
return childLevel;
};
@@ -127,8 +127,8 @@ SummaryArticle.prototype.isFile = function(file) {
* @return {Boolean}
*/
SummaryArticle.prototype.isReadme = function(book) {
- var readme = book.getFile? book : book.getReadme();
- var file = readme.getFile();
+ const readme = book.getFile ? book : book.getReadme();
+ const file = readme.getFile();
return this.isFile(file);
};
@@ -149,7 +149,7 @@ SummaryArticle.prototype.isExternal = function() {
* @return {SummaryArticle}
*/
SummaryArticle.create = function(def, level) {
- var articles = (def.articles || []).map(function(article, i) {
+ const articles = (def.articles || []).map(function(article, i) {
if (article instanceof SummaryArticle) {
return article;
}
@@ -157,7 +157,7 @@ SummaryArticle.create = function(def, level) {
});
return new SummaryArticle({
- level: level,
+ level,
title: def.title,
ref: def.ref || def.path || '',
articles: Immutable.List(articles)
@@ -172,7 +172,7 @@ SummaryArticle.create = function(def, level) {
* @return {Article}
*/
SummaryArticle.findArticle = function(base, iter) {
- var articles = base.getArticles();
+ const articles = base.getArticles();
return articles.reduce(function(result, article) {
if (result) return result;
diff --git a/packages/gitbook/lib/models/summaryPart.js b/packages/gitbook/src/models/summaryPart.js
index f0e6f57..0bb5369 100644
--- a/packages/gitbook/lib/models/summaryPart.js
+++ b/packages/gitbook/src/models/summaryPart.js
@@ -1,12 +1,12 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var SummaryArticle = require('./summaryArticle');
+const SummaryArticle = require('./summaryArticle');
/*
A part represents a section in the Summary / table of Contents
*/
-var SummaryPart = Immutable.Record({
+const SummaryPart = Immutable.Record({
level: String(),
title: String(),
articles: Immutable.List()
@@ -30,9 +30,9 @@ SummaryPart.prototype.getArticles = function() {
* @return {String}
*/
SummaryPart.prototype.createChildLevel = function() {
- var level = this.getLevel();
- var subArticles = this.getArticles();
- var childLevel = level + '.' + (subArticles.size + 1);
+ const level = this.getLevel();
+ const subArticles = this.getArticles();
+ const childLevel = level + '.' + (subArticles.size + 1);
return childLevel;
};
@@ -44,7 +44,7 @@ SummaryPart.prototype.createChildLevel = function() {
* @return {SummaryPart}
*/
SummaryPart.create = function(def, level) {
- var articles = (def.articles || []).map(function(article, i) {
+ const articles = (def.articles || []).map(function(article, i) {
if (article instanceof SummaryArticle) {
return article;
}
diff --git a/packages/gitbook/lib/models/templateBlock.js b/packages/gitbook/src/models/templateBlock.js
index 458f084..a0b9aaa 100644
--- a/packages/gitbook/lib/models/templateBlock.js
+++ b/packages/gitbook/src/models/templateBlock.js
@@ -1,14 +1,14 @@
-var is = require('is');
-var extend = require('extend');
-var Immutable = require('immutable');
+const is = require('is');
+const extend = require('extend');
+const Immutable = require('immutable');
-var Promise = require('../utils/promise');
-var genKey = require('../utils/genKey');
-var TemplateShortcut = require('./templateShortcut');
+const Promise = require('../utils/promise');
+const genKey = require('../utils/genKey');
+const TemplateShortcut = require('./templateShortcut');
-var NODE_ENDARGS = '%%endargs%%';
+const NODE_ENDARGS = '%%endargs%%';
-var TemplateBlock = Immutable.Record({
+const TemplateBlock = Immutable.Record({
// Name of block, also the start tag
name: String(),
@@ -47,7 +47,7 @@ TemplateBlock.prototype.getBlocks = function() {
* @return {TemplateShortcut|undefined}
*/
TemplateBlock.prototype.getShortcuts = function() {
- var shortcuts = this.get('shortcuts');
+ const shortcuts = this.get('shortcuts');
if (shortcuts.size === 0) {
return undefined;
}
@@ -70,33 +70,33 @@ TemplateBlock.prototype.getExtensionName = function() {
TemplateBlock.prototype.toNunjucksExt = function(mainContext, blocksOutput) {
blocksOutput = blocksOutput || {};
- var that = this;
- var name = this.getName();
- var endTag = this.getEndTag();
- var blocks = this.getBlocks().toJS();
+ const that = this;
+ const name = this.getName();
+ const endTag = this.getEndTag();
+ const blocks = this.getBlocks().toJS();
function Ext() {
this.tags = [name];
this.parse = function(parser, nodes) {
- var lastBlockName = null;
- var lastBlockArgs = null;
- var allBlocks = blocks.concat([endTag]);
+ let lastBlockName = null;
+ let lastBlockArgs = null;
+ const allBlocks = blocks.concat([endTag]);
// Parse first block
- var tok = parser.nextToken();
+ const tok = parser.nextToken();
lastBlockArgs = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(tok.value);
- var args = new nodes.NodeList();
- var bodies = [];
- var blockNamesNode = new nodes.Array(tok.lineno, tok.colno);
- var blockArgCounts = new nodes.Array(tok.lineno, tok.colno);
+ const args = new nodes.NodeList();
+ const bodies = [];
+ const blockNamesNode = new nodes.Array(tok.lineno, tok.colno);
+ const blockArgCounts = new nodes.Array(tok.lineno, tok.colno);
// Parse while we found "end<block>"
do {
// Read body
- var currentBody = parser.parseUntilBlocks.apply(parser, allBlocks);
+ const currentBody = parser.parseUntilBlocks(...allBlocks);
// Handle body with previous block name and args
blockNamesNode.addChild(new nodes.Literal(args.lineno, args.colno, lastBlockName));
@@ -126,53 +126,48 @@ TemplateBlock.prototype.toNunjucksExt = function(mainContext, blocksOutput) {
return new nodes.CallExtensionAsync(this, 'run', args, bodies);
};
- this.run = function(context) {
- var fnArgs = Array.prototype.slice.call(arguments, 1);
-
- var args;
- var blocks = [];
- var bodies = [];
- var blockNames;
- var blockArgCounts;
- var callback;
+ this.run = function(context, ...fnArgs) {
+ let args;
+ const blocks = [];
+ let bodies = [];
// Extract callback
- callback = fnArgs.pop();
+ const callback = fnArgs.pop();
// Detect end of arguments
- var endArgIndex = fnArgs.indexOf(NODE_ENDARGS);
+ const endArgIndex = fnArgs.indexOf(NODE_ENDARGS);
// Extract arguments and bodies
args = fnArgs.slice(0, endArgIndex);
bodies = fnArgs.slice(endArgIndex + 1);
// Extract block counts
- blockArgCounts = args.pop();
- blockNames = args.pop();
+ const blockArgCounts = args.pop();
+ const blockNames = args.pop();
// Recreate list of blocks
- blockNames.forEach(function(name, i) {
- var countArgs = blockArgCounts[i];
- var blockBody = bodies.shift();
+ blockNames.forEach((blkName, i) => {
+ const countArgs = blockArgCounts[i];
+ const blockBody = bodies.shift();
- var blockArgs = countArgs > 0? args.slice(0, countArgs) : [];
+ const blockArgs = countArgs > 0 ? args.slice(0, countArgs) : [];
args = args.slice(countArgs);
- var blockKwargs = extractKwargs(blockArgs);
+ const blockKwargs = extractKwargs(blockArgs);
blocks.push({
- name: name,
+ blkName,
body: blockBody(),
args: blockArgs,
kwargs: blockKwargs
});
});
- var mainBlock = blocks.shift();
+ const mainBlock = blocks.shift();
mainBlock.blocks = blocks;
Promise()
.then(function() {
- var ctx = extend({
+ const ctx = extend({
ctx: context
}, mainContext || {});
@@ -195,14 +190,14 @@ TemplateBlock.prototype.toNunjucksExt = function(mainContext, blocksOutput) {
* @return {Promise<String>|String}
*/
TemplateBlock.prototype.applyBlock = function(inner, context) {
- var processFn = this.getProcess();
+ const processFn = this.getProcess();
inner = inner || {};
inner.args = inner.args || [];
inner.kwargs = inner.kwargs || {};
inner.blocks = inner.blocks || [];
- var r = processFn.call(context, inner);
+ const r = processFn.call(context, inner);
if (Promise.isPromiseAlike(r)) {
return r.then(this.normalizeBlockResult.bind(this));
@@ -232,8 +227,8 @@ TemplateBlock.prototype.normalizeBlockResult = function(result) {
* @return {String}
*/
TemplateBlock.prototype.blockResultToHtml = function(result, blocksOutput) {
- var indexedKey;
- var toIndex = (!result.parse) || (result.post !== undefined);
+ let indexedKey;
+ const toIndex = (!result.parse) || (result.post !== undefined);
if (toIndex) {
indexedKey = genKey();
@@ -274,8 +269,8 @@ TemplateBlock.create = function(blockName, block) {
* @return {Object}
*/
function extractKwargs(args) {
- var last = args[args.length - 1];
- return (is.object(last) && last.__keywords)? args.pop() : {};
+ const last = args[args.length - 1];
+ return (is.object(last) && last.__keywords) ? args.pop() : {};
}
module.exports = TemplateBlock;
diff --git a/packages/gitbook/lib/models/templateEngine.js b/packages/gitbook/src/models/templateEngine.js
index 5724d55..b218a9d 100644
--- a/packages/gitbook/lib/models/templateEngine.js
+++ b/packages/gitbook/src/models/templateEngine.js
@@ -1,7 +1,7 @@
-var nunjucks = require('nunjucks');
-var Immutable = require('immutable');
+const nunjucks = require('nunjucks');
+const Immutable = require('immutable');
-var TemplateEngine = Immutable.Record({
+const TemplateEngine = Immutable.Record({
// Map of {TemplateBlock}
blocks: Immutable.Map(),
@@ -56,7 +56,7 @@ TemplateEngine.prototype.getExtensions = function() {
@return {TemplateBlock}
*/
TemplateEngine.prototype.getBlock = function(name) {
- var blocks = this.getBlocks();
+ const blocks = this.getBlocks();
return blocks.find(function(block) {
return block.getName() === name;
});
@@ -68,14 +68,14 @@ TemplateEngine.prototype.getBlock = function(name) {
@return {Nunjucks.Environment}
*/
TemplateEngine.prototype.toNunjucks = function(blocksOutput) {
- var loader = this.getLoader();
- var blocks = this.getBlocks();
- var filters = this.getFilters();
- var globals = this.getGlobals();
- var extensions = this.getExtensions();
- var context = this.getContext();
-
- var env = new nunjucks.Environment(
+ const loader = this.getLoader();
+ const blocks = this.getBlocks();
+ const filters = this.getFilters();
+ const globals = this.getGlobals();
+ const extensions = this.getExtensions();
+ const context = this.getContext();
+
+ const env = new nunjucks.Environment(
loader,
{
// Escaping is done after by the asciidoc/markdown parser
@@ -100,8 +100,8 @@ TemplateEngine.prototype.toNunjucks = function(blocksOutput) {
// Add blocks
blocks.forEach(function(block) {
- var extName = block.getExtensionName();
- var Ext = block.toNunjucksExt(context, blocksOutput);
+ const extName = block.getExtensionName();
+ const Ext = block.toNunjucksExt(context, blocksOutput);
env.addExtension(extName, new Ext());
});
diff --git a/packages/gitbook/lib/models/templateOutput.js b/packages/gitbook/src/models/templateOutput.js
index ae63c06..c6ff730 100644
--- a/packages/gitbook/lib/models/templateOutput.js
+++ b/packages/gitbook/src/models/templateOutput.js
@@ -1,6 +1,6 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var TemplateOutput = Immutable.Record({
+const TemplateOutput = Immutable.Record({
// Text content of the template
content: String(),
@@ -34,7 +34,7 @@ TemplateOutput.prototype.setContent = function(content) {
*/
TemplateOutput.create = function(content, blocks) {
return new TemplateOutput({
- content: content,
+ content,
blocks: Immutable.fromJS(blocks)
});
};
diff --git a/packages/gitbook/lib/models/templateShortcut.js b/packages/gitbook/src/models/templateShortcut.js
index 309fa6d..b6e1ed9 100644
--- a/packages/gitbook/lib/models/templateShortcut.js
+++ b/packages/gitbook/src/models/templateShortcut.js
@@ -1,11 +1,11 @@
-var Immutable = require('immutable');
-var is = require('is');
+const Immutable = require('immutable');
+const is = require('is');
/*
A TemplateShortcut is defined in plugin's template blocks
to replace content with a templating block using delimiters.
*/
-var TemplateShortcut = Immutable.Record({
+const TemplateShortcut = Immutable.Record({
// List of parser names accepting this shortcut
parsers: Immutable.Map(),
@@ -47,7 +47,7 @@ TemplateShortcut.prototype.acceptParser = function(parser) {
parser = parser.getName();
}
- var parserNames = this.get('parsers');
+ const parserNames = this.get('parsers');
return parserNames.includes(parser);
};
diff --git a/packages/gitbook/lib/modifiers/config/__tests__/addPlugin.js b/packages/gitbook/src/modifiers/config/__tests__/addPlugin.js
index 61082c9..65fd8f9 100644
--- a/packages/gitbook/lib/modifiers/config/__tests__/addPlugin.js
+++ b/packages/gitbook/src/modifiers/config/__tests__/addPlugin.js
@@ -1,13 +1,13 @@
-var addPlugin = require('../addPlugin');
-var Config = require('../../../models/config');
+const addPlugin = require('../addPlugin');
+const Config = require('../../../models/config');
describe('addPlugin', function() {
- var config = Config.createWithValues({
+ const config = Config.createWithValues({
plugins: ['hello', 'world', '-disabled']
});
it('should have correct state of dependencies', function() {
- var disabledDep = config.getPluginDependency('disabled');
+ const disabledDep = config.getPluginDependency('disabled');
expect(disabledDep).toBeDefined();
expect(disabledDep.getVersion()).toEqual('*');
@@ -15,18 +15,17 @@ describe('addPlugin', function() {
});
it('should add the plugin to the list', function() {
- var newConfig = addPlugin(config, 'test');
+ const newConfig = addPlugin(config, 'test');
- var testDep = newConfig.getPluginDependency('test');
+ const testDep = newConfig.getPluginDependency('test');
expect(testDep).toBeDefined();
expect(testDep.getVersion()).toEqual('*');
expect(testDep.isEnabled()).toBeTruthy();
- var disabledDep = newConfig.getPluginDependency('disabled');
+ const disabledDep = newConfig.getPluginDependency('disabled');
expect(disabledDep).toBeDefined();
expect(disabledDep.getVersion()).toEqual('*');
expect(disabledDep.isEnabled()).toBeFalsy();
});
});
-
diff --git a/packages/gitbook/lib/modifiers/config/__tests__/removePlugin.js b/packages/gitbook/src/modifiers/config/__tests__/removePlugin.js
index 253cc39..5450b30 100644
--- a/packages/gitbook/lib/modifiers/config/__tests__/removePlugin.js
+++ b/packages/gitbook/src/modifiers/config/__tests__/removePlugin.js
@@ -1,33 +1,32 @@
-var removePlugin = require('../removePlugin');
-var Config = require('../../../models/config');
+const removePlugin = require('../removePlugin');
+const Config = require('../../../models/config');
describe('removePlugin', function() {
- var config = Config.createWithValues({
+ const config = Config.createWithValues({
plugins: ['hello', 'world', '-disabled']
});
it('should remove the plugin from the list', function() {
- var newConfig = removePlugin(config, 'hello');
+ const newConfig = removePlugin(config, 'hello');
- var testDep = newConfig.getPluginDependency('hello');
+ const testDep = newConfig.getPluginDependency('hello');
expect(testDep).toNotBeDefined();
});
it('should remove the disabled plugin from the list', function() {
- var newConfig = removePlugin(config, 'disabled');
+ const newConfig = removePlugin(config, 'disabled');
- var testDep = newConfig.getPluginDependency('disabled');
+ const testDep = newConfig.getPluginDependency('disabled');
expect(testDep).toNotBeDefined();
});
it('should disable default plugin', function() {
- var newConfig = removePlugin(config, 'search');
+ const newConfig = removePlugin(config, 'search');
- var disabledDep = newConfig.getPluginDependency('search');
+ const disabledDep = newConfig.getPluginDependency('search');
expect(disabledDep).toBeDefined();
expect(disabledDep.getVersion()).toEqual('*');
expect(disabledDep.isEnabled()).toBeFalsy();
});
});
-
diff --git a/packages/gitbook/lib/modifiers/config/__tests__/togglePlugin.js b/packages/gitbook/src/modifiers/config/__tests__/togglePlugin.js
index 4127853..6d23ae0 100644
--- a/packages/gitbook/lib/modifiers/config/__tests__/togglePlugin.js
+++ b/packages/gitbook/src/modifiers/config/__tests__/togglePlugin.js
@@ -1,28 +1,27 @@
-var togglePlugin = require('../togglePlugin');
-var Config = require('../../../models/config');
+const togglePlugin = require('../togglePlugin');
+const Config = require('../../../models/config');
describe('togglePlugin', function() {
- var config = Config.createWithValues({
+ const config = Config.createWithValues({
plugins: ['hello', 'world', '-disabled']
});
it('should enable plugin', function() {
- var newConfig = togglePlugin(config, 'disabled');
+ const newConfig = togglePlugin(config, 'disabled');
- var testDep = newConfig.getPluginDependency('disabled');
+ const testDep = newConfig.getPluginDependency('disabled');
expect(testDep).toBeDefined();
expect(testDep.getVersion()).toEqual('*');
expect(testDep.isEnabled()).toBeTruthy();
});
it('should disable plugin', function() {
- var newConfig = togglePlugin(config, 'world');
+ const newConfig = togglePlugin(config, 'world');
- var testDep = newConfig.getPluginDependency('world');
+ const testDep = newConfig.getPluginDependency('world');
expect(testDep).toBeDefined();
expect(testDep.getVersion()).toEqual('*');
expect(testDep.isEnabled()).toBeFalsy();
});
});
-
diff --git a/packages/gitbook/lib/modifiers/config/addPlugin.js b/packages/gitbook/src/modifiers/config/addPlugin.js
index b8d4ea1..e9ed259 100644
--- a/packages/gitbook/lib/modifiers/config/addPlugin.js
+++ b/packages/gitbook/src/modifiers/config/addPlugin.js
@@ -1,6 +1,6 @@
-var PluginDependency = require('../../models/pluginDependency');
-var togglePlugin = require('./togglePlugin');
-var isDefaultPlugin = require('./isDefaultPlugin');
+const PluginDependency = require('../../models/pluginDependency');
+const togglePlugin = require('./togglePlugin');
+const isDefaultPlugin = require('./isDefaultPlugin');
/**
* Add a plugin to a book's configuration
@@ -15,8 +15,8 @@ function addPlugin(config, pluginName, version) {
return togglePlugin(config, pluginName, true);
}
- var deps = config.getPluginDependencies();
- var dep = PluginDependency.create(pluginName, version);
+ let deps = config.getPluginDependencies();
+ const dep = PluginDependency.create(pluginName, version);
deps = deps.push(dep);
return config.setPluginDependencies(deps);
diff --git a/packages/gitbook/lib/modifiers/config/editPlugin.js b/packages/gitbook/src/modifiers/config/editPlugin.js
index a792acd..dd7fd11 100644
--- a/packages/gitbook/lib/modifiers/config/editPlugin.js
+++ b/packages/gitbook/src/modifiers/config/editPlugin.js
@@ -7,7 +7,7 @@
* @return {Config}
*/
function editPlugin(config, pluginName, pluginConfig) {
- return config.setValue('pluginsConfig.'+pluginName, pluginConfig);
+ return config.setValue('pluginsConfig.' + pluginName, pluginConfig);
}
module.exports = editPlugin;
diff --git a/packages/gitbook/lib/modifiers/config/getPluginConfig.js b/packages/gitbook/src/modifiers/config/getPluginConfig.js
index ae76de8..ed7d6ea 100644
--- a/packages/gitbook/lib/modifiers/config/getPluginConfig.js
+++ b/packages/gitbook/src/modifiers/config/getPluginConfig.js
@@ -5,11 +5,11 @@
* @return {Object}
*/
function getPluginConfig(config, pluginName) {
- var pluginsConfig = config.getValues().get('pluginsConfig');
+ const pluginsConfig = config.getValues().get('pluginsConfig');
if (pluginsConfig === undefined) {
return {};
}
- var pluginConf = pluginsConfig.get(pluginName);
+ const pluginConf = pluginsConfig.get(pluginName);
if (pluginConf === undefined) {
return {};
} else {
diff --git a/packages/gitbook/lib/modifiers/config/hasPlugin.js b/packages/gitbook/src/modifiers/config/hasPlugin.js
index 9aab4f2..9aab4f2 100644
--- a/packages/gitbook/lib/modifiers/config/hasPlugin.js
+++ b/packages/gitbook/src/modifiers/config/hasPlugin.js
diff --git a/packages/gitbook/lib/modifiers/config/index.js b/packages/gitbook/src/modifiers/config/index.js
index b3de0b0..b3de0b0 100644
--- a/packages/gitbook/lib/modifiers/config/index.js
+++ b/packages/gitbook/src/modifiers/config/index.js
diff --git a/packages/gitbook/lib/modifiers/config/isDefaultPlugin.js b/packages/gitbook/src/modifiers/config/isDefaultPlugin.js
index 63a141d..096e21a 100644
--- a/packages/gitbook/lib/modifiers/config/isDefaultPlugin.js
+++ b/packages/gitbook/src/modifiers/config/isDefaultPlugin.js
@@ -1,5 +1,5 @@
-var DEFAULT_PLUGINS = require('../../constants/defaultPlugins');
-var hasPlugin = require('./hasPlugin');
+const DEFAULT_PLUGINS = require('../../constants/defaultPlugins');
+const hasPlugin = require('./hasPlugin');
/**
* Test if a plugin is a default one
diff --git a/packages/gitbook/lib/modifiers/config/removePlugin.js b/packages/gitbook/src/modifiers/config/removePlugin.js
index ec06d1e..c80ab84 100644
--- a/packages/gitbook/lib/modifiers/config/removePlugin.js
+++ b/packages/gitbook/src/modifiers/config/removePlugin.js
@@ -1,5 +1,5 @@
-var togglePlugin = require('./togglePlugin');
-var isDefaultPlugin = require('./isDefaultPlugin');
+const togglePlugin = require('./togglePlugin');
+const isDefaultPlugin = require('./isDefaultPlugin');
/**
* Remove a plugin from a book's configuration
@@ -8,7 +8,7 @@ var isDefaultPlugin = require('./isDefaultPlugin');
* @return {Config}
*/
function removePlugin(config, pluginName) {
- var deps = config.getPluginDependencies();
+ let deps = config.getPluginDependencies();
// For default plugin, we have to disable it instead of removing from the list
if (isDefaultPlugin(pluginName)) {
diff --git a/packages/gitbook/lib/modifiers/config/togglePlugin.js b/packages/gitbook/src/modifiers/config/togglePlugin.js
index a49e3b9..12a6dec 100644
--- a/packages/gitbook/lib/modifiers/config/togglePlugin.js
+++ b/packages/gitbook/src/modifiers/config/togglePlugin.js
@@ -1,6 +1,6 @@
-var PluginDependency = require('../../models/pluginDependency');
-var hasPlugin = require('./hasPlugin');
-var isDefaultPlugin = require('./isDefaultPlugin');
+const PluginDependency = require('../../models/pluginDependency');
+const hasPlugin = require('./hasPlugin');
+const isDefaultPlugin = require('./isDefaultPlugin');
/**
* Enable/disable a plugin dependency
@@ -10,7 +10,7 @@ var isDefaultPlugin = require('./isDefaultPlugin');
* @return {Config}
*/
function togglePlugin(config, pluginName, state) {
- var deps = config.getPluginDependencies();
+ let deps = config.getPluginDependencies();
// For default plugin, we should ensure it's listed first
if (isDefaultPlugin(pluginName) && !hasPlugin(deps, pluginName)) {
diff --git a/packages/gitbook/lib/modifiers/index.js b/packages/gitbook/src/modifiers/index.js
index ad24604..ad24604 100644
--- a/packages/gitbook/lib/modifiers/index.js
+++ b/packages/gitbook/src/modifiers/index.js
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/editArticle.js b/packages/gitbook/src/modifiers/summary/__tests__/editArticle.js
index e69de29..e69de29 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/editArticle.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/editArticle.js
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/editPartTitle.js b/packages/gitbook/src/modifiers/summary/__tests__/editPartTitle.js
index d1b916b..aa14a34 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/editPartTitle.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/editPartTitle.js
@@ -1,9 +1,9 @@
-var Summary = require('../../../models/summary');
-var File = require('../../../models/file');
+const Summary = require('../../../models/summary');
+const File = require('../../../models/file');
describe('editPartTitle', function() {
- var editPartTitle = require('../editPartTitle');
- var summary = Summary.createFromParts(File(), [
+ const editPartTitle = require('../editPartTitle');
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -22,23 +22,22 @@ describe('editPartTitle', function() {
]);
it('should correctly set title of first part', function() {
- var newSummary = editPartTitle(summary, 0, 'Hello World');
- var part = newSummary.getPart(0);
+ const newSummary = editPartTitle(summary, 0, 'Hello World');
+ const part = newSummary.getPart(0);
expect(part.getTitle()).toBe('Hello World');
});
it('should correctly set title of second part', function() {
- var newSummary = editPartTitle(summary, 1, 'Hello');
- var part = newSummary.getPart(1);
+ const newSummary = editPartTitle(summary, 1, 'Hello');
+ const part = newSummary.getPart(1);
expect(part.getTitle()).toBe('Hello');
});
it('should not fail if part doesn\'t exist', function() {
- var newSummary = editPartTitle(summary, 3, 'Hello');
+ const newSummary = editPartTitle(summary, 3, 'Hello');
expect(newSummary.getParts().size).toBe(2);
});
});
-
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/insertArticle.js b/packages/gitbook/src/modifiers/summary/__tests__/insertArticle.js
index 1ee1c8a..d5ae9bc 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/insertArticle.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/insertArticle.js
@@ -1,10 +1,10 @@
-var Summary = require('../../../models/summary');
-var SummaryArticle = require('../../../models/summaryArticle');
-var File = require('../../../models/file');
+const Summary = require('../../../models/summary');
+const SummaryArticle = require('../../../models/summaryArticle');
+const File = require('../../../models/file');
describe('insertArticle', function() {
- var insertArticle = require('../insertArticle');
- var summary = Summary.createFromParts(File(), [
+ const insertArticle = require('../insertArticle');
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -43,14 +43,14 @@ describe('insertArticle', function() {
]);
it('should insert an article at a given level', function() {
- var article = SummaryArticle.create({
+ const article = SummaryArticle.create({
title: 'Inserted'
}, 'fake.level');
- var newSummary = insertArticle(summary, article, '2.1.1');
+ const newSummary = insertArticle(summary, article, '2.1.1');
- var inserted = newSummary.getByLevel('2.1.1');
- var nextOne = newSummary.getByLevel('2.1.2');
+ const inserted = newSummary.getByLevel('2.1.1');
+ const nextOne = newSummary.getByLevel('2.1.2');
expect(inserted.getTitle()).toBe('Inserted');
expect(inserted.getLevel()).toBe('2.1.1');
@@ -60,14 +60,14 @@ describe('insertArticle', function() {
});
it('should insert an article in last position', function() {
- var article = SummaryArticle.create({
+ const article = SummaryArticle.create({
title: 'Inserted'
}, 'fake.level');
- var newSummary = insertArticle(summary, article, '2.2');
+ const newSummary = insertArticle(summary, article, '2.2');
- var inserted = newSummary.getByLevel('2.2');
- var previousOne = newSummary.getByLevel('2.1');
+ const inserted = newSummary.getByLevel('2.2');
+ const previousOne = newSummary.getByLevel('2.1');
expect(inserted.getTitle()).toBe('Inserted');
expect(inserted.getLevel()).toBe('2.2');
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/insertPart.js b/packages/gitbook/src/modifiers/summary/__tests__/insertPart.js
index 11c2cbc..5112931 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/insertPart.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/insertPart.js
@@ -1,11 +1,11 @@
-var Summary = require('../../../models/summary');
-var SummaryPart = require('../../../models/summaryPart');
+const Summary = require('../../../models/summary');
+const SummaryPart = require('../../../models/summaryPart');
-var File = require('../../../models/file');
+const File = require('../../../models/file');
describe('insertPart', function() {
- var insertPart = require('../insertPart');
- var summary = Summary.createFromParts(File(), [
+ const insertPart = require('../insertPart');
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -31,29 +31,29 @@ describe('insertPart', function() {
]);
it('should insert an part at a given level', function() {
- var part = SummaryPart.create({
+ const part = SummaryPart.create({
title: 'Inserted'
}, 'meaningless.level');
- var newSummary = insertPart(summary, part, 1);
+ const newSummary = insertPart(summary, part, 1);
- var inserted = newSummary.getPart(1);
+ const inserted = newSummary.getPart(1);
expect(inserted.getTitle()).toBe('Inserted');
expect(newSummary.getParts().count()).toBe(3);
- var otherArticle = newSummary.getByLevel('3.1');
+ const otherArticle = newSummary.getByLevel('3.1');
expect(otherArticle.getTitle()).toBe('2.1');
expect(otherArticle.getLevel()).toBe('3.1');
});
it('should insert an part in last position', function() {
- var part = SummaryPart.create({
+ const part = SummaryPart.create({
title: 'Inserted'
}, 'meaningless.level');
- var newSummary = insertPart(summary, part, 2);
+ const newSummary = insertPart(summary, part, 2);
- var inserted = newSummary.getPart(2);
+ const inserted = newSummary.getPart(2);
expect(inserted.getTitle()).toBe('Inserted');
expect(newSummary.getParts().count()).toBe(3);
});
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/mergeAtLevel.js b/packages/gitbook/src/modifiers/summary/__tests__/mergeAtLevel.js
index e2635ec..e0d4a62 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/mergeAtLevel.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/mergeAtLevel.js
@@ -1,10 +1,10 @@
-var Immutable = require('immutable');
-var Summary = require('../../../models/summary');
-var File = require('../../../models/file');
+const Immutable = require('immutable');
+const Summary = require('../../../models/summary');
+const File = require('../../../models/file');
describe('mergeAtLevel', function() {
- var mergeAtLevel = require('../mergeAtLevel');
- var summary = Summary.createFromParts(File(), [
+ const mergeAtLevel = require('../mergeAtLevel');
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -24,9 +24,9 @@ describe('mergeAtLevel', function() {
]);
it('should edit a part', function() {
- var beforeChildren = summary.getByLevel('1').getArticles();
- var newSummary = mergeAtLevel(summary, '1', {title: 'Part O'});
- var edited = newSummary.getByLevel('1');
+ const beforeChildren = summary.getByLevel('1').getArticles();
+ const newSummary = mergeAtLevel(summary, '1', {title: 'Part O'});
+ const edited = newSummary.getByLevel('1');
expect(edited.getTitle()).toBe('Part O');
// Same children
@@ -34,9 +34,9 @@ describe('mergeAtLevel', function() {
});
it('should edit a part', function() {
- var beforePath = summary.getByLevel('1.2').getPath();
- var newSummary = mergeAtLevel(summary, '1.2', {title: 'Renamed article'});
- var edited = newSummary.getByLevel('1.2');
+ const beforePath = summary.getByLevel('1.2').getPath();
+ const newSummary = mergeAtLevel(summary, '1.2', {title: 'Renamed article'});
+ const edited = newSummary.getByLevel('1.2');
expect(edited.getTitle()).toBe('Renamed article');
// Same children
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/moveArticle.js b/packages/gitbook/src/modifiers/summary/__tests__/moveArticle.js
index aed0b94..a7d111b 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/moveArticle.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/moveArticle.js
@@ -1,10 +1,10 @@
-var Immutable = require('immutable');
-var Summary = require('../../../models/summary');
-var File = require('../../../models/file');
+const Immutable = require('immutable');
+const Summary = require('../../../models/summary');
+const File = require('../../../models/file');
describe('moveArticle', function() {
- var moveArticle = require('../moveArticle');
- var summary = Summary.createFromParts(File(), [
+ const moveArticle = require('../moveArticle');
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -43,24 +43,24 @@ describe('moveArticle', function() {
]);
it('should move an article to the same place', function() {
- var newSummary = moveArticle(summary, '2.1', '2.1');
+ const newSummary = moveArticle(summary, '2.1', '2.1');
expect(Immutable.is(summary, newSummary)).toBe(true);
});
it('should move an article to an previous level', function() {
- var newSummary = moveArticle(summary, '2.2', '2.1');
- var moved = newSummary.getByLevel('2.1');
- var other = newSummary.getByLevel('2.2');
+ const newSummary = moveArticle(summary, '2.2', '2.1');
+ const moved = newSummary.getByLevel('2.1');
+ const other = newSummary.getByLevel('2.2');
expect(moved.getTitle()).toBe('2.2');
expect(other.getTitle()).toBe('2.1');
});
it('should move an article to a next level', function() {
- var newSummary = moveArticle(summary, '2.1', '2.2');
- var moved = newSummary.getByLevel('2.1');
- var other = newSummary.getByLevel('2.2');
+ const newSummary = moveArticle(summary, '2.1', '2.2');
+ const moved = newSummary.getByLevel('2.1');
+ const other = newSummary.getByLevel('2.2');
expect(moved.getTitle()).toBe('2.2');
expect(other.getTitle()).toBe('2.1');
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/moveArticleAfter.js b/packages/gitbook/src/modifiers/summary/__tests__/moveArticleAfter.js
index c380575..446d8a4 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/moveArticleAfter.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/moveArticleAfter.js
@@ -1,10 +1,10 @@
-var Immutable = require('immutable');
-var Summary = require('../../../models/summary');
-var File = require('../../../models/file');
+const Immutable = require('immutable');
+const Summary = require('../../../models/summary');
+const File = require('../../../models/file');
describe('moveArticleAfter', function() {
- var moveArticleAfter = require('../moveArticleAfter');
- var summary = Summary.createFromParts(File(), [
+ const moveArticleAfter = require('../moveArticleAfter');
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -43,28 +43,28 @@ describe('moveArticleAfter', function() {
]);
it('moving right after itself should be invariant', function() {
- var newSummary = moveArticleAfter(summary, '2.1', '2.1');
+ const newSummary = moveArticleAfter(summary, '2.1', '2.1');
expect(Immutable.is(summary, newSummary)).toBe(true);
});
it('moving after previous one should be invariant too', function() {
- var newSummary = moveArticleAfter(summary, '2.1', '2.0');
+ const newSummary = moveArticleAfter(summary, '2.1', '2.0');
expect(Immutable.is(summary, newSummary)).toBe(true);
});
it('should move an article after a previous level', function() {
- var newSummary = moveArticleAfter(summary, '2.2', '2.0');
- var moved = newSummary.getByLevel('2.1');
+ const newSummary = moveArticleAfter(summary, '2.2', '2.0');
+ const moved = newSummary.getByLevel('2.1');
expect(moved.getTitle()).toBe('2.2');
expect(newSummary.getByLevel('2.2').getTitle()).toBe('2.1');
});
it('should move an article after a previous and less deep level', function() {
- var newSummary = moveArticleAfter(summary, '2.1.1', '2.0');
- var moved = newSummary.getByLevel('2.1');
+ const newSummary = moveArticleAfter(summary, '2.1.1', '2.0');
+ const moved = newSummary.getByLevel('2.1');
expect(moved.getTitle()).toBe('2.1.1');
expect(newSummary.getByLevel('2.2.1').getTitle()).toBe('2.1.2');
@@ -72,8 +72,8 @@ describe('moveArticleAfter', function() {
});
it('should move an article after a next level', function() {
- var newSummary = moveArticleAfter(summary, '2.1', '2.2');
- var moved = newSummary.getByLevel('2.2');
+ const newSummary = moveArticleAfter(summary, '2.1', '2.2');
+ const moved = newSummary.getByLevel('2.2');
expect(moved.getTitle()).toBe('2.1');
expect(newSummary.getByLevel('2.1').getTitle()).toBe('2.2');
diff --git a/packages/gitbook/lib/modifiers/summary/__tests__/removeArticle.js b/packages/gitbook/src/modifiers/summary/__tests__/removeArticle.js
index b45fb49..14587ca 100644
--- a/packages/gitbook/lib/modifiers/summary/__tests__/removeArticle.js
+++ b/packages/gitbook/src/modifiers/summary/__tests__/removeArticle.js
@@ -1,9 +1,9 @@
-var Summary = require('../../../models/summary');
-var File = require('../../../models/file');
+const Summary = require('../../../models/summary');
+const File = require('../../../models/file');
describe('removeArticle', function() {
- var removeArticle = require('../removeArticle');
- var summary = Summary.createFromParts(File(), [
+ const removeArticle = require('../removeArticle');
+ const summary = Summary.createFromParts(File(), [
{
articles: [
{
@@ -42,10 +42,10 @@ describe('removeArticle', function() {
]);
it('should remove an article at a given level', function() {
- var newSummary = removeArticle(summary, '2.1.1');
+ const newSummary = removeArticle(summary, '2.1.1');
- var removed = newSummary.getByLevel('2.1.1');
- var nextOne = newSummary.getByLevel('2.1.2');
+ const removed = newSummary.getByLevel('2.1.1');
+ const nextOne = newSummary.getByLevel('2.1.2');
expect(removed.getTitle()).toBe('2.1.2');
expect(nextOne).toBe(null);
diff --git a/packages/gitbook/lib/modifiers/summary/editArticleRef.js b/packages/gitbook/src/modifiers/summary/editArticleRef.js
index 7106960..c5c1868 100644
--- a/packages/gitbook/lib/modifiers/summary/editArticleRef.js
+++ b/packages/gitbook/src/modifiers/summary/editArticleRef.js
@@ -1,4 +1,4 @@
-var mergeAtLevel = require('./mergeAtLevel');
+const mergeAtLevel = require('./mergeAtLevel');
/**
Edit the ref of an article
diff --git a/packages/gitbook/lib/modifiers/summary/editArticleTitle.js b/packages/gitbook/src/modifiers/summary/editArticleTitle.js
index 4edee83..f55c97e 100644
--- a/packages/gitbook/lib/modifiers/summary/editArticleTitle.js
+++ b/packages/gitbook/src/modifiers/summary/editArticleTitle.js
@@ -1,4 +1,4 @@
-var mergeAtLevel = require('./mergeAtLevel');
+const mergeAtLevel = require('./mergeAtLevel');
/**
Edit title of an article
diff --git a/packages/gitbook/lib/modifiers/summary/editPartTitle.js b/packages/gitbook/src/modifiers/summary/editPartTitle.js
index b79ac1e..ace7058 100644
--- a/packages/gitbook/lib/modifiers/summary/editPartTitle.js
+++ b/packages/gitbook/src/modifiers/summary/editPartTitle.js
@@ -7,9 +7,9 @@
@return {Summary}
*/
function editPartTitle(summary, index, newTitle) {
- var parts = summary.getParts();
+ let parts = summary.getParts();
- var part = parts.get(index);
+ let part = parts.get(index);
if (!part) {
return summary;
}
diff --git a/packages/gitbook/lib/modifiers/summary/index.js b/packages/gitbook/src/modifiers/summary/index.js
index f91fdb6..f91fdb6 100644
--- a/packages/gitbook/lib/modifiers/summary/index.js
+++ b/packages/gitbook/src/modifiers/summary/index.js
diff --git a/packages/gitbook/lib/modifiers/summary/indexArticleLevels.js b/packages/gitbook/src/modifiers/summary/indexArticleLevels.js
index f311f74..03c26c7 100644
--- a/packages/gitbook/lib/modifiers/summary/indexArticleLevels.js
+++ b/packages/gitbook/src/modifiers/summary/indexArticleLevels.js
@@ -8,7 +8,7 @@
*/
function indexArticleLevels(article, baseLevel) {
baseLevel = baseLevel || article.getLevel();
- var articles = article.getArticles();
+ let articles = article.getArticles();
articles = articles.map(function(inner, i) {
return indexArticleLevels(inner, baseLevel + '.' + (i + 1));
@@ -16,7 +16,7 @@ function indexArticleLevels(article, baseLevel) {
return article.merge({
level: baseLevel,
- articles: articles
+ articles
});
}
diff --git a/packages/gitbook/lib/modifiers/summary/indexLevels.js b/packages/gitbook/src/modifiers/summary/indexLevels.js
index 604e9ff..deb76da 100644
--- a/packages/gitbook/lib/modifiers/summary/indexLevels.js
+++ b/packages/gitbook/src/modifiers/summary/indexLevels.js
@@ -1,4 +1,4 @@
-var indexPartLevels = require('./indexPartLevels');
+const indexPartLevels = require('./indexPartLevels');
/**
Index all levels in the summary
@@ -7,7 +7,7 @@ var indexPartLevels = require('./indexPartLevels');
@return {Summary}
*/
function indexLevels(summary) {
- var parts = summary.getParts();
+ let parts = summary.getParts();
parts = parts.map(indexPartLevels);
return summary.set('parts', parts);
diff --git a/packages/gitbook/lib/modifiers/summary/indexPartLevels.js b/packages/gitbook/src/modifiers/summary/indexPartLevels.js
index d19c70a..6e48778 100644
--- a/packages/gitbook/lib/modifiers/summary/indexPartLevels.js
+++ b/packages/gitbook/src/modifiers/summary/indexPartLevels.js
@@ -1,4 +1,4 @@
-var indexArticleLevels = require('./indexArticleLevels');
+const indexArticleLevels = require('./indexArticleLevels');
/**
Index levels in a part
@@ -8,8 +8,8 @@ var indexArticleLevels = require('./indexArticleLevels');
@return {Part}
*/
function indexPartLevels(part, index) {
- var baseLevel = String(index + 1);
- var articles = part.getArticles();
+ const baseLevel = String(index + 1);
+ let articles = part.getArticles();
articles = articles.map(function(inner, i) {
return indexArticleLevels(inner, baseLevel + '.' + (i + 1));
@@ -17,7 +17,7 @@ function indexPartLevels(part, index) {
return part.merge({
level: baseLevel,
- articles: articles
+ articles
});
}
diff --git a/packages/gitbook/lib/modifiers/summary/insertArticle.js b/packages/gitbook/src/modifiers/summary/insertArticle.js
index 3a084b3..537f548 100644
--- a/packages/gitbook/lib/modifiers/summary/insertArticle.js
+++ b/packages/gitbook/src/modifiers/summary/insertArticle.js
@@ -1,7 +1,7 @@
-var is = require('is');
-var SummaryArticle = require('../../models/summaryArticle');
-var mergeAtLevel = require('./mergeAtLevel');
-var indexArticleLevels = require('./indexArticleLevels');
+const is = require('is');
+const SummaryArticle = require('../../models/summaryArticle');
+const mergeAtLevel = require('./mergeAtLevel');
+const indexArticleLevels = require('./indexArticleLevels');
/**
Returns a new Summary with the article at the given level, with
@@ -14,16 +14,16 @@ var indexArticleLevels = require('./indexArticleLevels');
*/
function insertArticle(summary, article, level) {
article = SummaryArticle(article);
- level = is.string(level)? level : level.getLevel();
+ level = is.string(level) ? level : level.getLevel();
- var parent = summary.getParent(level);
+ let parent = summary.getParent(level);
if (!parent) {
return summary;
}
// Find the index to insert at
- var articles = parent.getArticles();
- var index = getLeafIndex(level);
+ let articles = parent.getArticles();
+ const index = getLeafIndex(level);
// Insert the article at the right index
articles = articles.insert(index, article);
@@ -40,7 +40,7 @@ function insertArticle(summary, article, level) {
@return {Number} The index of this level within its parent's children
*/
function getLeafIndex(level) {
- var arr = level.split('.').map(function (char) {
+ const arr = level.split('.').map(function(char) {
return parseInt(char, 10);
});
return arr[arr.length - 1] - 1;
diff --git a/packages/gitbook/lib/modifiers/summary/insertPart.js b/packages/gitbook/src/modifiers/summary/insertPart.js
index 199cba7..ea99f89 100644
--- a/packages/gitbook/lib/modifiers/summary/insertPart.js
+++ b/packages/gitbook/src/modifiers/summary/insertPart.js
@@ -1,5 +1,5 @@
-var SummaryPart = require('../../models/summaryPart');
-var indexLevels = require('./indexLevels');
+const SummaryPart = require('../../models/summaryPart');
+const indexLevels = require('./indexLevels');
/**
Returns a new Summary with a part inserted at given index
@@ -12,7 +12,7 @@ var indexLevels = require('./indexLevels');
function insertPart(summary, part, index) {
part = SummaryPart(part);
- var parts = summary.getParts().insert(index, part);
+ const parts = summary.getParts().insert(index, part);
return indexLevels(summary.set('parts', parts));
}
diff --git a/packages/gitbook/lib/modifiers/summary/mergeAtLevel.js b/packages/gitbook/src/modifiers/summary/mergeAtLevel.js
index 9a95ffc..ea01763 100644
--- a/packages/gitbook/lib/modifiers/summary/mergeAtLevel.js
+++ b/packages/gitbook/src/modifiers/summary/mergeAtLevel.js
@@ -9,14 +9,14 @@
*/
function editArticleInList(articles, level, newArticle) {
return articles.map(function(article) {
- var articleLevel = article.getLevel();
+ const articleLevel = article.getLevel();
if (articleLevel === level) {
// it is the article to edit
return article.merge(newArticle);
} else if (level.indexOf(articleLevel) === 0) {
// it is a parent
- var articles = editArticleInList(article.getArticles(), level, newArticle);
+ const articles = editArticleInList(article.getArticles(), level, newArticle);
return article.set('articles', articles);
} else {
// This is not the article you are looking for
@@ -35,7 +35,7 @@ function editArticleInList(articles, level, newArticle) {
@return {Part}
*/
function editArticleInPart(part, level, newArticle) {
- var articles = part.getArticles();
+ let articles = part.getArticles();
articles = editArticleInList(articles, level, newArticle);
return part.set('articles', articles);
@@ -51,16 +51,16 @@ function editArticleInPart(part, level, newArticle) {
@return {Summary}
*/
function mergeAtLevel(summary, level, newValue) {
- var levelParts = level.split('.');
- var partIndex = Number(levelParts[0]) -1;
+ const levelParts = level.split('.');
+ const partIndex = Number(levelParts[0]) - 1;
- var parts = summary.getParts();
- var part = parts.get(partIndex);
+ let parts = summary.getParts();
+ let part = parts.get(partIndex);
if (!part) {
return summary;
}
- var isEditingPart = levelParts.length < 2;
+ const isEditingPart = levelParts.length < 2;
if (isEditingPart) {
part = part.merge(newValue);
} else {
diff --git a/packages/gitbook/lib/modifiers/summary/moveArticle.js b/packages/gitbook/src/modifiers/summary/moveArticle.js
index 5cb1868..29d4748 100644
--- a/packages/gitbook/lib/modifiers/summary/moveArticle.js
+++ b/packages/gitbook/src/modifiers/summary/moveArticle.js
@@ -1,6 +1,6 @@
-var is = require('is');
-var removeArticle = require('./removeArticle');
-var insertArticle = require('./insertArticle');
+const is = require('is');
+const removeArticle = require('./removeArticle');
+const insertArticle = require('./insertArticle');
/**
Returns a new summary, with the given article removed from its
@@ -13,12 +13,12 @@ var insertArticle = require('./insertArticle');
*/
function moveArticle(summary, origin, target) {
// Coerce to level
- var originLevel = is.string(origin)? origin : origin.getLevel();
- var targetLevel = is.string(target)? target : target.getLevel();
- var article = summary.getByLevel(originLevel);
+ const originLevel = is.string(origin) ? origin : origin.getLevel();
+ const targetLevel = is.string(target) ? target : target.getLevel();
+ const article = summary.getByLevel(originLevel);
// Remove first
- var removed = removeArticle(summary, originLevel);
+ const removed = removeArticle(summary, originLevel);
return insertArticle(removed, article, targetLevel);
}
diff --git a/packages/gitbook/lib/modifiers/summary/moveArticleAfter.js b/packages/gitbook/src/modifiers/summary/moveArticleAfter.js
index e268f73..a1ed28f 100644
--- a/packages/gitbook/lib/modifiers/summary/moveArticleAfter.js
+++ b/packages/gitbook/src/modifiers/summary/moveArticleAfter.js
@@ -1,6 +1,6 @@
-var is = require('is');
-var removeArticle = require('./removeArticle');
-var insertArticle = require('./insertArticle');
+const is = require('is');
+const removeArticle = require('./removeArticle');
+const insertArticle = require('./insertArticle');
/**
Returns a new summary, with the an article moved after another
@@ -14,20 +14,20 @@ var insertArticle = require('./insertArticle');
*/
function moveArticleAfter(summary, origin, afterTarget) {
// Coerce to level
- var originLevel = is.string(origin)? origin : origin.getLevel();
- var afterTargetLevel = is.string(afterTarget)? afterTarget : afterTarget.getLevel();
- var article = summary.getByLevel(originLevel);
+ const originLevel = is.string(origin) ? origin : origin.getLevel();
+ const afterTargetLevel = is.string(afterTarget) ? afterTarget : afterTarget.getLevel();
+ const article = summary.getByLevel(originLevel);
- var targetLevel = increment(afterTargetLevel);
+ const targetLevel = increment(afterTargetLevel);
if (targetLevel < origin) {
// Remove first
- var removed = removeArticle(summary, originLevel);
+ const removed = removeArticle(summary, originLevel);
// Insert then
return insertArticle(removed, article, targetLevel);
} else {
// Insert right after first
- var inserted = insertArticle(summary, article, targetLevel);
+ const inserted = insertArticle(summary, article, targetLevel);
// Remove old one
return removeArticle(inserted, originLevel);
}
@@ -38,7 +38,7 @@ function moveArticleAfter(summary, origin, afterTarget) {
@return {Array<Number>}
*/
function levelToArray(l) {
- return l.split('.').map(function (char) {
+ return l.split('.').map(function(char) {
return parseInt(char, 10);
});
}
diff --git a/packages/gitbook/lib/modifiers/summary/removeArticle.js b/packages/gitbook/src/modifiers/summary/removeArticle.js
index 8a30d0a..0c4cd33 100644
--- a/packages/gitbook/lib/modifiers/summary/removeArticle.js
+++ b/packages/gitbook/src/modifiers/summary/removeArticle.js
@@ -1,6 +1,6 @@
-var is = require('is');
-var mergeAtLevel = require('./mergeAtLevel');
-var indexArticleLevels = require('./indexArticleLevels');
+const is = require('is');
+const mergeAtLevel = require('./mergeAtLevel');
+const indexArticleLevels = require('./indexArticleLevels');
/**
Remove an article from a level.
@@ -11,13 +11,13 @@ var indexArticleLevels = require('./indexArticleLevels');
*/
function removeArticle(summary, level) {
// Coerce to level
- level = is.string(level)? level : level.getLevel();
+ level = is.string(level) ? level : level.getLevel();
- var parent = summary.getParent(level);
+ let parent = summary.getParent(level);
- var articles = parent.getArticles();
+ let articles = parent.getArticles();
// Find the index to remove
- var index = articles.findIndex(function(art) {
+ const index = articles.findIndex(function(art) {
return art.getLevel() === level;
});
if (index === -1) {
diff --git a/packages/gitbook/lib/modifiers/summary/removePart.js b/packages/gitbook/src/modifiers/summary/removePart.js
index 2f8affc..30502dc 100644
--- a/packages/gitbook/lib/modifiers/summary/removePart.js
+++ b/packages/gitbook/src/modifiers/summary/removePart.js
@@ -1,4 +1,4 @@
-var indexLevels = require('./indexLevels');
+const indexLevels = require('./indexLevels');
/**
Remove a part at given index
@@ -8,7 +8,7 @@ var indexLevels = require('./indexLevels');
@return {Summary}
*/
function removePart(summary, index) {
- var parts = summary.getParts().remove(index);
+ const parts = summary.getParts().remove(index);
return indexLevels(summary.set('parts', parts));
}
diff --git a/packages/gitbook/lib/modifiers/summary/unshiftArticle.js b/packages/gitbook/src/modifiers/summary/unshiftArticle.js
index d1ebc05..c5810f0 100644
--- a/packages/gitbook/lib/modifiers/summary/unshiftArticle.js
+++ b/packages/gitbook/src/modifiers/summary/unshiftArticle.js
@@ -1,7 +1,7 @@
-var SummaryArticle = require('../../models/summaryArticle');
-var SummaryPart = require('../../models/summaryPart');
+const SummaryArticle = require('../../models/summaryArticle');
+const SummaryPart = require('../../models/summaryPart');
-var indexLevels = require('./indexLevels');
+const indexLevels = require('./indexLevels');
/**
Insert an article at the beginning of summary
@@ -13,10 +13,10 @@ var indexLevels = require('./indexLevels');
function unshiftArticle(summary, article) {
article = SummaryArticle(article);
- var parts = summary.getParts();
- var part = parts.get(0) || SummaryPart();
+ let parts = summary.getParts();
+ let part = parts.get(0) || SummaryPart();
- var articles = part.getArticles();
+ let articles = part.getArticles();
articles = articles.unshift(article);
part = part.set('articles', articles);
diff --git a/packages/gitbook/lib/output/__tests__/createMock.js b/packages/gitbook/src/output/__tests__/createMock.js
index f21c544..09b93da 100644
--- a/packages/gitbook/lib/output/__tests__/createMock.js
+++ b/packages/gitbook/src/output/__tests__/createMock.js
@@ -1,10 +1,10 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Output = require('../../models/output');
-var Book = require('../../models/book');
-var parseBook = require('../../parse/parseBook');
-var createMockFS = require('../../fs/mock');
-var preparePlugins = require('../preparePlugins');
+const Output = require('../../models/output');
+const Book = require('../../models/book');
+const parseBook = require('../../parse/parseBook');
+const createMockFS = require('../../fs/mock');
+const preparePlugins = require('../preparePlugins');
/**
* Create an output using a generator
@@ -16,9 +16,9 @@ var preparePlugins = require('../preparePlugins');
* @return {Promise<Output>}
*/
function createMockOutput(generator, files, options) {
- var fs = createMockFS(files);
- var book = Book.createForFS(fs);
- var state = generator.State? generator.State({}) : Immutable.Map();
+ const fs = createMockFS(files);
+ let book = Book.createForFS(fs);
+ const state = generator.State ? generator.State({}) : Immutable.Map();
book = book.setLogLevel('disabled');
options = generator.Options(options);
@@ -27,8 +27,8 @@ function createMockOutput(generator, files, options) {
.then(function(resultBook) {
return new Output({
book: resultBook,
- options: options,
- state: state,
+ options,
+ state,
generator: generator.name
});
})
diff --git a/packages/gitbook/lib/output/__tests__/ebook.js b/packages/gitbook/src/output/__tests__/ebook.js
index 9266e9f..425ab6b 100644
--- a/packages/gitbook/lib/output/__tests__/ebook.js
+++ b/packages/gitbook/src/output/__tests__/ebook.js
@@ -1,5 +1,5 @@
-var generateMock = require('./generateMock');
-var EbookGenerator = require('../ebook');
+const generateMock = require('./generateMock');
+const EbookGenerator = require('../ebook');
describe('EbookGenerator', function() {
diff --git a/packages/gitbook/lib/output/__tests__/generateMock.js b/packages/gitbook/src/output/__tests__/generateMock.js
index 691ee2d..a0be244 100644
--- a/packages/gitbook/lib/output/__tests__/generateMock.js
+++ b/packages/gitbook/src/output/__tests__/generateMock.js
@@ -1,9 +1,9 @@
-var tmp = require('tmp');
+const tmp = require('tmp');
-var Book = require('../../models/book');
-var createMockFS = require('../../fs/mock');
-var parseBook = require('../../parse/parseBook');
-var generateBook = require('../generateBook');
+const Book = require('../../models/book');
+const createMockFS = require('../../fs/mock');
+const parseBook = require('../../parse/parseBook');
+const generateBook = require('../generateBook');
/**
* Generate a book using a generator
@@ -16,13 +16,13 @@ var generateBook = require('../generateBook');
* @return {Promise<String>}
*/
function generateMock(Generator, files) {
- var fs = createMockFS(files);
- var book = Book.createForFS(fs);
- var dir;
+ const fs = createMockFS(files);
+ let book = Book.createForFS(fs);
+ let dir;
try {
dir = tmp.dirSync();
- } catch(err) {
+ } catch (err) {
throw err;
}
diff --git a/packages/gitbook/lib/output/__tests__/json.js b/packages/gitbook/src/output/__tests__/json.js
index 12ab567..d4992ec 100644
--- a/packages/gitbook/lib/output/__tests__/json.js
+++ b/packages/gitbook/src/output/__tests__/json.js
@@ -1,5 +1,5 @@
-var generateMock = require('./generateMock');
-var JSONGenerator = require('../json');
+const generateMock = require('./generateMock');
+const JSONGenerator = require('../json');
describe('JSONGenerator', function() {
diff --git a/packages/gitbook/lib/output/__tests__/website.js b/packages/gitbook/src/output/__tests__/website.js
index 1f8c3c0..d39842f 100644
--- a/packages/gitbook/lib/output/__tests__/website.js
+++ b/packages/gitbook/src/output/__tests__/website.js
@@ -1,6 +1,6 @@
-var fs = require('fs');
-var generateMock = require('./generateMock');
-var WebsiteGenerator = require('../website');
+const fs = require('fs');
+const generateMock = require('./generateMock');
+const WebsiteGenerator = require('../website');
describe('WebsiteGenerator', function() {
@@ -14,7 +14,7 @@ describe('WebsiteGenerator', function() {
});
describe('Glossary', function() {
- var folder;
+ let folder;
before(function() {
return generateMock(WebsiteGenerator, {
@@ -35,12 +35,12 @@ describe('WebsiteGenerator', function() {
});
it('should correctly resolve glossary links in README', function() {
- var html = fs.readFileSync(folder + '/index.html', 'utf8');
+ const html = fs.readFileSync(folder + '/index.html', 'utf8');
expect(html).toHaveDOMElement('.page-inner a[href="GLOSSARY.html#hello"]');
});
it('should correctly resolve glossary links in directory', function() {
- var html = fs.readFileSync(folder + '/folder/page.html', 'utf8');
+ const html = fs.readFileSync(folder + '/folder/page.html', 'utf8');
expect(html).toHaveDOMElement('.page-inner a[href="../GLOSSARY.html#hello"]');
});
@@ -54,7 +54,7 @@ describe('WebsiteGenerator', function() {
expect(folder).toHaveFile('custom.html');
expect(folder).toNotHaveFile('GLOSSARY.html');
- var html = fs.readFileSync(folder + '/index.html', 'utf8');
+ const html = fs.readFileSync(folder + '/index.html', 'utf8');
expect(html).toHaveDOMElement('.page-inner a[href="custom.html#hello"]');
});
});
diff --git a/packages/gitbook/lib/output/callHook.js b/packages/gitbook/src/output/callHook.js
index 4914e52..2180102 100644
--- a/packages/gitbook/lib/output/callHook.js
+++ b/packages/gitbook/src/output/callHook.js
@@ -1,6 +1,6 @@
-var Promise = require('../utils/promise');
-var timing = require('../utils/timing');
-var Api = require('../api');
+const Promise = require('../utils/promise');
+const timing = require('../utils/timing');
+const Api = require('../api');
function defaultGetArgument() {
return undefined;
@@ -23,13 +23,13 @@ function callHook(name, getArgument, handleResult, output) {
getArgument = getArgument || defaultGetArgument;
handleResult = handleResult || defaultHandleResult;
- var logger = output.getLogger();
- var plugins = output.getPlugins();
+ const logger = output.getLogger();
+ const plugins = output.getPlugins();
logger.debug.ln('calling hook "' + name + '"');
// Create the JS context for plugins
- var context = Api.encodeGlobal(output);
+ const context = Api.encodeGlobal(output);
return timing.measure(
'call.hook.' + name,
@@ -40,7 +40,7 @@ function callHook(name, getArgument, handleResult, output) {
// Call the hooks in serie
.then(function(arg) {
return Promise.reduce(plugins, function(prev, plugin) {
- var hook = plugin.getHook(name);
+ const hook = plugin.getHook(name);
if (!hook) {
return prev;
}
diff --git a/packages/gitbook/lib/output/callPageHook.js b/packages/gitbook/src/output/callPageHook.js
index c66cef0..af249c9 100644
--- a/packages/gitbook/lib/output/callPageHook.js
+++ b/packages/gitbook/src/output/callPageHook.js
@@ -1,5 +1,5 @@
-var Api = require('../api');
-var callHook = require('./callHook');
+const Api = require('../api');
+const callHook = require('./callHook');
/**
Call a hook for a specific page
diff --git a/packages/gitbook/src/output/createTemplateEngine.js b/packages/gitbook/src/output/createTemplateEngine.js
new file mode 100644
index 0000000..03e7d84
--- /dev/null
+++ b/packages/gitbook/src/output/createTemplateEngine.js
@@ -0,0 +1,45 @@
+const Templating = require('../templating');
+const TemplateEngine = require('../models/templateEngine');
+
+const Api = require('../api');
+const Plugins = require('../plugins');
+
+const defaultBlocks = require('../constants/defaultBlocks');
+const defaultFilters = require('../constants/defaultFilters');
+
+/**
+ Create template engine for an output.
+ It adds default filters/blocks, then add the ones from plugins
+
+ @param {Output} output
+ @return {TemplateEngine}
+*/
+function createTemplateEngine(output) {
+ const plugins = output.getPlugins();
+ const book = output.getBook();
+ const rootFolder = book.getContentRoot();
+ const logger = book.getLogger();
+
+ let filters = Plugins.listFilters(plugins);
+ let blocks = Plugins.listBlocks(plugins);
+
+ // Extend with default
+ blocks = defaultBlocks.merge(blocks);
+ filters = defaultFilters.merge(filters);
+
+ // Create loader
+ const transformFn = Templating.replaceShortcuts.bind(null, blocks);
+ const loader = new Templating.ConrefsLoader(rootFolder, transformFn, logger);
+
+ // Create API context
+ const context = Api.encodeGlobal(output);
+
+ return new TemplateEngine({
+ filters,
+ blocks,
+ loader,
+ context
+ });
+}
+
+module.exports = createTemplateEngine;
diff --git a/packages/gitbook/lib/output/ebook/getConvertOptions.js b/packages/gitbook/src/output/ebook/getConvertOptions.js
index bc80493..b37c68e 100644
--- a/packages/gitbook/lib/output/ebook/getConvertOptions.js
+++ b/packages/gitbook/src/output/ebook/getConvertOptions.js
@@ -1,8 +1,8 @@
-var extend = require('extend');
+const extend = require('extend');
-var Promise = require('../../utils/promise');
-var getPDFTemplate = require('./getPDFTemplate');
-var getCoverPath = require('./getCoverPath');
+const Promise = require('../../utils/promise');
+const getPDFTemplate = require('./getPDFTemplate');
+const getCoverPath = require('./getCoverPath');
/**
Generate options for ebook-convert
@@ -11,16 +11,16 @@ var getCoverPath = require('./getCoverPath');
@return {Promise<Object>}
*/
function getConvertOptions(output) {
- var options = output.getOptions();
- var format = options.get('format');
+ const options = output.getOptions();
+ const format = options.get('format');
- var book = output.getBook();
- var config = book.getConfig();
+ const book = output.getBook();
+ const config = book.getConfig();
return Promise()
.then(function() {
- var coverPath = getCoverPath(output);
- var options = {
+ const coverPath = getCoverPath(output);
+ let options = {
'--cover': coverPath,
'--title': config.getValue('title'),
'--comments': config.getValue('description'),
@@ -36,7 +36,7 @@ function getConvertOptions(output) {
'--max-levels': '1',
'--no-chapters-in-toc': true,
'--breadth-first': true,
- '--dont-split-on-page-breaks': format === 'epub'? true : undefined
+ '--dont-split-on-page-breaks': format === 'epub' ? true : undefined
};
if (format !== 'pdf') {
@@ -48,7 +48,7 @@ function getConvertOptions(output) {
getPDFTemplate(output, 'footer')
])
.spread(function(headerTpl, footerTpl) {
- var pdfOptions = config.getValue('pdf').toJS();
+ const pdfOptions = config.getValue('pdf').toJS();
return options = extend(options, {
'--chapter-mark': String(pdfOptions.chapterMark),
diff --git a/packages/gitbook/lib/output/ebook/getCoverPath.js b/packages/gitbook/src/output/ebook/getCoverPath.js
index ab6b579..cf18c8d 100644
--- a/packages/gitbook/lib/output/ebook/getCoverPath.js
+++ b/packages/gitbook/src/output/ebook/getCoverPath.js
@@ -1,5 +1,5 @@
-var path = require('path');
-var fs = require('../../utils/fs');
+const path = require('path');
+const fs = require('../../utils/fs');
/**
Resolve path to cover file to use
@@ -8,13 +8,13 @@ var fs = require('../../utils/fs');
@return {String}
*/
function getCoverPath(output) {
- var outputRoot = output.getRoot();
- var book = output.getBook();
- var config = book.getConfig();
- var coverName = config.getValue('cover', 'cover.jpg');
+ const outputRoot = output.getRoot();
+ const book = output.getBook();
+ const config = book.getConfig();
+ const coverName = config.getValue('cover', 'cover.jpg');
// Resolve to absolute
- var cover = fs.pickFile(outputRoot, coverName);
+ let cover = fs.pickFile(outputRoot, coverName);
if (cover) {
return cover;
}
diff --git a/packages/gitbook/lib/output/ebook/getPDFTemplate.js b/packages/gitbook/src/output/ebook/getPDFTemplate.js
index b767daf..c0faed3 100644
--- a/packages/gitbook/lib/output/ebook/getPDFTemplate.js
+++ b/packages/gitbook/src/output/ebook/getPDFTemplate.js
@@ -1,9 +1,9 @@
-var juice = require('juice');
+const juice = require('juice');
-var WebsiteGenerator = require('../website');
-var JSONUtils = require('../../json');
-var Templating = require('../../templating');
-var Promise = require('../../utils/promise');
+const WebsiteGenerator = require('../website');
+const JSONUtils = require('../../json');
+const Templating = require('../../templating');
+const Promise = require('../../utils/promise');
/**
@@ -14,12 +14,12 @@ var Promise = require('../../utils/promise');
@return {String}
*/
function getPDFTemplate(output, type) {
- var filePath = 'pdf_' + type + '.html';
- var outputRoot = output.getRoot();
- var engine = WebsiteGenerator.createTemplateEngine(output, filePath);
+ const filePath = 'pdf_' + type + '.html';
+ const outputRoot = output.getRoot();
+ const engine = WebsiteGenerator.createTemplateEngine(output, filePath);
// Generate context
- var context = JSONUtils.encodeOutput(output);
+ const context = JSONUtils.encodeOutput(output);
context.page = {
num: '_PAGENUM_',
title: '_SECTION_'
diff --git a/packages/gitbook/lib/output/ebook/index.js b/packages/gitbook/src/output/ebook/index.js
index 786a10a..c5c07c2 100644
--- a/packages/gitbook/lib/output/ebook/index.js
+++ b/packages/gitbook/src/output/ebook/index.js
@@ -1,5 +1,5 @@
-var extend = require('extend');
-var WebsiteGenerator = require('../website');
+const extend = require('extend');
+const WebsiteGenerator = require('../website');
module.exports = extend({}, WebsiteGenerator, {
name: 'ebook',
diff --git a/packages/gitbook/lib/output/ebook/onFinish.js b/packages/gitbook/src/output/ebook/onFinish.js
index 7f21548..adff798 100644
--- a/packages/gitbook/lib/output/ebook/onFinish.js
+++ b/packages/gitbook/src/output/ebook/onFinish.js
@@ -1,15 +1,15 @@
-var path = require('path');
+const path = require('path');
-var WebsiteGenerator = require('../website');
-var JSONUtils = require('../../json');
-var Templating = require('../../templating');
-var Promise = require('../../utils/promise');
-var error = require('../../utils/error');
-var command = require('../../utils/command');
-var writeFile = require('../helper/writeFile');
+const WebsiteGenerator = require('../website');
+const JSONUtils = require('../../json');
+const Templating = require('../../templating');
+const Promise = require('../../utils/promise');
+const error = require('../../utils/error');
+const command = require('../../utils/command');
+const writeFile = require('../helper/writeFile');
-var getConvertOptions = require('./getConvertOptions');
-var SUMMARY_FILE = 'SUMMARY.html';
+const getConvertOptions = require('./getConvertOptions');
+const SUMMARY_FILE = 'SUMMARY.html';
/**
Write the SUMMARY.html
@@ -18,12 +18,12 @@ var SUMMARY_FILE = 'SUMMARY.html';
@return {Output}
*/
function writeSummary(output) {
- var options = output.getOptions();
- var prefix = options.get('prefix');
+ const options = output.getOptions();
+ const prefix = options.get('prefix');
- var filePath = SUMMARY_FILE;
- var engine = WebsiteGenerator.createTemplateEngine(output, filePath);
- var context = JSONUtils.encodeOutput(output);
+ const filePath = SUMMARY_FILE;
+ const engine = WebsiteGenerator.createTemplateEngine(output, filePath);
+ const context = JSONUtils.encodeOutput(output);
// Render the theme
return Templating.renderFile(engine, prefix + '/summary.html', context)
@@ -41,10 +41,10 @@ function writeSummary(output) {
@return {Output}
*/
function runEbookConvert(output) {
- var logger = output.getLogger();
- var options = output.getOptions();
- var format = options.get('format');
- var outputFolder = output.getRoot();
+ const logger = output.getLogger();
+ const options = output.getOptions();
+ const format = options.get('format');
+ const outputFolder = output.getRoot();
if (!format) {
return Promise(output);
@@ -52,7 +52,7 @@ function runEbookConvert(output) {
return getConvertOptions(output)
.then(function(options) {
- var cmd = [
+ const cmd = [
'ebook-convert',
path.resolve(outputFolder, SUMMARY_FILE),
path.resolve(outputFolder, 'index.' + format),
diff --git a/packages/gitbook/lib/output/ebook/onPage.js b/packages/gitbook/src/output/ebook/onPage.js
index b7b9b42..520d296 100644
--- a/packages/gitbook/lib/output/ebook/onPage.js
+++ b/packages/gitbook/src/output/ebook/onPage.js
@@ -1,5 +1,5 @@
-var WebsiteGenerator = require('../website');
-var Modifiers = require('../modifiers');
+const WebsiteGenerator = require('../website');
+const Modifiers = require('../modifiers');
/**
Write a page for ebook output
@@ -8,7 +8,7 @@ var Modifiers = require('../modifiers');
@param {Output}
*/
function onPage(output, page) {
- var options = output.getOptions();
+ const options = output.getOptions();
// Inline assets
return Modifiers.modifyHTML(page, [
diff --git a/packages/gitbook/lib/output/ebook/options.js b/packages/gitbook/src/output/ebook/options.js
index ea7b8b4..4156fac 100644
--- a/packages/gitbook/lib/output/ebook/options.js
+++ b/packages/gitbook/src/output/ebook/options.js
@@ -1,6 +1,6 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Options = Immutable.Record({
+const Options = Immutable.Record({
// Root folder for the output
root: String(),
diff --git a/packages/gitbook/lib/output/generateAssets.js b/packages/gitbook/src/output/generateAssets.js
index 7a6e104..2129553 100644
--- a/packages/gitbook/lib/output/generateAssets.js
+++ b/packages/gitbook/src/output/generateAssets.js
@@ -1,4 +1,4 @@
-var Promise = require('../utils/promise');
+const Promise = require('../utils/promise');
/**
Output all assets using a generator
@@ -8,8 +8,8 @@ var Promise = require('../utils/promise');
@return {Promise<Output>}
*/
function generateAssets(generator, output) {
- var assets = output.getAssets();
- var logger = output.getLogger();
+ const assets = output.getAssets();
+ const logger = output.getLogger();
// Is generator ignoring assets?
if (!generator.onAsset) {
diff --git a/packages/gitbook/lib/output/generateBook.js b/packages/gitbook/src/output/generateBook.js
index 46712bd..ea8c78e 100644
--- a/packages/gitbook/lib/output/generateBook.js
+++ b/packages/gitbook/src/output/generateBook.js
@@ -1,16 +1,16 @@
-var path = require('path');
-var Immutable = require('immutable');
+const path = require('path');
+const Immutable = require('immutable');
-var Output = require('../models/output');
-var Promise = require('../utils/promise');
-var fs = require('../utils/fs');
+const Output = require('../models/output');
+const Promise = require('../utils/promise');
+const fs = require('../utils/fs');
-var callHook = require('./callHook');
-var preparePlugins = require('./preparePlugins');
-var preparePages = require('./preparePages');
-var prepareAssets = require('./prepareAssets');
-var generateAssets = require('./generateAssets');
-var generatePages = require('./generatePages');
+const callHook = require('./callHook');
+const preparePlugins = require('./preparePlugins');
+const preparePages = require('./preparePages');
+const prepareAssets = require('./prepareAssets');
+const generateAssets = require('./generateAssets');
+const generatePages = require('./generatePages');
/**
* Process an output to generate the book
@@ -29,15 +29,15 @@ function processOutput(generator, startOutput) {
callHook.bind(null,
'config',
function(output) {
- var book = output.getBook();
- var config = book.getConfig();
- var values = config.getValues();
+ const book = output.getBook();
+ const config = book.getConfig();
+ const values = config.getValues();
return values.toJS();
},
function(output, result) {
- var book = output.getBook();
- var config = book.getConfig();
+ let book = output.getBook();
+ let config = book.getConfig();
config = config.updateValues(result);
book = book.set('config', config);
@@ -70,28 +70,28 @@ function processOutput(generator, startOutput) {
.then(generatePages.bind(null, generator))
.tap(function(output) {
- var book = output.getBook();
+ const book = output.getBook();
if (!book.isMultilingual()) {
return;
}
- var logger = book.getLogger();
- var books = book.getBooks();
- var outputRoot = output.getRoot();
- var plugins = output.getPlugins();
- var state = output.getState();
- var options = output.getOptions();
+ const logger = book.getLogger();
+ const books = book.getBooks();
+ const outputRoot = output.getRoot();
+ const plugins = output.getPlugins();
+ const state = output.getState();
+ const options = output.getOptions();
return Promise.forEach(books, function(langBook) {
// Inherits plugins list, options and state
- var langOptions = options.set('root', path.join(outputRoot, langBook.getLanguage()));
- var langOutput = new Output({
+ const langOptions = options.set('root', path.join(outputRoot, langBook.getLanguage()));
+ const langOutput = new Output({
book: langBook,
options: langOptions,
- state: state,
+ state,
generator: generator.name,
- plugins: plugins
+ plugins
});
logger.info.ln('');
@@ -154,22 +154,22 @@ function processOutput(generator, startOutput) {
*/
function generateBook(generator, book, options) {
options = generator.Options(options);
- var state = generator.State? generator.State({}) : Immutable.Map();
- var start = Date.now();
+ const state = generator.State ? generator.State({}) : Immutable.Map();
+ const start = Date.now();
return Promise(
new Output({
- book: book,
- options: options,
- state: state,
+ book,
+ options,
+ state,
generator: generator.name
})
)
// Cleanup output folder
.then(function(output) {
- var logger = output.getLogger();
- var rootFolder = output.getRoot();
+ const logger = output.getLogger();
+ const rootFolder = output.getRoot();
logger.debug.ln('cleanup folder "' + rootFolder + '"');
return fs.ensureFolder(rootFolder)
@@ -180,9 +180,9 @@ function generateBook(generator, book, options) {
// Log duration and end message
.then(function(output) {
- var logger = output.getLogger();
- var end = Date.now();
- var duration = (end - start)/1000;
+ const logger = output.getLogger();
+ const end = Date.now();
+ const duration = (end - start) / 1000;
logger.info.ok('generation finished with success in ' + duration.toFixed(1) + 's !');
diff --git a/packages/gitbook/lib/output/generatePage.js b/packages/gitbook/src/output/generatePage.js
index 090a870..0fc99a3 100644
--- a/packages/gitbook/lib/output/generatePage.js
+++ b/packages/gitbook/src/output/generatePage.js
@@ -1,13 +1,13 @@
-var path = require('path');
+const path = require('path');
-var Promise = require('../utils/promise');
-var error = require('../utils/error');
-var timing = require('../utils/timing');
+const Promise = require('../utils/promise');
+const error = require('../utils/error');
+const timing = require('../utils/timing');
-var Templating = require('../templating');
-var JSONUtils = require('../json');
-var createTemplateEngine = require('./createTemplateEngine');
-var callPageHook = require('./callPageHook');
+const Templating = require('../templating');
+const JSONUtils = require('../json');
+const createTemplateEngine = require('./createTemplateEngine');
+const callPageHook = require('./callPageHook');
/**
* Prepare and generate HTML for a page
@@ -17,17 +17,17 @@ var callPageHook = require('./callPageHook');
* @return {Promise<Page>}
*/
function generatePage(output, page) {
- var book = output.getBook();
- var engine = createTemplateEngine(output);
+ const book = output.getBook();
+ const engine = createTemplateEngine(output);
return timing.measure(
'page.generate',
Promise(page)
.then(function(resultPage) {
- var file = resultPage.getFile();
- var filePath = file.getPath();
- var parser = file.getParser();
- var context = JSONUtils.encodeOutputWithPage(output, resultPage);
+ const file = resultPage.getFile();
+ const filePath = file.getPath();
+ const parser = file.getParser();
+ const context = JSONUtils.encodeOutputWithPage(output, resultPage);
if (!parser) {
return Promise.reject(error.FileNotParsableError({
@@ -45,12 +45,12 @@ function generatePage(output, page) {
// Render templating syntax
.then(function(content) {
- var absoluteFilePath = path.join(book.getContentRoot(), filePath);
+ const absoluteFilePath = path.join(book.getContentRoot(), filePath);
return Templating.render(engine, absoluteFilePath, content, context);
})
.then(function(output) {
- var content = output.getContent();
+ const content = output.getContent();
return parser.parsePage(content)
.then(function(result) {
diff --git a/packages/gitbook/lib/output/generatePages.js b/packages/gitbook/src/output/generatePages.js
index 73c5c09..21b6610 100644
--- a/packages/gitbook/lib/output/generatePages.js
+++ b/packages/gitbook/src/output/generatePages.js
@@ -1,5 +1,5 @@
-var Promise = require('../utils/promise');
-var generatePage = require('./generatePage');
+const Promise = require('../utils/promise');
+const generatePage = require('./generatePage');
/**
Output all pages using a generator
@@ -9,8 +9,8 @@ var generatePage = require('./generatePage');
@return {Promise<Output>}
*/
function generatePages(generator, output) {
- var pages = output.getPages();
- var logger = output.getLogger();
+ const pages = output.getPages();
+ const logger = output.getLogger();
// Is generator ignoring assets?
if (!generator.onPage) {
@@ -18,7 +18,7 @@ function generatePages(generator, output) {
}
return Promise.reduce(pages, function(out, page) {
- var file = page.getFile();
+ const file = page.getFile();
logger.debug.ln('generate page "' + file.getPath() + '"');
diff --git a/packages/gitbook/lib/output/getModifiers.js b/packages/gitbook/src/output/getModifiers.js
index bb44e80..df32fcb 100644
--- a/packages/gitbook/lib/output/getModifiers.js
+++ b/packages/gitbook/src/output/getModifiers.js
@@ -1,12 +1,12 @@
-var Modifiers = require('./modifiers');
-var resolveFileToURL = require('./helper/resolveFileToURL');
-var Api = require('../api');
-var Plugins = require('../plugins');
-var Promise = require('../utils/promise');
-var defaultBlocks = require('../constants/defaultBlocks');
-var fileToOutput = require('./helper/fileToOutput');
+const Modifiers = require('./modifiers');
+const resolveFileToURL = require('./helper/resolveFileToURL');
+const Api = require('../api');
+const Plugins = require('../plugins');
+const Promise = require('../utils/promise');
+const defaultBlocks = require('../constants/defaultBlocks');
+const fileToOutput = require('./helper/fileToOutput');
-var CODEBLOCK = 'code';
+const CODEBLOCK = 'code';
/**
* Return default modifier to prepare a page for
@@ -15,25 +15,25 @@ var CODEBLOCK = 'code';
* @return {Array<Modifier>}
*/
function getModifiers(output, page) {
- var book = output.getBook();
- var plugins = output.getPlugins();
- var glossary = book.getGlossary();
- var file = page.getFile();
+ const book = output.getBook();
+ const plugins = output.getPlugins();
+ const glossary = book.getGlossary();
+ const file = page.getFile();
// Glossary entries
- var entries = glossary.getEntries();
- var glossaryFile = glossary.getFile();
- var glossaryFilename = fileToOutput(output, glossaryFile.getPath());
+ const entries = glossary.getEntries();
+ const glossaryFile = glossary.getFile();
+ const glossaryFilename = fileToOutput(output, glossaryFile.getPath());
// Current file path
- var currentFilePath = file.getPath();
+ const currentFilePath = file.getPath();
// Get TemplateBlock for highlighting
- var blocks = Plugins.listBlocks(plugins);
- var code = blocks.get(CODEBLOCK) || defaultBlocks.get(CODEBLOCK);
+ const blocks = Plugins.listBlocks(plugins);
+ const code = blocks.get(CODEBLOCK) || defaultBlocks.get(CODEBLOCK);
// Current context
- var context = Api.encodeGlobal(output);
+ const context = Api.encodeGlobal(output);
return [
// Normalize IDs on headings
diff --git a/packages/gitbook/lib/output/helper/fileToOutput.js b/packages/gitbook/src/output/helper/fileToOutput.js
index 361c6eb..a514854 100644
--- a/packages/gitbook/lib/output/helper/fileToOutput.js
+++ b/packages/gitbook/src/output/helper/fileToOutput.js
@@ -1,9 +1,9 @@
-var path = require('path');
+const path = require('path');
-var PathUtils = require('../../utils/path');
-var LocationUtils = require('../../utils/location');
+const PathUtils = require('../../utils/path');
+const LocationUtils = require('../../utils/location');
-var OUTPUT_EXTENSION = '.html';
+const OUTPUT_EXTENSION = '.html';
/**
* Convert a filePath (absolute) to a filename for output
@@ -13,9 +13,9 @@ var OUTPUT_EXTENSION = '.html';
* @return {String}
*/
function fileToOutput(output, filePath) {
- var book = output.getBook();
- var readme = book.getReadme();
- var fileReadme = readme.getFile();
+ const book = output.getBook();
+ const readme = book.getReadme();
+ const fileReadme = readme.getFile();
if (
path.basename(filePath, path.extname(filePath)) == 'README' ||
diff --git a/packages/gitbook/lib/output/helper/fileToURL.js b/packages/gitbook/src/output/helper/fileToURL.js
index 44ad2d8..a42bca6 100644
--- a/packages/gitbook/lib/output/helper/fileToURL.js
+++ b/packages/gitbook/src/output/helper/fileToURL.js
@@ -1,7 +1,7 @@
-var path = require('path');
-var LocationUtils = require('../../utils/location');
+const path = require('path');
+const LocationUtils = require('../../utils/location');
-var fileToOutput = require('./fileToOutput');
+const fileToOutput = require('./fileToOutput');
/**
Convert a filePath (absolute) to an url (without hostname).
@@ -16,8 +16,8 @@ var fileToOutput = require('./fileToOutput');
@return {String}
*/
function fileToURL(output, filePath) {
- var options = output.getOptions();
- var directoryIndex = options.get('directoryIndex');
+ const options = output.getOptions();
+ const directoryIndex = options.get('directoryIndex');
filePath = fileToOutput(output, filePath);
diff --git a/packages/gitbook/lib/output/helper/index.js b/packages/gitbook/src/output/helper/index.js
index f8bc109..f8bc109 100644
--- a/packages/gitbook/lib/output/helper/index.js
+++ b/packages/gitbook/src/output/helper/index.js
diff --git a/packages/gitbook/lib/output/helper/resolveFileToURL.js b/packages/gitbook/src/output/helper/resolveFileToURL.js
index 3f52713..907cfdd 100644
--- a/packages/gitbook/lib/output/helper/resolveFileToURL.js
+++ b/packages/gitbook/src/output/helper/resolveFileToURL.js
@@ -1,6 +1,6 @@
-var LocationUtils = require('../../utils/location');
+const LocationUtils = require('../../utils/location');
-var fileToURL = require('./fileToURL');
+const fileToURL = require('./fileToURL');
/**
* Resolve an absolute path (extracted from a link)
@@ -13,7 +13,7 @@ function resolveFileToURL(output, filePath) {
// Convert /test.png -> test.png
filePath = LocationUtils.toAbsolute(filePath, '', '');
- var page = output.getPage(filePath);
+ const page = output.getPage(filePath);
// if file is a page, return correct .html url
if (page) {
diff --git a/packages/gitbook/lib/output/helper/writeFile.js b/packages/gitbook/src/output/helper/writeFile.js
index a6d4645..01a8e68 100644
--- a/packages/gitbook/lib/output/helper/writeFile.js
+++ b/packages/gitbook/src/output/helper/writeFile.js
@@ -1,5 +1,5 @@
-var path = require('path');
-var fs = require('../../utils/fs');
+const path = require('path');
+const fs = require('../../utils/fs');
/**
Write a file to the output folder
@@ -10,7 +10,7 @@ var fs = require('../../utils/fs');
@return {Promise}
*/
function writeFile(output, filePath, content) {
- var rootFolder = output.getRoot();
+ const rootFolder = output.getRoot();
filePath = path.join(rootFolder, filePath);
return fs.ensureFile(filePath)
diff --git a/packages/gitbook/lib/output/index.js b/packages/gitbook/src/output/index.js
index 9b8ec17..574b3df 100644
--- a/packages/gitbook/lib/output/index.js
+++ b/packages/gitbook/src/output/index.js
@@ -1,6 +1,6 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var generators = Immutable.List([
+const generators = Immutable.List([
require('./json'),
require('./website'),
require('./ebook')
@@ -20,5 +20,5 @@ function getGenerator(name) {
module.exports = {
generate: require('./generateBook'),
- getGenerator: getGenerator
+ getGenerator
};
diff --git a/packages/gitbook/lib/output/json/index.js b/packages/gitbook/src/output/json/index.js
index 361da06..361da06 100644
--- a/packages/gitbook/lib/output/json/index.js
+++ b/packages/gitbook/src/output/json/index.js
diff --git a/packages/gitbook/lib/output/json/onFinish.js b/packages/gitbook/src/output/json/onFinish.js
index d41d778..b05057a 100644
--- a/packages/gitbook/lib/output/json/onFinish.js
+++ b/packages/gitbook/src/output/json/onFinish.js
@@ -1,8 +1,8 @@
-var path = require('path');
+const path = require('path');
-var Promise = require('../../utils/promise');
-var fs = require('../../utils/fs');
-var JSONUtils = require('../../json');
+const Promise = require('../../utils/promise');
+const fs = require('../../utils/fs');
+const JSONUtils = require('../../json');
/**
Finish the generation
@@ -11,23 +11,23 @@ var JSONUtils = require('../../json');
@return {Output}
*/
function onFinish(output) {
- var book = output.getBook();
- var outputRoot = output.getRoot();
+ const book = output.getBook();
+ const outputRoot = output.getRoot();
if (!book.isMultilingual()) {
return Promise(output);
}
// Get main language
- var languages = book.getLanguages();
- var mainLanguage = languages.getDefaultLanguage();
+ const languages = book.getLanguages();
+ const mainLanguage = languages.getDefaultLanguage();
// Read the main JSON
return fs.readFile(path.resolve(outputRoot, mainLanguage.getID(), 'README.json'), 'utf8')
// Extend the JSON
.then(function(content) {
- var json = JSON.parse(content);
+ const json = JSON.parse(content);
json.languages = JSONUtils.encodeLanguages(languages);
diff --git a/packages/gitbook/lib/output/json/onPage.js b/packages/gitbook/src/output/json/onPage.js
index 2315ba0..8bee711 100644
--- a/packages/gitbook/lib/output/json/onPage.js
+++ b/packages/gitbook/src/output/json/onPage.js
@@ -1,10 +1,10 @@
-var JSONUtils = require('../../json');
-var PathUtils = require('../../utils/path');
-var Modifiers = require('../modifiers');
-var writeFile = require('../helper/writeFile');
-var getModifiers = require('../getModifiers');
+const JSONUtils = require('../../json');
+const PathUtils = require('../../utils/path');
+const Modifiers = require('../modifiers');
+const writeFile = require('../helper/writeFile');
+const getModifiers = require('../getModifiers');
-var JSON_VERSION = '3';
+const JSON_VERSION = '3';
/**
* Write a page as a json file
@@ -13,13 +13,13 @@ var JSON_VERSION = '3';
* @param {Page} page
*/
function onPage(output, page) {
- var file = page.getFile();
- var readme = output.getBook().getReadme().getFile();
+ const file = page.getFile();
+ const readme = output.getBook().getReadme().getFile();
return Modifiers.modifyHTML(page, getModifiers(output, page))
.then(function(resultPage) {
// Generate the JSON
- var json = JSONUtils.encodeBookWithPage(output.getBook(), resultPage);
+ const json = JSONUtils.encodeBookWithPage(output.getBook(), resultPage);
// Delete some private properties
delete json.config;
@@ -28,7 +28,7 @@ function onPage(output, page) {
json.version = JSON_VERSION;
// File path in the output folder
- var filePath = file.getPath() == readme.getPath()? 'README.json' : file.getPath();
+ let filePath = file.getPath() == readme.getPath() ? 'README.json' : file.getPath();
filePath = PathUtils.setExtension(filePath, '.json');
// Write it to the disk
diff --git a/packages/gitbook/lib/output/json/options.js b/packages/gitbook/src/output/json/options.js
index 79167b1..2a9de0e 100644
--- a/packages/gitbook/lib/output/json/options.js
+++ b/packages/gitbook/src/output/json/options.js
@@ -1,6 +1,6 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Options = Immutable.Record({
+const Options = Immutable.Record({
// Root folder for the output
root: String()
});
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/addHeadingId.js b/packages/gitbook/src/output/modifiers/__tests__/addHeadingId.js
index a3b1d81..4d77e75 100644
--- a/packages/gitbook/lib/output/modifiers/__tests__/addHeadingId.js
+++ b/packages/gitbook/src/output/modifiers/__tests__/addHeadingId.js
@@ -1,26 +1,25 @@
-var cheerio = require('cheerio');
-var addHeadingId = require('../addHeadingId');
+const cheerio = require('cheerio');
+const addHeadingId = require('../addHeadingId');
describe('addHeadingId', function() {
it('should add an ID if none', function() {
- var $ = cheerio.load('<h1>Hello World</h1><h2>Cool !!</h2>');
+ const $ = cheerio.load('<h1>Hello World</h1><h2>Cool !!</h2>');
return addHeadingId($)
.then(function() {
- var html = $.html();
+ const html = $.html();
expect(html).toBe('<h1 id="hello-world">Hello World</h1><h2 id="cool-">Cool !!</h2>');
});
});
it('should not change existing IDs', function() {
- var $ = cheerio.load('<h1 id="awesome">Hello World</h1>');
+ const $ = cheerio.load('<h1 id="awesome">Hello World</h1>');
return addHeadingId($)
.then(function() {
- var html = $.html();
+ const html = $.html();
expect(html).toBe('<h1 id="awesome">Hello World</h1>');
});
});
});
-
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/annotateText.js b/packages/gitbook/src/output/modifiers/__tests__/annotateText.js
index 67e7a10..28a5cc5 100644
--- a/packages/gitbook/lib/output/modifiers/__tests__/annotateText.js
+++ b/packages/gitbook/src/output/modifiers/__tests__/annotateText.js
@@ -1,46 +1,45 @@
-var Immutable = require('immutable');
-var cheerio = require('cheerio');
-var GlossaryEntry = require('../../../models/glossaryEntry');
-var annotateText = require('../annotateText');
+const Immutable = require('immutable');
+const cheerio = require('cheerio');
+const GlossaryEntry = require('../../../models/glossaryEntry');
+const annotateText = require('../annotateText');
describe('annotateText', function() {
- var entries = Immutable.List([
+ const entries = Immutable.List([
GlossaryEntry({ name: 'Word' }),
GlossaryEntry({ name: 'Multiple Words' })
]);
it('should annotate text', function() {
- var $ = cheerio.load('<p>This is a word, and multiple words</p>');
+ const $ = cheerio.load('<p>This is a word, and multiple words</p>');
annotateText(entries, 'GLOSSARY.md', $);
- var links = $('a');
+ const links = $('a');
expect(links.length).toBe(2);
- var word = $(links.get(0));
+ const word = $(links.get(0));
expect(word.attr('href')).toBe('/GLOSSARY.md#word');
expect(word.text()).toBe('word');
expect(word.hasClass('glossary-term')).toBeTruthy();
- var words = $(links.get(1));
+ const words = $(links.get(1));
expect(words.attr('href')).toBe('/GLOSSARY.md#multiple-words');
expect(words.text()).toBe('multiple words');
expect(words.hasClass('glossary-term')).toBeTruthy();
});
it('should not annotate scripts', function() {
- var $ = cheerio.load('<script>This is a word, and multiple words</script>');
+ const $ = cheerio.load('<script>This is a word, and multiple words</script>');
annotateText(entries, 'GLOSSARY.md', $);
expect($('a').length).toBe(0);
});
it('should not annotate when has class "no-glossary"', function() {
- var $ = cheerio.load('<p class="no-glossary">This is a word, and multiple words</p>');
+ const $ = cheerio.load('<p class="no-glossary">This is a word, and multiple words</p>');
annotateText(entries, 'GLOSSARY.md', $);
expect($('a').length).toBe(0);
});
});
-
diff --git a/packages/gitbook/src/output/modifiers/__tests__/fetchRemoteImages.js b/packages/gitbook/src/output/modifiers/__tests__/fetchRemoteImages.js
new file mode 100644
index 0000000..9145cae
--- /dev/null
+++ b/packages/gitbook/src/output/modifiers/__tests__/fetchRemoteImages.js
@@ -0,0 +1,39 @@
+const cheerio = require('cheerio');
+const tmp = require('tmp');
+const path = require('path');
+
+const URL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/280px-PNG_transparency_demonstration_1.png';
+
+describe('fetchRemoteImages', function() {
+ let dir;
+ const fetchRemoteImages = require('../fetchRemoteImages');
+
+ beforeEach(function() {
+ dir = tmp.dirSync();
+ });
+
+ it('should download image file', function() {
+ const $ = cheerio.load('<img src="' + URL + '" />');
+
+ return fetchRemoteImages(dir.name, 'index.html', $)
+ .then(function() {
+ const $img = $('img');
+ const src = $img.attr('src');
+
+ expect(dir.name).toHaveFile(src);
+ });
+ });
+
+ it('should download image file and replace with relative path', function() {
+ const $ = cheerio.load('<img src="' + URL + '" />');
+
+ return fetchRemoteImages(dir.name, 'test/index.html', $)
+ .then(function() {
+ const $img = $('img');
+ const src = $img.attr('src');
+
+ expect(dir.name).toHaveFile(path.join('test', src));
+ });
+ });
+});
+
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/highlightCode.js b/packages/gitbook/src/output/modifiers/__tests__/highlightCode.js
index 75d9902..d93417b 100644
--- a/packages/gitbook/lib/output/modifiers/__tests__/highlightCode.js
+++ b/packages/gitbook/src/output/modifiers/__tests__/highlightCode.js
@@ -1,6 +1,6 @@
-var cheerio = require('cheerio');
-var Promise = require('../../../utils/promise');
-var highlightCode = require('../highlightCode');
+const cheerio = require('cheerio');
+const Promise = require('../../../utils/promise');
+const highlightCode = require('../highlightCode');
describe('highlightCode', function() {
function doHighlight(lang, code) {
@@ -17,44 +17,43 @@ describe('highlightCode', function() {
}
it('should call it for normal code element', function() {
- var $ = cheerio.load('<p>This is a <code>test</code></p>');
+ const $ = cheerio.load('<p>This is a <code>test</code></p>');
return highlightCode(doHighlight, $)
.then(function() {
- var $code = $('code');
+ const $code = $('code');
expect($code.text()).toBe('$test');
});
});
it('should call it for markdown code block', function() {
- var $ = cheerio.load('<pre><code class="lang-js">test</code></pre>');
+ const $ = cheerio.load('<pre><code class="lang-js">test</code></pre>');
return highlightCode(doHighlight, $)
.then(function() {
- var $code = $('code');
+ const $code = $('code');
expect($code.text()).toBe('js$test');
});
});
it('should call it for asciidoc code block', function() {
- var $ = cheerio.load('<pre><code class="language-python">test</code></pre>');
+ const $ = cheerio.load('<pre><code class="language-python">test</code></pre>');
return highlightCode(doHighlight, $)
.then(function() {
- var $code = $('code');
+ const $code = $('code');
expect($code.text()).toBe('python$test');
});
});
it('should accept async highlighter', function() {
- var $ = cheerio.load('<pre><code class="language-python">test</code></pre>');
+ const $ = cheerio.load('<pre><code class="language-python">test</code></pre>');
return highlightCode(doHighlightAsync, $)
.then(function() {
- var $code = $('code');
+ const $code = $('code');
expect($code.text()).toBe('python$test');
});
});
});
-
diff --git a/packages/gitbook/src/output/modifiers/__tests__/inlinePng.js b/packages/gitbook/src/output/modifiers/__tests__/inlinePng.js
new file mode 100644
index 0000000..fd031b0
--- /dev/null
+++ b/packages/gitbook/src/output/modifiers/__tests__/inlinePng.js
@@ -0,0 +1,24 @@
+const cheerio = require('cheerio');
+const tmp = require('tmp');
+const inlinePng = require('../inlinePng');
+
+describe('inlinePng', function() {
+ let dir;
+
+ beforeEach(function() {
+ dir = tmp.dirSync();
+ });
+
+ it('should write an inline PNG using data URI as a file', function() {
+ const $ = cheerio.load('<img alt="GitBook Logo 20x20" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUEAYAAADdGcFOAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsTAAALEwEAmpwYAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgpMwidZAAAF+klEQVRIDY3Wf5CVVR3H8c9z791fyI9dQwdQ4TTI7wEWnQZZAa/mJE4Z0OaKUuN1KoaykZxUGGHay+iIVFMoEYrUPhDCKEKW2ChT8dA0RCSxWi6EW3sYYpcfxq5C+4O9957O+7m7O/qHQ9/XzH1+nHuec57z8wkWTsKw0y6N/LxXN6KzTnEUHi8eP/l3YStSU/MdsYvBbGh8six2YXcbcgc++QkfTQkWz/81KtqDA0hlUoWnsX+5uxe5X365BB9my2bjrHNHccLk16BpS9CExjcmXMDbD6wehdyEjxbjz1uK1zn9qga6dcfnMLXeXY/qjuQqTF4W1MKke8ZgeNhjMCxMPIWSd4OF78C55CFI/1kF6WwXpMqjkAZ/CKniNDrCsmU4lE1YbPlgR2x7R39FF23D4mq3A1+Z35PGTNs1E1XhxcGQOh6HNPwXkK56BVJhOaRg/pvoHXNxHFw410B25EYE2RMvI0i/twFJvXcrFObykEa+DmnQGLwYqR0l2a6JqItaj8C/4E2QxtZCofkC8tF1t8HZc/fAZaLnIF2xEsoEtW1w7vBSSFtfhDTnCki9cSi81Ain1uko2Ld+Dmf2rkUq0/5t+PYbFtPQdkjzNiAXTWtDEF49FgkzJInAVPwNyhzcDOmrdZCm/Rn+ebWtcPs+/U24hmg2XL0rRkPPELh9R8fDtXR2oC/VuZbGaci79Ajkb6lZgfyYtyzy/X9s6T/pO/ZfN/RdNxxIwTWM2wbX8KVmuIaEqmKm6zEondwGpd0SyOy5DrJ//TFkX9kMhd3XQHbEVCSsm4OECV5HIv2p15CwfWPSntoHRbv2Q1HzSvSlSqZwATIuBxk/zZBOBbdB+u9hSKU3Q7pwAjInZkFm6U8hu7MSMqe/Dqn8fUj5GVCmpxK+4N/F1LMa0p5eSOPqIPP7NGSunAI/+R6GnzQzIBt8A1LC/QZ+6HwLst1rITv0n5CtXgSZ78yFTNkR+FdeDZneJkip3fAtsQ5Scilkek7CH9dAmjIWvkK7IXXOh6/IzZDNPQdZXR1TQmdjKv0ZfEu0YKDpNflpyG5aDtnRv8VAuu3dBV+huyBbvgdS97tQNLQc0mfugKy5Cb4BipPIXvsUpK5N8Mvao/Bd3QDZRH9Rrtj3Cl6FHwPFMLmNkKrj8BnHoT+XX6f2wl+XxFS4Ab7C72Dgf7bi+5DpTkNm8kQMpCs/BzIlz8LfPxnzLdh3EjwMX4GX4Ju4GNb9A1L7k/D3J8b6kv2LFCtmCmcgUzoJsr2z4MfwFsh87xikZefg188fYaAhpPUxm3ge/vFnYkoED0HqeQiyJYcwkNGWnoNv6s9C1p1Bf/389VYoCjohW7UfMms3wXdpBv7+FEiPLIHs4DIMNERUNhbSpY3wk6QOsqlCDVx2xCrInMpBmfNPQOnzKxBkkrugdOl9GKigSZZCUWIm/GqwDtLUI5D+WAOlb9wKP0YvQLbjZSjsaYaL/n0/FA3fDtnCGihK5UYjCK+ZDr+TDIKLdm2Fs1UOzo76F5wO74XSZj0S6d7RCMLkCshcXALZxaWQRjXDZQ62oRAdCeG/Ju5HELX2QFH3C0hkRy6GovyfwF58AoVbguOxyB2H7/I34Gf11yANnQSp7Vr4MbQH0vg7kbNNp5AM3UrIVDchnz56B1Jm573wW9gZSFVPwO/hefg5FsIvN09CchtQCIOFw/F5U8ii3CZn4cqo7C8YlXEPYkx9cacZl00+iwnprrtwVdj1Q/gXmAs/pu6LZc9XQOGgSvh19n2cDZN341g2EcfxTEGwH/RewqlMsUfbbWIGLjUG+j/j9nokD1beiOvLS5dhjr30Gu6ZnivgdtM/6VJvY1+6pBHbH+h9CX84vfMxNJtisYVFlys+WNCIZJNmIsjohlhNSQC3f8R55H+y/hjkN8GPR9ndCLJxT4/3n0Px51ay8XQnNrYfDJHf//Fc0oMrEZSeeQGJ7+Z+gKCgLbHNWgXnB9FlYt5JaN38JIINC95EakjtAqQeuUx21c5B6tEFf0fSfbEFQf28Z6D6y+X/H0jf40QQJhYwAAAAAElFTkSuQmCC"/>');
+
+ return inlinePng(dir.name, 'index.html', $)
+ .then(function() {
+ const $img = $('img');
+ const src = $img.attr('src');
+
+ expect(dir.name).toHaveFile(src);
+ });
+ });
+});
+
diff --git a/packages/gitbook/lib/output/modifiers/__tests__/resolveLinks.js b/packages/gitbook/src/output/modifiers/__tests__/resolveLinks.js
index 8904c11..167af5d 100644
--- a/packages/gitbook/lib/output/modifiers/__tests__/resolveLinks.js
+++ b/packages/gitbook/src/output/modifiers/__tests__/resolveLinks.js
@@ -1,6 +1,6 @@
-var path = require('path');
-var cheerio = require('cheerio');
-var resolveLinks = require('../resolveLinks');
+const path = require('path');
+const cheerio = require('cheerio');
+const resolveLinks = require('../resolveLinks');
describe('resolveLinks', function() {
function resolveFileBasic(href) {
@@ -16,24 +16,24 @@ describe('resolveLinks', function() {
}
describe('Absolute path', function() {
- var TEST = '<p>This is a <a href="/test/cool.md"></a></p>';
+ const TEST = '<p>This is a <a href="/test/cool.md"></a></p>';
it('should resolve path starting by "/" in root directory', function() {
- var $ = cheerio.load(TEST);
+ const $ = cheerio.load(TEST);
return resolveLinks('hello.md', resolveFileBasic, $)
.then(function() {
- var link = $('a');
+ const link = $('a');
expect(link.attr('href')).toBe('fakeDir/test/cool.md');
});
});
it('should resolve path starting by "/" in child directory', function() {
- var $ = cheerio.load(TEST);
+ const $ = cheerio.load(TEST);
return resolveLinks('afolder/hello.md', resolveFileBasic, $)
.then(function() {
- var link = $('a');
+ const link = $('a');
expect(link.attr('href')).toBe('../fakeDir/test/cool.md');
});
});
@@ -41,61 +41,61 @@ describe('resolveLinks', function() {
describe('Anchor', function() {
it('should prevent anchors in resolution', function() {
- var TEST = '<p>This is a <a href="test/cool.md#an-anchor"></a></p>';
- var $ = cheerio.load(TEST);
+ const TEST = '<p>This is a <a href="test/cool.md#an-anchor"></a></p>';
+ const $ = cheerio.load(TEST);
return resolveLinks('hello.md', resolveFileCustom, $)
.then(function() {
- var link = $('a');
+ const link = $('a');
expect(link.attr('href')).toBe('test/cool.html#an-anchor');
});
});
it('should ignore pure anchor links', function() {
- var TEST = '<p>This is a <a href="#an-anchor"></a></p>';
- var $ = cheerio.load(TEST);
+ const TEST = '<p>This is a <a href="#an-anchor"></a></p>';
+ const $ = cheerio.load(TEST);
return resolveLinks('hello.md', resolveFileCustom, $)
.then(function() {
- var link = $('a');
+ const link = $('a');
expect(link.attr('href')).toBe('#an-anchor');
});
});
});
describe('Custom Resolver', function() {
- var TEST = '<p>This is a <a href="/test/cool.md"></a> <a href="afile.png"></a></p>';
+ const TEST = '<p>This is a <a href="/test/cool.md"></a> <a href="afile.png"></a></p>';
it('should resolve path correctly for absolute path', function() {
- var $ = cheerio.load(TEST);
+ const $ = cheerio.load(TEST);
return resolveLinks('hello.md', resolveFileCustom, $)
.then(function() {
- var link = $('a').first();
+ const link = $('a').first();
expect(link.attr('href')).toBe('test/cool.html');
});
});
it('should resolve path correctly for absolute path (2)', function() {
- var $ = cheerio.load(TEST);
+ const $ = cheerio.load(TEST);
return resolveLinks('afodler/hello.md', resolveFileCustom, $)
.then(function() {
- var link = $('a').first();
+ const link = $('a').first();
expect(link.attr('href')).toBe('../test/cool.html');
});
});
});
describe('External link', function() {
- var TEST = '<p>This is a <a href="http://www.github.com">external link</a></p>';
+ const TEST = '<p>This is a <a href="http://www.github.com">external link</a></p>';
it('should have target="_blank" attribute', function() {
- var $ = cheerio.load(TEST);
+ const $ = cheerio.load(TEST);
return resolveLinks('hello.md', resolveFileBasic, $)
.then(function() {
- var link = $('a');
+ const link = $('a');
expect(link.attr('target')).toBe('_blank');
});
});
diff --git a/packages/gitbook/src/output/modifiers/__tests__/svgToImg.js b/packages/gitbook/src/output/modifiers/__tests__/svgToImg.js
new file mode 100644
index 0000000..4bdab59
--- /dev/null
+++ b/packages/gitbook/src/output/modifiers/__tests__/svgToImg.js
@@ -0,0 +1,24 @@
+const cheerio = require('cheerio');
+const tmp = require('tmp');
+
+describe('svgToImg', function() {
+ let dir;
+ const svgToImg = require('../svgToImg');
+
+ beforeEach(function() {
+ dir = tmp.dirSync();
+ });
+
+ it('should write svg as a file', function() {
+ const $ = cheerio.load('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" version="1.1"><rect width="200" height="100" stroke="black" stroke-width="6" fill="green"/></svg>');
+
+ return svgToImg(dir.name, 'index.html', $)
+ .then(function() {
+ const $img = $('img');
+ const src = $img.attr('src');
+
+ expect(dir.name).toHaveFile(src);
+ });
+ });
+});
+
diff --git a/packages/gitbook/src/output/modifiers/__tests__/svgToPng.js b/packages/gitbook/src/output/modifiers/__tests__/svgToPng.js
new file mode 100644
index 0000000..0a12938
--- /dev/null
+++ b/packages/gitbook/src/output/modifiers/__tests__/svgToPng.js
@@ -0,0 +1,32 @@
+const cheerio = require('cheerio');
+const tmp = require('tmp');
+const path = require('path');
+
+const svgToImg = require('../svgToImg');
+const svgToPng = require('../svgToPng');
+
+describe('svgToPng', function() {
+ let dir;
+
+ beforeEach(function() {
+ dir = tmp.dirSync();
+ });
+
+ it('should write svg as png file', function() {
+ const $ = cheerio.load('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" version="1.1"><rect width="200" height="100" stroke="black" stroke-width="6" fill="green"/></svg>');
+ const fileName = 'index.html';
+
+ return svgToImg(dir.name, fileName, $)
+ .then(function() {
+ return svgToPng(dir.name, fileName, $);
+ })
+ .then(function() {
+ const $img = $('img');
+ const src = $img.attr('src');
+
+ expect(dir.name).toHaveFile(src);
+ expect(path.extname(src)).toBe('.png');
+ });
+ });
+});
+
diff --git a/packages/gitbook/lib/output/modifiers/addHeadingId.js b/packages/gitbook/src/output/modifiers/addHeadingId.js
index e2e2720..e5bab3e 100644
--- a/packages/gitbook/lib/output/modifiers/addHeadingId.js
+++ b/packages/gitbook/src/output/modifiers/addHeadingId.js
@@ -1,5 +1,5 @@
-var slug = require('github-slugid');
-var editHTMLElement = require('./editHTMLElement');
+const slug = require('github-slugid');
+const editHTMLElement = require('./editHTMLElement');
/**
Add ID to an heading
diff --git a/packages/gitbook/lib/output/modifiers/annotateText.js b/packages/gitbook/src/output/modifiers/annotateText.js
index 490c228..36ee4e9 100644
--- a/packages/gitbook/lib/output/modifiers/annotateText.js
+++ b/packages/gitbook/src/output/modifiers/annotateText.js
@@ -1,46 +1,43 @@
-var escape = require('escape-html');
+const escape = require('escape-html');
// Selector to ignore
-var ANNOTATION_IGNORE = '.no-glossary,code,pre,a,script,h1,h2,h3,h4,h5,h6';
+const ANNOTATION_IGNORE = '.no-glossary,code,pre,a,script,h1,h2,h3,h4,h5,h6';
-function pregQuote( str ) {
- return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, '\\$1');
+function pregQuote(str) {
+ return (str + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, '\\$1');
}
-function replaceText($, el, search, replace, text_only ) {
- return $(el).each(function(){
- var node = this.firstChild,
- val,
- new_val,
-
- // Elements to be removed at the end.
- remove = [];
+function replaceText($, el, search, replace, text_only) {
+ return $(el).each(function() {
+ let node = this.firstChild, val, new_val;
+ // Elements to be removed at the end.
+ const remove = [];
// Only continue if firstChild exists.
- if ( node ) {
+ if (node) {
// Loop over all childNodes.
while (node) {
// Only process text nodes.
- if ( node.nodeType === 3 ) {
+ if (node.nodeType === 3) {
// The original node value.
val = node.nodeValue;
// The new value.
- new_val = val.replace( search, replace );
+ new_val = val.replace(search, replace);
// Only replace text if the new value is actually different!
- if ( new_val !== val ) {
+ if (new_val !== val) {
- if ( !text_only && /</.test( new_val ) ) {
+ if (!text_only && /</.test(new_val)) {
// The new value contains HTML, set it in a slower but far more
// robust way.
- $(node).before( new_val );
+ $(node).before(new_val);
// Don't remove the node yet, or the loop will lose its place.
- remove.push( node );
+ remove.push(node);
} else {
// The new value contains no HTML, so it can be set in this
// very fast, simple way.
@@ -67,13 +64,13 @@ function replaceText($, el, search, replace, text_only ) {
*/
function annotateText(entries, glossaryFilePath, $) {
entries.forEach(function(entry) {
- var entryId = entry.getID();
- var name = entry.getName();
- var description = entry.getDescription();
- var searchRegex = new RegExp( '\\b(' + pregQuote(name.toLowerCase()) + ')\\b' , 'gi' );
+ const entryId = entry.getID();
+ const name = entry.getName();
+ const description = entry.getDescription();
+ const searchRegex = new RegExp('\\b(' + pregQuote(name.toLowerCase()) + ')\\b' , 'gi');
$('*').each(function() {
- var $this = $(this);
+ const $this = $(this);
if (
$this.is(ANNOTATION_IGNORE) ||
diff --git a/packages/gitbook/lib/output/modifiers/editHTMLElement.js b/packages/gitbook/src/output/modifiers/editHTMLElement.js
index 755598e..d0d2b19 100644
--- a/packages/gitbook/lib/output/modifiers/editHTMLElement.js
+++ b/packages/gitbook/src/output/modifiers/editHTMLElement.js
@@ -1,13 +1,13 @@
-var Promise = require('../../utils/promise');
+const Promise = require('../../utils/promise');
/**
Edit all elements matching a selector
*/
function editHTMLElement($, selector, fn) {
- var $elements = $(selector);
+ const $elements = $(selector);
return Promise.forEach($elements, function(el) {
- var $el = $(el);
+ const $el = $(el);
return fn($el);
});
}
diff --git a/packages/gitbook/lib/output/modifiers/fetchRemoteImages.js b/packages/gitbook/src/output/modifiers/fetchRemoteImages.js
index ef868b9..1732247 100644
--- a/packages/gitbook/lib/output/modifiers/fetchRemoteImages.js
+++ b/packages/gitbook/src/output/modifiers/fetchRemoteImages.js
@@ -1,9 +1,9 @@
-var path = require('path');
-var crc = require('crc');
+const path = require('path');
+const crc = require('crc');
-var editHTMLElement = require('./editHTMLElement');
-var fs = require('../../utils/fs');
-var LocationUtils = require('../../utils/location');
+const editHTMLElement = require('./editHTMLElement');
+const fs = require('../../utils/fs');
+const LocationUtils = require('../../utils/location');
/**
Fetch all remote images
@@ -14,20 +14,20 @@ var LocationUtils = require('../../utils/location');
@return {Promise}
*/
function fetchRemoteImages(rootFolder, currentFile, $) {
- var currentDirectory = path.dirname(currentFile);
+ const currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
- var src = $img.attr('src');
- var extension = path.extname(src);
+ let src = $img.attr('src');
+ const extension = path.extname(src);
if (!LocationUtils.isExternal(src)) {
return;
}
// We avoid generating twice the same PNG
- var hash = crc.crc32(src).toString(16);
- var fileName = hash + extension;
- var filePath = path.join(rootFolder, fileName);
+ const hash = crc.crc32(src).toString(16);
+ const fileName = hash + extension;
+ const filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return fs.download(src, filePath);
diff --git a/packages/gitbook/lib/output/modifiers/highlightCode.js b/packages/gitbook/src/output/modifiers/highlightCode.js
index 5d397bb..622432d 100644
--- a/packages/gitbook/lib/output/modifiers/highlightCode.js
+++ b/packages/gitbook/src/output/modifiers/highlightCode.js
@@ -1,8 +1,8 @@
-var is = require('is');
-var Immutable = require('immutable');
+const is = require('is');
+const Immutable = require('immutable');
-var Promise = require('../../utils/promise');
-var editHTMLElement = require('./editHTMLElement');
+const Promise = require('../../utils/promise');
+const editHTMLElement = require('./editHTMLElement');
/**
Return language for a code blocks from a list of class names
@@ -40,9 +40,9 @@ function getLanguageForClass(classNames) {
*/
function highlightCode(highlight, $) {
return editHTMLElement($, 'code', function($code) {
- var classNames = ($code.attr('class') || '').split(' ');
- var lang = getLanguageForClass(classNames);
- var source = $code.text();
+ const classNames = ($code.attr('class') || '').split(' ');
+ const lang = getLanguageForClass(classNames);
+ const source = $code.text();
return Promise(highlight(lang, source))
.then(function(r) {
diff --git a/packages/gitbook/lib/output/modifiers/index.js b/packages/gitbook/src/output/modifiers/index.js
index f1daa2b..f1daa2b 100644
--- a/packages/gitbook/lib/output/modifiers/index.js
+++ b/packages/gitbook/src/output/modifiers/index.js
diff --git a/packages/gitbook/lib/output/modifiers/inlineAssets.js b/packages/gitbook/src/output/modifiers/inlineAssets.js
index 7cd874b..1ed4344 100644
--- a/packages/gitbook/lib/output/modifiers/inlineAssets.js
+++ b/packages/gitbook/src/output/modifiers/inlineAssets.js
@@ -1,10 +1,10 @@
-var svgToImg = require('./svgToImg');
-var svgToPng = require('./svgToPng');
-var inlinePng = require('./inlinePng');
-var resolveImages = require('./resolveImages');
-var fetchRemoteImages = require('./fetchRemoteImages');
+const svgToImg = require('./svgToImg');
+const svgToPng = require('./svgToPng');
+const inlinePng = require('./inlinePng');
+const resolveImages = require('./resolveImages');
+const fetchRemoteImages = require('./fetchRemoteImages');
-var Promise = require('../../utils/promise');
+const Promise = require('../../utils/promise');
/**
Inline all assets in a page
diff --git a/packages/gitbook/lib/output/modifiers/inlinePng.js b/packages/gitbook/src/output/modifiers/inlinePng.js
index 161f164..218aaa2 100644
--- a/packages/gitbook/lib/output/modifiers/inlinePng.js
+++ b/packages/gitbook/src/output/modifiers/inlinePng.js
@@ -1,11 +1,11 @@
-var crc = require('crc');
-var path = require('path');
+const crc = require('crc');
+const path = require('path');
-var imagesUtil = require('../../utils/images');
-var fs = require('../../utils/fs');
-var LocationUtils = require('../../utils/location');
+const imagesUtil = require('../../utils/images');
+const fs = require('../../utils/fs');
+const LocationUtils = require('../../utils/location');
-var editHTMLElement = require('./editHTMLElement');
+const editHTMLElement = require('./editHTMLElement');
/**
Convert all inline PNG images to PNG file
@@ -15,20 +15,20 @@ var editHTMLElement = require('./editHTMLElement');
@return {Promise}
*/
function inlinePng(rootFolder, currentFile, $) {
- var currentDirectory = path.dirname(currentFile);
+ const currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
- var src = $img.attr('src');
+ const src = $img.attr('src');
if (!LocationUtils.isDataURI(src)) {
return;
}
// We avoid generating twice the same PNG
- var hash = crc.crc32(src).toString(16);
- var fileName = hash + '.png';
+ const hash = crc.crc32(src).toString(16);
+ let fileName = hash + '.png';
// Result file path
- var filePath = path.join(rootFolder, fileName);
+ const filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return imagesUtil.convertInlinePNG(src, filePath);
diff --git a/packages/gitbook/lib/output/modifiers/modifyHTML.js b/packages/gitbook/src/output/modifiers/modifyHTML.js
index cd3d6e5..00177fc 100644
--- a/packages/gitbook/lib/output/modifiers/modifyHTML.js
+++ b/packages/gitbook/src/output/modifiers/modifyHTML.js
@@ -1,5 +1,5 @@
-var cheerio = require('cheerio');
-var Promise = require('../../utils/promise');
+const cheerio = require('cheerio');
+const Promise = require('../../utils/promise');
/**
Apply a list of operations to a page and
@@ -10,14 +10,14 @@ var Promise = require('../../utils/promise');
@return {Promise<Page>}
*/
function modifyHTML(page, operations) {
- var html = page.getContent();
- var $ = cheerio.load(html);
+ const html = page.getContent();
+ const $ = cheerio.load(html);
return Promise.forEach(operations, function(op) {
return op($);
})
.then(function() {
- var resultHTML = $.html();
+ const resultHTML = $.html();
return page.set('content', resultHTML);
});
}
diff --git a/packages/gitbook/lib/output/modifiers/resolveImages.js b/packages/gitbook/src/output/modifiers/resolveImages.js
index cc25cfa..339ddeb 100644
--- a/packages/gitbook/lib/output/modifiers/resolveImages.js
+++ b/packages/gitbook/src/output/modifiers/resolveImages.js
@@ -1,7 +1,7 @@
-var path = require('path');
+const path = require('path');
-var LocationUtils = require('../../utils/location');
-var editHTMLElement = require('./editHTMLElement');
+const LocationUtils = require('../../utils/location');
+const editHTMLElement = require('./editHTMLElement');
/**
Resolve all HTML images:
@@ -11,10 +11,10 @@ var editHTMLElement = require('./editHTMLElement');
@param {HTMLDom} $
*/
function resolveImages(currentFile, $) {
- var currentDirectory = path.dirname(currentFile);
+ const currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
- var src = $img.attr('src');
+ let src = $img.attr('src');
if (LocationUtils.isExternal(src) || LocationUtils.isDataURI(src)) {
return;
diff --git a/packages/gitbook/lib/output/modifiers/resolveLinks.js b/packages/gitbook/src/output/modifiers/resolveLinks.js
index 9d15e5e..8b15315 100644
--- a/packages/gitbook/lib/output/modifiers/resolveLinks.js
+++ b/packages/gitbook/src/output/modifiers/resolveLinks.js
@@ -1,8 +1,8 @@
-var path = require('path');
-var url = require('url');
+const path = require('path');
+const url = require('url');
-var LocationUtils = require('../../utils/location');
-var editHTMLElement = require('./editHTMLElement');
+const LocationUtils = require('../../utils/location');
+const editHTMLElement = require('./editHTMLElement');
/**
Resolve all HTML links:
@@ -13,10 +13,10 @@ var editHTMLElement = require('./editHTMLElement');
@param {HTMLDom} $
*/
function resolveLinks(currentFile, resolveFile, $) {
- var currentDirectory = path.dirname(currentFile);
+ const currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'a', function($a) {
- var href = $a.attr('href');
+ let href = $a.attr('href');
// Don't change a tag without href
if (!href) {
@@ -29,7 +29,7 @@ function resolveLinks(currentFile, resolveFile, $) {
}
// Split anchor
- var parsed = url.parse(href);
+ const parsed = url.parse(href);
href = parsed.pathname || '';
if (href) {
diff --git a/packages/gitbook/lib/output/modifiers/svgToImg.js b/packages/gitbook/src/output/modifiers/svgToImg.js
index f31b06d..ac37d07 100644
--- a/packages/gitbook/lib/output/modifiers/svgToImg.js
+++ b/packages/gitbook/src/output/modifiers/svgToImg.js
@@ -1,10 +1,10 @@
-var path = require('path');
-var crc = require('crc');
-var domSerializer = require('dom-serializer');
+const path = require('path');
+const crc = require('crc');
+const domSerializer = require('dom-serializer');
-var editHTMLElement = require('./editHTMLElement');
-var fs = require('../../utils/fs');
-var LocationUtils = require('../../utils/location');
+const editHTMLElement = require('./editHTMLElement');
+const fs = require('../../utils/fs');
+const LocationUtils = require('../../utils/location');
/**
Render a cheerio DOM as html
@@ -18,7 +18,7 @@ function renderDOM($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
- options = options|| dom.options || $._options;
+ options = options || dom.options || $._options;
return domSerializer(dom, options);
}
@@ -29,16 +29,16 @@ function renderDOM($, dom, options) {
@param {HTMLDom} $
*/
function svgToImg(baseFolder, currentFile, $) {
- var currentDirectory = path.dirname(currentFile);
+ const currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'svg', function($svg) {
- var content = '<?xml version="1.0" encoding="UTF-8"?>' +
+ const content = '<?xml version="1.0" encoding="UTF-8"?>' +
renderDOM($, $svg);
// We avoid generating twice the same PNG
- var hash = crc.crc32(content).toString(16);
- var fileName = hash + '.svg';
- var filePath = path.join(baseFolder, fileName);
+ const hash = crc.crc32(content).toString(16);
+ const fileName = hash + '.svg';
+ const filePath = path.join(baseFolder, fileName);
// Write the svg to the file
return fs.assertFile(filePath, function() {
@@ -47,7 +47,7 @@ function svgToImg(baseFolder, currentFile, $) {
// Return as image
.then(function() {
- var src = LocationUtils.relative(currentDirectory, fileName);
+ const src = LocationUtils.relative(currentDirectory, fileName);
$svg.replaceWith('<img src="' + src + '" />');
});
});
diff --git a/packages/gitbook/lib/output/modifiers/svgToPng.js b/packages/gitbook/src/output/modifiers/svgToPng.js
index 1093106..ad3f31f 100644
--- a/packages/gitbook/lib/output/modifiers/svgToPng.js
+++ b/packages/gitbook/src/output/modifiers/svgToPng.js
@@ -1,11 +1,11 @@
-var crc = require('crc');
-var path = require('path');
+const crc = require('crc');
+const path = require('path');
-var imagesUtil = require('../../utils/images');
-var fs = require('../../utils/fs');
-var LocationUtils = require('../../utils/location');
+const imagesUtil = require('../../utils/images');
+const fs = require('../../utils/fs');
+const LocationUtils = require('../../utils/location');
-var editHTMLElement = require('./editHTMLElement');
+const editHTMLElement = require('./editHTMLElement');
/**
Convert all SVG images to PNG
@@ -15,10 +15,10 @@ var editHTMLElement = require('./editHTMLElement');
@return {Promise}
*/
function svgToPng(rootFolder, currentFile, $) {
- var currentDirectory = path.dirname(currentFile);
+ const currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'img', function($img) {
- var src = $img.attr('src');
+ let src = $img.attr('src');
if (path.extname(src) !== '.svg') {
return;
}
@@ -27,14 +27,14 @@ function svgToPng(rootFolder, currentFile, $) {
src = LocationUtils.toAbsolute(src, currentDirectory, '.');
// We avoid generating twice the same PNG
- var hash = crc.crc32(src).toString(16);
- var fileName = hash + '.png';
+ const hash = crc.crc32(src).toString(16);
+ let fileName = hash + '.png';
// Input file path
- var inputPath = path.join(rootFolder, src);
+ const inputPath = path.join(rootFolder, src);
// Result file path
- var filePath = path.join(rootFolder, fileName);
+ const filePath = path.join(rootFolder, fileName);
return fs.assertFile(filePath, function() {
return imagesUtil.convertSVGToPNG(inputPath, filePath);
diff --git a/packages/gitbook/lib/output/prepareAssets.js b/packages/gitbook/src/output/prepareAssets.js
index ae9b55a..6694a74 100644
--- a/packages/gitbook/lib/output/prepareAssets.js
+++ b/packages/gitbook/src/output/prepareAssets.js
@@ -1,4 +1,4 @@
-var Parse = require('../parse');
+const Parse = require('../parse');
/**
List all assets in the book
@@ -7,9 +7,9 @@ var Parse = require('../parse');
@return {Promise<Output>}
*/
function prepareAssets(output) {
- var book = output.getBook();
- var pages = output.getPages();
- var logger = output.getLogger();
+ const book = output.getBook();
+ const pages = output.getPages();
+ const logger = output.getLogger();
return Parse.listAssets(book, pages)
.then(function(assets) {
diff --git a/packages/gitbook/lib/output/preparePages.js b/packages/gitbook/src/output/preparePages.js
index 83944ed..e65367e 100644
--- a/packages/gitbook/lib/output/preparePages.js
+++ b/packages/gitbook/src/output/preparePages.js
@@ -1,5 +1,5 @@
-var Parse = require('../parse');
-var Promise = require('../utils/promise');
+const Parse = require('../parse');
+const Promise = require('../utils/promise');
/**
List and prepare all pages
@@ -8,8 +8,8 @@ var Promise = require('../utils/promise');
@return {Promise<Output>}
*/
function preparePages(output) {
- var book = output.getBook();
- var logger = book.getLogger();
+ const book = output.getBook();
+ const logger = book.getLogger();
if (book.isMultilingual()) {
return Promise(output);
diff --git a/packages/gitbook/lib/output/preparePlugins.js b/packages/gitbook/src/output/preparePlugins.js
index 5c4be93..c84bade 100644
--- a/packages/gitbook/lib/output/preparePlugins.js
+++ b/packages/gitbook/src/output/preparePlugins.js
@@ -1,5 +1,5 @@
-var Plugins = require('../plugins');
-var Promise = require('../utils/promise');
+const Plugins = require('../plugins');
+const Promise = require('../utils/promise');
/**
* Load and setup plugins
@@ -8,7 +8,7 @@ var Promise = require('../utils/promise');
* @return {Promise<Output>}
*/
function preparePlugins(output) {
- var book = output.getBook();
+ const book = output.getBook();
return Promise()
@@ -27,7 +27,7 @@ function preparePlugins(output) {
.then(function(newBook) {
return output.merge({
book: newBook,
- plugins: plugins
+ plugins
});
});
});
diff --git a/packages/gitbook/lib/output/website/__tests__/i18n.js b/packages/gitbook/src/output/website/__tests__/i18n.js
index fd610fb..24f01f3 100644
--- a/packages/gitbook/lib/output/website/__tests__/i18n.js
+++ b/packages/gitbook/src/output/website/__tests__/i18n.js
@@ -1,8 +1,8 @@
-var createMockOutput = require('../../__tests__/createMock');
-var prepareI18n = require('../prepareI18n');
-var createTemplateEngine = require('../createTemplateEngine');
+const createMockOutput = require('../../__tests__/createMock');
+const prepareI18n = require('../prepareI18n');
+const createTemplateEngine = require('../createTemplateEngine');
-var WebsiteGenerator = require('../');
+const WebsiteGenerator = require('../');
describe('i18n', function() {
it('should correctly use english as default language', function() {
@@ -13,8 +13,8 @@ describe('i18n', function() {
return prepareI18n(output);
})
.then(function(output) {
- var engine = createTemplateEngine(output, 'README.md');
- var t = engine.getFilters().get('t');
+ const engine = createTemplateEngine(output, 'README.md');
+ const t = engine.getFilters().get('t');
expect(t('SUMMARY_INTRODUCTION')).toEqual('Introduction');
});
@@ -29,8 +29,8 @@ describe('i18n', function() {
return prepareI18n(output);
})
.then(function(output) {
- var engine = createTemplateEngine(output, 'README.md');
- var t = engine.getFilters().get('t');
+ const engine = createTemplateEngine(output, 'README.md');
+ const t = engine.getFilters().get('t');
expect(t('GITBOOK_LINK')).toEqual('Publié avec GitBook');
});
diff --git a/packages/gitbook/lib/output/website/copyPluginAssets.js b/packages/gitbook/src/output/website/copyPluginAssets.js
index 9150636..315804a 100644
--- a/packages/gitbook/lib/output/website/copyPluginAssets.js
+++ b/packages/gitbook/src/output/website/copyPluginAssets.js
@@ -1,8 +1,8 @@
-var path = require('path');
+const path = require('path');
-var ASSET_FOLDER = require('../../constants/pluginAssetsFolder');
-var Promise = require('../../utils/promise');
-var fs = require('../../utils/fs');
+const ASSET_FOLDER = require('../../constants/pluginAssetsFolder');
+const Promise = require('../../utils/promise');
+const fs = require('../../utils/fs');
/**
Copy all assets from plugins.
@@ -13,7 +13,7 @@ var fs = require('../../utils/fs');
@return {Promise}
*/
function copyPluginAssets(output) {
- var book = output.getBook();
+ const book = output.getBook();
// Don't copy plugins assets for language book
// It'll be resolved to the parent folder
@@ -21,7 +21,7 @@ function copyPluginAssets(output) {
return Promise(output);
}
- var plugins = output.getPlugins()
+ const plugins = output.getPlugins()
// We reverse the order of plugins to copy
// so that first plugins can replace assets from other plugins.
@@ -43,15 +43,15 @@ function copyPluginAssets(output) {
@return {Promise}
*/
function copyAssets(output, plugin) {
- var logger = output.getLogger();
- var pluginRoot = plugin.getPath();
- var options = output.getOptions();
+ const logger = output.getLogger();
+ const pluginRoot = plugin.getPath();
+ const options = output.getOptions();
- var outputRoot = options.get('root');
- var assetOutputFolder = path.join(outputRoot, 'gitbook');
- var prefix = options.get('prefix');
+ const outputRoot = options.get('root');
+ const assetOutputFolder = path.join(outputRoot, 'gitbook');
+ const prefix = options.get('prefix');
- var assetFolder = path.join(pluginRoot, ASSET_FOLDER, prefix);
+ const assetFolder = path.join(pluginRoot, ASSET_FOLDER, prefix);
if (!fs.existsSync(assetFolder)) {
return Promise();
@@ -76,19 +76,19 @@ function copyAssets(output, plugin) {
@return {Promise}
*/
function copyResources(output, plugin) {
- var logger = output.getLogger();
+ const logger = output.getLogger();
- var options = output.getOptions();
- var outputRoot = options.get('root');
+ const options = output.getOptions();
+ const outputRoot = options.get('root');
- var state = output.getState();
- var resources = state.getResources();
+ const state = output.getState();
+ const resources = state.getResources();
- var pluginRoot = plugin.getPath();
- var pluginResources = resources.get(plugin.getName());
+ const pluginRoot = plugin.getPath();
+ const pluginResources = resources.get(plugin.getName());
- var assetsFolder = pluginResources.get('assets');
- var assetOutputFolder = path.join(outputRoot, 'gitbook', plugin.getNpmID());
+ let assetsFolder = pluginResources.get('assets');
+ const assetOutputFolder = path.join(outputRoot, 'gitbook', plugin.getNpmID());
if (!assetsFolder) {
return Promise();
diff --git a/packages/gitbook/lib/output/website/createTemplateEngine.js b/packages/gitbook/src/output/website/createTemplateEngine.js
index 02ec796..42a0bea 100644
--- a/packages/gitbook/lib/output/website/createTemplateEngine.js
+++ b/packages/gitbook/src/output/website/createTemplateEngine.js
@@ -1,21 +1,21 @@
-var path = require('path');
-var nunjucks = require('nunjucks');
-var DoExtension = require('nunjucks-do')(nunjucks);
-
-var Api = require('../../api');
-var deprecate = require('../../api/deprecate');
-var JSONUtils = require('../../json');
-var LocationUtils = require('../../utils/location');
-var fs = require('../../utils/fs');
-var PathUtils = require('../../utils/path');
-var TemplateEngine = require('../../models/templateEngine');
-var templatesFolder = require('../../constants/templatesFolder');
-var defaultFilters = require('../../constants/defaultFilters');
-var Templating = require('../../templating');
-var listSearchPaths = require('./listSearchPaths');
-
-var fileToURL = require('../helper/fileToURL');
-var resolveFileToURL = require('../helper/resolveFileToURL');
+const path = require('path');
+const nunjucks = require('nunjucks');
+const DoExtension = require('nunjucks-do')(nunjucks);
+
+const Api = require('../../api');
+const deprecate = require('../../api/deprecate');
+const JSONUtils = require('../../json');
+const LocationUtils = require('../../utils/location');
+const fs = require('../../utils/fs');
+const PathUtils = require('../../utils/path');
+const TemplateEngine = require('../../models/templateEngine');
+const templatesFolder = require('../../constants/templatesFolder');
+const defaultFilters = require('../../constants/defaultFilters');
+const Templating = require('../../templating');
+const listSearchPaths = require('./listSearchPaths');
+
+const fileToURL = require('../helper/fileToURL');
+const resolveFileToURL = require('../helper/resolveFileToURL');
/**
* Directory for a theme with the templates
@@ -32,25 +32,25 @@ function templateFolder(dir) {
* @return {TemplateEngine}
*/
function createTemplateEngine(output, currentFile) {
- var book = output.getBook();
- var state = output.getState();
- var i18n = state.getI18n();
- var config = book.getConfig();
- var summary = book.getSummary();
- var outputFolder = output.getRoot();
+ const book = output.getBook();
+ const state = output.getState();
+ const i18n = state.getI18n();
+ const config = book.getConfig();
+ const summary = book.getSummary();
+ const outputFolder = output.getRoot();
// Search paths for templates
- var searchPaths = listSearchPaths(output);
- var tplSearchPaths = searchPaths.map(templateFolder);
+ const searchPaths = listSearchPaths(output);
+ const tplSearchPaths = searchPaths.map(templateFolder);
// Create loader
- var loader = new Templating.ThemesLoader(tplSearchPaths);
+ const loader = new Templating.ThemesLoader(tplSearchPaths);
// Get languages
- var language = config.getValue('language');
+ const language = config.getValue('language');
// Create API context
- var context = Api.encodeGlobal(output);
+ const context = Api.encodeGlobal(output);
/**
@@ -63,7 +63,7 @@ function createTemplateEngine(output, currentFile) {
return false;
}
- var filePath = PathUtils.resolveInRoot(outputFolder, fileName);
+ const filePath = PathUtils.resolveInRoot(outputFolder, fileName);
return fs.existsSync(filePath);
}
@@ -73,7 +73,7 @@ function createTemplateEngine(output, currentFile) {
* @return {Object|undefined}
*/
function getArticleByPath(filePath) {
- var article = summary.getByPath(filePath);
+ const article = summary.getByPath(filePath);
if (!article) return undefined;
return JSONUtils.encodeSummaryArticle(article);
@@ -85,24 +85,25 @@ function createTemplateEngine(output, currentFile) {
* @return {Object|undefined}
*/
function getPageByPath(filePath) {
- var page = output.getPage(filePath);
+ const page = output.getPage(filePath);
if (!page) return undefined;
return JSONUtils.encodePage(page, summary);
}
return TemplateEngine.create({
- loader: loader,
+ loader,
- context: context,
+ context,
globals: {
- getArticleByPath: getArticleByPath,
- getPageByPath: getPageByPath,
- fileExists: fileExists
+ getArticleByPath,
+ getPageByPath,
+ fileExists
},
filters: defaultFilters.merge({
+
/**
* Translate a sentence
*/
@@ -115,12 +116,12 @@ function createTemplateEngine(output, currentFile) {
* relative path.
* it also resolve pages
*/
- resolveFile: function(filePath) {
+ resolveFile(filePath) {
filePath = resolveFileToURL(output, filePath);
return LocationUtils.relativeForFile(currentFile, filePath);
},
- resolveAsset: function(filePath) {
+ resolveAsset(filePath) {
filePath = LocationUtils.toAbsolute(filePath, '', '');
filePath = path.join('gitbook', filePath);
filePath = LocationUtils.relativeForFile(currentFile, filePath);
@@ -137,7 +138,7 @@ function createTemplateEngine(output, currentFile) {
fileExists: deprecate.method(book, 'fileExists', fileExists, 'Filter "fileExists" is deprecated, use "fileExists(filename)" '),
getArticleByPath: deprecate.method(book, 'getArticleByPath', fileExists, 'Filter "getArticleByPath" is deprecated, use "getArticleByPath(filename)" '),
- contentURL: function(filePath) {
+ contentURL(filePath) {
return fileToURL(output, filePath);
}
}),
diff --git a/packages/gitbook/lib/output/website/index.js b/packages/gitbook/src/output/website/index.js
index 7818a28..7818a28 100644
--- a/packages/gitbook/lib/output/website/index.js
+++ b/packages/gitbook/src/output/website/index.js
diff --git a/packages/gitbook/lib/output/website/listSearchPaths.js b/packages/gitbook/src/output/website/listSearchPaths.js
index c45f39c..c07dade 100644
--- a/packages/gitbook/lib/output/website/listSearchPaths.js
+++ b/packages/gitbook/src/output/website/listSearchPaths.js
@@ -6,10 +6,10 @@
@return {List<String>}
*/
function listSearchPaths(output) {
- var book = output.getBook();
- var plugins = output.getPlugins();
+ const book = output.getBook();
+ const plugins = output.getPlugins();
- var searchPaths = plugins
+ const searchPaths = plugins
.valueSeq()
.map(function(plugin) {
return plugin.getPath();
diff --git a/packages/gitbook/lib/output/website/onAsset.js b/packages/gitbook/src/output/website/onAsset.js
index 69dfc4f..b996375 100644
--- a/packages/gitbook/lib/output/website/onAsset.js
+++ b/packages/gitbook/src/output/website/onAsset.js
@@ -1,5 +1,5 @@
-var path = require('path');
-var fs = require('../../utils/fs');
+const path = require('path');
+const fs = require('../../utils/fs');
/**
Copy an asset to the output folder
@@ -8,12 +8,12 @@ var fs = require('../../utils/fs');
@param {Page} page
*/
function onAsset(output, asset) {
- var book = output.getBook();
- var options = output.getOptions();
- var bookFS = book.getContentFS();
+ const book = output.getBook();
+ const options = output.getOptions();
+ const bookFS = book.getContentFS();
- var outputFolder = options.get('root');
- var outputPath = path.resolve(outputFolder, asset);
+ const outputFolder = options.get('root');
+ const outputPath = path.resolve(outputFolder, asset);
return fs.ensureFile(outputPath)
.then(function() {
diff --git a/packages/gitbook/src/output/website/onFinish.js b/packages/gitbook/src/output/website/onFinish.js
new file mode 100644
index 0000000..b032c90
--- /dev/null
+++ b/packages/gitbook/src/output/website/onFinish.js
@@ -0,0 +1,35 @@
+const Promise = require('../../utils/promise');
+const JSONUtils = require('../../json');
+const Templating = require('../../templating');
+const writeFile = require('../helper/writeFile');
+const createTemplateEngine = require('./createTemplateEngine');
+
+/**
+ Finish the generation, write the languages index
+
+ @param {Output}
+ @return {Output}
+*/
+function onFinish(output) {
+ const book = output.getBook();
+ const options = output.getOptions();
+ const prefix = options.get('prefix');
+
+ if (!book.isMultilingual()) {
+ return Promise(output);
+ }
+
+ const filePath = 'index.html';
+ const engine = createTemplateEngine(output, filePath);
+ const context = JSONUtils.encodeOutput(output);
+
+ // Render the theme
+ return Templating.renderFile(engine, prefix + '/languages.html', context)
+
+ // Write it to the disk
+ .then(function(tplOut) {
+ return writeFile(output, filePath, tplOut.getContent());
+ });
+}
+
+module.exports = onFinish;
diff --git a/packages/gitbook/lib/output/website/onInit.js b/packages/gitbook/src/output/website/onInit.js
index 3465eef..3f6d26e 100644
--- a/packages/gitbook/lib/output/website/onInit.js
+++ b/packages/gitbook/src/output/website/onInit.js
@@ -1,8 +1,8 @@
-var Promise = require('../../utils/promise');
+const Promise = require('../../utils/promise');
-var copyPluginAssets = require('./copyPluginAssets');
-var prepareI18n = require('./prepareI18n');
-var prepareResources = require('./prepareResources');
+const copyPluginAssets = require('./copyPluginAssets');
+const prepareI18n = require('./prepareI18n');
+const prepareResources = require('./prepareResources');
/**
Initialize the generator
diff --git a/packages/gitbook/lib/output/website/onPage.js b/packages/gitbook/src/output/website/onPage.js
index 5fb40a7..3b40536 100644
--- a/packages/gitbook/lib/output/website/onPage.js
+++ b/packages/gitbook/src/output/website/onPage.js
@@ -1,15 +1,15 @@
-var path = require('path');
-var omit = require('omit-keys');
+const path = require('path');
+const omit = require('omit-keys');
-var Templating = require('../../templating');
-var Plugins = require('../../plugins');
-var JSONUtils = require('../../json');
-var LocationUtils = require('../../utils/location');
-var Modifiers = require('../modifiers');
-var writeFile = require('../helper/writeFile');
-var getModifiers = require('../getModifiers');
-var createTemplateEngine = require('./createTemplateEngine');
-var fileToOutput = require('../helper/fileToOutput');
+const Templating = require('../../templating');
+const Plugins = require('../../plugins');
+const JSONUtils = require('../../json');
+const LocationUtils = require('../../utils/location');
+const Modifiers = require('../modifiers');
+const writeFile = require('../helper/writeFile');
+const getModifiers = require('../getModifiers');
+const createTemplateEngine = require('./createTemplateEngine');
+const fileToOutput = require('../helper/fileToOutput');
/**
* Write a page as a json file
@@ -18,41 +18,41 @@ var fileToOutput = require('../helper/fileToOutput');
* @param {Page} page
*/
function onPage(output, page) {
- var options = output.getOptions();
- var prefix = options.get('prefix');
+ const options = output.getOptions();
+ const prefix = options.get('prefix');
- var file = page.getFile();
+ const file = page.getFile();
- var book = output.getBook();
- var plugins = output.getPlugins();
- var state = output.getState();
- var resources = state.getResources();
+ const book = output.getBook();
+ const plugins = output.getPlugins();
+ const state = output.getState();
+ const resources = state.getResources();
- var engine = createTemplateEngine(output, page.getPath());
+ const engine = createTemplateEngine(output, page.getPath());
// Output file path
- var filePath = fileToOutput(output, file.getPath());
+ const filePath = fileToOutput(output, file.getPath());
// Calcul relative path to the root
- var outputDirName = path.dirname(filePath);
- var basePath = LocationUtils.normalize(path.relative(outputDirName, './'));
+ const outputDirName = path.dirname(filePath);
+ const basePath = LocationUtils.normalize(path.relative(outputDirName, './'));
return Modifiers.modifyHTML(page, getModifiers(output, page))
.then(function(resultPage) {
// Generate the context
- var context = JSONUtils.encodeOutputWithPage(output, resultPage);
+ const context = JSONUtils.encodeOutputWithPage(output, resultPage);
context.plugins = {
resources: Plugins.listResources(plugins, resources).toJS()
};
context.template = {
- getJSContext: function() {
+ getJSContext() {
return {
page: omit(context.page, 'content'),
config: context.config,
file: context.file,
gitbook: context.gitbook,
- basePath: basePath,
+ basePath,
book: {
language: book.getLanguage()
}
diff --git a/packages/gitbook/lib/output/website/options.js b/packages/gitbook/src/output/website/options.js
index ac9cdad..43314df 100644
--- a/packages/gitbook/lib/output/website/options.js
+++ b/packages/gitbook/src/output/website/options.js
@@ -1,6 +1,6 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Options = Immutable.Record({
+const Options = Immutable.Record({
// Root folder for the output
root: String(),
diff --git a/packages/gitbook/lib/output/website/prepareI18n.js b/packages/gitbook/src/output/website/prepareI18n.js
index cedd3b9..b02ef77 100644
--- a/packages/gitbook/lib/output/website/prepareI18n.js
+++ b/packages/gitbook/src/output/website/prepareI18n.js
@@ -1,8 +1,8 @@
-var path = require('path');
+const path = require('path');
-var fs = require('../../utils/fs');
-var Promise = require('../../utils/promise');
-var listSearchPaths = require('./listSearchPaths');
+const fs = require('../../utils/fs');
+const Promise = require('../../utils/promise');
+const listSearchPaths = require('./listSearchPaths');
/**
* Prepare i18n, load translations from plugins and book
@@ -11,14 +11,14 @@ var listSearchPaths = require('./listSearchPaths');
* @return {Promise<Output>}
*/
function prepareI18n(output) {
- var state = output.getState();
- var i18n = state.getI18n();
- var searchPaths = listSearchPaths(output);
+ const state = output.getState();
+ const i18n = state.getI18n();
+ const searchPaths = listSearchPaths(output);
searchPaths
.reverse()
.forEach(function(searchPath) {
- var i18nRoot = path.resolve(searchPath, '_i18n');
+ const i18nRoot = path.resolve(searchPath, '_i18n');
if (!fs.existsSync(i18nRoot)) return;
i18n.load(i18nRoot);
diff --git a/packages/gitbook/lib/output/website/prepareResources.js b/packages/gitbook/src/output/website/prepareResources.js
index 4e6835d..e93f45f 100644
--- a/packages/gitbook/lib/output/website/prepareResources.js
+++ b/packages/gitbook/src/output/website/prepareResources.js
@@ -1,8 +1,8 @@
-var is = require('is');
-var Immutable = require('immutable');
-var Promise = require('../../utils/promise');
+const is = require('is');
+const Immutable = require('immutable');
+const Promise = require('../../utils/promise');
-var Api = require('../../api');
+const Api = require('../../api');
/**
Prepare plugins resources, add all output corresponding type resources
@@ -11,16 +11,16 @@ var Api = require('../../api');
@return {Promise<Output>}
*/
function prepareResources(output) {
- var plugins = output.getPlugins();
- var options = output.getOptions();
- var type = options.get('prefix');
- var state = output.getState();
- var context = Api.encodeGlobal(output);
+ const plugins = output.getPlugins();
+ const options = output.getOptions();
+ const type = options.get('prefix');
+ let state = output.getState();
+ const context = Api.encodeGlobal(output);
- var result = Immutable.Map();
+ let result = Immutable.Map();
return Promise.forEach(plugins, function(plugin) {
- var pluginResources = plugin.getResources(type);
+ const pluginResources = plugin.getResources(type);
return Promise()
.then(function() {
@@ -44,11 +44,11 @@ function prepareResources(output) {
});
output = output.merge({
- state: state
+ state
});
return output;
});
}
-module.exports = prepareResources; \ No newline at end of file
+module.exports = prepareResources;
diff --git a/packages/gitbook/lib/output/website/state.js b/packages/gitbook/src/output/website/state.js
index cb8f750..813b850 100644
--- a/packages/gitbook/lib/output/website/state.js
+++ b/packages/gitbook/src/output/website/state.js
@@ -1,7 +1,7 @@
-var I18n = require('i18n-t');
-var Immutable = require('immutable');
+const I18n = require('i18n-t');
+const Immutable = require('immutable');
-var GeneratorState = Immutable.Record({
+const GeneratorState = Immutable.Record({
i18n: I18n(),
// List of plugins' resources
diff --git a/packages/gitbook/lib/parse/__tests__/listAssets.js b/packages/gitbook/src/parse/__tests__/listAssets.js
index 4c5b0a0..102aed9 100644
--- a/packages/gitbook/lib/parse/__tests__/listAssets.js
+++ b/packages/gitbook/src/parse/__tests__/listAssets.js
@@ -1,20 +1,20 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Book = require('../../models/book');
-var createMockFS = require('../../fs/mock');
-var listAssets = require('../listAssets');
-var parseGlossary = require('../parseGlossary');
+const Book = require('../../models/book');
+const createMockFS = require('../../fs/mock');
+const listAssets = require('../listAssets');
+const parseGlossary = require('../parseGlossary');
describe('listAssets', function() {
it('should not list glossary as asset', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'GLOSSARY.md': '# Glossary\n\n## Hello\nDescription for hello',
'assetFile.js': '',
'assets': {
'file.js': ''
}
});
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseGlossary(book)
.then(function(resultBook) {
diff --git a/packages/gitbook/lib/parse/__tests__/parseBook.js b/packages/gitbook/src/parse/__tests__/parseBook.js
index b1236c9..d5de25c 100644
--- a/packages/gitbook/lib/parse/__tests__/parseBook.js
+++ b/packages/gitbook/src/parse/__tests__/parseBook.js
@@ -1,11 +1,11 @@
-var Book = require('../../models/book');
-var createMockFS = require('../../fs/mock');
+const Book = require('../../models/book');
+const createMockFS = require('../../fs/mock');
describe('parseBook', function() {
- var parseBook = require('../parseBook');
+ const parseBook = require('../parseBook');
it('should parse multilingual book', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'LANGS.md': '# Languages\n\n* [en](en)\n* [fr](fr)',
'en': {
'README.md': 'Hello'
@@ -14,12 +14,12 @@ describe('parseBook', function() {
'README.md': 'Bonjour'
}
});
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseBook(book)
.then(function(resultBook) {
- var languages = resultBook.getLanguages();
- var books = resultBook.getBooks();
+ const languages = resultBook.getLanguages();
+ const books = resultBook.getBooks();
expect(resultBook.isMultilingual()).toBe(true);
expect(languages.getList().size).toBe(2);
@@ -28,7 +28,7 @@ describe('parseBook', function() {
});
it('should extend configuration for multilingual book', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'LANGS.md': '# Languages\n\n* [en](en)\n* [fr](fr)',
'book.json': '{ "title": "Test", "author": "GitBook" }',
'en': {
@@ -39,20 +39,20 @@ describe('parseBook', function() {
'README.md': 'Bonjour'
}
});
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseBook(book)
.then(function(resultBook) {
- var books = resultBook.getBooks();
+ const books = resultBook.getBooks();
expect(resultBook.isMultilingual()).toBe(true);
expect(books.size).toBe(2);
- var en = books.get('en');
- var fr = books.get('fr');
+ const en = books.get('en');
+ const fr = books.get('fr');
- var enConfig = en.getConfig();
- var frConfig = fr.getConfig();
+ const enConfig = en.getConfig();
+ const frConfig = fr.getConfig();
expect(enConfig.getValue('title')).toBe('Test EN');
expect(enConfig.getValue('author')).toBe('GitBook');
@@ -63,7 +63,7 @@ describe('parseBook', function() {
});
it('should parse book in a directory', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'book.json': JSON.stringify({
root: './test'
}),
@@ -73,13 +73,13 @@ describe('parseBook', function() {
'page.md': 'Page'
}
});
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseBook(book)
.then(function(resultBook) {
- var readme = resultBook.getReadme();
- var summary = resultBook.getSummary();
- var articles = summary.getArticlesAsList();
+ const readme = resultBook.getReadme();
+ const summary = resultBook.getSummary();
+ const articles = summary.getArticlesAsList();
expect(summary.getFile().exists()).toBe(true);
expect(readme.getFile().exists()).toBe(true);
diff --git a/packages/gitbook/lib/parse/__tests__/parseGlossary.js b/packages/gitbook/src/parse/__tests__/parseGlossary.js
index 9069af6..ba2e407 100644
--- a/packages/gitbook/lib/parse/__tests__/parseGlossary.js
+++ b/packages/gitbook/src/parse/__tests__/parseGlossary.js
@@ -1,20 +1,20 @@
-var Book = require('../../models/book');
-var createMockFS = require('../../fs/mock');
+const Book = require('../../models/book');
+const createMockFS = require('../../fs/mock');
describe('parseGlossary', function() {
- var parseGlossary = require('../parseGlossary');
+ const parseGlossary = require('../parseGlossary');
it('should parse glossary if exists', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'GLOSSARY.md': '# Glossary\n\n## Hello\nDescription for hello'
});
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseGlossary(book)
.then(function(resultBook) {
- var glossary = resultBook.getGlossary();
- var file = glossary.getFile();
- var entries = glossary.getEntries();
+ const glossary = resultBook.getGlossary();
+ const file = glossary.getFile();
+ const entries = glossary.getEntries();
expect(file.exists()).toBeTruthy();
expect(entries.size).toBe(1);
@@ -22,13 +22,13 @@ describe('parseGlossary', function() {
});
it('should not fail if doesn\'t exist', function() {
- var fs = createMockFS({});
- var book = Book.createForFS(fs);
+ const fs = createMockFS({});
+ const book = Book.createForFS(fs);
return parseGlossary(book)
.then(function(resultBook) {
- var glossary = resultBook.getGlossary();
- var file = glossary.getFile();
+ const glossary = resultBook.getGlossary();
+ const file = glossary.getFile();
expect(file.exists()).toBeFalsy();
});
diff --git a/packages/gitbook/lib/parse/__tests__/parseIgnore.js b/packages/gitbook/src/parse/__tests__/parseIgnore.js
index 54e7dae..b1bd43c 100644
--- a/packages/gitbook/lib/parse/__tests__/parseIgnore.js
+++ b/packages/gitbook/src/parse/__tests__/parseIgnore.js
@@ -1,9 +1,9 @@
-var Book = require('../../models/book');
-var createMockFS = require('../../fs/mock');
+const Book = require('../../models/book');
+const createMockFS = require('../../fs/mock');
describe('parseIgnore', function() {
- var parseIgnore = require('../parseIgnore');
- var fs = createMockFS({
+ const parseIgnore = require('../parseIgnore');
+ const fs = createMockFS({
'.ignore': 'test-1.js',
'.gitignore': 'test-2.js\ntest-3.js',
'.bookignore': '!test-3.js',
@@ -13,7 +13,7 @@ describe('parseIgnore', function() {
});
function getBook() {
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseIgnore(book);
}
diff --git a/packages/gitbook/lib/parse/__tests__/parsePageFromString.js b/packages/gitbook/src/parse/__tests__/parsePageFromString.js
index 2911fa3..13bc544 100644
--- a/packages/gitbook/lib/parse/__tests__/parsePageFromString.js
+++ b/packages/gitbook/src/parse/__tests__/parsePageFromString.js
@@ -1,25 +1,25 @@
-var parsePageFromString = require('../parsePageFromString');
-var Page = require('../../models/page');
+const parsePageFromString = require('../parsePageFromString');
+const Page = require('../../models/page');
describe('parsePageFromString', function() {
- var page = new Page();
+ const page = new Page();
it('should parse YAML frontmatter', function() {
- var CONTENT = '---\nhello: true\nworld: "cool"\n---\n# Hello World\n';
- var newPage = parsePageFromString(page, CONTENT);
+ const CONTENT = '---\nhello: true\nworld: "cool"\n---\n# Hello World\n';
+ const newPage = parsePageFromString(page, CONTENT);
expect(newPage.getDir()).toBe('ltr');
expect(newPage.getContent()).toBe('# Hello World\n');
- var attrs = newPage.getAttributes();
+ const attrs = newPage.getAttributes();
expect(attrs.size).toBe(2);
expect(attrs.get('hello')).toBe(true);
expect(attrs.get('world')).toBe('cool');
});
it('should parse text direction (english)', function() {
- var CONTENT = 'Hello World';
- var newPage = parsePageFromString(page, CONTENT);
+ const CONTENT = 'Hello World';
+ const newPage = parsePageFromString(page, CONTENT);
expect(newPage.getDir()).toBe('ltr');
expect(newPage.getContent()).toBe('Hello World');
@@ -27,8 +27,8 @@ describe('parsePageFromString', function() {
});
it('should parse text direction (arab)', function() {
- var CONTENT = 'مرحبا بالعالم';
- var newPage = parsePageFromString(page, CONTENT);
+ const CONTENT = 'مرحبا بالعالم';
+ const newPage = parsePageFromString(page, CONTENT);
expect(newPage.getDir()).toBe('rtl');
expect(newPage.getContent()).toBe('مرحبا بالعالم');
diff --git a/packages/gitbook/lib/parse/__tests__/parseReadme.js b/packages/gitbook/src/parse/__tests__/parseReadme.js
index 4270ea3..45ecfa3 100644
--- a/packages/gitbook/lib/parse/__tests__/parseReadme.js
+++ b/packages/gitbook/src/parse/__tests__/parseReadme.js
@@ -1,20 +1,20 @@
-var Promise = require('../../utils/promise');
-var Book = require('../../models/book');
-var createMockFS = require('../../fs/mock');
+const Promise = require('../../utils/promise');
+const Book = require('../../models/book');
+const createMockFS = require('../../fs/mock');
describe('parseReadme', function() {
- var parseReadme = require('../parseReadme');
+ const parseReadme = require('../parseReadme');
it('should parse summary if exists', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'README.md': '# Hello\n\nAnd here is the description.'
});
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseReadme(book)
.then(function(resultBook) {
- var readme = resultBook.getReadme();
- var file = readme.getFile();
+ const readme = resultBook.getReadme();
+ const file = readme.getFile();
expect(file.exists()).toBeTruthy();
expect(readme.getTitle()).toBe('Hello');
@@ -23,8 +23,8 @@ describe('parseReadme', function() {
});
it('should fail if doesn\'t exist', function() {
- var fs = createMockFS({});
- var book = Book.createForFS(fs);
+ const fs = createMockFS({});
+ const book = Book.createForFS(fs);
return parseReadme(book)
.then(function(resultBook) {
diff --git a/packages/gitbook/lib/parse/__tests__/parseSummary.js b/packages/gitbook/src/parse/__tests__/parseSummary.js
index 55a445e..8b86c45 100644
--- a/packages/gitbook/lib/parse/__tests__/parseSummary.js
+++ b/packages/gitbook/src/parse/__tests__/parseSummary.js
@@ -1,32 +1,32 @@
-var Book = require('../../models/book');
-var createMockFS = require('../../fs/mock');
+const Book = require('../../models/book');
+const createMockFS = require('../../fs/mock');
describe('parseSummary', function() {
- var parseSummary = require('../parseSummary');
+ const parseSummary = require('../parseSummary');
it('should parse summary if exists', function() {
- var fs = createMockFS({
+ const fs = createMockFS({
'SUMMARY.md': '# Summary\n\n* [Hello](hello.md)'
});
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
return parseSummary(book)
.then(function(resultBook) {
- var summary = resultBook.getSummary();
- var file = summary.getFile();
+ const summary = resultBook.getSummary();
+ const file = summary.getFile();
expect(file.exists()).toBeTruthy();
});
});
it('should not fail if doesn\'t exist', function() {
- var fs = createMockFS({});
- var book = Book.createForFS(fs);
+ const fs = createMockFS({});
+ const book = Book.createForFS(fs);
return parseSummary(book)
.then(function(resultBook) {
- var summary = resultBook.getSummary();
- var file = summary.getFile();
+ const summary = resultBook.getSummary();
+ const file = summary.getFile();
expect(file.exists()).toBeFalsy();
});
diff --git a/packages/gitbook/lib/parse/findParsableFile.js b/packages/gitbook/src/parse/findParsableFile.js
index 51e2dd0..c30dbbd 100644
--- a/packages/gitbook/lib/parse/findParsableFile.js
+++ b/packages/gitbook/src/parse/findParsableFile.js
@@ -1,7 +1,7 @@
-var path = require('path');
+const path = require('path');
-var Promise = require('../utils/promise');
-var parsers = require('../parsers');
+const Promise = require('../utils/promise');
+const parsers = require('../parsers');
/**
Find a file parsable (Markdown or AsciiDoc) in a book
@@ -11,16 +11,16 @@ var parsers = require('../parsers');
@return {Promise<File | Undefined>}
*/
function findParsableFile(book, filename) {
- var fs = book.getContentFS();
- var ext = path.extname(filename);
- var basename = path.basename(filename, ext);
- var basedir = path.dirname(filename);
+ const fs = book.getContentFS();
+ const ext = path.extname(filename);
+ const basename = path.basename(filename, ext);
+ const basedir = path.dirname(filename);
// Ordered list of extensions to test
- var exts = parsers.extensions;
+ const exts = parsers.extensions;
return Promise.some(exts, function(ext) {
- var filepath = basename + ext;
+ const filepath = basename + ext;
return fs.findFile(basedir, filepath)
.then(function(found) {
diff --git a/packages/gitbook/lib/parse/index.js b/packages/gitbook/src/parse/index.js
index 1f73946..1f73946 100644
--- a/packages/gitbook/lib/parse/index.js
+++ b/packages/gitbook/src/parse/index.js
diff --git a/packages/gitbook/lib/parse/listAssets.js b/packages/gitbook/src/parse/listAssets.js
index d83d8fd..07cf2e1 100644
--- a/packages/gitbook/lib/parse/listAssets.js
+++ b/packages/gitbook/src/parse/listAssets.js
@@ -1,4 +1,4 @@
-var timing = require('../utils/timing');
+const timing = require('../utils/timing');
/**
List all assets in a book
@@ -9,19 +9,19 @@ var timing = require('../utils/timing');
@param
*/
function listAssets(book, pages) {
- var fs = book.getContentFS();
+ const fs = book.getContentFS();
- var summary = book.getSummary();
- var summaryFile = summary.getFile().getPath();
+ const summary = book.getSummary();
+ const summaryFile = summary.getFile().getPath();
- var glossary = book.getGlossary();
- var glossaryFile = glossary.getFile().getPath();
+ const glossary = book.getGlossary();
+ const glossaryFile = glossary.getFile().getPath();
- var langs = book.getLanguages();
- var langsFile = langs.getFile().getPath();
+ const langs = book.getLanguages();
+ const langsFile = langs.getFile().getPath();
- var config = book.getConfig();
- var configFile = config.getFile().getPath();
+ const config = book.getConfig();
+ const configFile = config.getFile().getPath();
function filterFile(file) {
return !(
diff --git a/packages/gitbook/lib/parse/lookupStructureFile.js b/packages/gitbook/src/parse/lookupStructureFile.js
index 36b37f8..e54a769 100644
--- a/packages/gitbook/lib/parse/lookupStructureFile.js
+++ b/packages/gitbook/src/parse/lookupStructureFile.js
@@ -1,4 +1,4 @@
-var findParsableFile = require('./findParsableFile');
+const findParsableFile = require('./findParsableFile');
/**
Lookup a structure file (ex: SUMMARY.md, GLOSSARY.md) in a book. Uses
@@ -10,9 +10,9 @@ var findParsableFile = require('./findParsableFile');
to the book content root.
*/
function lookupStructureFile(book, type) {
- var config = book.getConfig();
+ const config = book.getConfig();
- var fileToSearch = config.getValue(['structure', type]);
+ const fileToSearch = config.getValue(['structure', type]);
return findParsableFile(book, fileToSearch);
}
diff --git a/packages/gitbook/lib/parse/parseBook.js b/packages/gitbook/src/parse/parseBook.js
index a92f39e..85f4519 100644
--- a/packages/gitbook/lib/parse/parseBook.js
+++ b/packages/gitbook/src/parse/parseBook.js
@@ -1,13 +1,13 @@
-var Promise = require('../utils/promise');
-var timing = require('../utils/timing');
-var Book = require('../models/book');
+const Promise = require('../utils/promise');
+const timing = require('../utils/timing');
+const Book = require('../models/book');
-var parseIgnore = require('./parseIgnore');
-var parseConfig = require('./parseConfig');
-var parseGlossary = require('./parseGlossary');
-var parseSummary = require('./parseSummary');
-var parseReadme = require('./parseReadme');
-var parseLanguages = require('./parseLanguages');
+const parseIgnore = require('./parseIgnore');
+const parseConfig = require('./parseConfig');
+const parseGlossary = require('./parseGlossary');
+const parseSummary = require('./parseSummary');
+const parseReadme = require('./parseReadme');
+const parseLanguages = require('./parseLanguages');
/**
Parse content of a book
@@ -29,13 +29,13 @@ function parseBookContent(book) {
@return {Promise<Book>}
*/
function parseMultilingualBook(book) {
- var languages = book.getLanguages();
- var langList = languages.getList();
+ const languages = book.getLanguages();
+ const langList = languages.getList();
return Promise.reduce(langList, function(currentBook, lang) {
- var langID = lang.getID();
- var child = Book.createFromParent(currentBook, langID);
- var ignore = currentBook.getIgnore();
+ const langID = lang.getID();
+ const child = Book.createFromParent(currentBook, langID);
+ let ignore = currentBook.getIgnore();
return Promise(child)
.then(parseConfig)
diff --git a/packages/gitbook/lib/parse/parseConfig.js b/packages/gitbook/src/parse/parseConfig.js
index a411af8..cd27426 100644
--- a/packages/gitbook/lib/parse/parseConfig.js
+++ b/packages/gitbook/src/parse/parseConfig.js
@@ -1,7 +1,7 @@
-var Promise = require('../utils/promise');
+const Promise = require('../utils/promise');
-var validateConfig = require('./validateConfig');
-var CONFIG_FILES = require('../constants/configFiles');
+const validateConfig = require('./validateConfig');
+const CONFIG_FILES = require('../constants/configFiles');
/**
Parse configuration from "book.json" or "book.js"
@@ -10,8 +10,8 @@ var CONFIG_FILES = require('../constants/configFiles');
@return {Promise<Book>}
*/
function parseConfig(book) {
- var fs = book.getFS();
- var config = book.getConfig();
+ const fs = book.getFS();
+ let config = book.getConfig();
return Promise.some(CONFIG_FILES, function(filename) {
// Is this file ignored?
@@ -25,19 +25,19 @@ function parseConfig(book) {
return fs.statFile(filename)
.then(function(file) {
return {
- file: file,
+ file,
values: cfg
};
});
})
.fail(function(err) {
- if (err.code != 'MODULE_NOT_FOUND') throw(err);
+ if (err.code != 'MODULE_NOT_FOUND') throw (err);
else return Promise(false);
});
})
.then(function(result) {
- var values = result? result.values : {};
+ let values = result ? result.values : {};
values = validateConfig(values);
// Set the file
diff --git a/packages/gitbook/lib/parse/parseGlossary.js b/packages/gitbook/src/parse/parseGlossary.js
index a96e5fc..052985b 100644
--- a/packages/gitbook/lib/parse/parseGlossary.js
+++ b/packages/gitbook/src/parse/parseGlossary.js
@@ -1,5 +1,5 @@
-var parseStructureFile = require('./parseStructureFile');
-var Glossary = require('../models/glossary');
+const parseStructureFile = require('./parseStructureFile');
+const Glossary = require('../models/glossary');
/**
Parse glossary
@@ -8,7 +8,7 @@ var Glossary = require('../models/glossary');
@return {Promise<Book>}
*/
function parseGlossary(book) {
- var logger = book.getLogger();
+ const logger = book.getLogger();
return parseStructureFile(book, 'glossary')
.spread(function(file, entries) {
@@ -18,7 +18,7 @@ function parseGlossary(book) {
logger.debug.ln('glossary index file found at', file.getPath());
- var glossary = Glossary.createFromEntries(file, entries);
+ const glossary = Glossary.createFromEntries(file, entries);
return book.set('glossary', glossary);
});
}
diff --git a/packages/gitbook/lib/parse/parseIgnore.js b/packages/gitbook/src/parse/parseIgnore.js
index 84d8c33..3059447 100644
--- a/packages/gitbook/lib/parse/parseIgnore.js
+++ b/packages/gitbook/src/parse/parseIgnore.js
@@ -1,7 +1,7 @@
-var Promise = require('../utils/promise');
-var IGNORE_FILES = require('../constants/ignoreFiles');
+const Promise = require('../utils/promise');
+const IGNORE_FILES = require('../constants/ignoreFiles');
-var DEFAULT_IGNORES = [
+const DEFAULT_IGNORES = [
// Skip Git stuff
'.git/',
@@ -29,8 +29,8 @@ function parseIgnore(book) {
return Promise.reject(new Error('Ignore files could be parsed for language books'));
}
- var fs = book.getFS();
- var ignore = book.getIgnore();
+ const fs = book.getFS();
+ let ignore = book.getIgnore();
ignore = ignore.add(DEFAULT_IGNORES);
diff --git a/packages/gitbook/lib/parse/parseLanguages.js b/packages/gitbook/src/parse/parseLanguages.js
index 346f3a3..1b28930 100644
--- a/packages/gitbook/lib/parse/parseLanguages.js
+++ b/packages/gitbook/src/parse/parseLanguages.js
@@ -1,5 +1,5 @@
-var parseStructureFile = require('./parseStructureFile');
-var Languages = require('../models/languages');
+const parseStructureFile = require('./parseStructureFile');
+const Languages = require('../models/languages');
/**
Parse languages list from book
@@ -8,7 +8,7 @@ var Languages = require('../models/languages');
@return {Promise<Book>}
*/
function parseLanguages(book) {
- var logger = book.getLogger();
+ const logger = book.getLogger();
return parseStructureFile(book, 'langs')
.spread(function(file, result) {
@@ -16,7 +16,7 @@ function parseLanguages(book) {
return book;
}
- var languages = Languages.createFromList(file, result);
+ const languages = Languages.createFromList(file, result);
logger.debug.ln('languages index file found at', file.getPath());
logger.info.ln('parsing multilingual book, with', languages.getList().size, 'languages');
diff --git a/packages/gitbook/lib/parse/parsePage.js b/packages/gitbook/src/parse/parsePage.js
index fdc56a3..72f9ddf 100644
--- a/packages/gitbook/lib/parse/parsePage.js
+++ b/packages/gitbook/src/parse/parsePage.js
@@ -1,4 +1,4 @@
-var parsePageFromString = require('./parsePageFromString');
+const parsePageFromString = require('./parsePageFromString');
/**
* Parse a page, read its content and parse the YAMl header
@@ -8,8 +8,8 @@ var parsePageFromString = require('./parsePageFromString');
* @return {Promise<Page>}
*/
function parsePage(book, page) {
- var fs = book.getContentFS();
- var file = page.getFile();
+ const fs = book.getContentFS();
+ const file = page.getFile();
return fs.readAsString(file.getPath())
.then(function(content) {
diff --git a/packages/gitbook/lib/parse/parsePageFromString.js b/packages/gitbook/src/parse/parsePageFromString.js
index 80c147b..2e4a598 100644
--- a/packages/gitbook/lib/parse/parsePageFromString.js
+++ b/packages/gitbook/src/parse/parsePageFromString.js
@@ -1,6 +1,6 @@
-var Immutable = require('immutable');
-var fm = require('front-matter');
-var direction = require('direction');
+const Immutable = require('immutable');
+const fm = require('front-matter');
+const direction = require('direction');
/**
* Parse a page, its content and the YAMl header
@@ -9,7 +9,7 @@ var direction = require('direction');
* @return {Page}
*/
function parsePageFromString(page, content) {
- var parsed = fm(content);
+ const parsed = fm(content);
return page.merge({
content: parsed.body,
diff --git a/packages/gitbook/lib/parse/parsePagesList.js b/packages/gitbook/src/parse/parsePagesList.js
index 1cf42f5..ddac20e 100644
--- a/packages/gitbook/lib/parse/parsePagesList.js
+++ b/packages/gitbook/src/parse/parsePagesList.js
@@ -1,9 +1,9 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var timing = require('../utils/timing');
-var Page = require('../models/page');
-var walkSummary = require('./walkSummary');
-var parsePage = require('./parsePage');
+const timing = require('../utils/timing');
+const Page = require('../models/page');
+const walkSummary = require('./walkSummary');
+const parsePage = require('./parsePage');
/**
@@ -14,11 +14,11 @@ var parsePage = require('./parsePage');
@return {Page}
*/
function parseFilePage(book, filePath) {
- var fs = book.getContentFS();
+ const fs = book.getContentFS();
return fs.statFile(filePath)
.then(function(file) {
- var page = Page.createForFile(file);
+ const page = Page.createForFile(file);
return parsePage(book, page);
});
}
@@ -31,9 +31,9 @@ function parseFilePage(book, filePath) {
@return {Promise<OrderedMap<Page>>}
*/
function parsePagesList(book) {
- var summary = book.getSummary();
- var glossary = book.getGlossary();
- var map = Immutable.OrderedMap();
+ const summary = book.getSummary();
+ const glossary = book.getGlossary();
+ let map = Immutable.OrderedMap();
// Parse pages from summary
return timing.measure(
@@ -41,7 +41,7 @@ function parsePagesList(book) {
walkSummary(summary, function(article) {
if (!article.isPage()) return;
- var filepath = article.getPath();
+ const filepath = article.getPath();
// Is the page ignored?
if (book.isContentFileIgnored(filepath)) return;
@@ -57,7 +57,7 @@ function parsePagesList(book) {
// Parse glossary
.then(function() {
- var file = glossary.getFile();
+ const file = glossary.getFile();
if (!file.exists()) {
return;
diff --git a/packages/gitbook/lib/parse/parseReadme.js b/packages/gitbook/src/parse/parseReadme.js
index a2ede77..82f8f19 100644
--- a/packages/gitbook/lib/parse/parseReadme.js
+++ b/packages/gitbook/src/parse/parseReadme.js
@@ -1,7 +1,7 @@
-var parseStructureFile = require('./parseStructureFile');
-var Readme = require('../models/readme');
+const parseStructureFile = require('./parseStructureFile');
+const Readme = require('../models/readme');
-var error = require('../utils/error');
+const error = require('../utils/error');
/**
Parse readme from book
@@ -10,7 +10,7 @@ var error = require('../utils/error');
@return {Promise<Book>}
*/
function parseReadme(book) {
- var logger = book.getLogger();
+ const logger = book.getLogger();
return parseStructureFile(book, 'readme')
.spread(function(file, result) {
@@ -20,7 +20,7 @@ function parseReadme(book) {
logger.debug.ln('readme found at', file.getPath());
- var readme = Readme.create(file, result);
+ const readme = Readme.create(file, result);
return book.set('readme', readme);
});
}
diff --git a/packages/gitbook/lib/parse/parseStructureFile.js b/packages/gitbook/src/parse/parseStructureFile.js
index 718f731..951da96 100644
--- a/packages/gitbook/lib/parse/parseStructureFile.js
+++ b/packages/gitbook/src/parse/parseStructureFile.js
@@ -1,6 +1,6 @@
-var Promise = require('../utils/promise');
-var error = require('../utils/error');
-var lookupStructureFile = require('./lookupStructureFile');
+const Promise = require('../utils/promise');
+const error = require('../utils/error');
+const lookupStructureFile = require('./lookupStructureFile');
/**
Parse a ParsableFile using a specific method
@@ -11,8 +11,8 @@ var lookupStructureFile = require('./lookupStructureFile');
@return {Promise<Array<String, List|Map>>}
*/
function parseFile(fs, file, type) {
- var filepath = file.getPath();
- var parser = file.getParser();
+ const filepath = file.getPath();
+ const parser = file.getParser();
if (!parser) {
return Promise.reject(
@@ -54,7 +54,7 @@ function parseFile(fs, file, type) {
@return {Promise<List|Map>}
*/
function parseStructureFile(book, type) {
- var fs = book.getContentFS();
+ const fs = book.getContentFS();
return lookupStructureFile(book, type)
.then(function(file) {
diff --git a/packages/gitbook/lib/parse/parseSummary.js b/packages/gitbook/src/parse/parseSummary.js
index 2c1e3b3..9488341 100644
--- a/packages/gitbook/lib/parse/parseSummary.js
+++ b/packages/gitbook/src/parse/parseSummary.js
@@ -1,6 +1,6 @@
-var parseStructureFile = require('./parseStructureFile');
-var Summary = require('../models/summary');
-var SummaryModifier = require('../modifiers').Summary;
+const parseStructureFile = require('./parseStructureFile');
+const Summary = require('../models/summary');
+const SummaryModifier = require('../modifiers').Summary;
/**
Parse summary in a book, the summary can only be parsed
@@ -10,13 +10,13 @@ var SummaryModifier = require('../modifiers').Summary;
@return {Promise<Book>}
*/
function parseSummary(book) {
- var readme = book.getReadme();
- var logger = book.getLogger();
- var readmeFile = readme.getFile();
+ const readme = book.getReadme();
+ const logger = book.getLogger();
+ const readmeFile = readme.getFile();
return parseStructureFile(book, 'summary')
.spread(function(file, result) {
- var summary;
+ let summary;
if (!file) {
logger.warn.ln('no summary file in this book');
@@ -27,7 +27,7 @@ function parseSummary(book) {
}
// Insert readme as first entry if not in SUMMARY.md
- var readmeArticle = summary.getByPath(readmeFile.getPath());
+ const readmeArticle = summary.getByPath(readmeFile.getPath());
if (readmeFile.exists() && !readmeArticle) {
summary = SummaryModifier.unshiftArticle(summary, {
diff --git a/packages/gitbook/lib/parse/validateConfig.js b/packages/gitbook/src/parse/validateConfig.js
index 21294ac..e766fae 100644
--- a/packages/gitbook/lib/parse/validateConfig.js
+++ b/packages/gitbook/src/parse/validateConfig.js
@@ -1,9 +1,9 @@
-var jsonschema = require('jsonschema');
-var jsonSchemaDefaults = require('json-schema-defaults');
+const jsonschema = require('jsonschema');
+const jsonSchemaDefaults = require('json-schema-defaults');
-var schema = require('../constants/configSchema');
-var error = require('../utils/error');
-var mergeDefaults = require('../utils/mergeDefaults');
+const schema = require('../constants/configSchema');
+const error = require('../utils/error');
+const mergeDefaults = require('../utils/mergeDefaults');
/**
Validate a book.json content
@@ -13,8 +13,8 @@ var mergeDefaults = require('../utils/mergeDefaults');
@return {Object}
*/
function validateConfig(bookJson) {
- var v = new jsonschema.Validator();
- var result = v.validate(bookJson, schema, {
+ const v = new jsonschema.Validator();
+ const result = v.validate(bookJson, schema, {
propertyName: 'config'
});
@@ -24,7 +24,7 @@ function validateConfig(bookJson) {
}
// Insert default values
- var defaults = jsonSchemaDefaults(schema);
+ const defaults = jsonSchemaDefaults(schema);
return mergeDefaults(bookJson, defaults);
}
diff --git a/packages/gitbook/lib/parse/walkSummary.js b/packages/gitbook/src/parse/walkSummary.js
index 0117752..47feb1f 100644
--- a/packages/gitbook/lib/parse/walkSummary.js
+++ b/packages/gitbook/src/parse/walkSummary.js
@@ -1,4 +1,4 @@
-var Promise = require('../utils/promise');
+const Promise = require('../utils/promise');
/**
Walk over a list of articles
@@ -24,7 +24,7 @@ function walkArticles(articles, fn) {
@return {Promise}
*/
function walkSummary(summary, fn) {
- var parts = summary.getParts();
+ const parts = summary.getParts();
return Promise.forEach(parts, function(part) {
return walkArticles(part.getArticles(), fn);
diff --git a/packages/gitbook/lib/parsers.js b/packages/gitbook/src/parsers.js
index 70e44f4..62c3776 100644
--- a/packages/gitbook/lib/parsers.js
+++ b/packages/gitbook/src/parsers.js
@@ -1,15 +1,15 @@
-var path = require('path');
-var Immutable = require('immutable');
+const path = require('path');
+const Immutable = require('immutable');
-var markdownParser = require('gitbook-markdown');
-var asciidocParser = require('gitbook-asciidoc');
+const markdownParser = require('gitbook-markdown');
+const asciidocParser = require('gitbook-asciidoc');
-var EXTENSIONS_MARKDOWN = require('./constants/extsMarkdown');
-var EXTENSIONS_ASCIIDOC = require('./constants/extsAsciidoc');
-var Parser = require('./models/parser');
+const EXTENSIONS_MARKDOWN = require('./constants/extsMarkdown');
+const EXTENSIONS_ASCIIDOC = require('./constants/extsAsciidoc');
+const Parser = require('./models/parser');
// This list is ordered by priority of parsers to use
-var parsers = Immutable.List([
+const parsers = Immutable.List([
Parser.create('markdown', EXTENSIONS_MARKDOWN, markdownParser),
Parser.create('asciidoc', EXTENSIONS_ASCIIDOC, asciidocParser)
]);
@@ -49,14 +49,14 @@ function getParserForFile(filename) {
}
// List all parsable extensions
-var extensions = parsers
+const extensions = parsers
.map(function(parser) {
return parser.getExtensions();
})
.flatten();
module.exports = {
- extensions: extensions,
+ extensions,
get: getParser,
getByExt: getParserByExt,
getForFile: getParserForFile
diff --git a/packages/gitbook/lib/plugins/__tests__/findForBook.js b/packages/gitbook/src/plugins/__tests__/findForBook.js
index d8af2e9..41df77e 100644
--- a/packages/gitbook/lib/plugins/__tests__/findForBook.js
+++ b/packages/gitbook/src/plugins/__tests__/findForBook.js
@@ -1,14 +1,14 @@
-var path = require('path');
+const path = require('path');
-var Book = require('../../models/book');
-var createNodeFS = require('../../fs/node');
-var findForBook = require('../findForBook');
+const Book = require('../../models/book');
+const createNodeFS = require('../../fs/node');
+const findForBook = require('../findForBook');
describe('findForBook', function() {
- var fs = createNodeFS(
+ const fs = createNodeFS(
path.resolve(__dirname, '../../..')
);
- var book = Book.createForFS(fs);
+ const book = Book.createForFS(fs);
it('should list default plugins', function() {
return findForBook(book)
diff --git a/packages/gitbook/lib/plugins/__tests__/findInstalled.js b/packages/gitbook/src/plugins/__tests__/findInstalled.js
index 9377190..dcaa62b 100644
--- a/packages/gitbook/lib/plugins/__tests__/findInstalled.js
+++ b/packages/gitbook/src/plugins/__tests__/findInstalled.js
@@ -1,13 +1,13 @@
-var path = require('path');
-var Immutable = require('immutable');
+const path = require('path');
+const Immutable = require('immutable');
describe('findInstalled', function() {
- var findInstalled = require('../findInstalled');
+ const findInstalled = require('../findInstalled');
it('must list default plugins for gitbook directory', function() {
// Read gitbook-plugins from package.json
- var pkg = require(path.resolve(__dirname, '../../../package.json'));
- var gitbookPlugins = Immutable.Seq(pkg.dependencies)
+ const pkg = require(path.resolve(__dirname, '../../../package.json'));
+ const gitbookPlugins = Immutable.Seq(pkg.dependencies)
.filter(function(v, k) {
return k.indexOf('gitbook-plugin') === 0;
})
diff --git a/packages/gitbook/src/plugins/__tests__/installPlugin.js b/packages/gitbook/src/plugins/__tests__/installPlugin.js
new file mode 100644
index 0000000..1a8debe
--- /dev/null
+++ b/packages/gitbook/src/plugins/__tests__/installPlugin.js
@@ -0,0 +1,29 @@
+const path = require('path');
+
+const PluginDependency = require('../../models/pluginDependency');
+const Book = require('../../models/book');
+const NodeFS = require('../../fs/node');
+const installPlugin = require('../installPlugin');
+
+const Parse = require('../../parse');
+
+describe('installPlugin', function() {
+ let book;
+
+ this.timeout(30000);
+
+ before(function() {
+ const fs = NodeFS(path.resolve(__dirname, '../../../'));
+ const baseBook = Book.createForFS(fs);
+
+ return Parse.parseConfig(baseBook)
+ .then(function(_book) {
+ book = _book;
+ });
+ });
+
+ it('must install a plugin from NPM', function() {
+ const dep = PluginDependency.createFromString('ga');
+ return installPlugin(book, dep);
+ });
+});
diff --git a/packages/gitbook/lib/plugins/__tests__/installPlugins.js b/packages/gitbook/src/plugins/__tests__/installPlugins.js
index 1a66f90..b6bb1f4 100644
--- a/packages/gitbook/lib/plugins/__tests__/installPlugins.js
+++ b/packages/gitbook/src/plugins/__tests__/installPlugins.js
@@ -1,19 +1,19 @@
-var path = require('path');
+const path = require('path');
-var Book = require('../../models/book');
-var NodeFS = require('../../fs/node');
-var installPlugins = require('../installPlugins');
+const Book = require('../../models/book');
+const NodeFS = require('../../fs/node');
+const installPlugins = require('../installPlugins');
-var Parse = require('../../parse');
+const Parse = require('../../parse');
describe('installPlugins', function() {
- var book;
+ let book;
this.timeout(30000);
before(function() {
- var fs = NodeFS(path.resolve(__dirname, '../../../'));
- var baseBook = Book.createForFS(fs);
+ const fs = NodeFS(path.resolve(__dirname, '../../../'));
+ const baseBook = Book.createForFS(fs);
return Parse.parseConfig(baseBook)
.then(function(_book) {
diff --git a/packages/gitbook/lib/plugins/__tests__/listDependencies.js b/packages/gitbook/src/plugins/__tests__/listDependencies.js
index 940faba..d30e46c 100644
--- a/packages/gitbook/lib/plugins/__tests__/listDependencies.js
+++ b/packages/gitbook/src/plugins/__tests__/listDependencies.js
@@ -1,12 +1,12 @@
-var PluginDependency = require('../../models/pluginDependency');
-var listDependencies = require('../listDependencies');
-var toNames = require('../toNames');
+const PluginDependency = require('../../models/pluginDependency');
+const listDependencies = require('../listDependencies');
+const toNames = require('../toNames');
describe('listDependencies', function() {
it('must list default', function() {
- var deps = PluginDependency.listFromString('ga,great');
- var plugins = listDependencies(deps);
- var names = toNames(plugins);
+ const deps = PluginDependency.listFromString('ga,great');
+ const plugins = listDependencies(deps);
+ const names = toNames(plugins);
expect(names).toEqual([
'ga', 'great',
@@ -15,9 +15,9 @@ describe('listDependencies', function() {
});
it('must list from array with -', function() {
- var deps = PluginDependency.listFromString('ga,-great');
- var plugins = listDependencies(deps);
- var names = toNames(plugins);
+ const deps = PluginDependency.listFromString('ga,-great');
+ const plugins = listDependencies(deps);
+ const names = toNames(plugins);
expect(names).toEqual([
'ga',
@@ -26,9 +26,9 @@ describe('listDependencies', function() {
});
it('must remove default plugins using -', function() {
- var deps = PluginDependency.listFromString('ga,-search');
- var plugins = listDependencies(deps);
- var names = toNames(plugins);
+ const deps = PluginDependency.listFromString('ga,-search');
+ const plugins = listDependencies(deps);
+ const names = toNames(plugins);
expect(names).toEqual([
'ga',
diff --git a/packages/gitbook/lib/plugins/__tests__/locateRootFolder.js b/packages/gitbook/src/plugins/__tests__/locateRootFolder.js
index bb414a3..54e095b 100644
--- a/packages/gitbook/lib/plugins/__tests__/locateRootFolder.js
+++ b/packages/gitbook/src/plugins/__tests__/locateRootFolder.js
@@ -1,5 +1,5 @@
-var path = require('path');
-var locateRootFolder = require('../locateRootFolder');
+const path = require('path');
+const locateRootFolder = require('../locateRootFolder');
describe('locateRootFolder', function() {
it('should correctly resolve the node_modules for gitbook', function() {
diff --git a/packages/gitbook/lib/plugins/__tests__/resolveVersion.js b/packages/gitbook/src/plugins/__tests__/resolveVersion.js
index 1877c9e..949d078 100644
--- a/packages/gitbook/lib/plugins/__tests__/resolveVersion.js
+++ b/packages/gitbook/src/plugins/__tests__/resolveVersion.js
@@ -1,9 +1,9 @@
-var PluginDependency = require('../../models/pluginDependency');
-var resolveVersion = require('../resolveVersion');
+const PluginDependency = require('../../models/pluginDependency');
+const resolveVersion = require('../resolveVersion');
describe('resolveVersion', function() {
it('must skip resolving and return non-semver versions', function() {
- var plugin = PluginDependency.createFromString('ga@git+ssh://samy@github.com/GitbookIO/plugin-ga.git');
+ const plugin = PluginDependency.createFromString('ga@git+ssh://samy@github.com/GitbookIO/plugin-ga.git');
return resolveVersion(plugin)
.then(function(version) {
@@ -12,7 +12,7 @@ describe('resolveVersion', function() {
});
it('must resolve a normal plugin dependency', function() {
- var plugin = PluginDependency.createFromString('ga@>0.9.0 < 1.0.1');
+ const plugin = PluginDependency.createFromString('ga@>0.9.0 < 1.0.1');
return resolveVersion(plugin)
.then(function(version) {
diff --git a/packages/gitbook/lib/plugins/__tests__/sortDependencies.js b/packages/gitbook/src/plugins/__tests__/sortDependencies.js
index 87df477..a08d59d 100644
--- a/packages/gitbook/lib/plugins/__tests__/sortDependencies.js
+++ b/packages/gitbook/src/plugins/__tests__/sortDependencies.js
@@ -1,17 +1,17 @@
-var PluginDependency = require('../../models/pluginDependency');
-var sortDependencies = require('../sortDependencies');
-var toNames = require('../toNames');
+const PluginDependency = require('../../models/pluginDependency');
+const sortDependencies = require('../sortDependencies');
+const toNames = require('../toNames');
describe('sortDependencies', function() {
it('must load themes after plugins', function() {
- var allPlugins = PluginDependency.listFromArray([
+ const allPlugins = PluginDependency.listFromArray([
'hello',
'theme-test',
'world'
]);
- var sorted = sortDependencies(allPlugins);
- var names = toNames(sorted);
+ const sorted = sortDependencies(allPlugins);
+ const names = toNames(sorted);
expect(names).toEqual([
'hello',
@@ -21,15 +21,15 @@ describe('sortDependencies', function() {
});
it('must keep order of themes', function() {
- var allPlugins = PluginDependency.listFromArray([
+ const allPlugins = PluginDependency.listFromArray([
'theme-test',
'theme-test1',
'hello',
'theme-test2',
'world'
]);
- var sorted = sortDependencies(allPlugins);
- var names = toNames(sorted);
+ const sorted = sortDependencies(allPlugins);
+ const names = toNames(sorted);
expect(names).toEqual([
'hello',
@@ -39,4 +39,4 @@ describe('sortDependencies', function() {
'theme-test2'
]);
});
-}); \ No newline at end of file
+});
diff --git a/packages/gitbook/lib/plugins/__tests__/validatePlugin.js b/packages/gitbook/src/plugins/__tests__/validatePlugin.js
index 635423c..a2bd23b 100644
--- a/packages/gitbook/lib/plugins/__tests__/validatePlugin.js
+++ b/packages/gitbook/src/plugins/__tests__/validatePlugin.js
@@ -1,10 +1,10 @@
-var Promise = require('../../utils/promise');
-var Plugin = require('../../models/plugin');
-var validatePlugin = require('../validatePlugin');
+const Promise = require('../../utils/promise');
+const Plugin = require('../../models/plugin');
+const validatePlugin = require('../validatePlugin');
describe('validatePlugin', function() {
it('must not validate a not loaded plugin', function() {
- var plugin = Plugin.createFromString('test');
+ const plugin = Plugin.createFromString('test');
return validatePlugin(plugin)
.then(function() {
diff --git a/packages/gitbook/lib/plugins/findForBook.js b/packages/gitbook/src/plugins/findForBook.js
index be2ad9f..b72d526 100644
--- a/packages/gitbook/lib/plugins/findForBook.js
+++ b/packages/gitbook/src/plugins/findForBook.js
@@ -1,9 +1,9 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Promise = require('../utils/promise');
-var timing = require('../utils/timing');
-var findInstalled = require('./findInstalled');
-var locateRootFolder = require('./locateRootFolder');
+const Promise = require('../utils/promise');
+const timing = require('../utils/timing');
+const findInstalled = require('./findInstalled');
+const locateRootFolder = require('./locateRootFolder');
/**
* List all plugins installed in a book
diff --git a/packages/gitbook/lib/plugins/findInstalled.js b/packages/gitbook/src/plugins/findInstalled.js
index 06cc6c4..15556b6 100644
--- a/packages/gitbook/lib/plugins/findInstalled.js
+++ b/packages/gitbook/src/plugins/findInstalled.js
@@ -1,11 +1,11 @@
-var readInstalled = require('read-installed');
-var Immutable = require('immutable');
-var path = require('path');
+const readInstalled = require('read-installed');
+const Immutable = require('immutable');
+const path = require('path');
-var Promise = require('../utils/promise');
-var fs = require('../utils/fs');
-var Plugin = require('../models/plugin');
-var PREFIX = require('../constants/pluginPrefix');
+const Promise = require('../utils/promise');
+const fs = require('../utils/fs');
+const Plugin = require('../models/plugin');
+const PREFIX = require('../constants/pluginPrefix');
/**
* Validate if a package name is a GitBook plugin
@@ -24,33 +24,33 @@ function validateId(name) {
* @return {OrderedMap<String:Plugin>}
*/
function findInstalled(folder) {
- var options = {
+ const options = {
dev: false,
- log: function() {},
+ log() {},
depth: 4
};
- var results = Immutable.OrderedMap();
+ let results = Immutable.OrderedMap();
function onPackage(pkg, parent) {
if (!pkg.name) return;
- var name = pkg.name;
- var version = pkg.version;
- var pkgPath = pkg.realPath;
- var depth = pkg.depth;
- var dependencies = pkg.dependencies;
+ const name = pkg.name;
+ const version = pkg.version;
+ const pkgPath = pkg.realPath;
+ const depth = pkg.depth;
+ const dependencies = pkg.dependencies;
- var pluginName = name.slice(PREFIX.length);
+ const pluginName = name.slice(PREFIX.length);
- if (!validateId(name)){
+ if (!validateId(name)) {
if (parent) return;
} else {
results = results.set(pluginName, Plugin({
name: pluginName,
- version: version,
+ version,
path: pkgPath,
- depth: depth,
- parent: parent
+ depth,
+ parent
}));
}
@@ -60,7 +60,7 @@ function findInstalled(folder) {
}
// Search for gitbook-plugins in node_modules folder
- var node_modules = path.join(folder, 'node_modules');
+ const node_modules = path.join(folder, 'node_modules');
// List all folders in node_modules
return fs.readdir(node_modules)
@@ -75,7 +75,7 @@ function findInstalled(folder) {
}
// Read gitbook-plugin package details
- var module_folder = path.join(node_modules, module);
+ const module_folder = path.join(node_modules, module);
return Promise.nfcall(readInstalled, module_folder, options)
.then(function(data) {
onPackage(data);
diff --git a/packages/gitbook/lib/plugins/index.js b/packages/gitbook/src/plugins/index.js
index 607a7f1..607a7f1 100644
--- a/packages/gitbook/lib/plugins/index.js
+++ b/packages/gitbook/src/plugins/index.js
diff --git a/packages/gitbook/lib/plugins/installPlugin.js b/packages/gitbook/src/plugins/installPlugin.js
index 37852df..edf4dc5 100644
--- a/packages/gitbook/lib/plugins/installPlugin.js
+++ b/packages/gitbook/src/plugins/installPlugin.js
@@ -1,7 +1,7 @@
-var npmi = require('npmi');
+const npmi = require('npmi');
-var Promise = require('../utils/promise');
-var resolveVersion = require('./resolveVersion');
+const Promise = require('../utils/promise');
+const resolveVersion = require('./resolveVersion');
/**
Install a plugin for a book
@@ -11,11 +11,11 @@ var resolveVersion = require('./resolveVersion');
@return {Promise}
*/
function installPlugin(book, plugin) {
- var logger = book.getLogger();
+ const logger = book.getLogger();
- var installFolder = book.getRoot();
- var name = plugin.getName();
- var requirement = plugin.getVersion();
+ const installFolder = book.getRoot();
+ const name = plugin.getName();
+ const requirement = plugin.getVersion();
logger.info.ln('');
logger.info.ln('installing plugin "' + name + '"');
@@ -27,10 +27,10 @@ function installPlugin(book, plugin) {
throw new Error('Found no satisfactory version for plugin "' + name + '" with requirement "' + requirement + '"');
}
- logger.info.ln('install plugin "' + name +'" (' + requirement + ') from NPM with version', version);
+ logger.info.ln('install plugin "' + name + '" (' + requirement + ') from NPM with version', version);
return Promise.nfcall(npmi, {
'name': plugin.getNpmID(),
- 'version': version,
+ version,
'path': installFolder,
'npmLoad': {
'loglevel': 'silent',
diff --git a/packages/gitbook/lib/plugins/installPlugins.js b/packages/gitbook/src/plugins/installPlugins.js
index 307c41e..8c36c92 100644
--- a/packages/gitbook/lib/plugins/installPlugins.js
+++ b/packages/gitbook/src/plugins/installPlugins.js
@@ -1,8 +1,8 @@
-var npmi = require('npmi');
+const npmi = require('npmi');
-var DEFAULT_PLUGINS = require('../constants/defaultPlugins');
-var Promise = require('../utils/promise');
-var installPlugin = require('./installPlugin');
+const DEFAULT_PLUGINS = require('../constants/defaultPlugins');
+const Promise = require('../utils/promise');
+const installPlugin = require('./installPlugin');
/**
Install plugin requirements for a book
@@ -11,14 +11,14 @@ var installPlugin = require('./installPlugin');
@return {Promise<Number>}
*/
function installPlugins(book) {
- var logger = book.getLogger();
- var config = book.getConfig();
- var plugins = config.getPluginDependencies();
+ const logger = book.getLogger();
+ const config = book.getConfig();
+ let plugins = config.getPluginDependencies();
// Remove default plugins
// (only if version is same as installed)
plugins = plugins.filterNot(function(plugin) {
- var dependency = DEFAULT_PLUGINS.find(function(dep) {
+ const dependency = DEFAULT_PLUGINS.find(function(dep) {
return dep.getName() === plugin.getName();
});
diff --git a/packages/gitbook/lib/plugins/listBlocks.js b/packages/gitbook/src/plugins/listBlocks.js
index 3ac28af..991b386 100644
--- a/packages/gitbook/lib/plugins/listBlocks.js
+++ b/packages/gitbook/src/plugins/listBlocks.js
@@ -1,4 +1,4 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
/**
List blocks from a list of plugins
@@ -10,7 +10,7 @@ function listBlocks(plugins) {
return plugins
.reverse()
.reduce(function(result, plugin) {
- var blocks = plugin.getBlocks();
+ const blocks = plugin.getBlocks();
return result.merge(blocks);
}, Immutable.Map());
}
diff --git a/packages/gitbook/lib/plugins/listDependencies.js b/packages/gitbook/src/plugins/listDependencies.js
index d52eaa9..3930ae7 100644
--- a/packages/gitbook/lib/plugins/listDependencies.js
+++ b/packages/gitbook/src/plugins/listDependencies.js
@@ -1,5 +1,5 @@
-var DEFAULT_PLUGINS = require('../constants/defaultPlugins');
-var sortDependencies = require('./sortDependencies');
+const DEFAULT_PLUGINS = require('../constants/defaultPlugins');
+const sortDependencies = require('./sortDependencies');
/**
* List all dependencies for a book, including default plugins.
@@ -10,7 +10,7 @@ var sortDependencies = require('./sortDependencies');
*/
function listDependencies(deps) {
// Extract list of plugins to disable (starting with -)
- var toRemove = deps
+ const toRemove = deps
.filter(function(plugin) {
return !plugin.isEnabled();
})
diff --git a/packages/gitbook/lib/plugins/listDepsForBook.js b/packages/gitbook/src/plugins/listDepsForBook.js
index 196e3aa..b173572 100644
--- a/packages/gitbook/lib/plugins/listDepsForBook.js
+++ b/packages/gitbook/src/plugins/listDepsForBook.js
@@ -1,4 +1,4 @@
-var listDependencies = require('./listDependencies');
+const listDependencies = require('./listDependencies');
/**
* List all plugin requirements for a book.
@@ -9,8 +9,8 @@ var listDependencies = require('./listDependencies');
* @return {List<PluginDependency>}
*/
function listDepsForBook(book) {
- var config = book.getConfig();
- var plugins = config.getPluginDependencies();
+ const config = book.getConfig();
+ const plugins = config.getPluginDependencies();
return listDependencies(plugins);
}
diff --git a/packages/gitbook/lib/plugins/listFilters.js b/packages/gitbook/src/plugins/listFilters.js
index 4d8a471..edf6c0d 100644
--- a/packages/gitbook/lib/plugins/listFilters.js
+++ b/packages/gitbook/src/plugins/listFilters.js
@@ -1,4 +1,4 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
/**
List filters from a list of plugins
diff --git a/packages/gitbook/lib/plugins/listResources.js b/packages/gitbook/src/plugins/listResources.js
index fe31b5a..df50097 100644
--- a/packages/gitbook/lib/plugins/listResources.js
+++ b/packages/gitbook/src/plugins/listResources.js
@@ -1,8 +1,8 @@
-var Immutable = require('immutable');
-var path = require('path');
+const Immutable = require('immutable');
+const path = require('path');
-var LocationUtils = require('../utils/location');
-var PLUGIN_RESOURCES = require('../constants/pluginResources');
+const LocationUtils = require('../utils/location');
+const PLUGIN_RESOURCES = require('../constants/pluginResources');
/**
List all resources from a list of plugins
@@ -13,14 +13,14 @@ var PLUGIN_RESOURCES = require('../constants/pluginResources');
*/
function listResources(plugins, resources) {
return plugins.reduce(function(result, plugin) {
- var npmId = plugin.getNpmID();
- var pluginResources = resources.get(plugin.getName());
+ const npmId = plugin.getNpmID();
+ const pluginResources = resources.get(plugin.getName());
PLUGIN_RESOURCES.forEach(function(resourceType) {
- var assets = pluginResources.get(resourceType);
+ let assets = pluginResources.get(resourceType);
if (!assets) return;
- var list = result.get(resourceType) || Immutable.List();
+ let list = result.get(resourceType) || Immutable.List();
assets = assets.map(function(assetFile) {
if (LocationUtils.isExternal(assetFile)) {
diff --git a/packages/gitbook/lib/plugins/loadForBook.js b/packages/gitbook/src/plugins/loadForBook.js
index 757677e..0baa78e 100644
--- a/packages/gitbook/lib/plugins/loadForBook.js
+++ b/packages/gitbook/src/plugins/loadForBook.js
@@ -1,9 +1,9 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var Promise = require('../utils/promise');
-var listDepsForBook = require('./listDepsForBook');
-var findForBook = require('./findForBook');
-var loadPlugin = require('./loadPlugin');
+const Promise = require('../utils/promise');
+const listDepsForBook = require('./listDepsForBook');
+const findForBook = require('./findForBook');
+const loadPlugin = require('./loadPlugin');
/**
@@ -13,21 +13,21 @@ var loadPlugin = require('./loadPlugin');
* @return {Promise<Map<String:Plugin>}
*/
function loadForBook(book) {
- var logger = book.getLogger();
+ const logger = book.getLogger();
// List the dependencies
- var requirements = listDepsForBook(book);
+ const requirements = listDepsForBook(book);
// List all plugins installed in the book
return findForBook(book)
.then(function(installedMap) {
- var missing = [];
- var plugins = requirements.reduce(function(result, dep) {
- var name = dep.getName();
- var installed = installedMap.get(name);
+ const missing = [];
+ let plugins = requirements.reduce(function(result, dep) {
+ const name = dep.getName();
+ const installed = installedMap.get(name);
if (installed) {
- var deps = installedMap
+ const deps = installedMap
.filter(function(plugin) {
return plugin.getParent() === name;
})
diff --git a/packages/gitbook/lib/plugins/loadPlugin.js b/packages/gitbook/src/plugins/loadPlugin.js
index 9ed83a1..4a349e2 100644
--- a/packages/gitbook/lib/plugins/loadPlugin.js
+++ b/packages/gitbook/src/plugins/loadPlugin.js
@@ -1,12 +1,12 @@
-var path = require('path');
-var resolve = require('resolve');
-var Immutable = require('immutable');
+const path = require('path');
+const resolve = require('resolve');
+const Immutable = require('immutable');
-var Promise = require('../utils/promise');
-var error = require('../utils/error');
-var timing = require('../utils/timing');
+const Promise = require('../utils/promise');
+const error = require('../utils/error');
+const timing = require('../utils/timing');
-var validatePlugin = require('./validatePlugin');
+const validatePlugin = require('./validatePlugin');
// Return true if an error is a "module not found"
// Wait on https://github.com/substack/node-resolve/pull/81 to be merged
@@ -23,21 +23,21 @@ function isModuleNotFound(err) {
@return {Promise<Plugin>}
*/
function loadPlugin(book, plugin) {
- var logger = book.getLogger();
+ const logger = book.getLogger();
- var name = plugin.getName();
- var pkgPath = plugin.getPath();
+ const name = plugin.getName();
+ let pkgPath = plugin.getPath();
// Try loading plugins from different location
- var p = Promise()
+ let p = Promise()
.then(function() {
- var packageContent;
- var packageMain;
- var content;
+ let packageContent;
+ let packageMain;
+ let content;
// Locate plugin and load package.json
try {
- var res = resolve.sync('./package.json', { basedir: pkgPath });
+ const res = resolve.sync('./package.json', { basedir: pkgPath });
pkgPath = path.dirname(res);
packageContent = require(res);
@@ -52,7 +52,7 @@ function loadPlugin(book, plugin) {
// Locate the main package
try {
- var indexJs = path.normalize(packageContent.main || 'index.js');
+ const indexJs = path.normalize(packageContent.main || 'index.js');
packageMain = resolve.sync('./' + indexJs, { basedir: pkgPath });
} catch (err) {
if (!isModuleNotFound(err)) throw err;
@@ -63,7 +63,7 @@ function loadPlugin(book, plugin) {
if (packageMain) {
try {
content = require(packageMain);
- } catch(err) {
+ } catch (err) {
throw new error.PluginError(err, {
plugin: name
});
diff --git a/packages/gitbook/src/plugins/locateRootFolder.js b/packages/gitbook/src/plugins/locateRootFolder.js
new file mode 100644
index 0000000..64e06a8
--- /dev/null
+++ b/packages/gitbook/src/plugins/locateRootFolder.js
@@ -0,0 +1,22 @@
+const path = require('path');
+const resolve = require('resolve');
+
+const DEFAULT_PLUGINS = require('../constants/defaultPlugins');
+
+/**
+ * Resolve the root folder containing for node_modules
+ * since gitbook can be used as a library and dependency can be flattened.
+ *
+ * @return {String} folderPath
+ */
+function locateRootFolder() {
+ const firstDefaultPlugin = DEFAULT_PLUGINS.first();
+ const pluginPath = resolve.sync(firstDefaultPlugin.getNpmID() + '/package.json', {
+ basedir: __dirname
+ });
+ const nodeModules = path.resolve(pluginPath, '../../..');
+
+ return nodeModules;
+}
+
+module.exports = locateRootFolder;
diff --git a/packages/gitbook/lib/plugins/resolveVersion.js b/packages/gitbook/src/plugins/resolveVersion.js
index 61aef8d..07b771e 100644
--- a/packages/gitbook/lib/plugins/resolveVersion.js
+++ b/packages/gitbook/src/plugins/resolveVersion.js
@@ -1,12 +1,12 @@
-var npm = require('npm');
-var semver = require('semver');
-var Immutable = require('immutable');
+const npm = require('npm');
+const semver = require('semver');
+const Immutable = require('immutable');
-var Promise = require('../utils/promise');
-var Plugin = require('../models/plugin');
-var gitbook = require('../gitbook');
+const Promise = require('../utils/promise');
+const Plugin = require('../models/plugin');
+const gitbook = require('../gitbook');
-var npmIsReady;
+let npmIsReady;
/**
Initialize and prepare NPM
@@ -31,8 +31,8 @@ function initNPM() {
@return {Promise<String>}
*/
function resolveVersion(plugin) {
- var npmId = Plugin.nameToNpmID(plugin.getName());
- var requiredVersion = plugin.getVersion();
+ const npmId = Plugin.nameToNpmID(plugin.getName());
+ const requiredVersion = plugin.getVersion();
if (plugin.isGitDependency()) {
return Promise.resolve(requiredVersion);
@@ -45,7 +45,7 @@ function resolveVersion(plugin) {
.then(function(versions) {
versions = Immutable.Map(versions).entrySeq();
- var result = versions
+ const result = versions
.map(function(entry) {
return {
version: entry[0],
@@ -56,7 +56,7 @@ function resolveVersion(plugin) {
return v.gitbook && gitbook.satisfies(v.gitbook);
})
.sort(function(v1, v2) {
- return semver.lt(v1.version, v2.version)? 1 : -1;
+ return semver.lt(v1.version, v2.version) ? 1 : -1;
})
.get(0);
diff --git a/packages/gitbook/lib/plugins/sortDependencies.js b/packages/gitbook/src/plugins/sortDependencies.js
index 7f10095..2adfa20 100644
--- a/packages/gitbook/lib/plugins/sortDependencies.js
+++ b/packages/gitbook/src/plugins/sortDependencies.js
@@ -1,9 +1,9 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var THEME_PREFIX = require('../constants/themePrefix');
+const THEME_PREFIX = require('../constants/themePrefix');
-var TYPE_PLUGIN = 'plugin';
-var TYPE_THEME = 'theme';
+const TYPE_PLUGIN = 'plugin';
+const TYPE_THEME = 'theme';
/**
@@ -12,7 +12,7 @@ var TYPE_THEME = 'theme';
* @return {String}
*/
function pluginType(plugin) {
- var name = plugin.getName();
+ const name = plugin.getName();
return (name && name.indexOf(THEME_PREFIX) === 0) ? TYPE_THEME : TYPE_PLUGIN;
}
@@ -25,10 +25,10 @@ function pluginType(plugin) {
* @return {List<PluginDependency>}
*/
function sortDependencies(plugins) {
- var byTypes = plugins.groupBy(pluginType);
+ const byTypes = plugins.groupBy(pluginType);
return byTypes.get(TYPE_PLUGIN, Immutable.List())
.concat(byTypes.get(TYPE_THEME, Immutable.List()));
}
-module.exports = sortDependencies; \ No newline at end of file
+module.exports = sortDependencies;
diff --git a/packages/gitbook/lib/plugins/toNames.js b/packages/gitbook/src/plugins/toNames.js
index ad0dd8f..ad0dd8f 100644
--- a/packages/gitbook/lib/plugins/toNames.js
+++ b/packages/gitbook/src/plugins/toNames.js
diff --git a/packages/gitbook/lib/plugins/validateConfig.js b/packages/gitbook/src/plugins/validateConfig.js
index fab1fef..8e24775 100644
--- a/packages/gitbook/lib/plugins/validateConfig.js
+++ b/packages/gitbook/src/plugins/validateConfig.js
@@ -1,10 +1,10 @@
-var Immutable = require('immutable');
-var jsonschema = require('jsonschema');
-var jsonSchemaDefaults = require('json-schema-defaults');
+const Immutable = require('immutable');
+const jsonschema = require('jsonschema');
+const jsonSchemaDefaults = require('json-schema-defaults');
-var Promise = require('../utils/promise');
-var error = require('../utils/error');
-var mergeDefaults = require('../utils/mergeDefaults');
+const Promise = require('../utils/promise');
+const error = require('../utils/error');
+const mergeDefaults = require('../utils/mergeDefaults');
/**
Validate one plugin for a book and update book's confiration
@@ -14,17 +14,17 @@ var mergeDefaults = require('../utils/mergeDefaults');
@return {Book}
*/
function validatePluginConfig(book, plugin) {
- var config = book.getConfig();
- var packageInfos = plugin.getPackage();
+ let config = book.getConfig();
+ const packageInfos = plugin.getPackage();
- var configKey = [
+ const configKey = [
'pluginsConfig',
plugin.getName()
].join('.');
- var pluginConfig = config.getValue(configKey, {}).toJS();
+ let pluginConfig = config.getValue(configKey, {}).toJS();
- var schema = (packageInfos.get('gitbook') || Immutable.Map()).toJS();
+ const schema = (packageInfos.get('gitbook') || Immutable.Map()).toJS();
if (!schema) return book;
// Normalize schema
@@ -32,8 +32,8 @@ function validatePluginConfig(book, plugin) {
schema.type = 'object';
// Validate and throw if invalid
- var v = new jsonschema.Validator();
- var result = v.validate(pluginConfig, schema, {
+ const v = new jsonschema.Validator();
+ const result = v.validate(pluginConfig, schema, {
propertyName: configKey
});
@@ -43,7 +43,7 @@ function validatePluginConfig(book, plugin) {
}
// Insert default values
- var defaults = jsonSchemaDefaults(schema);
+ const defaults = jsonSchemaDefaults(schema);
pluginConfig = mergeDefaults(pluginConfig, defaults);
diff --git a/packages/gitbook/lib/plugins/validatePlugin.js b/packages/gitbook/src/plugins/validatePlugin.js
index 4baa911..f0e96ba 100644
--- a/packages/gitbook/lib/plugins/validatePlugin.js
+++ b/packages/gitbook/src/plugins/validatePlugin.js
@@ -1,6 +1,6 @@
-var gitbook = require('../gitbook');
+const gitbook = require('../gitbook');
-var Promise = require('../utils/promise');
+const Promise = require('../utils/promise');
/**
Validate a plugin
@@ -9,9 +9,9 @@ var Promise = require('../utils/promise');
@return {Promise<Plugin>}
*/
function validatePlugin(plugin) {
- var packageInfos = plugin.getPackage();
+ const packageInfos = plugin.getPackage();
- var isValid = (
+ const isValid = (
plugin.isLoaded() &&
packageInfos &&
packageInfos.get('name') &&
@@ -23,7 +23,7 @@ function validatePlugin(plugin) {
return Promise.reject(new Error('Error loading plugin "' + plugin.getName() + '" at "' + plugin.getPath() + '"'));
}
- var engine = packageInfos.get('engines').get('gitbook');
+ const engine = packageInfos.get('engines').get('gitbook');
if (!gitbook.satisfies(engine)) {
return Promise.reject(new Error('GitBook doesn\'t satisfy the requirements of this plugin: ' + engine));
}
diff --git a/packages/gitbook/lib/templating/__tests__/conrefsLoader.js b/packages/gitbook/src/templating/__tests__/conrefsLoader.js
index 196b513..431d0a3 100644
--- a/packages/gitbook/lib/templating/__tests__/conrefsLoader.js
+++ b/packages/gitbook/src/templating/__tests__/conrefsLoader.js
@@ -1,15 +1,15 @@
-var path = require('path');
+const path = require('path');
-var TemplateEngine = require('../../models/templateEngine');
-var renderTemplate = require('../render');
-var ConrefsLoader = require('../conrefsLoader');
+const TemplateEngine = require('../../models/templateEngine');
+const renderTemplate = require('../render');
+const ConrefsLoader = require('../conrefsLoader');
describe('ConrefsLoader', function() {
- var dirName = __dirname + '/';
- var fileName = path.join(dirName, 'test.md');
+ const dirName = __dirname + '/';
+ const fileName = path.join(dirName, 'test.md');
describe('Git', function() {
- var engine = TemplateEngine({
+ const engine = TemplateEngine({
loader: new ConrefsLoader(dirName)
});
@@ -36,7 +36,7 @@ describe('ConrefsLoader', function() {
});
describe('Local', function() {
- var engine = TemplateEngine({
+ const engine = TemplateEngine({
loader: new ConrefsLoader(dirName)
});
@@ -83,7 +83,7 @@ describe('ConrefsLoader', function() {
return 'test-' + source + '-endtest';
}
- var engine = TemplateEngine({
+ const engine = TemplateEngine({
loader: new ConrefsLoader(dirName, transform)
});
diff --git a/packages/gitbook/lib/templating/__tests__/include.md b/packages/gitbook/src/templating/__tests__/include.md
index 5e1c309..5e1c309 100644
--- a/packages/gitbook/lib/templating/__tests__/include.md
+++ b/packages/gitbook/src/templating/__tests__/include.md
diff --git a/packages/gitbook/lib/templating/__tests__/postRender.js b/packages/gitbook/src/templating/__tests__/postRender.js
index 131e29b..ff5bb61 100644
--- a/packages/gitbook/lib/templating/__tests__/postRender.js
+++ b/packages/gitbook/src/templating/__tests__/postRender.js
@@ -1,12 +1,12 @@
-var TemplateEngine = require('../../models/templateEngine');
-var TemplateBlock = require('../../models/templateBlock');
+const TemplateEngine = require('../../models/templateEngine');
+const TemplateBlock = require('../../models/templateBlock');
-var renderTemplate = require('../render');
-var postRender = require('../postRender');
+const renderTemplate = require('../render');
+const postRender = require('../postRender');
describe('postRender', function() {
- var testPost;
- var engine = TemplateEngine.create({
+ let testPost;
+ const engine = TemplateEngine.create({
blocks: [
TemplateBlock.create('lower', function(blk) {
return blk.body.toLowerCase();
@@ -14,7 +14,7 @@ describe('postRender', function() {
TemplateBlock.create('prefix', function(blk) {
return {
body: '_' + blk.body + '_',
- post: function() {
+ post() {
testPost = true;
}
};
diff --git a/packages/gitbook/lib/templating/__tests__/replaceShortcuts.js b/packages/gitbook/src/templating/__tests__/replaceShortcuts.js
index 216a1c8..cfd18b5 100644
--- a/packages/gitbook/lib/templating/__tests__/replaceShortcuts.js
+++ b/packages/gitbook/src/templating/__tests__/replaceShortcuts.js
@@ -1,10 +1,10 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
-var TemplateBlock = require('../../models/templateBlock');
-var replaceShortcuts = require('../replaceShortcuts');
+const TemplateBlock = require('../../models/templateBlock');
+const replaceShortcuts = require('../replaceShortcuts');
describe('replaceShortcuts', function() {
- var blocks = Immutable.List([
+ const blocks = Immutable.List([
TemplateBlock.create('math', {
shortcuts: {
start: '$$',
@@ -15,12 +15,12 @@ describe('replaceShortcuts', function() {
]);
it('should correctly replace inline matches by block', function() {
- var content = replaceShortcuts(blocks, 'test.md', 'Hello $$a = b$$');
+ const content = replaceShortcuts(blocks, 'test.md', 'Hello $$a = b$$');
expect(content).toBe('Hello {% math %}a = b{% endmath %}');
});
it('should correctly replace block matches', function() {
- var content = replaceShortcuts(blocks, 'test.md', 'Hello\n$$\na = b\n$$\n');
+ const content = replaceShortcuts(blocks, 'test.md', 'Hello\n$$\na = b\n$$\n');
expect(content).toBe('Hello\n{% math %}\na = b\n{% endmath %}\n');
});
});
diff --git a/packages/gitbook/lib/templating/conrefsLoader.js b/packages/gitbook/src/templating/conrefsLoader.js
index b3cdb3f..4024a19 100644
--- a/packages/gitbook/lib/templating/conrefsLoader.js
+++ b/packages/gitbook/src/templating/conrefsLoader.js
@@ -1,10 +1,10 @@
-var path = require('path');
-var nunjucks = require('nunjucks');
+const path = require('path');
+const nunjucks = require('nunjucks');
-var fs = require('../utils/fs');
-var Git = require('../utils/git');
-var LocationUtils = require('../utils/location');
-var PathUtils = require('../utils/path');
+const fs = require('../utils/fs');
+const Git = require('../utils/git');
+const LocationUtils = require('../utils/location');
+const PathUtils = require('../utils/path');
/**
@@ -17,18 +17,18 @@ var PathUtils = require('../utils/path');
* @param {Function(filePath, source)} transformFn (optional)
* @param {Logger} logger (optional)
*/
-var ConrefsLoader = nunjucks.Loader.extend({
+const ConrefsLoader = nunjucks.Loader.extend({
async: true,
- init: function(rootFolder, transformFn, logger) {
+ init(rootFolder, transformFn, logger) {
this.rootFolder = rootFolder;
this.transformFn = transformFn;
this.logger = logger;
this.git = new Git();
},
- getSource: function(sourceURL, callback) {
- var that = this;
+ getSource(sourceURL, callback) {
+ const that = this;
this.git.resolve(sourceURL)
.then(function(filepath) {
@@ -60,22 +60,22 @@ var ConrefsLoader = nunjucks.Loader.extend({
.nodeify(callback);
},
- resolve: function(from, to) {
+ resolve(from, to) {
// If origin is in the book, we enforce result file to be in the book
if (PathUtils.isInRoot(this.rootFolder, from)) {
// Path of current template in the rootFolder (not absolute to fs)
- var fromRelative = path.relative(this.rootFolder, from);
+ const fromRelative = path.relative(this.rootFolder, from);
// Resolve "to" to a filepath relative to rootFolder
- var href = LocationUtils.toAbsolute(to, path.dirname(fromRelative), '');
+ const href = LocationUtils.toAbsolute(to, path.dirname(fromRelative), '');
// Return absolute path
return PathUtils.resolveInRoot(this.rootFolder, href);
}
// If origin is in a git repository, we resolve file in the git repository
- var gitRoot = this.git.resolveRoot(from);
+ const gitRoot = this.git.resolveRoot(from);
if (gitRoot) {
return PathUtils.resolveInRoot(gitRoot, to);
}
@@ -85,7 +85,7 @@ var ConrefsLoader = nunjucks.Loader.extend({
},
// Handle all files as relative, so that nunjucks pass responsability to 'resolve'
- isRelative: function(filename) {
+ isRelative(filename) {
return LocationUtils.isRelative(filename);
}
});
diff --git a/packages/gitbook/lib/templating/index.js b/packages/gitbook/src/templating/index.js
index bd74aca..bd74aca 100644
--- a/packages/gitbook/lib/templating/index.js
+++ b/packages/gitbook/src/templating/index.js
diff --git a/packages/gitbook/lib/templating/listShortcuts.js b/packages/gitbook/src/templating/listShortcuts.js
index 8d0a64a..5df88bb 100644
--- a/packages/gitbook/lib/templating/listShortcuts.js
+++ b/packages/gitbook/src/templating/listShortcuts.js
@@ -1,5 +1,5 @@
-var Immutable = require('immutable');
-var parsers = require('../parsers');
+const Immutable = require('immutable');
+const parsers = require('../parsers');
/**
* Return a list of all shortcuts that can apply
@@ -10,7 +10,7 @@ var parsers = require('../parsers');
* @return {List<TemplateShortcut>}
*/
function listShortcuts(blocks, filePath) {
- var parser = parsers.getForFile(filePath);
+ const parser = parsers.getForFile(filePath);
if (!parser) {
return Immutable.List();
diff --git a/packages/gitbook/lib/templating/postRender.js b/packages/gitbook/src/templating/postRender.js
index f464f86..7fdfbf4 100644
--- a/packages/gitbook/lib/templating/postRender.js
+++ b/packages/gitbook/src/templating/postRender.js
@@ -1,4 +1,4 @@
-var Promise = require('../utils/promise');
+const Promise = require('../utils/promise');
/**
@@ -9,10 +9,10 @@ var Promise = require('../utils/promise');
* @return {Object} {blocks: Set, content: String}
*/
function replaceBlocks(content, blocks) {
- var newContent = content.replace(/\{\{\-\%([\s\S]+?)\%\-\}\}/g, function(match, key) {
- var replacedWith = match;
+ const newContent = content.replace(/\{\{\-\%([\s\S]+?)\%\-\}\}/g, function(match, key) {
+ let replacedWith = match;
- var block = blocks.get(key);
+ const block = blocks.get(key);
if (block) {
replacedWith = replaceBlocks(block.get('body'), blocks);
}
@@ -33,13 +33,13 @@ function replaceBlocks(content, blocks) {
* @return {Promise<String>}
*/
function postRender(engine, output) {
- var content = output.getContent();
- var blocks = output.getBlocks();
+ const content = output.getContent();
+ const blocks = output.getBlocks();
- var result = replaceBlocks(content, blocks);
+ const result = replaceBlocks(content, blocks);
return Promise.forEach(blocks, function(block) {
- var post = block.get('post');
+ const post = block.get('post');
if (!post) {
return;
diff --git a/packages/gitbook/lib/templating/render.js b/packages/gitbook/src/templating/render.js
index 1a8b0cd..53ed546 100644
--- a/packages/gitbook/lib/templating/render.js
+++ b/packages/gitbook/src/templating/render.js
@@ -1,7 +1,7 @@
-var Promise = require('../utils/promise');
-var timing = require('../utils/timing');
-var TemplateOutput = require('../models/templateOutput');
-var replaceShortcuts = require('./replaceShortcuts');
+const Promise = require('../utils/promise');
+const timing = require('../utils/timing');
+const TemplateOutput = require('../models/templateOutput');
+const replaceShortcuts = require('./replaceShortcuts');
/**
* Render a template
@@ -16,10 +16,10 @@ function renderTemplate(engine, filePath, content, context) {
context = context || {};
// Mutable objects to contains all blocks requiring post-processing
- var blocks = {};
+ const blocks = {};
// Create nunjucks environment
- var env = engine.toNunjucks(blocks);
+ const env = engine.toNunjucks(blocks);
// Replace shortcuts from plugin's blocks
content = replaceShortcuts(engine.getBlocks(), filePath, content);
diff --git a/packages/gitbook/lib/templating/renderFile.js b/packages/gitbook/src/templating/renderFile.js
index 8672e8b..a2463f8 100644
--- a/packages/gitbook/lib/templating/renderFile.js
+++ b/packages/gitbook/src/templating/renderFile.js
@@ -1,6 +1,6 @@
-var Promise = require('../utils/promise');
-var error = require('../utils/error');
-var render = require('./render');
+const Promise = require('../utils/promise');
+const error = require('../utils/error');
+const render = require('./render');
/**
* Render a template
@@ -11,10 +11,10 @@ var render = require('./render');
* @return {Promise<TemplateOutput>}
*/
function renderTemplateFile(engine, filePath, context) {
- var loader = engine.getLoader();
+ const loader = engine.getLoader();
// Resolve the filePath
- var resolvedFilePath = loader.resolve(null, filePath);
+ const resolvedFilePath = loader.resolve(null, filePath);
return Promise()
.then(function() {
@@ -22,7 +22,7 @@ function renderTemplateFile(engine, filePath, context) {
return loader.getSource(resolvedFilePath);
}
- var deferred = Promise.defer();
+ const deferred = Promise.defer();
loader.getSource(resolvedFilePath, deferred.makeNodeResolver());
return deferred.promise;
})
diff --git a/packages/gitbook/lib/templating/replaceShortcuts.js b/packages/gitbook/src/templating/replaceShortcuts.js
index 1cfdbf0..25f598f 100644
--- a/packages/gitbook/lib/templating/replaceShortcuts.js
+++ b/packages/gitbook/src/templating/replaceShortcuts.js
@@ -1,5 +1,5 @@
-var escapeStringRegexp = require('escape-string-regexp');
-var listShortcuts = require('./listShortcuts');
+const escapeStringRegexp = require('escape-string-regexp');
+const listShortcuts = require('./listShortcuts');
/**
* Apply a shortcut of block to a template
@@ -8,13 +8,13 @@ var listShortcuts = require('./listShortcuts');
* @return {String}
*/
function applyShortcut(content, shortcut) {
- var start = shortcut.getStart();
- var end = shortcut.getEnd();
+ const start = shortcut.getStart();
+ const end = shortcut.getEnd();
- var tagStart = shortcut.getStartTag();
- var tagEnd = shortcut.getEndTag();
+ const tagStart = shortcut.getStartTag();
+ const tagEnd = shortcut.getEndTag();
- var regex = new RegExp(
+ const regex = new RegExp(
escapeStringRegexp(start) + '([\\s\\S]*?[^\\$])' + escapeStringRegexp(end),
'g'
);
@@ -32,7 +32,7 @@ function applyShortcut(content, shortcut) {
* @return {String}
*/
function replaceShortcuts(blocks, filePath, content) {
- var shortcuts = listShortcuts(blocks, filePath);
+ const shortcuts = listShortcuts(blocks, filePath);
return shortcuts.reduce(applyShortcut, content);
}
diff --git a/packages/gitbook/lib/templating/themesLoader.js b/packages/gitbook/src/templating/themesLoader.js
index bae4c12..b1639c5 100644
--- a/packages/gitbook/lib/templating/themesLoader.js
+++ b/packages/gitbook/src/templating/themesLoader.js
@@ -1,13 +1,13 @@
-var Immutable = require('immutable');
-var nunjucks = require('nunjucks');
-var fs = require('fs');
-var path = require('path');
+const Immutable = require('immutable');
+const nunjucks = require('nunjucks');
+const fs = require('fs');
+const path = require('path');
-var PathUtils = require('../utils/path');
+const PathUtils = require('../utils/path');
-var ThemesLoader = nunjucks.Loader.extend({
- init: function(searchPaths) {
+const ThemesLoader = nunjucks.Loader.extend({
+ init(searchPaths) {
this.searchPaths = Immutable.List(searchPaths)
.map(path.normalize);
},
@@ -17,24 +17,24 @@ var ThemesLoader = nunjucks.Loader.extend({
* @param {String}
* @return {Object}
*/
- getSource: function(fullpath) {
+ getSource(fullpath) {
if (!fullpath) return null;
fullpath = this.resolve(null, fullpath);
- var templateName = this.getTemplateName(fullpath);
+ const templateName = this.getTemplateName(fullpath);
- if(!fullpath) {
+ if (!fullpath) {
return null;
}
- var src = fs.readFileSync(fullpath, 'utf-8');
+ let src = fs.readFileSync(fullpath, 'utf-8');
src = '{% do %}var template = template || {}; template.stack = template.stack || []; template.stack.push(template.self); template.self = ' + JSON.stringify(templateName) + '{% enddo %}\n' +
src +
'\n{% do %}template.self = template.stack.pop();{% enddo %}';
return {
- src: src,
+ src,
path: fullpath,
noCache: true
};
@@ -44,7 +44,7 @@ var ThemesLoader = nunjucks.Loader.extend({
* Nunjucks calls "isRelative" to determine when to call "resolve".
* We handle absolute paths ourselves in ".resolve" so we always return true
*/
- isRelative: function() {
+ isRelative() {
return true;
},
@@ -53,7 +53,7 @@ var ThemesLoader = nunjucks.Loader.extend({
* @param {String} filepath
* @return {String} searchPath
*/
- getSearchPath: function(filepath) {
+ getSearchPath(filepath) {
return this.searchPaths
.sortBy(function(s) {
return -s.length;
@@ -68,9 +68,9 @@ var ThemesLoader = nunjucks.Loader.extend({
* @param {String} filepath
* @return {String} name
*/
- getTemplateName: function(filepath) {
- var originalSearchPath = this.getSearchPath(filepath);
- return originalSearchPath? path.relative(originalSearchPath, filepath) : null;
+ getTemplateName(filepath) {
+ const originalSearchPath = this.getSearchPath(filepath);
+ return originalSearchPath ? path.relative(originalSearchPath, filepath) : null;
},
/**
@@ -79,8 +79,8 @@ var ThemesLoader = nunjucks.Loader.extend({
* @param {String} to
* @return {String|null}
*/
- resolve: function(from, to) {
- var searchPaths = this.searchPaths;
+ resolve(from, to) {
+ let searchPaths = this.searchPaths;
// Relative template like "./test.html"
if (PathUtils.isPureRelative(to) && from) {
@@ -88,19 +88,19 @@ var ThemesLoader = nunjucks.Loader.extend({
}
// Determine in which search folder we currently are
- var originalSearchPath = this.getSearchPath(from);
- var originalFilename = this.getTemplateName(from);
+ const originalSearchPath = this.getSearchPath(from);
+ const originalFilename = this.getTemplateName(from);
// If we are including same file from a different search path
// Slice the search paths to avoid including from previous ones
if (originalFilename == to) {
- var currentIndex = searchPaths.indexOf(originalSearchPath);
+ const currentIndex = searchPaths.indexOf(originalSearchPath);
searchPaths = searchPaths.slice(currentIndex + 1);
}
// Absolute template to resolve in root folder
- var resultFolder = searchPaths.find(function(basePath) {
- var p = path.resolve(basePath, to);
+ const resultFolder = searchPaths.find(function(basePath) {
+ const p = path.resolve(basePath, to);
return (
p.indexOf(basePath) === 0
diff --git a/packages/gitbook/lib/utils/__tests__/git.js b/packages/gitbook/src/utils/__tests__/git.js
index abc1ea1..445b8eb 100644
--- a/packages/gitbook/lib/utils/__tests__/git.js
+++ b/packages/gitbook/src/utils/__tests__/git.js
@@ -1,7 +1,7 @@
-var path = require('path');
-var os = require('os');
+const path = require('path');
+const os = require('os');
-var Git = require('../git');
+const Git = require('../git');
describe('Git', function() {
@@ -20,7 +20,7 @@ describe('Git', function() {
});
it('should parse HTTPS urls', function() {
- var parts = Git.parseUrl('git+https://gist.github.com/69ea4542e4c8967d2fa7.git/test.md');
+ const parts = Git.parseUrl('git+https://gist.github.com/69ea4542e4c8967d2fa7.git/test.md');
expect(parts.host).toBe('https://gist.github.com/69ea4542e4c8967d2fa7.git');
expect(parts.ref).toBe(null);
@@ -28,7 +28,7 @@ describe('Git', function() {
});
it('should parse HTTPS urls with a reference', function() {
- var parts = Git.parseUrl('git+https://gist.github.com/69ea4542e4c8967d2fa7.git/test.md#1.0.0');
+ const parts = Git.parseUrl('git+https://gist.github.com/69ea4542e4c8967d2fa7.git/test.md#1.0.0');
expect(parts.host).toBe('https://gist.github.com/69ea4542e4c8967d2fa7.git');
expect(parts.ref).toBe('1.0.0');
@@ -36,7 +36,7 @@ describe('Git', function() {
});
it('should parse SSH urls', function() {
- var parts = Git.parseUrl('git+git@github.com:GitbookIO/gitbook.git/directory/README.md#e1594cde2c32e4ff48f6c4eff3d3d461743d74e1');
+ const parts = Git.parseUrl('git+git@github.com:GitbookIO/gitbook.git/directory/README.md#e1594cde2c32e4ff48f6c4eff3d3d461743d74e1');
expect(parts.host).toBe('git@github.com:GitbookIO/gitbook.git');
expect(parts.ref).toBe('e1594cde2c32e4ff48f6c4eff3d3d461743d74e1');
@@ -46,7 +46,7 @@ describe('Git', function() {
describe('Cloning and resolving', function() {
it('should clone an HTTPS url', function() {
- var git = new Git(path.join(os.tmpdir(), 'test-git-'+Date.now()));
+ const git = new Git(path.join(os.tmpdir(), 'test-git-' + Date.now()));
return git.resolve('git+https://gist.github.com/69ea4542e4c8967d2fa7.git/test.md')
.then(function(filename) {
expect(path.extname(filename)).toBe('.md');
diff --git a/packages/gitbook/lib/utils/__tests__/location.js b/packages/gitbook/src/utils/__tests__/location.js
index 822338e..a565adb 100644
--- a/packages/gitbook/lib/utils/__tests__/location.js
+++ b/packages/gitbook/src/utils/__tests__/location.js
@@ -1,4 +1,4 @@
-var LocationUtils = require('../location');
+const LocationUtils = require('../location');
describe('LocationUtils', function() {
it('should correctly test external location', function() {
@@ -97,4 +97,3 @@ describe('LocationUtils', function() {
});
-
diff --git a/packages/gitbook/lib/utils/__tests__/path.js b/packages/gitbook/src/utils/__tests__/path.js
index 22bb016..1f8a1d3 100644
--- a/packages/gitbook/lib/utils/__tests__/path.js
+++ b/packages/gitbook/src/utils/__tests__/path.js
@@ -1,7 +1,7 @@
-var path = require('path');
+const path = require('path');
describe('Paths', function() {
- var PathUtils = require('..//path');
+ const PathUtils = require('..//path');
describe('setExtension', function() {
it('should correctly change extension of filename', function() {
diff --git a/packages/gitbook/lib/utils/command.js b/packages/gitbook/src/utils/command.js
index 90a556e..efa9699 100644
--- a/packages/gitbook/lib/utils/command.js
+++ b/packages/gitbook/src/utils/command.js
@@ -1,7 +1,7 @@
-var is = require('is');
-var childProcess = require('child_process');
-var spawn = require('spawn-cmd').spawn;
-var Promise = require('./promise');
+const is = require('is');
+const childProcess = require('child_process');
+const spawn = require('spawn-cmd').spawn;
+const Promise = require('./promise');
/**
Execute a command
@@ -11,9 +11,9 @@ var Promise = require('./promise');
@return {Promise}
*/
function exec(command, options) {
- var d = Promise.defer();
+ const d = Promise.defer();
- var child = childProcess.exec(command, options, function(err, stdout, stderr) {
+ const child = childProcess.exec(command, options, function(err, stdout, stderr) {
if (!err) {
return d.resolve();
}
@@ -22,11 +22,11 @@ function exec(command, options) {
d.reject(err);
});
- child.stdout.on('data', function (data) {
+ child.stdout.on('data', function(data) {
d.notify(data);
});
- child.stderr.on('data', function (data) {
+ child.stderr.on('data', function(data) {
d.notify(data);
});
@@ -42,18 +42,18 @@ function exec(command, options) {
@return {Promise}
*/
function spawnCmd(command, args, options) {
- var d = Promise.defer();
- var child = spawn(command, args, options);
+ const d = Promise.defer();
+ const child = spawn(command, args, options);
child.on('error', function(error) {
return d.reject(error);
});
- child.stdout.on('data', function (data) {
+ child.stdout.on('data', function(data) {
d.notify(data);
});
- child.stderr.on('data', function (data) {
+ child.stderr.on('data', function(data) {
d.notify(data);
});
@@ -61,7 +61,7 @@ function spawnCmd(command, args, options) {
if (code === 0) {
d.resolve();
} else {
- d.reject(new Error('Error with command "'+command+'"'));
+ d.reject(new Error('Error with command "' + command + '"'));
}
});
@@ -92,10 +92,10 @@ function escapeShellArg(value) {
@return {String}
*/
function optionsToShellArgs(options) {
- var result = [];
+ const result = [];
- for (var key in options) {
- var value = options[key];
+ for (const key in options) {
+ const value = options[key];
if (value === null || value === undefined || value === false) {
continue;
@@ -112,7 +112,7 @@ function optionsToShellArgs(options) {
}
module.exports = {
- exec: exec,
+ exec,
spawn: spawnCmd,
- optionsToShellArgs: optionsToShellArgs
+ optionsToShellArgs
};
diff --git a/packages/gitbook/lib/utils/error.js b/packages/gitbook/src/utils/error.js
index 7686779..925b5ff 100644
--- a/packages/gitbook/lib/utils/error.js
+++ b/packages/gitbook/src/utils/error.js
@@ -1,7 +1,7 @@
-var is = require('is');
+const is = require('is');
-var TypedError = require('error/typed');
-var WrappedError = require('error/wrapped');
+const TypedError = require('error/typed');
+const WrappedError = require('error/wrapped');
// Enforce as an Error object, and cleanup message
@@ -13,31 +13,31 @@ function enforce(err) {
}
// Random error wrappers during parsing/generation
-var ParsingError = WrappedError({
+const ParsingError = WrappedError({
message: 'Parsing Error: {origMessage}',
type: 'parse'
});
-var OutputError = WrappedError({
+const OutputError = WrappedError({
message: 'Output Error: {origMessage}',
type: 'generate'
});
// A file does not exists
-var FileNotFoundError = TypedError({
+const FileNotFoundError = TypedError({
type: 'file.not-found',
message: 'No "{filename}" file (or is ignored)',
filename: null
});
// A file cannot be parsed
-var FileNotParsableError = TypedError({
+const FileNotParsableError = TypedError({
type: 'file.not-parsable',
message: '"{filename}" file cannot be parsed',
filename: null
});
// A file is outside the scope
-var FileOutOfScopeError = TypedError({
+const FileOutOfScopeError = TypedError({
type: 'file.out-of-scope',
message: '"{filename}" not in "{root}"',
filename: null,
@@ -46,7 +46,7 @@ var FileOutOfScopeError = TypedError({
});
// A file is outside the scope
-var RequireInstallError = TypedError({
+const RequireInstallError = TypedError({
type: 'install.required',
message: '"{cmd}" is not installed.\n{install}',
cmd: null,
@@ -55,45 +55,45 @@ var RequireInstallError = TypedError({
});
// Error for nunjucks templates
-var TemplateError = WrappedError({
+const TemplateError = WrappedError({
message: 'Error compiling template "{filename}": {origMessage}',
type: 'template',
filename: null
});
// Error for nunjucks templates
-var PluginError = WrappedError({
+const PluginError = WrappedError({
message: 'Error with plugin "{plugin}": {origMessage}',
type: 'plugin',
plugin: null
});
// Error with the book's configuration
-var ConfigurationError = WrappedError({
+const ConfigurationError = WrappedError({
message: 'Error with book\'s configuration: {origMessage}',
type: 'configuration'
});
// Error during ebook generation
-var EbookError = WrappedError({
+const EbookError = WrappedError({
message: 'Error during ebook generation: {origMessage}\n{stdout}',
type: 'ebook',
stdout: ''
});
module.exports = {
- enforce: enforce,
+ enforce,
- ParsingError: ParsingError,
- OutputError: OutputError,
- RequireInstallError: RequireInstallError,
+ ParsingError,
+ OutputError,
+ RequireInstallError,
- FileNotParsableError: FileNotParsableError,
- FileNotFoundError: FileNotFoundError,
- FileOutOfScopeError: FileOutOfScopeError,
+ FileNotParsableError,
+ FileNotFoundError,
+ FileOutOfScopeError,
- TemplateError: TemplateError,
- PluginError: PluginError,
- ConfigurationError: ConfigurationError,
- EbookError: EbookError
+ TemplateError,
+ PluginError,
+ ConfigurationError,
+ EbookError
};
diff --git a/packages/gitbook/lib/utils/fs.js b/packages/gitbook/src/utils/fs.js
index 35839a3..17b2ebb 100644
--- a/packages/gitbook/lib/utils/fs.js
+++ b/packages/gitbook/src/utils/fs.js
@@ -1,30 +1,30 @@
-var fs = require('graceful-fs');
-var mkdirp = require('mkdirp');
-var destroy = require('destroy');
-var rmdir = require('rmdir');
-var tmp = require('tmp');
-var request = require('request');
-var path = require('path');
-var cp = require('cp');
-var cpr = require('cpr');
-
-var Promise = require('./promise');
+const fs = require('graceful-fs');
+const mkdirp = require('mkdirp');
+const destroy = require('destroy');
+const rmdir = require('rmdir');
+const tmp = require('tmp');
+const request = require('request');
+const path = require('path');
+const cp = require('cp');
+const cpr = require('cpr');
+
+const Promise = require('./promise');
// Write a stream to a file
function writeStream(filename, st) {
- var d = Promise.defer();
+ const d = Promise.defer();
- var wstream = fs.createWriteStream(filename);
- var cleanup = function() {
+ const wstream = fs.createWriteStream(filename);
+ const cleanup = function() {
destroy(wstream);
wstream.removeAllListeners();
};
- wstream.on('finish', function () {
+ wstream.on('finish', function() {
cleanup();
d.resolve();
});
- wstream.on('error', function (err) {
+ wstream.on('error', function(err) {
cleanup();
d.reject(err);
});
@@ -41,7 +41,7 @@ function writeStream(filename, st) {
// Return a promise resolved with a boolean
function fileExists(filename) {
- var d = Promise.defer();
+ const d = Promise.defer();
fs.exists(filename, function(exists) {
d.resolve(exists);
@@ -69,13 +69,13 @@ function download(uri, dest) {
// Find a filename available in a folder
function uniqueFilename(base, filename) {
- var ext = path.extname(filename);
+ const ext = path.extname(filename);
filename = path.resolve(base, filename);
filename = path.join(path.dirname(filename), path.basename(filename, ext));
- var _filename = filename+ext;
+ let _filename = filename + ext;
- var i = 0;
+ let i = 0;
while (fs.existsSync(filename)) {
_filename = filename + '_' + i + ext;
i = i + 1;
@@ -86,14 +86,14 @@ function uniqueFilename(base, filename) {
// Create all required folder to create a file
function ensureFile(filename) {
- var base = path.dirname(filename);
+ const base = path.dirname(filename);
return Promise.nfcall(mkdirp, base);
}
// Remove a folder
function rmDir(base) {
return Promise.nfcall(rmdir, base, {
- fs: fs
+ fs
});
}
@@ -121,7 +121,7 @@ function assertFile(filePath, generator) {
@return {String}
*/
function pickFile(rootFolder, fileName) {
- var result = path.join(rootFolder, fileName);
+ const result = path.join(rootFolder, fileName);
if (fs.existsSync(result)) {
return result;
}
@@ -151,20 +151,20 @@ module.exports = {
mkdirp: Promise.nfbind(mkdirp),
readFile: Promise.nfbind(fs.readFile),
writeFile: Promise.nfbind(fs.writeFile),
- assertFile: assertFile,
- pickFile: pickFile,
+ assertFile,
+ pickFile,
stat: Promise.nfbind(fs.stat),
statSync: fs.statSync,
readdir: Promise.nfbind(fs.readdir),
- writeStream: writeStream,
+ writeStream,
readStream: fs.createReadStream,
copy: Promise.nfbind(cp),
copyDir: Promise.nfbind(cpr),
tmpFile: genTmpFile,
tmpDir: genTmpDir,
- download: download,
- uniqueFilename: uniqueFilename,
- ensureFile: ensureFile,
- ensureFolder: ensureFolder,
- rmDir: rmDir
+ download,
+ uniqueFilename,
+ ensureFile,
+ ensureFolder,
+ rmDir
};
diff --git a/packages/gitbook/lib/utils/genKey.js b/packages/gitbook/src/utils/genKey.js
index 0650011..e4982f4 100644
--- a/packages/gitbook/lib/utils/genKey.js
+++ b/packages/gitbook/src/utils/genKey.js
@@ -1,4 +1,4 @@
-var lastKey = 0;
+let lastKey = 0;
/*
Generate a random key
@@ -6,7 +6,7 @@ var lastKey = 0;
*/
function generateKey() {
lastKey += 1;
- var str = lastKey.toString(16);
+ const str = lastKey.toString(16);
return '00000'.slice(str.length) + str;
}
diff --git a/packages/gitbook/src/utils/git.js b/packages/gitbook/src/utils/git.js
new file mode 100644
index 0000000..8ec23dd
--- /dev/null
+++ b/packages/gitbook/src/utils/git.js
@@ -0,0 +1,135 @@
+const is = require('is');
+const path = require('path');
+const crc = require('crc');
+const URI = require('urijs');
+
+const pathUtil = require('./path');
+const Promise = require('./promise');
+const command = require('./command');
+const fs = require('./fs');
+
+const GIT_PREFIX = 'git+';
+
+class Git {
+ constructor() {
+ this.tmpDir = null;
+ this.cloned = {};
+ }
+
+ // Return an unique ID for a combinaison host/ref
+ repoID(host, ref) {
+ return crc.crc32(host + '#' + (ref || '')).toString(16);
+ }
+
+ // Allocate a temporary folder for cloning repos in it
+ allocateDir() {
+ const that = this;
+
+ if (this.tmpDir) return Promise();
+
+ return fs.tmpDir()
+ .then(function(dir) {
+ that.tmpDir = dir;
+ });
+ }
+
+ // Clone a git repository if non existant
+ clone(host, ref) {
+ const that = this;
+
+ return this.allocateDir()
+
+ // Return or clone the git repo
+ .then(function() {
+ // Unique ID for repo/ref combinaison
+ const repoId = that.repoID(host, ref);
+
+ // Absolute path to the folder
+ const repoPath = path.join(that.tmpDir, repoId);
+
+ if (that.cloned[repoId]) return repoPath;
+
+ // Clone repo
+ return command.exec('git clone ' + host + ' ' + repoPath)
+
+ // Checkout reference if specified
+ .then(function() {
+ that.cloned[repoId] = true;
+
+ if (!ref) return;
+ return command.exec('git checkout ' + ref, { cwd: repoPath });
+ })
+ .thenResolve(repoPath);
+ });
+ }
+
+ // Get file from a git repo
+ resolve(giturl) {
+ // Path to a file in a git repo?
+ if (!Git.isUrl(giturl)) {
+ if (this.resolveRoot(giturl)) return Promise(giturl);
+ return Promise(null);
+ }
+ if (is.string(giturl)) giturl = Git.parseUrl(giturl);
+ if (!giturl) return Promise(null);
+
+ // Clone or get from cache
+ return this.clone(giturl.host, giturl.ref)
+ .then(function(repo) {
+ return path.resolve(repo, giturl.filepath);
+ });
+ }
+
+ // Return root of git repo from a filepath
+ resolveRoot(filepath) {
+ // No git repo cloned, or file is not in a git repository
+ if (!this.tmpDir || !pathUtil.isInRoot(this.tmpDir, filepath)) return null;
+
+ // Extract first directory (is the repo id)
+ const relativeToGit = path.relative(this.tmpDir, filepath);
+ const repoId = relativeToGit.split(path.sep)[0];
+
+ if (!repoId) {
+ return;
+ }
+
+ // Return an absolute file
+ return path.resolve(this.tmpDir, repoId);
+ }
+
+ // Check if an url is a git dependency url
+ static isUrl(giturl) {
+ return (giturl.indexOf(GIT_PREFIX) === 0);
+ }
+
+ // Parse and extract infos
+ static parseUrl(giturl) {
+ if (!Git.isUrl(giturl)) {
+ return null;
+ }
+ giturl = giturl.slice(GIT_PREFIX.length);
+
+ const uri = new URI(giturl);
+ const ref = uri.fragment() || null;
+ uri.fragment(null);
+
+ // Extract file inside the repo (after the .git)
+ const fileParts = uri.path().split('.git');
+ let filepath = fileParts.length > 1 ? fileParts.slice(1).join('.git') : '';
+ if (filepath[0] == '/') {
+ filepath = filepath.slice(1);
+ }
+
+ // Recreate pathname without the real filename
+ uri.path(fileParts[0] + '.git');
+
+ return {
+ host: uri.toString(),
+ ref,
+ filepath
+ };
+ }
+
+}
+
+module.exports = Git;
diff --git a/packages/gitbook/lib/utils/images.js b/packages/gitbook/src/utils/images.js
index 6d4b927..808be63 100644
--- a/packages/gitbook/lib/utils/images.js
+++ b/packages/gitbook/src/utils/images.js
@@ -1,7 +1,7 @@
-var Promise = require('./promise');
-var command = require('./command');
-var fs = require('./fs');
-var error = require('./error');
+const Promise = require('./promise');
+const command = require('./command');
+const fs = require('./fs');
+const error = require('./error');
// Convert a svg file to a pmg
function convertSVGToPNG(source, dest, options) {
@@ -20,7 +20,7 @@ function convertSVGToPNG(source, dest, options) {
.then(function() {
if (fs.existsSync(dest)) return;
- throw new Error('Error converting '+source+' into '+dest);
+ throw new Error('Error converting ' + source + ' into ' + dest);
});
}
@@ -42,19 +42,19 @@ function convertSVGBufferToPNG(buf, dest) {
function convertInlinePNG(source, dest) {
if (!/^data\:image\/png/.test(source)) return Promise.reject(new Error('Source is not a PNG data-uri'));
- var base64data = source.split('data:image/png;base64,')[1];
- var buf = new Buffer(base64data, 'base64');
+ const base64data = source.split('data:image/png;base64,')[1];
+ const buf = new Buffer(base64data, 'base64');
return fs.writeFile(dest, buf)
.then(function() {
if (fs.existsSync(dest)) return;
- throw new Error('Error converting '+source+' into '+dest);
+ throw new Error('Error converting ' + source + ' into ' + dest);
});
}
module.exports = {
- convertSVGToPNG: convertSVGToPNG,
- convertSVGBufferToPNG: convertSVGBufferToPNG,
- convertInlinePNG: convertInlinePNG
-}; \ No newline at end of file
+ convertSVGToPNG,
+ convertSVGBufferToPNG,
+ convertInlinePNG
+};
diff --git a/packages/gitbook/lib/utils/location.js b/packages/gitbook/src/utils/location.js
index 00d8004..6dc41ba 100644
--- a/packages/gitbook/lib/utils/location.js
+++ b/packages/gitbook/src/utils/location.js
@@ -1,11 +1,11 @@
-var url = require('url');
-var path = require('path');
+const url = require('url');
+const path = require('path');
// Is the url an external url
function isExternal(href) {
try {
return Boolean(url.parse(href).protocol) && !isDataURI(href);
- } catch(err) {
+ } catch (err) {
return false;
}
}
@@ -14,7 +14,7 @@ function isExternal(href) {
function isDataURI(href) {
try {
return Boolean(url.parse(href).protocol) && (url.parse(href).protocol === 'data:');
- } catch(err) {
+ } catch (err) {
return false;
}
}
@@ -27,9 +27,9 @@ function isRelative(href) {
// Return true if the link is an achor
function isAnchor(href) {
try {
- var parsed = url.parse(href);
+ const parsed = url.parse(href);
return !!(!parsed.protocol && !parsed.path && parsed.hash);
- } catch(err) {
+ } catch (err) {
return false;
}
}
@@ -67,14 +67,14 @@ function toAbsolute(_href, dir, outdir) {
return _href;
}
- outdir = outdir == undefined? dir : outdir;
+ outdir = outdir == undefined ? dir : outdir;
_href = normalize(_href);
dir = normalize(dir);
outdir = normalize(outdir);
// Path "_href" inside the base folder
- var hrefInRoot = normalize(path.join(dir, _href));
+ let hrefInRoot = normalize(path.join(dir, _href));
if (_href[0] == '/') {
hrefInRoot = normalize(_href.slice(1));
}
@@ -97,8 +97,8 @@ function toAbsolute(_href, dir, outdir) {
* @return {String}
*/
function relative(dir, file) {
- var isDirectory = file.slice(-1) === '/';
- return normalize(path.relative(dir, file)) + (isDirectory? '/': '');
+ const isDirectory = file.slice(-1) === '/';
+ return normalize(path.relative(dir, file)) + (isDirectory ? '/' : '');
}
/**
@@ -126,14 +126,14 @@ function areIdenticalPaths(p1, p2) {
}
module.exports = {
- areIdenticalPaths: areIdenticalPaths,
- isDataURI: isDataURI,
- isExternal: isExternal,
- isRelative: isRelative,
- isAnchor: isAnchor,
- normalize: normalize,
- toAbsolute: toAbsolute,
- relative: relative,
- relativeForFile: relativeForFile,
- flatten: flatten
+ areIdenticalPaths,
+ isDataURI,
+ isExternal,
+ isRelative,
+ isAnchor,
+ normalize,
+ toAbsolute,
+ relative,
+ relativeForFile,
+ flatten
};
diff --git a/packages/gitbook/lib/utils/logger.js b/packages/gitbook/src/utils/logger.js
index 6fac92b..25f8517 100644
--- a/packages/gitbook/lib/utils/logger.js
+++ b/packages/gitbook/src/utils/logger.js
@@ -1,9 +1,9 @@
-var is = require('is');
-var util = require('util');
-var color = require('bash-color');
-var Immutable = require('immutable');
+const is = require('is');
+const util = require('util');
+const color = require('bash-color');
+const Immutable = require('immutable');
-var LEVELS = Immutable.Map({
+const LEVELS = Immutable.Map({
DEBUG: 0,
INFO: 1,
WARN: 2,
@@ -11,7 +11,7 @@ var LEVELS = Immutable.Map({
DISABLED: 10
});
-var COLORS = Immutable.Map({
+const COLORS = Immutable.Map({
DEBUG: color.purple,
INFO: color.cyan,
WARN: color.yellow,
@@ -22,7 +22,7 @@ function Logger(write, logLevel) {
if (!(this instanceof Logger)) return new Logger(write, logLevel);
this._write = write || function(msg) {
- if(process.stdout) {
+ if (process.stdout) {
process.stdout.write(msg);
}
};
@@ -82,8 +82,8 @@ Logger.prototype.write = function(msg) {
/**
Format a string using the first argument as a printf-like format.
*/
-Logger.prototype.format = function() {
- return util.format.apply(util, arguments);
+Logger.prototype.format = function(...args) {
+ return util.format(...args);
};
/**
@@ -92,7 +92,7 @@ Logger.prototype.format = function() {
@param {String}
*/
Logger.prototype.writeLn = function(msg) {
- return this.write((msg || '')+'\n');
+ return this.write((msg || '') + '\n');
};
/**
@@ -100,17 +100,16 @@ Logger.prototype.writeLn = function(msg) {
@param {Number} level
*/
-Logger.prototype.log = function(level) {
+Logger.prototype.log = function(level, ...args) {
if (level < this.logLevel) return;
- var levelKey = LEVELS.findKey(function(v) {
+ const levelKey = LEVELS.findKey(function(v) {
return v === level;
});
- var args = Array.prototype.slice.apply(arguments, [1]);
- var msg = this.format.apply(this, args);
+ let msg = this.format(...args);
if (this.lastChar == '\n') {
- msg = COLORS.get(levelKey)(levelKey.toLowerCase()+':')+' '+msg;
+ msg = COLORS.get(levelKey)(levelKey.toLowerCase() + ':') + ' ' + msg;
}
return this.write(msg);
@@ -119,21 +118,20 @@ Logger.prototype.log = function(level) {
/**
Log/Print a line if level is allowed
*/
-Logger.prototype.logLn = function() {
+Logger.prototype.logLn = function(...args) {
if (this.lastChar != '\n') this.write('\n');
- var args = Array.prototype.slice.apply(arguments);
args.push('\n');
- return this.log.apply(this, args);
+ return this.log(...args);
};
/**
Log a confirmation [OK]
*/
-Logger.prototype.ok = function(level) {
- var args = Array.prototype.slice.apply(arguments, [1]);
- var msg = this.format.apply(this, args);
- if (arguments.length > 1) {
+Logger.prototype.ok = function(level, ...args) {
+ const msg = this.format(...args);
+
+ if (args.length > 0) {
this.logLn(level, color.green('>> ') + msg.trim().replace(/\n/g, color.green('\n>> ')));
} else {
this.log(level, color.green('OK'), '\n');
@@ -155,10 +153,10 @@ Logger.prototype.fail = function(level) {
@return {Promise}
*/
Logger.prototype.promise = function(level, p) {
- var that = this;
+ const that = this;
- return p.
- then(function(st) {
+ return p
+ .then(function(st) {
that.ok(level);
return st;
}, function(err) {
diff --git a/packages/gitbook/lib/utils/mergeDefaults.js b/packages/gitbook/src/utils/mergeDefaults.js
index 47a374b..b2e8c3d 100644
--- a/packages/gitbook/lib/utils/mergeDefaults.js
+++ b/packages/gitbook/src/utils/mergeDefaults.js
@@ -1,4 +1,4 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
/**
* Merge
@@ -7,8 +7,8 @@ var Immutable = require('immutable');
* @return {Object}
*/
function mergeDefaults(obj, src) {
- var objValue = Immutable.fromJS(obj);
- var srcValue = Immutable.fromJS(src);
+ const objValue = Immutable.fromJS(obj);
+ const srcValue = Immutable.fromJS(src);
return srcValue.mergeDeep(objValue).toJS();
}
diff --git a/packages/gitbook/lib/utils/path.js b/packages/gitbook/src/utils/path.js
index 26b6005..01c2cbf 100644
--- a/packages/gitbook/lib/utils/path.js
+++ b/packages/gitbook/src/utils/path.js
@@ -1,5 +1,5 @@
-var path = require('path');
-var error = require('./error');
+const path = require('path');
+const error = require('./error');
// Normalize a filename
function normalizePath(filename) {
@@ -23,24 +23,21 @@ function isInRoot(root, filename) {
// Resolve paths in a specific folder
// Throw error if file is outside this folder
-function resolveInRoot(root) {
- var input, result;
- var args = Array.prototype.slice.call(arguments, 1);
-
- input = args
+function resolveInRoot(root, ...args) {
+ const input = args
.reduce(function(current, p) {
// Handle path relative to book root ("/README.md")
if (p[0] == '/' || p[0] == '\\') return p.slice(1);
- return current? path.join(current, p) : path.normalize(p);
+ return current ? path.join(current, p) : path.normalize(p);
}, '');
- result = path.resolve(root, input);
+ const result = path.resolve(root, input);
if (!isInRoot(root, result)) {
throw new error.FileOutOfScopeError({
filename: result,
- root: root
+ root
});
}
@@ -66,9 +63,9 @@ function isPureRelative(filename) {
}
module.exports = {
- isInRoot: isInRoot,
- resolveInRoot: resolveInRoot,
+ isInRoot,
+ resolveInRoot,
normalize: normalizePath,
- setExtension: setExtension,
- isPureRelative: isPureRelative
+ setExtension,
+ isPureRelative
};
diff --git a/packages/gitbook/lib/utils/promise.js b/packages/gitbook/src/utils/promise.js
index b5cca4b..8cbbd47 100644
--- a/packages/gitbook/lib/utils/promise.js
+++ b/packages/gitbook/src/utils/promise.js
@@ -1,5 +1,5 @@
-var Q = require('q');
-var Immutable = require('immutable');
+const Q = require('q');
+const Immutable = require('immutable');
// Debugging for long stack traces
if (process.env.DEBUG || process.env.CI) {
@@ -14,7 +14,7 @@ if (process.env.DEBUG || process.env.CI) {
* @return {Promise<Mixed>}
*/
function reduce(arr, iter, base) {
- arr = Immutable.Iterable.isIterable(arr)? arr : Immutable.List(arr);
+ arr = Immutable.Iterable.isIterable(arr) ? arr : Immutable.List(arr);
return arr.reduce(function(prev, elem, key) {
return prev
@@ -99,7 +99,7 @@ function mapAsList(arr, iter) {
*/
function map(arr, iter) {
if (Immutable.Map.isMap(arr)) {
- var type = 'Map';
+ let type = 'Map';
if (Immutable.OrderedMap.isOrderedMap(arr)) {
type = 'OrderedMap';
}
@@ -129,12 +129,10 @@ function map(arr, iter) {
* @return {Funciton}
*/
function wrap(func) {
- return function() {
- var args = Array.prototype.slice.call(arguments, 0);
-
+ return function(...args) {
return Q()
.then(function() {
- return func.apply(null, args);
+ return func(...args);
});
};
}
diff --git a/packages/gitbook/lib/utils/reducedObject.js b/packages/gitbook/src/utils/reducedObject.js
index 7bcfd5b..196a72c 100644
--- a/packages/gitbook/lib/utils/reducedObject.js
+++ b/packages/gitbook/src/utils/reducedObject.js
@@ -1,4 +1,4 @@
-var Immutable = require('immutable');
+const Immutable = require('immutable');
/**
* Reduce the difference between a map and its default version
@@ -7,15 +7,15 @@ var Immutable = require('immutable');
* @return {Map} The properties of currentVersion that differs from defaultVersion
*/
function reducedObject(defaultVersion, currentVersion) {
- if(defaultVersion === undefined) {
+ if (defaultVersion === undefined) {
return currentVersion;
}
return currentVersion.reduce(function(result, value, key) {
- var defaultValue = defaultVersion.get(key);
+ const defaultValue = defaultVersion.get(key);
if (Immutable.Map.isMap(value)) {
- var diffs = reducedObject(defaultValue, value);
+ const diffs = reducedObject(defaultValue, value);
if (diffs.size > 0) {
return result.set(key, diffs);
diff --git a/packages/gitbook/lib/utils/timing.js b/packages/gitbook/src/utils/timing.js
index e6b0323..1dce2a1 100644
--- a/packages/gitbook/lib/utils/timing.js
+++ b/packages/gitbook/src/utils/timing.js
@@ -1,8 +1,8 @@
-var Immutable = require('immutable');
-var is = require('is');
+const Immutable = require('immutable');
+const is = require('is');
-var timers = {};
-var startDate = Date.now();
+const timers = {};
+const startDate = Date.now();
/**
Mesure an operation
@@ -13,19 +13,19 @@ var startDate = Date.now();
*/
function measure(type, p) {
timers[type] = timers[type] || {
- type: type,
+ type,
count: 0,
total: 0,
min: undefined,
max: 0
};
- var start = Date.now();
+ const start = Date.now();
return p
.fin(function() {
- var end = Date.now();
- var duration = (end - start);
+ const end = Date.now();
+ const duration = (end - start);
timers[type].count ++;
timers[type].total += duration;
@@ -51,7 +51,7 @@ function time(ms) {
return (ms.toFixed(0)) + 'ms';
}
- return (ms/1000).toFixed(2) + 's';
+ return (ms / 1000).toFixed(2) + 's';
}
/**
@@ -60,12 +60,12 @@ function time(ms) {
@param {Logger} logger
*/
function dump(logger) {
- var prefix = ' > ';
- var measured = 0;
- var totalDuration = Date.now() - startDate;
+ const prefix = ' > ';
+ let measured = 0;
+ const totalDuration = Date.now() - startDate;
// Enable debug logging
- var logLevel = logger.getLevel();
+ const logLevel = logger.getLevel();
logger.setLevel('debug');
Immutable.Map(timers)
@@ -75,11 +75,11 @@ function dump(logger) {
return timer.total;
})
.forEach(function(timer) {
- var percent = (timer.total * 100) / totalDuration;
+ const percent = (timer.total * 100) / totalDuration;
logger.debug.ln((percent.toFixed(1)) + '% of time spent in "' + timer.type + '" (' + timer.count + ' times) :');
- logger.debug.ln(prefix + 'Total: ' + time(timer.total)+ ' | Average: ' + time(timer.total / timer.count));
+ logger.debug.ln(prefix + 'Total: ' + time(timer.total) + ' | Average: ' + time(timer.total / timer.count));
logger.debug.ln(prefix + 'Min: ' + time(timer.min) + ' | Max: ' + time(timer.max));
logger.debug.ln('---------------------------');
});
@@ -92,6 +92,6 @@ function dump(logger) {
}
module.exports = {
- measure: measure,
- dump: dump
+ measure,
+ dump
};