refactor(v2): add flowtype + refactor test (#1443)

* chore(v2): add flow setup

* nits

* fix

* add flow-typed

* ignore compiled library

* fix error

* fix typing

* fix module name mapper

* setup for @docusaurus/core

* dont try remove type without @flow

* fix can't find @docusaurus/utils

* fix test

* remove obscure relative paths

* more refactoring

* add typing for server/load/theme.js

* no need to ship .flow source
This commit is contained in:
Endi 2019-05-08 23:03:52 +07:00 committed by GitHub
parent 6f011d8e7a
commit c2ebde997a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
103 changed files with 8901 additions and 1589 deletions

View file

@ -41,6 +41,9 @@ jobs:
- run: - run:
name: Check ESLint name: Check ESLint
command: yarn lint command: yarn lint
- run:
name: Check Flow
command: yarn flow check
- run: - run:
name: Check Prettier name: Check Prettier
command: yarn prettier:diff command: yarn prettier:diff

View file

@ -10,3 +10,5 @@ scripts
packages/docusaurus-1.x/lib/core/metadata.js packages/docusaurus-1.x/lib/core/metadata.js
packages/docusaurus-1.x/lib/core/MetadataBlog.js packages/docusaurus-1.x/lib/core/MetadataBlog.js
packages/docusaurus-1.x/lib/core/__tests__/split-tab.test.js packages/docusaurus-1.x/lib/core/__tests__/split-tab.test.js
packages/docusaurus-utils/lib
packages/docusaurus/lib

14
.flowconfig Normal file
View file

@ -0,0 +1,14 @@
[ignore]
<PROJECT_ROOT>/packages/.*/lib
<PROJECT_ROOT>/packages/.*/__tests__
[include]
[libs]
[lints]
[options]
module.name_mapper='^@docusaurus\/\([a-zA-Z0-9_\-]+\)$' -> '<PROJECT_ROOT>/packages/docusaurus-\1/src/index'
[strict]

3
.gitignore vendored
View file

@ -11,3 +11,6 @@ yarn-error.log
build build
.docusaurus .docusaurus
.cache-loader .cache-loader
packages/docusaurus-utils/lib
packages/docusaurus/lib/

View file

@ -2,3 +2,6 @@ dist
node_modules node_modules
build build
.docusaurus .docusaurus
packages/docusaurus-utils/lib
packages/docusaurus/lib
flow-typed

View file

@ -6,7 +6,18 @@
*/ */
module.exports = { module.exports = {
presets: ['@babel/env', '@babel/react'], presets: [
[
'@babel/env',
{
targets: {
node: 'current',
},
},
],
'@babel/react',
'@babel/preset-flow',
],
plugins: [ plugins: [
'@babel/plugin-proposal-class-properties', '@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread', '@babel/plugin-proposal-object-rest-spread',

View file

@ -5,6 +5,6 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
const babelConfig = require('./babel.config'); declare module 'escape-string-regexp' {
declare module.exports: (input: string) => string;
module.exports = require('babel-jest').createTransformer(babelConfig); }

768
flow-typed/npm/fs-extra_v7.x.x.js vendored Normal file
View file

@ -0,0 +1,768 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare module 'fs-extra' {
import type {Stats, ReadStream, WriteStream} from 'fs';
declare export type SymlinkType = 'dir' | 'file';
declare export type FsSymlinkType = 'dir' | 'file' | 'junction';
declare export type CopyFilterSync = (src: string, dest: string) => boolean;
declare export type CopyFilterAsync = (
src: string,
dest: string,
) => Promise<boolean>;
declare export type CopyOptions = {
dereference?: boolean,
overwrite?: boolean,
preserveTimestamps?: boolean,
errorOnExist?: boolean,
recursive?: boolean,
};
declare export type CopyOptionsAync = CopyOptions & {
filter?: CopyFilterSync | CopyFilterAsync,
};
declare export type CopyOptionsSync = CopyOptions & {
filter?: CopyFilterSync,
};
declare export type MoveOptions = {
overwrite?: boolean,
limit?: number,
};
declare export type ReadOptions = {
throws?: boolean,
fs?: Object,
reviver?: any,
encoding?: string,
flag?: string,
};
declare export type WriteFileOptions = {
encoding?: string,
flag?: string,
mode?: number,
};
declare export type WriteOptions = WriteFileOptions & {
fs?: Object,
replacer?: any,
spaces?: number | string,
EOL?: string,
};
declare export type ReadResult = {
bytesRead: number,
buffer: Buffer,
};
declare export type WriteResult = {
bytesWritten: number,
buffer: Buffer,
};
declare export function copy(
src: string,
dest: string,
options?: CopyOptionsAync,
): Promise<void>;
declare export function copy(
src: string,
dest: string,
callback: (err: Error) => void,
): void;
declare export function copy(
src: string,
dest: string,
options: CopyOptionsAync,
callback: (err: Error) => void,
): void;
declare export function copySync(
src: string,
dest: string,
options?: CopyOptionsSync,
): void;
declare export function move(
src: string,
dest: string,
options?: MoveOptions,
): Promise<void>;
declare export function move(
src: string,
dest: string,
callback: (err: Error) => void,
): void;
declare export function move(
src: string,
dest: string,
options: MoveOptions,
callback: (err: Error) => void,
): void;
declare export function moveSync(
src: string,
dest: string,
options?: MoveOptions,
): void;
declare export function createFile(file: string): Promise<void>;
declare export function createFile(
file: string,
callback: (err: Error) => void,
): void;
declare export function createFileSync(file: string): void;
declare export function createReadStream(
path: string,
options?: Object,
): ReadStream;
declare export function createWriteStream(
path: string,
options?: Object,
): WriteStream;
declare export function ensureDir(path: string): Promise<void>;
declare export function ensureDir(
path: string,
callback: (err: Error) => void,
): void;
declare export function ensureDirSync(path: string): void;
declare export function exists(path: string): Promise<boolean>;
declare export function exists(
path: string,
callback?: (exists: boolean) => void,
): void;
declare export function mkdirs(dir: string): Promise<void>;
declare export function mkdirs(
dir: string,
callback: (err: Error) => void,
): void;
declare export function mkdirsSync(dir: string): void;
declare export function mkdirp(dir: string): Promise<void>;
declare export function mkdirp(
dir: string,
callback: (err: Error) => void,
): void;
declare export function mkdirpSync(dir: string): void;
declare export function outputFile(
file: string,
data: any,
options?: WriteFileOptions | string,
): Promise<void>;
declare export function outputFile(
file: string,
data: any,
callback: (err: Error) => void,
): void;
declare export function outputFile(
file: string,
data: any,
options: WriteFileOptions | string,
callback: (err: Error) => void,
): void;
declare export function outputFileSync(
file: string,
data: any,
options?: WriteFileOptions | string,
): void;
declare export function readJson(
file: string,
options?: ReadOptions,
): Promise<any>;
declare export function readJson(
file: string,
callback: (err: Error, jsonObject: any) => void,
): void;
declare export function readJson(
file: string,
options: ReadOptions,
callback: (err: Error, jsonObject: any) => void,
): void;
declare export function readJSON(
file: string,
options?: ReadOptions,
): Promise<any>;
declare export function readJSON(
file: string,
callback: (err: Error, jsonObject: any) => void,
): void;
declare export function readJSON(
file: string,
options: ReadOptions,
callback: (err: Error, jsonObject: any) => void,
): void;
declare export function readJsonSync(
file: string,
options?: ReadOptions,
): any;
declare export function readJSONSync(
file: string,
options?: ReadOptions,
): any;
declare export function remove(dir: string): Promise<void>;
declare export function remove(
dir: string,
callback: (err: Error) => void,
): void;
declare export function removeSync(dir: string): void;
declare export function outputJson(
file: string,
data: any,
options?: WriteOptions,
): Promise<void>;
declare export function outputJSON(
file: string,
data: any,
options?: WriteOptions,
): Promise<void>;
declare export function outputJson(
file: string,
data: any,
options: WriteOptions,
callback: (err: Error) => void,
): void;
declare export function outputJSON(
file: string,
data: any,
options: WriteOptions,
callback: (err: Error) => void,
): void;
declare export function outputJson(
file: string,
data: any,
callback: (err: Error) => void,
): void;
declare export function outputJSON(
file: string,
data: any,
callback: (err: Error) => void,
): void;
declare export function outputJsonSync(
file: string,
data: any,
options?: WriteOptions,
): void;
declare export function outputJSONSync(
file: string,
data: any,
options?: WriteOptions,
): void;
declare export function writeJSON(
file: string,
object: any,
options?: WriteOptions,
): Promise<void>;
declare export function writeJSON(
file: string,
object: any,
callback: (err: Error) => void,
): void;
declare export function writeJSON(
file: string,
object: any,
options: WriteOptions,
callback: (err: Error) => void,
): void;
declare export function writeJson(
file: string,
object: any,
options?: WriteOptions,
): Promise<void>;
declare export function writeJson(
file: string,
object: any,
callback: (err: Error) => void,
): void;
declare export function writeJson(
file: string,
object: any,
options: WriteOptions,
callback: (err: Error) => void,
): void;
declare export function writeJsonSync(
file: string,
object: any,
options?: WriteOptions,
): void;
declare export function writeJSONSync(
file: string,
object: any,
options?: WriteOptions,
): void;
declare export function ensureFile(path: string): Promise<void>;
declare export function ensureFile(
path: string,
callback: (err: Error) => void,
): void;
declare export function ensureFileSync(path: string): void;
declare export function ensureLink(src: string, dest: string): Promise<void>;
declare export function ensureLink(
src: string,
dest: string,
callback: (err: Error) => void,
): void;
declare export function ensureLinkSync(src: string, dest: string): void;
declare export function ensureSymlink(
src: string,
dest: string,
type?: SymlinkType,
): Promise<void>;
declare export function ensureSymlink(
src: string,
dest: string,
type: SymlinkType,
callback: (err: Error) => void,
): void;
declare export function ensureSymlink(
src: string,
dest: string,
callback: (err: Error) => void,
): void;
declare export function ensureSymlinkSync(
src: string,
dest: string,
type?: SymlinkType,
): void;
declare export function emptyDir(path: string): Promise<void>;
declare export function emptyDir(
path: string,
callback: (err: Error) => void,
): void;
declare export function emptyDirSync(path: string): void;
declare export function pathExists(path: string): Promise<boolean>;
declare export function pathExists(
path: string,
callback: (err: Error, exists: boolean) => void,
): void;
declare export function pathExistsSync(path: string): boolean;
declare export function access(
path: string | Buffer,
callback: (err: ErrnoError) => void,
): void;
declare export function access(
path: string | Buffer,
mode: number,
callback: (err: ErrnoError) => void,
): void;
declare export function access(
path: string | Buffer,
mode?: number,
): Promise<void>;
declare export function appendFile(
file: string | Buffer | number,
data: any,
options: {encoding?: string, mode?: number | string, flag?: string},
callback: (err: ErrnoError) => void,
): void;
declare export function appendFile(
file: string | Buffer | number,
data: any,
callback: (err: ErrnoError) => void,
): void;
declare export function appendFile(
file: string | Buffer | number,
data: any,
options?: {encoding?: string, mode?: number | string, flag?: string},
): Promise<void>;
declare export function chmod(
path: string | Buffer,
mode: string | number,
callback: (err: ErrnoError) => void,
): void;
declare export function chmod(
path: string | Buffer,
mode: string | number,
): Promise<void>;
declare export function chown(
path: string | Buffer,
uid: number,
gid: number,
): Promise<void>;
declare export function chown(
path: string | Buffer,
uid: number,
gid: number,
callback: (err: ErrnoError) => void,
): void;
declare export function close(
fd: number,
callback: (err: ErrnoError) => void,
): void;
declare export function close(fd: number): Promise<void>;
declare export function fchmod(
fd: number,
mode: string | number,
callback: (err: ErrnoError) => void,
): void;
declare export function fchmod(
fd: number,
mode: string | number,
): Promise<void>;
declare export function fchown(
fd: number,
uid: number,
gid: number,
callback: (err: ErrnoError) => void,
): void;
declare export function fchown(
fd: number,
uid: number,
gid: number,
): Promise<void>;
declare export function fdatasync(fd: number, callback: () => void): void;
declare export function fdatasync(fd: number): Promise<void>;
declare export function fstat(
fd: number,
callback: (err: ErrnoError, stats: Stats) => any,
): void;
declare export function fstat(fd: number): Promise<Stats>;
declare export function fsync(
fd: number,
callback: (err: ErrnoError) => void,
): void;
declare export function fsync(fd: number): Promise<void>;
declare export function ftruncate(
fd: number,
callback: (err: ErrnoError) => void,
): void;
declare export function ftruncate(
fd: number,
len: number,
callback: (err: ErrnoError) => void,
): void;
declare export function ftruncate(fd: number, len?: number): Promise<void>;
declare export function futimes(
fd: number,
atime: number,
mtime: number,
callback: (err: ErrnoError) => void,
): void;
declare export function futimes(
fd: number,
atime: Date,
mtime: Date,
callback: (err: ErrnoError) => void,
): void;
declare export function futimes(
fd: number,
atime: number,
mtime: number,
): Promise<void>;
declare export function futimes(
fd: number,
atime: Date,
mtime: Date,
): Promise<void>;
declare export function lchown(
path: string | Buffer,
uid: number,
gid: number,
callback: (err: ErrnoError) => void,
): void;
declare export function lchown(
path: string | Buffer,
uid: number,
gid: number,
): Promise<void>;
declare export function link(
srcpath: string | Buffer,
dstpath: string | Buffer,
callback: (err: ErrnoError) => void,
): void;
declare export function link(
srcpath: string | Buffer,
dstpath: string | Buffer,
): Promise<void>;
declare export function lstat(
path: string | Buffer,
callback: (err: ErrnoError, stats: Stats) => any,
): void;
declare export function lstat(path: string | Buffer): Promise<Stats>;
declare export function mkdir(
path: string | Buffer,
callback: (err: ErrnoError) => void,
): void;
declare export function mkdir(
path: string | Buffer,
mode: number | string,
callback: (err: ErrnoError) => void,
): void;
declare export function mkdir(path: string | Buffer): Promise<void>;
declare export function open(
path: string | Buffer,
flags: string | number,
callback: (err: ErrnoError, fd: number) => void,
): void;
declare export function open(
path: string | Buffer,
flags: string | number,
mode: number,
callback: (err: ErrnoError, fd: number) => void,
): void;
declare export function open(
path: string | Buffer,
flags: string | number,
mode?: number,
): Promise<number>;
declare export function read(
fd: number,
buffer: Buffer,
offset: number,
length: number,
position: number | null,
callback: (err: ErrnoError, bytesRead: number, buffer: Buffer) => void,
): void;
declare export function read(
fd: number,
buffer: Buffer,
offset: number,
length: number,
position: number | null,
): Promise<ReadResult>;
declare export function readFile(
file: string | Buffer | number,
callback: (err: ErrnoError, data: Buffer) => void,
): void;
declare export function readFile(
file: string | Buffer | number,
encoding: string,
callback: (err: ErrnoError, data: string) => void,
): void;
declare export function readFile(
file: string | Buffer | number,
options: {flag?: string} | {encoding: string, flag?: string},
callback: (err: ErrnoError, data: Buffer) => void,
): void;
declare export function readFile(
file: string | Buffer | number,
options: {flag?: string} | {encoding: string, flag?: string},
): Promise<string>;
declare export function readFile(
file: string | Buffer | number,
encoding: string,
): Promise<string>;
declare export function readFile(
file: string | Buffer | number,
): Promise<Buffer>;
declare export function readdir(
path: string | Buffer,
callback: (err: ErrnoError, files: string[]) => void,
): void;
declare export function readdir(path: string | Buffer): Promise<string[]>;
declare export function readlink(
path: string | Buffer,
callback: (err: ErrnoError, linkString: string) => any,
): void;
declare export function readlink(path: string | Buffer): Promise<string>;
declare export function realpath(
path: string | Buffer,
callback: (err: ErrnoError, resolvedPath: string) => any,
): void;
declare export function realpath(
path: string | Buffer,
cache: {[path: string]: string},
callback: (err: ErrnoError, resolvedPath: string) => any,
): void;
declare export function realpath(
path: string | Buffer,
cache?: {[path: string]: string},
): Promise<string>;
declare export function rename(
oldPath: string,
newPath: string,
callback: (err: ErrnoError) => void,
): void;
declare export function rename(
oldPath: string,
newPath: string,
): Promise<void>;
declare export function rmdir(
path: string | Buffer,
callback: (err: ErrnoError) => void,
): void;
declare export function rmdir(path: string | Buffer): Promise<void>;
declare export function stat(
path: string | Buffer,
callback: (err: ErrnoError, stats: Stats) => any,
): void;
declare export function stat(path: string | Buffer): Promise<Stats>;
declare export function statSync(path: string): Stats;
declare export function symlink(
srcpath: string | Buffer,
dstpath: string | Buffer,
type: FsSymlinkType | void,
callback: (err: ErrnoError) => void,
): void;
declare export function symlink(
srcpath: string | Buffer,
dstpath: string | Buffer,
callback: (err: ErrnoError) => void,
): void;
declare export function symlink(
srcpath: string | Buffer,
dstpath: string | Buffer,
type?: FsSymlinkType,
): Promise<void>;
declare export function truncate(
path: string | Buffer,
callback: (err: ErrnoError) => void,
): void;
declare export function truncate(
path: string | Buffer,
len: number,
callback: (err: ErrnoError) => void,
): void;
declare export function truncate(
path: string | Buffer,
len?: number,
): Promise<void>;
declare export function unlink(
path: string | Buffer,
callback: (err: ErrnoError) => void,
): void;
declare export function unlink(path: string | Buffer): Promise<void>;
declare export function utimes(
path: string | Buffer,
atime: number,
mtime: number,
callback: (err: ErrnoError) => void,
): void;
declare export function utimes(
path: string | Buffer,
atime: Date,
mtime: Date,
callback: (err: ErrnoError) => void,
): void;
declare export function utimes(
path: string | Buffer,
atime: number,
mtime: number,
): Promise<void>;
declare export function utimes(
path: string | Buffer,
atime: Date,
mtime: Date,
): Promise<void>;
declare export function write(
fd: number,
buffer: Buffer,
offset: number,
length: number,
position: number | null,
callback: (err: ErrnoError, written: number, buffer: Buffer) => void,
): void;
declare export function write(
fd: number,
buffer: Buffer,
offset: number,
length: number,
callback: (err: ErrnoError, written: number, buffer: Buffer) => void,
): void;
declare export function write(
fd: number,
data: any,
callback: (err: ErrnoError, written: number, str: string) => void,
): void;
declare export function write(
fd: number,
data: any,
offset: number,
callback: (err: ErrnoError, written: number, str: string) => void,
): void;
declare export function write(
fd: number,
data: any,
offset: number,
encoding: string,
callback: (err: ErrnoError, written: number, str: string) => void,
): void;
declare export function write(
fd: number,
buffer: Buffer,
offset: number,
length: number,
position?: number | null,
): Promise<WriteResult>;
declare export function write(
fd: number,
data: any,
offset: number,
encoding?: string,
): Promise<WriteResult>;
declare export function writeFile(
file: string | Buffer | number,
data: any,
callback: (err: ErrnoError) => void,
): void;
declare export function writeFile(
file: string | Buffer | number,
data: any,
options?: WriteFileOptions | string,
): Promise<void>;
declare export function writeFile(
file: string | Buffer | number,
data: any,
options: WriteFileOptions | string,
callback: (err: ErrnoError) => void,
): void;
declare export function mkdtemp(prefix: string): Promise<string>;
declare export function mkdtemp(
prefix: string,
callback: (err: ErrnoError, folder: string) => void,
): void;
}

6047
flow-typed/npm/lodash_v4.x.x.js vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -12,11 +12,8 @@ module.exports = {
verbose: true, verbose: true,
testURL: 'http://localhost/', testURL: 'http://localhost/',
testEnvironment: 'node', testEnvironment: 'node',
moduleNameMapper: { testPathIgnorePatterns: ['/node_modules/', '__fixtures__'],
'^@lib/(.*)$': '<rootDir>/packages/docusaurus/lib/$1',
},
testPathIgnorePatterns: ['loadSetup.js', '/node_modules/', '__fixtures__'],
transform: { transform: {
'^.+\\.js$': '<rootDir>/jest.transform.js', '^.+\\.js$': 'babel-jest',
}, },
}; };

View file

@ -6,6 +6,12 @@
"website-1.x" "website-1.x"
], ],
"scripts": { "scripts": {
"build": "lerna run --parallel build --no-private",
"build:clean": "lerna run --parallel build:clean --no-private",
"build:watch": "lerna run --parallel build:watch --no-private",
"flow": "flow",
"flow-typed": "flow-typed",
"install": "yarn run build",
"prettier": "prettier --config .prettierrc --write \"**/*.js\"", "prettier": "prettier --config .prettierrc --write \"**/*.js\"",
"prettier:diff": "prettier --config .prettierrc --list-different \"**/*.js\"", "prettier:diff": "prettier --config .prettierrc --list-different \"**/*.js\"",
"lint": "eslint --cache \"**/*.js\"", "lint": "eslint --cache \"**/*.js\"",
@ -13,7 +19,8 @@
"test": "jest" "test": "jest"
}, },
"devDependencies": { "devDependencies": {
"babel-core": "^7.0.0-0", "@babel/core": "^7.4.4",
"@babel/preset-flow": "^7.0.0",
"babel-eslint": "8", "babel-eslint": "8",
"enzyme": "^3.9.0", "enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1", "enzyme-adapter-react-16": "^1.12.1",
@ -26,16 +33,19 @@
"eslint-plugin-react": "^7.11.1", "eslint-plugin-react": "^7.11.1",
"eslint-plugin-react-hooks": "^0.0.0", "eslint-plugin-react-hooks": "^0.0.0",
"filepath": "^1.1.0", "filepath": "^1.1.0",
"flow-bin": "^0.98.1",
"flow-remove-types": "^1.2.3",
"flow-typed": "^2.5.1",
"front-matter": "^2.3.0", "front-matter": "^2.3.0",
"glob-promise": "^3.3.0", "glob-promise": "^3.3.0",
"husky": "^1.3.1", "husky": "^1.3.1",
"jest": "^24.1.0", "jest": "^24.6.0",
"lerna": "^3.13.1", "lerna": "^3.13.1",
"lint-staged": "^7.2.0", "lint-staged": "^7.2.0",
"prettier": "^1.13.7", "prettier": "^1.13.7",
"react": "^16.8.4", "react": "^16.8.4",
"react-dom": "^16.8.4", "react-dom": "^16.8.4",
"rimraf": "^2.6.2" "rimraf": "^2.6.3"
}, },
"lint-staged": { "lint-staged": {
"linters": { "linters": {

View file

@ -26,6 +26,9 @@ exports[`server utils autoprefix css 1`] = `
::-webkit-input-placeholder { ::-webkit-input-placeholder {
color: gray; color: gray;
} }
::-moz-placeholder {
color: gray;
}
:-ms-input-placeholder { :-ms-input-placeholder {
color: gray; color: gray;
} }

View file

@ -5,14 +5,17 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import '@babel/polyfill';
import path from 'path'; import path from 'path';
import loadSetup from '../../../docusaurus/lib/server/load/__tests__/loadSetup';
import DocusaurusPluginContentDocs from '../index'; import DocusaurusPluginContentDocs from '../index';
describe('loadDocs', () => { describe('loadDocs', () => {
test('simple website', async () => { test('simple website', async () => {
const {siteDir, siteConfig} = await loadSetup('simple'); const siteDir = path.join(__dirname, '__fixtures__', 'website');
const siteConfig = {
title: 'Hello',
baseUrl: '/',
url: 'https://docusaurus.io',
};
const sidebarPath = path.join(siteDir, 'sidebars.json'); const sidebarPath = path.join(siteDir, 'sidebars.json');
const plugin = new DocusaurusPluginContentDocs( const plugin = new DocusaurusPluginContentDocs(
{ {
@ -20,7 +23,7 @@ describe('loadDocs', () => {
siteConfig, siteConfig,
}, },
{ {
path: '../docs', path: 'docs',
sidebarPath, sidebarPath,
}, },
); );

View file

@ -8,13 +8,17 @@
import '@babel/polyfill'; import '@babel/polyfill';
import path from 'path'; import path from 'path';
import processMetadata from '../metadata'; import processMetadata from '../metadata';
import loadSetup from '../../../docusaurus/lib/server/load/__tests__/loadSetup';
describe('processMetadata', () => { describe('processMetadata', () => {
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const siteConfig = {
title: 'Hello',
baseUrl: '/',
url: 'https://docusaurus.io',
};
const docsDir = path.resolve(siteDir, 'docs');
test('normal docs', async () => { test('normal docs', async () => {
const props = await loadSetup('simple');
const {siteDir, siteConfig} = props;
const docsDir = path.resolve(siteDir, '..', 'docs');
const sourceA = path.join('foo', 'bar.md'); const sourceA = path.join('foo', 'bar.md');
const sourceB = path.join('hello.md'); const sourceB = path.join('hello.md');
const dataA = await processMetadata( const dataA = await processMetadata(
@ -46,9 +50,6 @@ describe('processMetadata', () => {
}); });
test('docs with custom permalink', async () => { test('docs with custom permalink', async () => {
const props = await loadSetup('simple');
const {siteDir, siteConfig} = props;
const docsDir = path.resolve(siteDir, '..', 'docs');
const source = path.join('permalink.md'); const source = path.join('permalink.md');
const data = await processMetadata(source, docsDir, {}, siteConfig, 'docs'); const data = await processMetadata(source, docsDir, {}, siteConfig, 'docs');
expect(data).toEqual({ expect(data).toEqual({

View file

@ -7,23 +7,23 @@
import path from 'path'; import path from 'path';
import loadSidebars from '../sidebars'; import loadSidebars from '../sidebars';
import loadSetup from '../../../docusaurus/lib/server/load/__tests__/loadSetup';
/* eslint-disable global-require, import/no-dynamic-require */ /* eslint-disable global-require, import/no-dynamic-require */
describe('loadSidebars', () => { describe('loadSidebars', () => {
const fixtures = path.join(__dirname, '..', '__fixtures__');
test('normal site with sidebars', async () => { test('normal site with sidebars', async () => {
const {siteDir} = await loadSetup('simple'); const sidebar = require(path.join(
const sidebar = require(path.join(siteDir, 'sidebars.json')); __dirname,
const result = loadSidebars({siteDir, sidebar}); '__fixtures__',
'website',
'sidebars.json',
));
const result = loadSidebars({sidebar});
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
test('site without sidebars', () => { test('site without sidebars', () => {
const siteDir = path.join(fixtures, 'bad-site'); const result = loadSidebars({sidebar: {}});
const result = loadSidebars({siteDir, sidebar: {}});
expect(result).toMatchSnapshot(); expect(result).toMatchSnapshot();
}); });
}); });

View file

@ -7,15 +7,23 @@
import path from 'path'; import path from 'path';
import loadSetup from '../../../docusaurus/lib/server/load/__tests__/loadSetup';
import DocusaurusPluginContentPages from '../index'; import DocusaurusPluginContentPages from '../index';
describe('docusaurus-plugin-content-pages', () => { describe('docusaurus-plugin-content-pages', () => {
describe('loadContent', () => { test('simple pages', async () => {
test.each([ const siteConfig = {
[ title: 'Hello',
'simple', baseUrl: '/',
pagesDir => [ url: 'https://docusaurus.io',
};
const siteDir = path.join(__dirname, '__fixtures__', 'website');
const plugin = new DocusaurusPluginContentPages({
siteDir,
siteConfig,
});
const pagesMetadatas = await plugin.loadContent();
const pagesDir = plugin.contentPath;
expect(pagesMetadatas).toEqual([
{ {
permalink: '/', permalink: '/',
source: path.join(pagesDir, 'index.js'), source: path.join(pagesDir, 'index.js'),
@ -24,18 +32,6 @@ describe('docusaurus-plugin-content-pages', () => {
permalink: '/hello/world', permalink: '/hello/world',
source: path.join(pagesDir, 'hello', 'world.js'), source: path.join(pagesDir, 'hello', 'world.js'),
}, },
], ]);
],
])('%s website', async (type, expected) => {
const {siteDir, siteConfig} = await loadSetup(type);
const plugin = new DocusaurusPluginContentPages({
siteDir,
siteConfig,
});
const pagesMetadatas = await plugin.loadContent();
const pagesDir = plugin.contentPath;
expect(pagesMetadatas).toEqual(expected(pagesDir));
});
}); });
}); });

View file

@ -5,13 +5,17 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import loadSetup from '../../../docusaurus/lib/server/load/__tests__/loadSetup';
import DocusaurusPluginSitemap from '../index'; import DocusaurusPluginSitemap from '../index';
describe('docusaurus-plugin-sitemap', () => { describe('docusaurus-plugin-sitemap', () => {
describe('createSitemap', () => { describe('createSitemap', () => {
test.each(['simple'])('%s website', async type => { test('simple site', async () => {
const context = await loadSetup(type); const context = {
siteConfig: {
url: 'https://example.com',
},
routesPaths: ['/', '/test'],
};
const plugin = new DocusaurusPluginSitemap(context, null); const plugin = new DocusaurusPluginSitemap(context, null);
const sitemap = await plugin.createSitemap(context); const sitemap = await plugin.createSitemap(context);
expect(sitemap).toContain( expect(sitemap).toContain(
@ -20,7 +24,7 @@ describe('docusaurus-plugin-sitemap', () => {
}); });
test('empty site', async () => { test('empty site', async () => {
const context = await loadSetup('empty'); const context = {};
const plugin = new DocusaurusPluginSitemap(context, null); const plugin = new DocusaurusPluginSitemap(context, null);
expect( expect(
plugin.createSitemap(context), plugin.createSitemap(context),

View file

@ -0,0 +1 @@
src

View file

@ -2,10 +2,17 @@
"name": "@docusaurus/utils", "name": "@docusaurus/utils",
"version": "2.0.0-alpha.13", "version": "2.0.0-alpha.13",
"description": "Node utility functions for Docusaurus packages", "description": "Node utility functions for Docusaurus packages",
"main": "src/index.js", "main": "lib/index.js",
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
}, },
"scripts": {
"prepublish": "yarn run build",
"build": "yarn run build:clean && yarn run build:lib",
"build:clean": "rimraf lib",
"build:lib": "flow-remove-types -q -x '.js,.css,.ejs' src --out-dir lib --ignore '/__tests__/'",
"build:watch": "watch \"yarn build\" src"
},
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"escape-string-regexp": "^1.0.5", "escape-string-regexp": "^1.0.5",

View file

@ -5,6 +5,8 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
/* @flow */
const path = require('path'); const path = require('path');
const fm = require('front-matter'); const fm = require('front-matter');
const {createHash} = require('crypto'); const {createHash} = require('crypto');
@ -14,7 +16,11 @@ const escapeStringRegexp = require('escape-string-regexp');
const fs = require('fs-extra'); const fs = require('fs-extra');
const fileHash = new Map(); const fileHash = new Map();
async function generate(generatedFilesDir, file, content) { async function generate(
generatedFilesDir: string,
file: string,
content: any,
): Promise<void> {
const filepath = path.join(generatedFilesDir, file); const filepath = path.join(generatedFilesDir, file);
const lastHash = fileHash.get(filepath); const lastHash = fileHash.get(filepath);
const currentHash = createHash('md5') const currentHash = createHash('md5')
@ -31,14 +37,14 @@ async function generate(generatedFilesDir, file, content) {
const indexRE = /(^|.*\/)index\.(md|js)$/i; const indexRE = /(^|.*\/)index\.(md|js)$/i;
const extRE = /\.(md|js)$/; const extRE = /\.(md|js)$/;
function fileToPath(file) { function fileToPath(file: string): string {
if (indexRE.test(file)) { if (indexRE.test(file)) {
return file.replace(indexRE, '/$1'); return file.replace(indexRE, '/$1');
} }
return `/${file.replace(extRE, '').replace(/\\/g, '/')}`; return `/${file.replace(extRE, '').replace(/\\/g, '/')}`;
} }
function encodePath(userpath) { function encodePath(userpath: string): string {
return userpath return userpath
.split('/') .split('/')
.map(item => encodeURIComponent(item)) .map(item => encodeURIComponent(item))
@ -50,7 +56,7 @@ function encodePath(userpath) {
* @param {string} str input string * @param {string} str input string
* @returns {string} * @returns {string}
*/ */
function docuHash(str) { function docuHash(str: string): string {
if (str === '/') { if (str === '/') {
return 'index'; return 'index';
} }
@ -66,7 +72,7 @@ function docuHash(str) {
* @param {string} pagePath * @param {string} pagePath
* @returns {string} unique react component name * @returns {string} unique react component name
*/ */
function genComponentName(pagePath) { function genComponentName(pagePath: string): string {
if (pagePath === '/') { if (pagePath === '/') {
return 'index'; return 'index';
} }
@ -83,7 +89,7 @@ function genComponentName(pagePath) {
* @param {string} str windows backslash paths * @param {string} str windows backslash paths
* @returns {string} posix-style path * @returns {string} posix-style path
*/ */
function posixPath(str) { function posixPath(str: string): string {
const isExtendedLengthPath = /^\\\\\?\\/.test(str); const isExtendedLengthPath = /^\\\\\?\\/.test(str);
const hasNonAscii = /[^\u0000-\u0080]+/.test(str); // eslint-disable-line const hasNonAscii = /[^\u0000-\u0080]+/.test(str); // eslint-disable-line
@ -94,7 +100,11 @@ function posixPath(str) {
} }
const chunkNameCache = new Map(); const chunkNameCache = new Map();
function genChunkName(modulePath, prefix, preferredName) { function genChunkName(
modulePath: string,
prefix?: string,
preferredName?: string,
): string {
let chunkName = chunkNameCache.get(modulePath); let chunkName = chunkNameCache.get(modulePath);
if (!chunkName) { if (!chunkName) {
let str = modulePath; let str = modulePath;
@ -112,7 +122,7 @@ function genChunkName(modulePath, prefix, preferredName) {
return chunkName; return chunkName;
} }
function idx(target, keyPaths) { function idx(target?: {}, keyPaths: string | string[]): any {
return ( return (
target && target &&
(Array.isArray(keyPaths) (Array.isArray(keyPaths)
@ -121,7 +131,7 @@ function idx(target, keyPaths) {
); );
} }
function getSubFolder(file, refDir) { function getSubFolder(file: string, refDir: string): ?string {
const separator = escapeStringRegexp(path.sep); const separator = escapeStringRegexp(path.sep);
const baseDir = escapeStringRegexp(path.basename(refDir)); const baseDir = escapeStringRegexp(path.basename(refDir));
const regexSubFolder = new RegExp( const regexSubFolder = new RegExp(
@ -131,7 +141,7 @@ function getSubFolder(file, refDir) {
return match && match[1]; return match && match[1];
} }
function parse(fileString) { function parse(fileString: string): {} {
if (!fm.test(fileString)) { if (!fm.test(fileString)) {
return {metadata: null, content: fileString}; return {metadata: null, content: fileString};
} }
@ -140,7 +150,7 @@ function parse(fileString) {
return {metadata, content}; return {metadata, content};
} }
function normalizeUrl(rawUrls) { function normalizeUrl(rawUrls: string[]): string {
const urls = rawUrls; const urls = rawUrls;
const resultArray = []; const resultArray = [];

View file

@ -0,0 +1 @@
src

View file

@ -23,7 +23,12 @@
"docusaurus": "bin/docusaurus.js" "docusaurus": "bin/docusaurus.js"
}, },
"scripts": { "scripts": {
"docusaurus": "node bin/docusaurus" "docusaurus": "node bin/docusaurus",
"prepublish": "yarn run build",
"build": "yarn run build:clean && yarn run build:lib",
"build:clean": "rimraf lib",
"build:lib": "flow-remove-types -q -x '.js,.css,.ejs' src --out-dir lib --ignore '/__tests__/'",
"build:watch": "watch \"yarn build\" src"
}, },
"bugs": { "bugs": {
"url": "https://github.com/facebook/Docusaurus/issues" "url": "https://github.com/facebook/Docusaurus/issues"
@ -35,7 +40,6 @@
"@babel/preset-env": "^7.4.2", "@babel/preset-env": "^7.4.2",
"@babel/preset-react": "^7.0.0", "@babel/preset-react": "^7.0.0",
"@docusaurus/utils": "^2.0.0-alpha.13", "@docusaurus/utils": "^2.0.0-alpha.13",
"babel-jest": "^24.1.0",
"babel-loader": "^8.0.0", "babel-loader": "^8.0.0",
"babel-plugin-dynamic-import-node": "^2.2.0", "babel-plugin-dynamic-import-node": "^2.2.0",
"cache-loader": "^2.0.1", "cache-loader": "^2.0.1",

View file

@ -0,0 +1,66 @@
---
id: bar
title: Bar
---
# Remarkable
> Experience real-time editing with Remarkable!
Click the `clear` link to start with a clean slate, or get the `permalink` to share or save your results.
***
# h1 Heading
## h2 Heading
### h3 Heading
#### h4 Heading
##### h5 Heading
###### h6 Heading
## Horizontal Rules
___
***
***
## Typographic replacements
Enable typographer option to see result.
(c) (C) (r) (R) (tm) (TM) (p) (P) +-
test.. test... test..... test?..... test!....
!!!!!! ???? ,,
Remarkable -- awesome
"Smartypants, double quotes"
'Smartypants, single quotes'
## Emphasis
**This is bold text**
__This is bold text__
*This is italic text*
_This is italic text_
~~Deleted text~~
Superscript: 19^th^
Subscript: H~2~O
++Inserted text++
==Marked text==

View file

@ -0,0 +1,74 @@
---
id: baz
title: baz
---
## Images
Like links, Images also have a footnote style syntax
![Alt text][id]
With a reference later in the document defining the URL location:
[id]: https://octodex.github.com/images/dojocat.jpg "The Dojocat"
## Links
[link text](http://dev.nodeca.com)
[link with title](http://nodeca.github.io/pica/demo/ "title text!")
Autoconverted link https://github.com/nodeca/pica (enable linkify to see)
## Footnotes
Footnote 1 link[^first].
Footnote 2 link[^second].
Inline footnote^[Text of inline footnote] definition.
Duplicated footnote reference[^second].
[^first]: Footnote **can have markup**
and multiple paragraphs.
[^second]: Footnote text.
## Definition lists
Term 1
: Definition 1
with lazy continuation.
Term 2 with *inline markup*
: Definition 2
{ some code, part of Definition 2 }
Third paragraph of definition 2.
_Compact style:_
Term 1
~ Definition 1
Term 2
~ Definition 2a
~ Definition 2b
## Abbreviations
This is HTML abbreviation example.
It converts "HTML", but keep intact partial entries like "xxxHTMLyyy" and so on.
*[HTML]: Hyper Text Markup Language

View file

@ -0,0 +1,54 @@
---
id: hello
title: Hello, World !
---
Hi, Endilie here :)
## Relative links
Replace this
[foo](foo/bar.md)
Can't replace this
[file](file.md)
Do not replace below
```
[hello](hello.md)
```
## Blockquotes
> Blockquotes can also be nested...
>> ...by using additional greater-than signs right next to each other...
> > > ...or with spaces between arrows.
## Lists
Unordered
+ Create a list by starting a line with `+`, `-`, or `*`
+ Sub-lists are made by indenting 2 spaces:
- Marker character change forces new list start:
* Ac tristique libero volutpat at
+ Facilisis in pretium nisl aliquet
- Nulla volutpat aliquam velit
+ Very easy!
Ordered
1. Lorem ipsum dolor sit amet
2. Consectetur adipiscing elit
3. Integer molestie lorem at massa
1. You can use sequential numbers...
1. ...or keep all the numbers as `1.`
Start numbering with offset:
57. foo
1. bar

View file

@ -0,0 +1,7 @@
---
id: permalink
title: Permalink
permalink: :baseUrl:docsUrl/endiliey/:id
---
This has a different permalink

View file

@ -0,0 +1,22 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Head from '@docusaurus/Head';
export default class World extends React.Component {
render() {
return (
<div>
<Head>
<title>World</title>
</Head>
<div>Hello World </div>
</div>
);
}
}

View file

@ -0,0 +1,23 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Head from '@docusaurus/Head';
export default class Home extends React.Component {
render() {
return (
<div>
<Head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="/css/basic.css" />
</Head>
<div>Home ... </div>
</div>
);
}
}

View file

@ -0,0 +1,11 @@
{
"docs": {
"Test": [
"foo/bar",
"foo/baz"
],
"Guides": [
"hello"
]
}
}

View file

@ -7,7 +7,7 @@
import path from 'path'; import path from 'path';
import loadConfig from '../config'; import loadConfig from '../config';
import loadSetup from './loadSetup'; import loadSetup from '../loadSetup';
describe('loadConfig', () => { describe('loadConfig', () => {
test('website with valid siteConfig', async () => { test('website with valid siteConfig', async () => {

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import loadSetup from './loadSetup'; import loadSetup from '../loadSetup';
describe('loadRoutes', () => { describe('loadRoutes', () => {
test('simple website', async () => { test('simple website', async () => {

View file

@ -7,11 +7,11 @@
import '@babel/polyfill'; import '@babel/polyfill';
import path from 'path'; import path from 'path';
import load from '../../index'; import load from '../index';
// Helper methods to setup dummy/fake projects // Helper methods to setup dummy/fake projects
const loadSetup = async name => { const loadSetup = async name => {
const fixtures = path.join(__dirname, '__fixtures__'); const fixtures = path.join(__dirname, '__tests__', '__fixtures__');
const simpleSite = path.join(fixtures, 'simple-site'); const simpleSite = path.join(fixtures, 'simple-site');
const customSite = path.join(fixtures, 'custom-site'); const customSite = path.join(fixtures, 'custom-site');

View file

@ -5,13 +5,15 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
/* @flow */
const globby = require('globby'); const globby = require('globby');
const fs = require('fs-extra'); const fs = require('fs-extra');
const path = require('path'); const path = require('path');
const {fileToPath, posixPath, normalizeUrl} = require('@docusaurus/utils'); const {fileToPath, posixPath, normalizeUrl} = require('@docusaurus/utils');
module.exports = async function loadTheme(themePath) { module.exports = async function loadTheme(themePath: string) {
if (!fs.existsSync(themePath)) { if (!fs.pathExistsSync(themePath)) {
return null; return null;
} }

View file

@ -7,7 +7,7 @@
import {validate} from 'webpack'; import {validate} from 'webpack';
import createBaseConfig from '../base'; import createBaseConfig from '../base';
import loadSetup from '../../server/load/__tests__/loadSetup'; import loadSetup from '../../server/load/loadSetup';
describe('webpack base config', () => { describe('webpack base config', () => {
test('simple', async () => { test('simple', async () => {

View file

@ -8,7 +8,7 @@
import {validate} from 'webpack'; import {validate} from 'webpack';
import createClientConfig from '../client'; import createClientConfig from '../client';
import loadSetup from '../../server/load/__tests__/loadSetup'; import loadSetup from '../../server/load/loadSetup';
describe('webpack dev config', () => { describe('webpack dev config', () => {
test('simple', async () => { test('simple', async () => {

View file

@ -8,7 +8,7 @@
import {validate} from 'webpack'; import {validate} from 'webpack';
import createServerConfig from '../server'; import createServerConfig from '../server';
import loadSetup from '../../server/load/__tests__/loadSetup'; import loadSetup from '../../server/load/loadSetup';
describe('webpack production config', () => { describe('webpack production config', () => {
test('simple', async () => { test('simple', async () => {

Some files were not shown because too many files have changed in this diff Show more