@travetto/doc 3.0.0-rc.2 → 3.0.0-rc.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/util/run.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  import { spawnSync } from 'child_process';
2
2
 
3
- import { PathUtil, ExecUtil, EnvUtil, ExecutionOptions, ExecutionState } from '@travetto/boot';
3
+ import { path, RootIndex } from '@travetto/manifest';
4
+ import { ExecUtil, ExecutionOptions, ExecutionState } from '@travetto/base';
5
+ import { stripAnsiCodes } from '@travetto/terminal';
6
+
7
+ export const COMMON_DATE = new Date('2029-03-14T00:00:00.000').getTime();
4
8
 
5
9
  export type RunConfig = {
6
10
  filter?: (line: string) => boolean;
7
- module?: 'base' | 'boot';
11
+ rewrite?: (text: string) => string;
12
+ module?: string;
8
13
  env?: Record<string, string>;
14
+ profiles?: string[];
9
15
  cwd?: string;
10
16
  };
11
17
 
@@ -16,7 +22,7 @@ type RunState = {
16
22
  };
17
23
 
18
24
  class DocState {
19
- baseline = new Date(`${new Date().getFullYear()}-03-14T00:00:00.000`).getTime();
25
+ baseline = COMMON_DATE;
20
26
  _s = 37;
21
27
  ids: Record<string, string> = {};
22
28
 
@@ -46,21 +52,19 @@ export class DocRunUtil {
46
52
 
47
53
  static runState(cmd: string, args: string[], config: RunConfig = {}): RunState {
48
54
  args = [...args];
49
- if (cmd.endsWith('.ts')) {
50
- const mod = config.module ?? 'base';
51
- args.unshift(require.resolve(`@travetto/${mod}/bin/main`), cmd);
52
- cmd = process.argv0;
53
- }
54
55
  return {
55
56
  cmd,
56
57
  args,
57
58
  opts: {
58
- cwd: config.cwd ?? PathUtil.cwd,
59
+ cwd: path.toPosix(config.cwd ?? path.cwd()),
59
60
  shell: '/bin/bash',
60
61
  env: {
61
- ...EnvUtil.getAll(),
62
- DEBUG: '',
63
- TRV_DEBUG: '0',
62
+ ...process.env,
63
+ DEBUG: '0',
64
+ TRV_MANIFEST: '',
65
+ TRV_BUILD: 'warn',
66
+ TRV_MODULE: config.module ?? '',
67
+ ...(config.profiles ? { TRV_PROFILES: config.profiles.join(' ') } : {}),
64
68
  ...(config.env ?? {})
65
69
  }
66
70
  }
@@ -71,18 +75,20 @@ export class DocRunUtil {
71
75
  * Clean run output
72
76
  */
73
77
  static cleanRunOutput(text: string, cfg: RunConfig): string {
74
- text = text.trim()
75
- // eslint-disable-next-line no-control-regex
76
- .replace(/\x1b\[[?]?[0-9]{1,2}[a-z]/gi, '')
77
- .replace(/[A-Za-z0-9_.\-\/\\]+\/travetto\/module\//g, '@trv:')
78
- .replace(new RegExp(PathUtil.cwd, 'g'), '.')
79
- .replace(/([.]trv_cache)[_A-Za-z0-9]+/g, (_, b) => b)
78
+ text = stripAnsiCodes(text.trim())
79
+ .replace(new RegExp(path.cwd(), 'g'), '.')
80
+ .replaceAll(RootIndex.manifest.workspacePath, '<workspace-root>')
81
+ .replace(/^(.{1,4})?Compiling[.]*/, '') // Compiling message, remove
82
+ .replace(/[A-Za-z0-9_.\-\/\\]+\/travetto\/module\//g, '@travetto/')
80
83
  .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}([.]\d{3})?Z?/g, this.#docState.getDate.bind(this.#docState))
81
84
  .replace(/\b[0-9a-f]{4}[0-9a-f\-]{8,40}\b/ig, this.#docState.getId.bind(this.#docState))
82
85
  .replace(/(\d+[.]\d+[.]\d+)-(alpha|rc)[.]\d+/g, (all, v) => v);
83
86
  if (cfg.filter) {
84
87
  text = text.split(/\n/g).filter(cfg.filter).join('\n');
85
88
  }
89
+ if (cfg.rewrite) {
90
+ text = cfg.rewrite(text);
91
+ }
86
92
  return text;
87
93
  }
88
94
 
@@ -104,17 +110,19 @@ export class DocRunUtil {
104
110
  let final: string;
105
111
  try {
106
112
  const state = this.runState(cmd, args, config);
107
- const res = spawnSync(state.cmd, state.args, {
113
+ const spawnCfg = {
108
114
  ...state.opts,
109
115
  stdio: 'pipe' as const,
110
116
  encoding: 'utf8',
111
117
  maxBuffer: 1024 * 1024 * 20,
112
- });
118
+ } as const;
119
+
120
+ const res = spawnSync(state.cmd, state.args, spawnCfg);
113
121
 
114
122
  if (res.error) {
115
123
  throw res.error;
116
124
  }
117
- final = res.stdout.toString() || res.stderr.toString();
125
+ final = stripAnsiCodes(res.stdout.toString()).trim() || stripAnsiCodes(res.stderr.toString()).trim();
118
126
  } catch (err) {
119
127
  if (err instanceof Error) {
120
128
  console.log('Found!', cmd, args, '\n', err);
@@ -0,0 +1,84 @@
1
+ import fs from 'fs/promises';
2
+
3
+ import { PackageUtil, path, RootIndex, watchFolders } from '@travetto/manifest';
4
+ import { ExecUtil, GlobalEnvConfig } from '@travetto/base';
5
+ import { CliCommand, OptionConfig, ListOptionConfig } from '@travetto/cli';
6
+
7
+ import { RenderUtil } from '../src/render/util';
8
+
9
+ type Options = {
10
+ input: OptionConfig<string>;
11
+ outputs: ListOptionConfig<string>;
12
+ watch: OptionConfig<boolean>;
13
+ };
14
+
15
+ /**
16
+ * Command line support for generating module docs.
17
+ */
18
+ export class DocCommand extends CliCommand<Options> {
19
+ name = 'doc';
20
+
21
+ getOptions(): Options {
22
+ const input = RootIndex.mainModule.files['doc']?.find(x => x.sourceFile.endsWith('DOC.ts'));
23
+ return {
24
+ input: this.option({ desc: 'Input File', def: input?.relativeFile ?? 'DOC.ts' }),
25
+ outputs: this.listOption({ desc: 'Outputs', def: [] }),
26
+ watch: this.boolOption({ desc: 'Watch' })
27
+ };
28
+ }
29
+
30
+ envInit(): GlobalEnvConfig {
31
+ return {
32
+ debug: false,
33
+ set: {
34
+ TRV_CONSOLE_WIDTH: 140,
35
+ TRV_CLI_IPC: '',
36
+ FORCE_COLOR: 0,
37
+ TRV_LOG_PLAIN: true
38
+ }
39
+ };
40
+ }
41
+
42
+ async action(): Promise<void> {
43
+ const docFile = path.resolve(this.cmd.input);
44
+ if (!(await fs.stat(docFile).catch(() => false))) {
45
+ console.error(`The input ${this.cmd.input} does not exist`);
46
+ return this.exit(1);
47
+ }
48
+
49
+ if (this.cmd.outputs.length === 0) {
50
+ const workspacePkg = PackageUtil.readPackage(RootIndex.manifest.workspacePath);
51
+ this.cmd.outputs = workspacePkg.travetto?.docOutputs ?? ['README.md'];
52
+ }
53
+
54
+ const outputs = this.cmd.outputs.map(output => output.includes('.') ? [path.extname(output).substring(1), path.resolve(output)] : [output, null] as const);
55
+
56
+ if (this.cmd.watch) {
57
+ const args = process.argv.slice(2).filter(x => !x.startsWith('-w') && !x.startsWith('--w'));
58
+ await watchFolders([path.dirname(docFile)],
59
+ () => ExecUtil.spawn('npx', ['trv', ...args], {
60
+ cwd: RootIndex.mainModule.sourcePath,
61
+ env: { TRV_QUIET: '1' },
62
+ stdio: 'inherit', catchAsResult: true
63
+ }), {
64
+ filter: ev => ev.action === 'update' && ev.file === docFile
65
+ });
66
+ }
67
+
68
+ try {
69
+ for (const [fmt, out] of outputs) {
70
+ const result = await RenderUtil.render(docFile, fmt);
71
+ if (out) {
72
+ const finalName = path.resolve(out);
73
+ await fs.writeFile(finalName, result, 'utf8');
74
+ console.log(`Wrote docs ${this.cmd.input}: ${finalName}`);
75
+ } else {
76
+ process.stdout.write(result);
77
+ }
78
+ }
79
+ } catch (err) {
80
+ console.error(err);
81
+ this.exit(1);
82
+ }
83
+ }
84
+ }
package/bin/cli-doc.ts DELETED
@@ -1,84 +0,0 @@
1
- import * as path from 'path';
2
- import * as fs from 'fs/promises';
3
-
4
- import { CliCommand, OptionConfig, ListOptionConfig } from '@travetto/cli/src/command';
5
- import { EnvInit } from '@travetto/base/bin/init';
6
- import { PathUtil } from '@travetto/boot';
7
-
8
- type Options = {
9
- input: OptionConfig<string>;
10
- output: ListOptionConfig<string>;
11
- format: OptionConfig<string>;
12
- watch: OptionConfig<boolean>;
13
- };
14
-
15
- /**
16
- * Command line support for generating module docs.
17
- */
18
- export class DocCommand extends CliCommand<Options> {
19
- name = 'doc';
20
-
21
- getOptions(): Options {
22
- return {
23
- input: this.option({ desc: 'Input File', def: 'doc.ts' }),
24
- output: this.listOption({ desc: 'Output files' }),
25
- format: this.option({ desc: 'Format', def: 'md' }),
26
- watch: this.boolOption({ desc: 'Watch' })
27
- };
28
- }
29
-
30
- async envInit(): Promise<void> {
31
- EnvInit.init({
32
- debug: '0',
33
- append: {
34
- TRV_SRC_LOCAL: 'doc',
35
- TRV_RESOURCES: 'doc/resources'
36
- },
37
- set: {
38
- TRV_CONSOLE_WIDTH: '140',
39
- TRV_CLI_JSON_IPC: '',
40
- TRV_COLOR: '0',
41
- TRV_LOG_PLAIN: '1'
42
- }
43
- });
44
- }
45
-
46
- async action(): Promise<void> {
47
- console.error(process.env);
48
-
49
- const { PhaseManager } = await import('@travetto/base');
50
- // Standard compile
51
- await PhaseManager.run('init');
52
-
53
- const { RenderUtil } = await import('../src/render/util');
54
-
55
- const docFile = PathUtil.resolveUnix(this.cmd.input);
56
-
57
- // If specifying output
58
- if (this.cmd.output.length) {
59
- const write = async (): Promise<void> => {
60
- RenderUtil.purge(docFile);
61
- for (const out of this.cmd.output) {
62
- const fmt = path.extname(out) ?? this.cmd.format;
63
- const finalName = await PathUtil.resolveUnix(out);
64
- const result = await RenderUtil.render(docFile, fmt);
65
- await fs.writeFile(finalName, result, 'utf8');
66
- }
67
- };
68
-
69
- if (this.cmd.watch) {
70
- const { WatchUtil } = await import('@travetto/watch');
71
- await WatchUtil.watchFile(docFile, write, true);
72
- } else {
73
- try {
74
- await write();
75
- } catch (err) {
76
- console.error(PathUtil.cwd, err);
77
- process.exit(1);
78
- }
79
- }
80
- } else {
81
- console.log(await RenderUtil.render(docFile, this.cmd.format));
82
- }
83
- }
84
- }
File without changes