-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdocz-core.fix.js
More file actions
2490 lines (2122 loc) · 70.6 KB
/
docz-core.fix.js
File metadata and controls
2490 lines (2122 loc) · 70.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// need to fix https://github.com/doczjs/docz/pull/1732
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var yargs = require('yargs');
var _get = _interopDefault(require('lodash/fp/get'));
var fs$1 = require('fs-extra');
var envDotProp = require('env-dot-prop');
var humanize = _interopDefault(require('humanize-string'));
var titleize = _interopDefault(require('titleize'));
var fs$2 = require('fs');
var path$1 = require('path');
var path$1__default = _interopDefault(path$1);
var resolve = require('resolve');
var _merge = _interopDefault(require('lodash/fp/merge'));
var _omit = _interopDefault(require('lodash/fp/omit'));
var loadCfg = require('load-cfg');
var detectPort = _interopDefault(require('detect-port'));
var _isFunction = _interopDefault(require('lodash/fp/isFunction'));
var logger = require('signale');
var logger__default = _interopDefault(logger);
var xstate = require('xstate');
var findUp = _interopDefault(require('find-up'));
var fs$3 = require('docz-utils/lib/fs');
var format = require('docz-utils/lib/format');
var spawn$1 = _interopDefault(require('cross-spawn'));
var waitOn = _interopDefault(require('wait-on'));
var get = _interopDefault(require('lodash/get'));
var chokidar = _interopDefault(require('chokidar'));
var getPkgRepo = _interopDefault(require('get-pkg-repo'));
var _assoc = _interopDefault(require('lodash/fp/assoc'));
var glob = _interopDefault(require('fast-glob'));
var sh = _interopDefault(require('shelljs'));
var equal = _interopDefault(require('fast-deep-equal'));
var _isString = _interopDefault(require('lodash/fp/isString'));
var _isRegExp = _interopDefault(require('lodash/fp/isRegExp'));
var tslib = require('tslib');
var mdast = require('docz-utils/lib/mdast');
var minimatch = _interopDefault(require('minimatch'));
var crypto = require('crypto');
var slugify = _interopDefault(require('@sindresorhus/slugify'));
var _propEq = _interopDefault(require('lodash/fp/propEq'));
var actualNameHandler = _interopDefault(require('react-docgen-actual-name-handler'));
var reactDocgen = require('react-docgen');
var _entries = _interopDefault(require('lodash/fp/entries'));
var _contains = _interopDefault(require('lodash/fp/contains'));
var _prop = _interopDefault(require('lodash/fp/prop'));
var _isEmpty = _interopDefault(require('lodash/fp/isEmpty'));
var reactDocgenTs = require('react-docgen-typescript');
var ts = _interopDefault(require('typescript'));
const ensureSlash = (filepath, needsSlash) => {
const hasSlash = filepath.endsWith('/');
if (hasSlash && !needsSlash) {
return filepath.substr(filepath, filepath.length - 1);
} else if (!hasSlash && needsSlash) {
return `${filepath}/`;
} else {
return filepath;
}
};
const root = fs$2.realpathSync(process.cwd());
const IS_DOCZ_PROJECT = path$1.parse(root).base === '.docz';
const resolveApp = to => path$1.resolve(root, IS_DOCZ_PROJECT ? '../' : './', to);
const checkIsDoczProject = config => {
return path$1.parse(config.root || root).base === '.docz';
};
const getRootDir = config => {
const isDoczProject = checkIsDoczProject(config);
return isDoczProject ? path$1.resolve(root, '../') : root;
};
const getThemesDir = config => {
// resolve normalizes the new path and removes trailing slashes
return path$1.resolve(path$1.join(getRootDir(config), config.themesDir));
};
const templates = path$1.join(resolve.sync('docz-core'), '../templates');
const servedPath = base => ensureSlash(base, true);
const docz = resolveApp('.docz');
const cache = path$1.resolve(docz, '.cache/');
const app = path$1.resolve(docz, 'app/');
const appPackageJson = resolveApp('package.json');
const appTsConfig = resolveApp('tsconfig.json');
const gatsbyConfig = resolveApp('gatsby-config.js');
const gatsbyBrowser = resolveApp('gatsby-browser.js');
const gatsbyNode = resolveApp('gatsby-node.js');
const gatsbySSR = resolveApp('gatsby-ssr.js');
const getDist = dest => path$1.join(root, dest);
const distPublic = dest => path$1.join(dest, 'public/');
const importsJs = path$1.resolve(app, 'imports.js');
const rootJs = path$1.resolve(app, 'root.jsx');
const indexJs = path$1.resolve(app, 'index.jsx');
const indexHtml = path$1.resolve(app, 'index.html');
const db = path$1.resolve(app, 'db.json');
var paths = /*#__PURE__*/Object.freeze({
ensureSlash: ensureSlash,
root: root,
resolveApp: resolveApp,
checkIsDoczProject: checkIsDoczProject,
getRootDir: getRootDir,
getThemesDir: getThemesDir,
templates: templates,
servedPath: servedPath,
docz: docz,
cache: cache,
app: app,
appPackageJson: appPackageJson,
appTsConfig: appTsConfig,
gatsbyConfig: gatsbyConfig,
gatsbyBrowser: gatsbyBrowser,
gatsbyNode: gatsbyNode,
gatsbySSR: gatsbySSR,
getDist: getDist,
distPublic: distPublic,
importsJs: importsJs,
rootJs: rootJs,
indexJs: indexJs,
indexHtml: indexHtml,
db: db
});
const pReduce = (iterable, reducer, initialValue) => new Promise((resolve, reject) => {
const iterator = iterable[Symbol.iterator]();
let index = 0;
const next = async total => {
const element = iterator.next();
if (element.done) {
resolve(total);
return;
}
try {
const value = await Promise.all([total, element.value]);
next(reducer(value[0], value[1], index++));
} catch (error) {
reject(error);
}
};
next(initialValue);
});
class Plugin {
constructor(p) {
this.setConfig = p.setConfig;
this.onCreateWebpackConfig = p.onCreateWebpackConfig;
this.onCreateBabelConfig = p.onCreateBabelConfig;
this.modifyFiles = p.modifyFiles;
this.modifyEntry = p.modifyEntry;
this.onCreateDevServer = p.onCreateDevServer;
this.onPreBuild = p.onPreBuild;
this.onPostBuild = p.onPostBuild;
}
static runPluginsMethod(plugins) {
return (method, ...args) => {
if (plugins && plugins.length > 0) {
for (const plugin of plugins) {
const fn = _get(method, plugin);
if (_isFunction(fn)) {
fn(...args);
}
}
}
};
}
static propsOfPlugins(plugins) {
return prop => plugins && plugins.length > 0 ? plugins.map(p => _get(prop, p)).filter(Boolean) : [];
}
static reduceFromPlugins(plugins) {
return (method, initial, ...args) => {
return [...(plugins || [])].reduce((obj, plugin) => {
const fn = _get(method, plugin);
return fn && _isFunction(fn) ? fn(obj, ...args) : obj;
}, initial);
};
}
static reduceFromPluginsAsync(plugins) {
return (method, initial, ...args) => {
return pReduce([...(plugins || [])], (obj, plugin) => {
const fn = _get(method, plugin);
return Promise.resolve(fn && _isFunction(fn) ? fn(obj, ...args) : obj);
}, initial);
};
}
}
function createPlugin(factory) {
return new Plugin(factory);
}
const toOmit = ['_', '$0', 'version', 'help'];
const doczRcBaseConfig = {
themeConfig: {},
src: './',
gatsbyRoot: null,
themesDir: 'src',
mdxExtensions: ['.md', '.mdx'],
docgenConfig: {},
menu: [],
plugins: [],
mdPlugins: [],
hastPlugins: [],
ignore: [/readme.md/i, /changelog.md/i, /code_of_conduct.md/i, /contributing.md/i, /license.md/i],
filterComponents: files => files.filter(filepath => {
const isTestFile = /\.(test|spec)\.(js|jsx|ts|tsx)$/.test(filepath);
if (isTestFile) {
return false;
}
const startsWithCapitalLetter = /\/([A-Z]\w*)\.(js|jsx|ts|tsx)$/.test(filepath);
const isCalledIndex = /\/index\.(js|jsx|ts|tsx)$/.test(filepath);
const hasJsxOrTsxExtension = /.(jsx|tsx)$/.test(filepath);
return startsWithCapitalLetter || isCalledIndex || hasJsxOrTsxExtension;
})
};
const getBaseConfig = (argv, custom) => {
const initial = _omit(toOmit, argv);
const base = Object.assign(Object.assign(Object.assign({}, doczRcBaseConfig), initial), {
paths
});
return _merge(base, custom);
};
const parseConfig = async (argv, custom) => {
const port = await detectPort(argv.port);
const defaultConfig = getBaseConfig(argv, Object.assign({
port
}, custom));
const config = argv.config ? loadCfg.loadFrom(path$1.join(docz, 'doczrc.js'), defaultConfig) : loadCfg.load('docz', defaultConfig);
const reduceAsync = Plugin.reduceFromPluginsAsync(config.plugins);
return reduceAsync('setConfig', config);
};
const getEnv = (val, defaultValue = null) => envDotProp.get(val, defaultValue, {
parse: true
});
const getInitialTitle = pkg => {
const name = _get('name', pkg) || 'MyDoc';
return titleize(humanize(name.replace(/^@.*\//, '')));
};
const getInitialDescription = pkg => _get('description', pkg) || 'My awesome app using docz';
const setArgs = yargs => {
const pkg = fs$1.readJsonSync(appPackageJson, {
throws: false
});
return yargs.option('root', {
type: 'string',
default: getEnv('docz.root', root)
}).option('base', {
type: 'string',
default: getEnv('docz.base', '/')
}).option('source', {
alias: 'src',
type: 'string',
default: getEnv('docz.source', doczRcBaseConfig.src)
}).option('gatsbyRoot', {
type: 'string',
default: getEnv('docz.gatsbyRoot', doczRcBaseConfig.gatsbyRoot)
}).option('files', {
type: 'string',
default: getEnv('docz.files', '**/*.{md,markdown,mdx}')
}).option('ignore', {
type: 'array',
default: getEnv('docz.ignore', [])
}).option('public', {
type: 'string',
default: getEnv('docz.public', '/public')
}).option('dest', {
alias: 'd',
type: 'string',
default: getEnv('docz.dest', '.docz/dist')
}).option('editBranch', {
alias: 'eb',
type: 'string',
default: getEnv('docz.edit.branch', 'master')
}).option('config', {
type: 'string',
default: getEnv('docz.config', '')
}).option('title', {
type: 'string',
default: getEnv('docz.title', getInitialTitle(pkg))
}).option('description', {
type: 'string',
default: getEnv('docz.description', getInitialDescription(pkg))
}).option('typescript', {
alias: 'ts',
type: 'boolean',
default: getEnv('docz.typescript', false)
}).option('propsParser', {
type: 'boolean',
default: getEnv('docz.props.parser', true)
}).option('debug', {
type: 'boolean',
default: getEnv('docz.debug', false)
}).option('host', {
type: 'string',
default: getEnv('docz.host', 'localhost')
}).option('port', {
alias: 'p',
type: 'number',
default: getEnv('docz.port', 3000)
}).option('native', {
type: 'boolean',
default: getEnv('docz.native', false)
}).option('separator', {
type: 'string',
default: getEnv('docz.separator', '-')
}).option('openBrowser', {
alias: ['o', 'open'],
describe: 'auto open browser in dev mode',
type: 'boolean',
default: null
});
};
const populateNodePath = () => {
// We support resolving modules according to `NODE_PATH`.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
envDotProp.set('node.path', envDotProp.get('node.path', '').split(path$1.delimiter).filter(folder => folder && !path$1.isAbsolute(folder)).map(folder => path$1.resolve(root, folder)).join(path$1.delimiter));
};
const configDotEnv = () => {
const NODE_ENV = envDotProp.get('node.env');
const dotenv = resolveApp('.env');
const dotenvFiles = [`${dotenv}.${NODE_ENV}.local`, `${dotenv}.${NODE_ENV}`, // Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${dotenv}.local`, dotenv]; // Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
dotenvFiles.filter(Boolean).forEach(dotenvFile => {
require('dotenv').config({
path: dotenvFile
});
});
};
const setEnv = env => {
envDotProp.set('babel.env', env);
envDotProp.set('node.env', env);
configDotEnv();
populateNodePath();
};
class Bundler {
constructor(params) {
const {
args,
server,
build
} = params;
this.args = args;
this.server = server;
this.builder = build;
}
async createApp() {
return this.server();
}
async build() {
const dist = getDist(this.args.dest);
const root = getRootDir(this.args);
if (root === path$1.resolve(dist)) {
logger__default.fatal(new Error('Unexpected option: "dest" cannot be set to the current working directory.'));
process.exit(1);
}
await this.builder(this.args, dist);
}
}
const fromTemplates = file => {
return path$1.join(templates, file);
};
const outputFileFromTemplate = async (templatePath, outputPath, templateProps, compileProps) => {
const filepath = fromTemplates(templatePath);
const template = await fs$3.compiled(filepath, compileProps || {
minimize: false
});
const file = template(templateProps || {});
const raw = await format.format(file);
await fs$1.outputFile(outputPath, raw);
};
const copyDoczRc = configPath => {
const sourceDoczRc = configPath ? path$1.join(root, configPath) : path$1.join(root, 'doczrc.js');
const hasDoczRc = fs$1.existsSync(sourceDoczRc);
if (!hasDoczRc) return;
const destinationDoczRc = path$1.join(docz, 'doczrc.js');
try {
fs$1.copySync(sourceDoczRc, destinationDoczRc);
} catch (err) {}
};
const copyAndModifyPkgJson = async ctx => {
const movePath = path$1.join(docz, 'package.json'); // const pkg = await fs.readJSON(filepath, { throws: false })
const newPkg = Object.assign({
name: 'docz-app',
license: 'MIT',
dependencies: {
gatsby: 'just-to-fool-cli-never-installed'
},
scripts: {
dev: 'gatsby develop',
build: 'gatsby build',
serve: 'gatsby serve'
}
}, ctx.isDoczRepo && {
private: true,
workspaces: ['../../../core/**', '../../../other-packages/**']
});
await fs$1.outputJSON(movePath, newPkg, {
spaces: 2
});
};
const writeEslintRc = async () => {
const possibleFilenames = ['.eslintrc.js', '.eslintrc.yaml', '.eslintrc.yml', '.eslintrc.json', '.eslintrc'];
for (const filename of possibleFilenames) {
const filepath = path$1.join(root, filename);
const dest = path$1.join(docz, filename);
if (fs$1.pathExistsSync(filepath)) {
await fs$1.copy(filepath, dest);
return;
}
}
};
const copyDotEnv = () => {
const filename = '.env';
const filepath = path$1.join(root, filename);
const dest = path$1.join(docz, filename);
if (fs$1.pathExistsSync(filepath)) {
fs$1.copySync(filepath, dest);
}
};
const copyEslintIgnore = async () => {
const filename = '.eslintignore';
const filepath = path$1.join(root, filename);
const dest = path$1.join(docz, filename);
if (fs$1.pathExistsSync(filepath)) {
await fs$1.copy(filepath, dest);
}
};
const writeDefaultNotFound = async () => {
const outputPath = path$1.join(docz, 'src/pages/404.js'); // If it exists then it would have been created in ensureFiles while copying the theme
if (fs$1.existsSync(outputPath)) return;
await outputFileFromTemplate('404.tpl.js', outputPath, {});
};
const writeGatsbyConfig = async ({
args,
isDoczRepo
}) => {
const outputPath = path$1.join(docz, 'gatsby-config.js');
const config = _omit(['plugins'], args);
const newConfig = Object.assign(Object.assign({}, config), {
root: docz
});
await outputFileFromTemplate('gatsby-config.tpl.js', outputPath, {
isDoczRepo,
config: newConfig,
opts: JSON.stringify(newConfig)
});
};
const writeGatsbyConfigNode = async () => {
const outputPath = path$1.join(docz, 'gatsby-node.js');
await outputFileFromTemplate('gatsby-node.tpl.js', outputPath);
};
const copyGatsbyConfigFile = async (from, to) => {
const filepath = path$1.join(root, from);
const dest = path$1.join(docz, to);
if (fs$1.pathExistsSync(filepath)) {
await fs$1.copy(filepath, dest);
}
};
const writeGatsbyConfigCustom = async () => copyGatsbyConfigFile('gatsby-config.js', 'gatsby-config.custom.js');
const writeGatsbyNodeCustom = async () => copyGatsbyConfigFile('gatsby-node.js', 'gatsby-node.custom.js');
const writeGatsbySSR = async () => copyGatsbyConfigFile('gatsby-ssr.js', 'gatsby-ssr.js');
const writeGatsbyBrowser = async () => copyGatsbyConfigFile('gatsby-browser.js', 'gatsby-browser.js');
const createResources = async ctx => {
try {
copyDoczRc(ctx.args.config);
copyDotEnv();
await copyAndModifyPkgJson(ctx);
await writeEslintRc();
await copyEslintIgnore();
await writeDefaultNotFound();
await writeGatsbyConfig(ctx);
await writeGatsbyConfigNode();
await writeGatsbyConfigCustom();
await writeGatsbyNodeCustom();
await writeGatsbyBrowser();
await writeGatsbySSR();
} catch (err) {
console.error(err);
}
};
const ensureDirs = async () => {
await fs$1.ensureDir(docz);
return await fs$1.ensureDir(path$1.join(docz, 'src/pages'));
};
/**
* Copyright (c) 2015-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.
*/
var chalk = require('chalk');
var execSync = require('child_process').execSync;
var spawn = require('cross-spawn');
var open = require('open'); // https://github.com/sindresorhus/open#app
var OSX_CHROME = 'google chrome';
const Actions = Object.freeze({
NONE: 0,
BROWSER: 1,
SCRIPT: 2
});
function getBrowserEnv() {
// Attempt to honor this environment variable.
// It is specific to the operating system.
// See https://github.com/sindresorhus/open#app for documentation.
const value = process.env.BROWSER;
let action;
if (!value) {
// Default.
action = Actions.BROWSER;
} else if (value.toLowerCase().endsWith('.js')) {
action = Actions.SCRIPT;
} else if (value.toLowerCase() === 'none') {
action = Actions.NONE;
} else {
action = Actions.BROWSER;
}
return {
action,
value
};
}
function executeNodeScript(scriptPath, url) {
const extraArgs = process.argv.slice(2);
const child = spawn('node', [scriptPath, ...extraArgs, url], {
stdio: 'inherit'
});
child.on('close', code => {
if (code !== 0) {
console.log();
console.log(chalk.red('The script specified as BROWSER environment variable failed.'));
console.log(chalk.cyan(scriptPath) + ' exited with code ' + code + '.');
console.log();
return;
}
});
return true;
}
function startBrowserProcess(browser, url) {
// If we're on OS X, the user hasn't specifically
// requested a different browser, we can try opening
// Chrome with AppleScript. This lets us reuse an
// existing tab when possible instead of creating a new one.
const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (typeof browser !== 'string' || browser === OSX_CHROME);
if (shouldTryOpenChromeWithAppleScript) {
try {
// Try our best to reuse existing tab
// on OS X Google Chrome with AppleScript
execSync('ps cax | grep "Google Chrome"');
execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
cwd: __dirname,
stdio: 'ignore'
});
return true;
} catch (err) {// Ignore errors.
}
} // Another special case: on OS X, check if BROWSER has been set to "open".
// In this case, instead of passing `open` to `open` (which won't work),
// just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
// https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
if (process.platform === 'darwin' && browser === 'open') {
browser = undefined;
} // Fallback to opn
// (It will always open new tab)
try {
var options = {
app: browser,
wait: false
};
open(url, options).catch(() => {}); // Prevent `unhandledRejection` error.
return true;
} catch (err) {
return false;
}
}
/**
* Reads the BROWSER environment variable and decides what to do with it. Returns
* true if it opened a browser or ran a node.js script, otherwise false.
*/
function openBrowser(url) {
const {
action,
value
} = getBrowserEnv();
switch (action) {
case Actions.NONE:
// Special case: BROWSER="none" will prevent opening completely.
return false;
case Actions.SCRIPT:
return executeNodeScript(value, url);
case Actions.BROWSER:
return startBrowserProcess(value, url);
default:
throw new Error('Not implemented.');
}
}
const findRootPath = async () => {
let repoRootPath = path$1__default.join(docz, '../');
try {
const foundRootPath = await findUp(async directory => {
const hasGatsby = await findUp.exists(path$1__default.join(directory, 'node_modules', 'gatsby'));
return hasGatsby ? directory : '';
}, {
type: 'directory'
});
if (typeof foundRootPath === 'string') {
repoRootPath = foundRootPath;
}
} catch (err) {
console.log(`Failed to find root folder ${err.message} \n Assuming it is ${repoRootPath}`);
}
return repoRootPath;
};
const execDevCommand = async ({
args
}) => {
// For monorepos that install dependencies higher in the fs tree
const repoRootPath = get(args, 'repoRootPath', (await findRootPath()));
const gatsbyPath = path$1__default.join(repoRootPath, 'node_modules/.bin/gatsby'); // const cliArgs = process.argv.slice(3)
// Has --https flag to enable https in dev mode
const useHttps = args.https;
const caFile = args.caFile;
const keyFile = args.keyFile;
const certFile = args.certFile;
const caFileOption = caFile ? ['--ca-file', caFile] : [];
const keyFileOption = keyFile ? ['--key-file', keyFile] : [];
const certFileOption = certFile ? ['--cert-file', certFile] : [];
spawn$1(gatsbyPath, ['develop', '--host', `${args.host}`, '--port', `${args.port}`, useHttps ? '--https' : '', ...caFileOption, ...keyFileOption, ...certFileOption].filter(Boolean), {
stdio: 'inherit',
cwd: docz
});
const protocol = useHttps ? 'https' : 'http';
const url = `${protocol}://${args.host}:${args.port}`;
console.log();
console.log('Building app');
await waitOn({
resources: [url],
timeout: 30000
});
console.log();
console.log('App ready on ' + url);
if (args.open !== null && Boolean(args.open) === false) {
return;
}
openBrowser(url);
};
const installDeps = async () => {
// No need to install dependencies
return;
};
const parseRepo = () => {
try {
const pkg = fs$1.readJsonSync(appPackageJson);
return getPkgRepo(pkg);
} catch (err) {
return null;
}
};
const getRepoUrl = () => {
const repo = parseRepo();
return repo && (repo.browsetemplate && repo.browsetemplate.replace('{domain}', repo.domain).replace('{user}', repo.user).replace('{project}', repo.project).replace('{/tree/committish}', '') || repo.browse && repo.browse());
};
const getBitBucketPath = (branch, relative) => {
const querystring = `?mode=edit&spa=0&at=${branch}&fileviewer=file-view-default`;
const filepath = path$1.join(`/src/${branch}`, relative, `{{filepath}}`);
return `${filepath}${querystring}`;
};
const getTree = (repo, branch, relative) => {
const defaultPath = path$1.join(`/edit/${branch}`, relative, `{{filepath}}`);
const bitBucketPath = getBitBucketPath(branch, relative);
if (repo && repo.type === 'bitbucket') return bitBucketPath;
return defaultPath;
};
const getRepoEditUrl = config => {
try {
const repo = parseRepo();
const gitDir = findUp.sync('.git', {
type: 'directory'
});
if (!gitDir) return null;
const project = path$1.parse(gitDir).dir;
const root = getRootDir(config);
const relative = path$1.relative(project, root);
const tree = getTree(repo, config.editBranch, relative);
return repo && repo.browsetemplate && repo.browsetemplate.replace('{domain}', repo.domain).replace('{user}', repo.user).replace('{project}', repo.project).replace('{/tree/committish}', tree);
} catch (err) {
console.log(err);
return null;
}
};
const getInitialConfig = config => {
const pkg = fs$1.readJsonSync(appPackageJson, {
throws: false
});
const repoUrl = getRepoUrl();
return {
title: config.title,
description: config.description,
menu: config.menu,
version: get(pkg, 'version'),
repository: repoUrl,
native: config.native,
themeConfig: config.themeConfig,
separator: config.separator
};
};
const update = async (params, initial, {
config
}) => {
const pathToConfig = path$1.join(docz, 'doczrc.js');
const next = config ? loadCfg.loadFrom(pathToConfig, initial, true, true) : loadCfg.load('docz', initial, true, true);
params.setState('config', next);
};
const WATCH_IGNORE = /(((^|[\/\\])\.((?!docz)(.+)))|(node_modules))/;
const createWatcher = (glob, config) => {
const ignored = config.watchIgnore || WATCH_IGNORE;
const watcher = chokidar.watch(glob, {
ignored,
cwd: root,
persistent: true
});
watcher.setMaxListeners(Infinity);
return watcher;
};
const state = (config, dev) => {
const glob = config.config || loadCfg.finds('docz');
const initial = getInitialConfig(config);
const watcher = createWatcher(glob, config);
return {
id: 'config',
start: async params => {
const fn = async () => update(params, initial, config);
await update(params, initial, config);
if (dev) {
watcher.on('add', fn);
watcher.on('change', fn);
watcher.on('unlink', fn);
}
},
close: () => {
watcher.close();
}
};
};
/**
* Maps a given relative 'filepath' from 'themesDir/...' to 'src/...'
*/
const replaceThemesDir = (filepath, args) => {
// Make the path to a given relative`filepath` relative to themesDir:
const rawFilePath = path$1.relative(getThemesDir(args), path$1.resolve(root, filepath)); // => e.g. '/gatsby-theme-docz/**/index.tsx'
// Prefix with 'src':
return path$1.join('src', rawFilePath); // => 'src/gatsby-theme-docz/**/index.tsx'
};
const watchGatsbyThemeFiles = args => {
const watcher = createWatcher(path$1.join(args.themesDir, 'gatsby-theme-**/**/*'), args);
const copy = filepath => {
const src = path$1.resolve(root, filepath);
const dest = path$1.resolve(docz, replaceThemesDir(filepath, args));
fs$1.copySync(src, dest);
};
const remove = filepath => {
fs$1.removeSync(path$1.resolve(docz, filepath));
};
watcher.on('add', copy).on('addDir', copy).on('change', copy).on('unlink', remove).on('unlinkDir', remove);
return () => watcher.close();
};
const createWatch = args => (glob, src, custom) => {
const watcher = createWatcher(glob, args);
const srcPath = path$1.join(root, src);
const destPath = path$1.join(docz, custom ? src.replace('.js', '.custom.js') : src);
const copyFile = () => fs$1.copySync(srcPath, destPath);
const deleteFile = () => fs$1.removeSync(destPath);
watcher.on('add', copyFile).on('change', copyFile).on('unlink', deleteFile);
return () => watcher.close();
};
const watchDoczRc = args => {
const watcher = createWatcher(path$1.join(root, args.config ? args.config : 'doczrc.js'), args);
const copy = filepath => {
const src = path$1.resolve(root, filepath);
const dest = path$1.resolve(docz, 'doczrc.js');
fs$1.copySync(src, dest);
};
const remove = () => {
fs$1.removeSync(path$1.resolve(docz, 'doczrc.js'));
};
watcher.on('add', copy).on('change', copy).on('unlink', remove);
return () => watcher.close();
};
const watchFiles = ({
args
}) => () => {
const watch = createWatch(args);
const doczrc = watchDoczRc(args);
const gatsbyBrowser$1 = watch(gatsbyBrowser, 'gatsby-browser.js');
const gatsbyNode$1 = watch(gatsbyNode, 'gatsby-node.js');
const gatsbySSR$1 = watch(gatsbySSR, 'gatsby-ssr.js');
const gatsbyConfig$1 = watch(gatsbyConfig, 'gatsby-config.js', true);
const themeFilesWatcher = watchGatsbyThemeFiles(args);
return () => {
doczrc();
gatsbyConfig$1();
gatsbyBrowser$1();
gatsbyNode$1();
gatsbySSR$1();
themeFilesWatcher();
};
};
var services = /*#__PURE__*/Object.freeze({
createResources: createResources,
ensureDirs: ensureDirs,
execDevCommand: execDevCommand,
installDeps: installDeps,
watchFiles: watchFiles
});
const ensureFile = (filename, toDelete) => {
const ghost = path$1.resolve(docz, toDelete || filename);
const original = path$1.resolve(root, filename);
if (fs$1.pathExistsSync(ghost) && !fs$1.pathExistsSync(original)) {
fs$1.removeSync(ghost);
}
};
const ensureFiles = ({
args
}) => {
// themesDir defaults to "src" to behave like a normal gatsby site
const appPath = path$1.join(root, args.themesDir);
const themeNames = glob.sync('gatsby-theme-**', {
cwd: appPath,
onlyDirectories: true
});
themeNames.forEach(themeName => {
fs$1.copySync(path$1.join(appPath, themeName), path$1.join(docz, 'src', themeName));
});
const userPagesPath = path$1.join(appPath, 'pages');
const doczPagesPath = path$1.join(docz, 'src', 'pages'); // Copy 404 and other possible Gatsby pages
if (fs$1.existsSync(userPagesPath)) {
fs$1.copySync(userPagesPath, doczPagesPath);
}
copyDoczRc(args.config);
ensureFile('gatsby-browser.js');
ensureFile('gatsby-ssr.js');
ensureFile('gatsby-node.js');
ensureFile('gatsby-config.js', 'gatsby-config.custom.js');
const publicPath = path$1.join(docz, '..', args.public);
if (fs$1.existsSync(publicPath)) {
const destinationPath = path$1.join(docz, 'static', args.public);
try {
fs$1.copySync(publicPath, destinationPath);
} catch (err) {
console.log(`Failed to copy static assets from ${publicPath} to ${destinationPath} : ${err.message}`);
}
}
};
const getIsFirstInstall = () => {
return !sh.test('-e', path$1.join(docz, 'package.json'));
};
const getIsDoczRepo = () => {
return sh.test('-e', path$1.join(root, '../../core'));
};
const assignFirstInstall = xstate.assign(ctx => {
const firstInstall = getIsFirstInstall();
return _assoc('firstInstall', firstInstall, ctx);
});
const checkIsDoczRepo = xstate.assign(ctx => {
const isDoczRepo = getIsDoczRepo();
return _assoc('isDoczRepo', isDoczRepo, ctx);
});
const logError = (ctx, ev) => {
logger__default.fatal(ev.data);