@diplodoc/cli 4.0.0

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.
Files changed (74) hide show
  1. package/CHANGELOG.md +785 -0
  2. package/LICENSE +21 -0
  3. package/README.md +62 -0
  4. package/README.ru.md +63 -0
  5. package/build/app.client.css +47 -0
  6. package/build/app.client.js +3 -0
  7. package/build/index.js +3993 -0
  8. package/build/index.js.map +7 -0
  9. package/build/lib.js +3374 -0
  10. package/build/lib.js.map +7 -0
  11. package/build/linter.js +1265 -0
  12. package/build/linter.js.map +7 -0
  13. package/package.json +126 -0
  14. package/src/cmd/build/index.ts +304 -0
  15. package/src/cmd/index.ts +4 -0
  16. package/src/cmd/publish/index.ts +92 -0
  17. package/src/cmd/publish/upload.ts +61 -0
  18. package/src/cmd/translate/index.ts +261 -0
  19. package/src/cmd/xliff/compose.ts +222 -0
  20. package/src/cmd/xliff/extract.ts +237 -0
  21. package/src/cmd/xliff/index.ts +27 -0
  22. package/src/constants.ts +122 -0
  23. package/src/globals.d.ts +1 -0
  24. package/src/index.ts +54 -0
  25. package/src/models.ts +249 -0
  26. package/src/packages/credentials/index.ts +1 -0
  27. package/src/packages/credentials/yandex-oauth.ts +42 -0
  28. package/src/resolvers/index.ts +3 -0
  29. package/src/resolvers/lintPage.ts +119 -0
  30. package/src/resolvers/md2html.ts +142 -0
  31. package/src/resolvers/md2md.ts +147 -0
  32. package/src/services/argv.ts +38 -0
  33. package/src/services/authors.ts +64 -0
  34. package/src/services/contributors.ts +104 -0
  35. package/src/services/includers/batteries/common.ts +34 -0
  36. package/src/services/includers/batteries/generic.ts +130 -0
  37. package/src/services/includers/batteries/index.ts +3 -0
  38. package/src/services/includers/batteries/sourcedocs.ts +33 -0
  39. package/src/services/includers/batteries/unarchive.ts +97 -0
  40. package/src/services/includers/index.ts +157 -0
  41. package/src/services/index.ts +6 -0
  42. package/src/services/leading.ts +88 -0
  43. package/src/services/metadata.ts +249 -0
  44. package/src/services/plugins.ts +76 -0
  45. package/src/services/preset.ts +55 -0
  46. package/src/services/tocs.ts +401 -0
  47. package/src/services/utils.ts +151 -0
  48. package/src/steps/index.ts +6 -0
  49. package/src/steps/processAssets.ts +36 -0
  50. package/src/steps/processExcludedFiles.ts +47 -0
  51. package/src/steps/processLinter.ts +100 -0
  52. package/src/steps/processLogs.ts +18 -0
  53. package/src/steps/processMapFile.ts +35 -0
  54. package/src/steps/processPages.ts +312 -0
  55. package/src/steps/processServiceFiles.ts +95 -0
  56. package/src/steps/publishFilesToS3.ts +47 -0
  57. package/src/utils/file.ts +17 -0
  58. package/src/utils/glob.ts +14 -0
  59. package/src/utils/index.ts +8 -0
  60. package/src/utils/logger.ts +42 -0
  61. package/src/utils/markup.ts +125 -0
  62. package/src/utils/path.ts +24 -0
  63. package/src/utils/presets.ts +20 -0
  64. package/src/utils/singlePage.ts +228 -0
  65. package/src/utils/toc.ts +87 -0
  66. package/src/utils/url.ts +3 -0
  67. package/src/utils/worker.ts +10 -0
  68. package/src/validator.ts +150 -0
  69. package/src/vcs-connector/client/github.ts +52 -0
  70. package/src/vcs-connector/connector-models.ts +76 -0
  71. package/src/vcs-connector/connector-validator.ts +114 -0
  72. package/src/vcs-connector/github.ts +333 -0
  73. package/src/vcs-connector/index.ts +15 -0
  74. package/src/workers/linter/index.ts +62 -0
package/build/index.js ADDED
@@ -0,0 +1,3993 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __defProps = Object.defineProperties;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
13
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __spreadValues = (a, b) => {
15
+ for (var prop in b || (b = {}))
16
+ if (__hasOwnProp.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ if (__getOwnPropSymbols)
19
+ for (var prop of __getOwnPropSymbols(b)) {
20
+ if (__propIsEnum.call(b, prop))
21
+ __defNormalProp(a, prop, b[prop]);
22
+ }
23
+ return a;
24
+ };
25
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
26
+ var __objRest = (source, exclude) => {
27
+ var target = {};
28
+ for (var prop in source)
29
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
30
+ target[prop] = source[prop];
31
+ if (source != null && __getOwnPropSymbols)
32
+ for (var prop of __getOwnPropSymbols(source)) {
33
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
34
+ target[prop] = source[prop];
35
+ }
36
+ return target;
37
+ };
38
+ var __commonJS = (cb, mod) => function __require() {
39
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
40
+ };
41
+ var __export = (target, all) => {
42
+ for (var name4 in all)
43
+ __defProp(target, name4, { get: all[name4], enumerable: true });
44
+ };
45
+ var __copyProps = (to, from, except, desc) => {
46
+ if (from && typeof from === "object" || typeof from === "function") {
47
+ for (let key of __getOwnPropNames(from))
48
+ if (!__hasOwnProp.call(to, key) && key !== except)
49
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
50
+ }
51
+ return to;
52
+ };
53
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
54
+ // If the importer is in node compatibility mode or this is not an ESM
55
+ // file that has been converted to a CommonJS file using a Babel-
56
+ // compatible transform (i.e. "__esModule" has not been set), then set
57
+ // "default" to the CommonJS "module.exports" for node compatibility.
58
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
59
+ mod
60
+ ));
61
+ var __async = (__this, __arguments, generator) => {
62
+ return new Promise((resolve17, reject) => {
63
+ var fulfilled = (value) => {
64
+ try {
65
+ step(generator.next(value));
66
+ } catch (e) {
67
+ reject(e);
68
+ }
69
+ };
70
+ var rejected = (value) => {
71
+ try {
72
+ step(generator.throw(value));
73
+ } catch (e) {
74
+ reject(e);
75
+ }
76
+ };
77
+ var step = (x) => x.done ? resolve17(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
78
+ step((generator = generator.apply(__this, __arguments)).next());
79
+ });
80
+ };
81
+
82
+ // scripts/client.js
83
+ var require_client = __commonJS({
84
+ "scripts/client.js"(exports, module2) {
85
+ "use strict";
86
+ var path = require("path");
87
+ var CLIENT_PATH = path.dirname(require.resolve("@diplodoc/client"));
88
+ var BUILD_PATH = path.resolve(__dirname, "..", "build");
89
+ var BUNDLE_JS_FILENAME = "app.client.js";
90
+ var BUNDLE_CSS_FILENAME = "app.client.css";
91
+ var src = (target) => path.resolve(CLIENT_PATH, target);
92
+ var dst = (target) => path.resolve(BUILD_PATH, target);
93
+ module2.exports = {
94
+ dst: {
95
+ js: dst(BUNDLE_JS_FILENAME),
96
+ css: dst(BUNDLE_CSS_FILENAME)
97
+ },
98
+ src: {
99
+ js: src(BUNDLE_JS_FILENAME),
100
+ css: src(BUNDLE_CSS_FILENAME)
101
+ },
102
+ bundle: {
103
+ js(bundlePath) {
104
+ return path.join(bundlePath, BUNDLE_JS_FILENAME);
105
+ },
106
+ css(bundlePath) {
107
+ return path.join(bundlePath, BUNDLE_CSS_FILENAME);
108
+ }
109
+ }
110
+ };
111
+ }
112
+ });
113
+
114
+ // src/index.ts
115
+ var import_yargs = __toESM(require("yargs"));
116
+ var import_helpers = require("yargs/helpers");
117
+ var import_log14 = __toESM(require("@doc-tools/transform/lib/log"));
118
+ var import_register = require("threads/register");
119
+
120
+ // src/constants.ts
121
+ var import_path = require("path");
122
+ var os = require("os");
123
+ var notes = require("@doc-tools/transform/lib/plugins/notes");
124
+ var anchors = require("@doc-tools/transform/lib/plugins/anchors");
125
+ var code = require("@doc-tools/transform/lib/plugins/code");
126
+ var cut = require("@doc-tools/transform/lib/plugins/cut");
127
+ var deflist = require("@doc-tools/transform/lib/plugins/deflist");
128
+ var imsize = require("@doc-tools/transform/lib/plugins/imsize");
129
+ var meta = require("@doc-tools/transform/lib/plugins/meta");
130
+ var sup = require("@doc-tools/transform/lib/plugins/sup");
131
+ var tabs = require("@doc-tools/transform/lib/plugins/tabs");
132
+ var video = require("@doc-tools/transform/lib/plugins/video");
133
+ var includes = require("@doc-tools/transform/lib/plugins/includes");
134
+ var links = require("@doc-tools/transform/lib/plugins/links");
135
+ var images = require("@doc-tools/transform/lib/plugins/images");
136
+ var monospace = require("@doc-tools/transform/lib/plugins/monospace");
137
+ var table = require("@doc-tools/transform/lib/plugins/table");
138
+ var term = require("@doc-tools/transform/lib/plugins/term");
139
+ var changelog = require("@doc-tools/transform/lib/plugins/changelog");
140
+ var mermaid = require("@diplodoc/mermaid-extension");
141
+ var openapi = require("@diplodoc/openapi-extension");
142
+ includes.collect = require("@doc-tools/transform/lib/plugins/includes/collect");
143
+ images.collect = require("@doc-tools/transform/lib/plugins/images/collect");
144
+ changelog.collect = require("@doc-tools/transform/lib/plugins/changelog/collect");
145
+ var BUNDLE_FOLDER = "_bundle";
146
+ var TMP_INPUT_FOLDER = ".tmp_input";
147
+ var TMP_OUTPUT_FOLDER = ".tmp_output";
148
+ var MAIN_TIMER_ID = "Build time";
149
+ var YFM_CONFIG_FILENAME = ".yfm";
150
+ var REDIRECTS_FILENAME = "redirects.yaml";
151
+ var LINT_CONFIG_FILENAME = ".yfmlint";
152
+ var SINGLE_PAGE_FILENAME = "single-page.html";
153
+ var SINGLE_PAGE_DATA_FILENAME = "single-page.json";
154
+ var CUSTOM_STYLE = "custom-style";
155
+ var ResourceType = /* @__PURE__ */ ((ResourceType2) => {
156
+ ResourceType2["style"] = "style";
157
+ ResourceType2["script"] = "script";
158
+ return ResourceType2;
159
+ })(ResourceType || {});
160
+ var BUILD_FOLDER_PATH = (0, import_path.dirname)(require.resolve("@diplodoc/client"));
161
+ var YFM_PLUGINS = [
162
+ meta,
163
+ deflist,
164
+ includes,
165
+ cut,
166
+ links,
167
+ images,
168
+ notes,
169
+ anchors,
170
+ tabs,
171
+ code,
172
+ imsize,
173
+ sup,
174
+ video,
175
+ monospace,
176
+ table,
177
+ term,
178
+ openapi.transform(),
179
+ mermaid.transform(),
180
+ changelog
181
+ ];
182
+ var PROCESSING_FINISHED = "Processing finished:";
183
+ var LINTING_FINISHED = "Linting finished:";
184
+ var GETTING_ALL_CONTRIBUTORS = "Getting all contributors.";
185
+ var ALL_CONTRIBUTORS_RECEIVED = "All contributors received.";
186
+ var getMsg\u0421onfigurationMustBeProvided = (repo) => `\u0421onfiguration must be provided for ${repo} like env variables or in .yfm file`;
187
+ var FIRST_COMMIT_FROM_ROBOT_IN_GITHUB = "2dce14271359cd20d7e874956d604de087560cf4";
188
+ var REGEXP_INCLUDE_CONTENTS = new RegExp("(?<=[{%]\\sinclude\\s).+(?=\\s[%}])", "gm");
189
+ var REGEXP_INCLUDE_FILE_PATH = new RegExp("(?<=[(]).+(?=[)])", "g");
190
+ var REGEXP_AUTHOR = new RegExp("(?<=author:\\s).+(?=\\r?\\n)", "g");
191
+ var MIN_CHUNK_SIZE = Number(process.env.MIN_CHUNK_SIZE) || 1e3;
192
+ var WORKERS_COUNT = Number(process.env.WORKERS_COUNT) || os.cpus().length - 1;
193
+ var metadataBorder = "---";
194
+
195
+ // src/validator.ts
196
+ var import_path2 = require("path");
197
+ var import_fs = require("fs");
198
+ var import_js_yaml = require("js-yaml");
199
+ var import_merge = __toESM(require("lodash/merge"));
200
+ var import_log = __toESM(require("@doc-tools/transform/lib/log"));
201
+ function notEmptyStringValidator(value) {
202
+ if (typeof value === "string") {
203
+ return Boolean(value);
204
+ }
205
+ return false;
206
+ }
207
+ function requiredValueValidator(value) {
208
+ return Boolean(value);
209
+ }
210
+ var validators = {
211
+ "storageEndpoint": {
212
+ errorMessage: "Endpoint of S3 storage must be provided when publishes.",
213
+ validateFn: notEmptyStringValidator
214
+ },
215
+ "storageBucket": {
216
+ errorMessage: "Bucket name of S3 storage must be provided when publishes.",
217
+ validateFn: notEmptyStringValidator
218
+ },
219
+ "storageKeyId": {
220
+ errorMessage: "Key Id of S3 storage must be provided when publishes.",
221
+ validateFn: notEmptyStringValidator,
222
+ defaultValue: process.env.YFM_STORAGE_KEY_ID
223
+ },
224
+ "storageSecretKey": {
225
+ errorMessage: "Secret key of S3 storage must be provided when publishes.",
226
+ validateFn: notEmptyStringValidator,
227
+ defaultValue: process.env.YFM_STORAGE_SECRET_KEY
228
+ },
229
+ "storageRegion": {
230
+ errorMessage: "Region of S3 storage must be provided when publishes.",
231
+ validateFn: notEmptyStringValidator,
232
+ defaultValue: "eu-central-1"
233
+ }
234
+ };
235
+ function validateRedirects(redirectsConfig, pathToRedirects) {
236
+ const redirects = Object.keys(redirectsConfig).reduce((res, redirectSectionName) => {
237
+ const sectionRedirects = redirectsConfig[redirectSectionName];
238
+ res.push(...sectionRedirects);
239
+ return res;
240
+ }, []);
241
+ const getContext = (from, to) => ` [Context:
242
+ - from: ${from}
243
+ - to: ${to} ]`;
244
+ const formatMessage = (message, pathname, from, to) => `${pathname}: ${message} ${getContext(from, to)}`;
245
+ redirects.forEach((redirect) => {
246
+ const { from, to } = redirect;
247
+ if (!from || !to) {
248
+ throw new Error(formatMessage("One of the two parameters is missing", pathToRedirects, from, to));
249
+ }
250
+ if (from === to) {
251
+ throw new Error(formatMessage("Parameters must be different", pathToRedirects, from, to));
252
+ }
253
+ });
254
+ }
255
+ function argvValidator(argv) {
256
+ var _a, _b;
257
+ try {
258
+ const pathToConfig = argv.config ? String(argv.config) : (0, import_path2.join)(String(argv.input), YFM_CONFIG_FILENAME);
259
+ const content = (0, import_fs.readFileSync)((0, import_path2.resolve)(pathToConfig), "utf8");
260
+ Object.assign(argv, (0, import_js_yaml.load)(content) || {});
261
+ } catch (error) {
262
+ if (error.name === "YAMLException") {
263
+ import_log.default.error(`Error to parse ${YFM_CONFIG_FILENAME}: ${error.message}`);
264
+ }
265
+ }
266
+ let lintConfig = {};
267
+ try {
268
+ const pathToConfig = (0, import_path2.join)(String(argv.input), LINT_CONFIG_FILENAME);
269
+ const content = (0, import_fs.readFileSync)((0, import_path2.resolve)(pathToConfig), "utf8");
270
+ lintConfig = (0, import_js_yaml.load)(content) || {};
271
+ } catch (error) {
272
+ if (error.name === "YAMLException") {
273
+ import_log.default.error(`Error to parse ${LINT_CONFIG_FILENAME}: ${error.message}`);
274
+ }
275
+ } finally {
276
+ const preparedLintConfig = (0, import_merge.default)(lintConfig, {
277
+ "log-levels": {
278
+ MD033: argv.allowHTML ? "disabled" : "error"
279
+ }
280
+ });
281
+ Object.assign(argv, { lintConfig: preparedLintConfig });
282
+ }
283
+ try {
284
+ const pathToRedirects = (0, import_path2.join)(String(argv.input), REDIRECTS_FILENAME);
285
+ const redirectsContent = (0, import_fs.readFileSync)((0, import_path2.resolve)(pathToRedirects), "utf8");
286
+ const redirects = (0, import_js_yaml.load)(redirectsContent);
287
+ validateRedirects(redirects, pathToRedirects);
288
+ } catch (error) {
289
+ if (error.name === "YAMLException") {
290
+ import_log.default.error(`Error to parse ${REDIRECTS_FILENAME}: ${error.message}`);
291
+ }
292
+ if (error.code !== "ENOENT") {
293
+ throw error;
294
+ }
295
+ }
296
+ if (argv.publish) {
297
+ for (const [field, validator] of Object.entries(validators)) {
298
+ const value = (_a = argv[field]) != null ? _a : validator.defaultValue;
299
+ if (!validator) {
300
+ continue;
301
+ }
302
+ const validateFn = (_b = validator.validateFn) != null ? _b : requiredValueValidator;
303
+ if (!validateFn(value)) {
304
+ throw new Error(validator.errorMessage);
305
+ }
306
+ argv[field] = value;
307
+ }
308
+ }
309
+ return true;
310
+ }
311
+
312
+ // src/cmd/build/index.ts
313
+ var import_path27 = require("path");
314
+
315
+ // src/services/tocs.ts
316
+ var import_path13 = require("path");
317
+ var import_fs4 = require("fs");
318
+ var import_js_yaml4 = require("js-yaml");
319
+ var import_shelljs2 = __toESM(require("shelljs"));
320
+ var import_walk_sync = __toESM(require("walk-sync"));
321
+ var import_liquid2 = __toESM(require("@doc-tools/transform/lib/liquid"));
322
+ var import_log3 = __toESM(require("@doc-tools/transform/lib/log"));
323
+ var import_chalk2 = require("chalk");
324
+
325
+ // src/services/metadata.ts
326
+ var import_js_yaml2 = require("js-yaml");
327
+
328
+ // src/utils/logger.ts
329
+ var import_log2 = __toESM(require("@doc-tools/transform/lib/log"));
330
+ var import_chalk = require("chalk");
331
+ function writeLog(msg, fatal = false) {
332
+ const { quiet } = argv_default.getConfig();
333
+ if (quiet && !fatal) {
334
+ return;
335
+ }
336
+ console.log(msg);
337
+ }
338
+ var logger = {
339
+ info: function(pathToFile, extraMessage) {
340
+ writeLog(`${(0, import_chalk.grey)("INFO")} ${extraMessage} ${pathToFile}`);
341
+ },
342
+ proc: function(pathToFile) {
343
+ writeLog(`${(0, import_chalk.blue)("PROC")} Processing file ${pathToFile}`);
344
+ },
345
+ copy: function(pathToFile) {
346
+ writeLog(`${(0, import_chalk.green)("COPY")} Copying file ${pathToFile}`);
347
+ },
348
+ upload: function(pathToFile) {
349
+ writeLog(`${(0, import_chalk.green)("UPLOAD")} Uploading file ${pathToFile}`);
350
+ },
351
+ warn: function(pathToFile, extraMessage) {
352
+ const message = `${(0, import_chalk.yellow)("WARNING")} file: ${pathToFile} error: ${extraMessage}`;
353
+ writeLog(message);
354
+ import_log2.default.warn(`file: ${pathToFile} ${extraMessage}`);
355
+ },
356
+ error: function(pathToFile, extraMessage) {
357
+ const message = `${(0, import_chalk.red)("ERROR")} file: ${pathToFile} error: ${extraMessage}`;
358
+ writeLog(message, true);
359
+ import_log2.default.error(`file: ${pathToFile} ${extraMessage}`);
360
+ }
361
+ };
362
+
363
+ // src/utils/markup.ts
364
+ var import_process = require("process");
365
+
366
+ // src/utils/singlePage.ts
367
+ var import_node_html_parser = require("node-html-parser");
368
+ var import_path3 = require("path");
369
+ var import_utilsFS = require("@doc-tools/transform/lib/utilsFS");
370
+ var import_url = __toESM(require("url"));
371
+ var import_lodash = __toESM(require("lodash"));
372
+
373
+ // src/utils/url.ts
374
+ function isExternalHref(href) {
375
+ return href.startsWith("http") || href.startsWith("//");
376
+ }
377
+
378
+ // src/utils/singlePage.ts
379
+ var HEADERS_SELECTOR = "h1, h2, h3, h4, h5, h6";
380
+ function getNewNode(options) {
381
+ const { rawTagName, innerHTML, attrEntries } = options;
382
+ const nodeNew = (0, import_node_html_parser.parse)(`<html><${rawTagName}></${rawTagName}></html>`).querySelector(`${rawTagName}`);
383
+ if (!nodeNew) {
384
+ return null;
385
+ }
386
+ if (attrEntries) {
387
+ for (const [name4, value] of attrEntries) {
388
+ nodeNew.setAttribute(name4, value);
389
+ }
390
+ }
391
+ nodeNew.innerHTML = innerHTML;
392
+ return nodeNew;
393
+ }
394
+ function decreaseHeadingLevels(root) {
395
+ const headersSelector = "h1, h2, h3, h4, h5";
396
+ root.querySelectorAll(headersSelector).forEach((node) => {
397
+ const { rawTagName } = node;
398
+ const newHeadingLevel = Number(rawTagName.charAt(1)) + 1;
399
+ node.rawTagName = `h${newHeadingLevel}`;
400
+ });
401
+ }
402
+ function tryFixFirstPageHeader(root) {
403
+ const firstPageHeader = root.querySelector(HEADERS_SELECTOR);
404
+ if (!firstPageHeader || firstPageHeader.rawTagName === "h1") {
405
+ return;
406
+ }
407
+ firstPageHeader.rawTagName = "h1";
408
+ }
409
+ function replaceLinks(rootEl, options) {
410
+ const { root, path, tocDir } = options;
411
+ rootEl.querySelectorAll('a:not(.yfm-anchor):not([target="_blank"])').forEach((node) => {
412
+ const href = node.getAttribute("href") || "";
413
+ const resolvedPath = (0, import_path3.resolve)(root, path);
414
+ const linkFullPath = (0, import_utilsFS.resolveRelativePath)(resolvedPath, href);
415
+ const isLinkOutOfToc = !linkFullPath.startsWith(tocDir);
416
+ let preparedHref = href;
417
+ if (isLinkOutOfToc) {
418
+ preparedHref = (0, import_path3.relative)(tocDir, linkFullPath);
419
+ } else {
420
+ const { pathname, hash } = import_url.default.parse(href);
421
+ if (pathname) {
422
+ preparedHref = getSinglePageAnchorId({
423
+ root,
424
+ currentPath: resolvedPath,
425
+ pathname,
426
+ hash
427
+ });
428
+ } else if (hash) {
429
+ preparedHref = getSinglePageAnchorId({ root, currentPath: resolvedPath, hash });
430
+ }
431
+ }
432
+ node.setAttribute("href", preparedHref);
433
+ });
434
+ }
435
+ function replaceImages(rootEl, options) {
436
+ const { root, path, tocDir } = options;
437
+ rootEl.querySelectorAll("img").forEach((node) => {
438
+ const href = node.getAttribute("src") || "";
439
+ if (isExternalHref(href)) {
440
+ return;
441
+ }
442
+ const resolvedPath = (0, import_path3.resolve)(root, path);
443
+ const linkFullPath = (0, import_utilsFS.resolveRelativePath)(resolvedPath, href);
444
+ const preparedHref = (0, import_path3.relative)(tocDir, linkFullPath);
445
+ node.setAttribute("src", preparedHref);
446
+ });
447
+ }
448
+ function prepareAnchorAttr(name4, value, pageId) {
449
+ switch (name4) {
450
+ case "href":
451
+ return `#${pageId}_${value.slice(1)}`;
452
+ case "id":
453
+ return `${pageId}_${value}`;
454
+ default:
455
+ return value;
456
+ }
457
+ }
458
+ function prepareAnchorAttrs(node, pageId) {
459
+ for (const [name4, value] of Object.entries(node.attributes)) {
460
+ const preparedValue = prepareAnchorAttr(name4, value, pageId);
461
+ node.setAttribute(name4, preparedValue);
462
+ }
463
+ }
464
+ function addPagePrefixToAnchors(rootEl, options) {
465
+ const { root, path } = options;
466
+ const resolvedPath = (0, import_path3.resolve)(root, path);
467
+ const pageIdAnchor = getSinglePageAnchorId({ root, currentPath: resolvedPath });
468
+ const originalArticleHref = transformLinkToOriginalArticle({ root, currentPath: resolvedPath });
469
+ const pageId = pageIdAnchor.slice(1);
470
+ const anchorSelector = ".yfm-anchor";
471
+ rootEl.querySelectorAll(anchorSelector).forEach((node) => {
472
+ prepareAnchorAttrs(node, pageId);
473
+ });
474
+ const mainHeader = rootEl.querySelector("h1");
475
+ if (mainHeader) {
476
+ const anchor = (0, import_node_html_parser.parse)(`<a class="yfm-anchor" aria-hidden="true" href="${pageIdAnchor}" id="${pageId}"></a>`);
477
+ if (!anchor) {
478
+ return;
479
+ }
480
+ mainHeader.setAttribute("data-original-article", `${originalArticleHref}.html`);
481
+ mainHeader.appendChild(anchor);
482
+ }
483
+ rootEl.querySelectorAll(HEADERS_SELECTOR).forEach((node) => {
484
+ prepareAnchorAttrs(node, pageId);
485
+ });
486
+ }
487
+ function addMainTitle(rootEl, options) {
488
+ const { title } = options;
489
+ if (!title) {
490
+ return;
491
+ }
492
+ const mainTitle = getNewNode({ innerHTML: title, rawTagName: "h1" });
493
+ if (!mainTitle) {
494
+ return;
495
+ }
496
+ rootEl.insertAdjacentHTML("afterbegin", mainTitle.toString());
497
+ }
498
+ function getSinglePageAnchorId(args) {
499
+ const { root, currentPath, pathname, hash } = args;
500
+ let resultAnchor = currentPath;
501
+ if (pathname) {
502
+ resultAnchor = (0, import_utilsFS.resolveRelativePath)(currentPath, pathname);
503
+ }
504
+ resultAnchor = resultAnchor.replace(root, "").replace(/\.(md|ya?ml|html)$/i, "").replace(new RegExp(import_lodash.default.escapeRegExp(import_path3.sep), "gi"), "_");
505
+ if (hash) {
506
+ resultAnchor = resultAnchor + "_" + hash.slice(1);
507
+ }
508
+ return `#${resultAnchor}`;
509
+ }
510
+ function transformLinkToOriginalArticle(opts) {
511
+ const { root, currentPath } = opts;
512
+ return currentPath.replace(root, "").replace(/\.(md|ya?ml|html)$/i, "");
513
+ }
514
+ function preprocessPageHtmlForSinglePage(content, options) {
515
+ const root = (0, import_node_html_parser.parse)(content);
516
+ addMainTitle(root, options);
517
+ tryFixFirstPageHeader(root);
518
+ addPagePrefixToAnchors(root, options);
519
+ decreaseHeadingLevels(root);
520
+ replaceLinks(root, options);
521
+ replaceImages(root, options);
522
+ return root.toString();
523
+ }
524
+
525
+ // src/utils/markup.ts
526
+ var import_client = require("@diplodoc/client");
527
+ var import_client2 = __toESM(require_client());
528
+ function generateStaticMarkup(props, pathToBundle) {
529
+ const { title: metaTitle, style, script } = props.data.meta || {};
530
+ const { title: tocTitle } = props.data.toc;
531
+ const { title: pageTitle } = props.data;
532
+ const title = getTitle({
533
+ metaTitle,
534
+ tocTitle,
535
+ pageTitle
536
+ });
537
+ const resources = getResources({ style, script });
538
+ const { staticContent } = argv_default.getConfig();
539
+ const html = staticContent ? (0, import_client.render)(props) : "";
540
+ return `
541
+ <!DOCTYPE html>
542
+ <html lang="${props.lang}">
543
+ <head>
544
+ <meta charset="utf-8">
545
+ ${getMetadata(props.data.meta)}
546
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
547
+ <title>${title}</title>
548
+ <style type="text/css">
549
+ body {
550
+ height: 100vh;
551
+ }
552
+ </style>
553
+ <link type="text/css" rel="stylesheet" href="${import_client2.default.bundle.css(pathToBundle)}" />
554
+ ${plugins_exports.getHeadContent()}
555
+ ${resources}
556
+ </head>
557
+ <body class="yc-root yc-root_theme_light">
558
+ <div id="root">${html}</div>
559
+ <script type="application/javascript">
560
+ window.STATIC_CONTENT = ${staticContent}
561
+ window.__DATA__ = ${JSON.stringify(props)};
562
+ </script>
563
+ <script type="application/javascript" src="${import_client2.default.bundle.js(pathToBundle)}"></script>
564
+ </body>
565
+ </html>
566
+ `;
567
+ }
568
+ function getTitle({ tocTitle, metaTitle, pageTitle }) {
569
+ const resultPageTitle = metaTitle || pageTitle;
570
+ if (!resultPageTitle && tocTitle) {
571
+ return tocTitle;
572
+ }
573
+ if (resultPageTitle && !tocTitle) {
574
+ return resultPageTitle;
575
+ }
576
+ return resultPageTitle && tocTitle ? `${resultPageTitle} | ${tocTitle}` : "";
577
+ }
578
+ function getMetadata(metadata) {
579
+ if (!metadata) {
580
+ return "";
581
+ }
582
+ const metaEntries = Object.entries(metadata).filter(([key]) => !Object.keys(ResourceType).includes(key));
583
+ return metaEntries.map(([name4, content]) => {
584
+ return `<meta name="${name4}" content="${content}">`;
585
+ }).join("\n");
586
+ }
587
+ function getResources({ style, script }) {
588
+ const resourcesTags = [];
589
+ if (style) {
590
+ style.forEach((el, id) => resourcesTags.push(
591
+ `<link rel="stylesheet" type="text/css" href="${el}" ${id === 0 && `id="${CUSTOM_STYLE}"`}>`
592
+ ));
593
+ }
594
+ if (script) {
595
+ script.forEach((el) => resourcesTags.push(
596
+ `<script src="${el}"></script>`
597
+ ));
598
+ }
599
+ return resourcesTags.join("\n");
600
+ }
601
+ var \u0441arriage = import_process.platform === "win32" /* WINDOWS */ ? "\r\n" : "\n";
602
+ function joinSinglePageResults(singlePageResults2, root, tocDir) {
603
+ const delimeter = `${\u0441arriage}${\u0441arriage}<hr class="yfm-page__delimeter">${\u0441arriage}${\u0441arriage}`;
604
+ return singlePageResults2.filter(({ content }) => content).map(({ content, path, title }) => preprocessPageHtmlForSinglePage(content, { root, path, tocDir, title })).join(delimeter);
605
+ }
606
+ function replaceDoubleToSingleQuotes(str) {
607
+ return str.replace(/"/g, "'");
608
+ }
609
+
610
+ // src/utils/path.ts
611
+ var import_path4 = require("path");
612
+ function addSlashPrefix(path) {
613
+ const slashPrefix = path.startsWith(import_path4.sep) ? "" : import_path4.sep;
614
+ return `${slashPrefix}${path}`;
615
+ }
616
+ function convertBackSlashToSlash(path) {
617
+ if (process.platform === "win32" /* WINDOWS */) {
618
+ return path.replace(/\\/g, "/");
619
+ }
620
+ return path;
621
+ }
622
+
623
+ // src/utils/toc.ts
624
+ var import_path5 = require("path");
625
+
626
+ // src/services/utils.ts
627
+ var import_evaluation = __toESM(require("@doc-tools/transform/lib/liquid/evaluation"));
628
+ var import_liquid = __toESM(require("@doc-tools/transform/lib/liquid"));
629
+ function filterFiles(items, itemsKey, vars, options) {
630
+ if (!Array.isArray(items)) {
631
+ return [];
632
+ }
633
+ const reducer = (results, item) => {
634
+ if (shouldProcessItem(item, vars, options)) {
635
+ const prop = item[itemsKey];
636
+ if (prop) {
637
+ const filteredProperty = filterFiles(prop, itemsKey, vars, options);
638
+ if (filteredProperty.length) {
639
+ results.push(__spreadProps(__spreadValues({}, item), {
640
+ [itemsKey]: filteredProperty
641
+ }));
642
+ }
643
+ } else {
644
+ results.push(item);
645
+ }
646
+ }
647
+ return results;
648
+ };
649
+ return items.reduce(reducer, []);
650
+ }
651
+ function filterTextItems(items, vars, options) {
652
+ if (!Array.isArray(items)) {
653
+ return items;
654
+ }
655
+ return items.reduce((result, item) => {
656
+ if (!isObject(item)) {
657
+ result.push(item);
658
+ return result;
659
+ }
660
+ const useItem = shouldProcessItem(item, vars, options);
661
+ if (useItem) {
662
+ if (Array.isArray(item.text)) {
663
+ result.push(...item.text);
664
+ } else {
665
+ result.push(item.text);
666
+ }
667
+ }
668
+ return result;
669
+ }, []);
670
+ }
671
+ function firstFilterTextItems(items, vars, options) {
672
+ const filteredItems = filterTextItems(items, vars, options);
673
+ if (!Array.isArray(filteredItems)) {
674
+ return filteredItems || "";
675
+ }
676
+ return filteredItems[0] || "";
677
+ }
678
+ function shouldProcessItem(item, vars, options) {
679
+ const { resolveConditions, removeHiddenTocItems } = options || {};
680
+ let useItem = true;
681
+ if (resolveConditions) {
682
+ const { when } = item;
683
+ useItem = when === true || when === void 0 || typeof when === "string" && (0, import_evaluation.default)(when, vars);
684
+ delete item.when;
685
+ }
686
+ if (useItem && removeHiddenTocItems) {
687
+ useItem = !item.hidden;
688
+ delete item.hidden;
689
+ }
690
+ return useItem;
691
+ }
692
+ function liquidFields(fields, vars, path) {
693
+ if (typeof fields === "string") {
694
+ return liquidField(fields, vars, path);
695
+ }
696
+ if (!Array.isArray(fields)) {
697
+ return fields;
698
+ }
699
+ return fields.map((item) => {
700
+ if (typeof item === "string") {
701
+ return liquidField(item, vars, path);
702
+ }
703
+ return item;
704
+ });
705
+ }
706
+ function liquidField(input, vars, path) {
707
+ const { applyPresets, resolveConditions } = argv_default.getConfig();
708
+ if (!applyPresets && !resolveConditions) {
709
+ return input;
710
+ }
711
+ return (0, import_liquid.default)(input, vars, path, {
712
+ substitutions: applyPresets,
713
+ conditions: resolveConditions,
714
+ keepNotVar: true,
715
+ withSourceMap: false
716
+ });
717
+ }
718
+ function isObject(o) {
719
+ return typeof o === "object" && o !== null;
720
+ }
721
+
722
+ // src/utils/toc.ts
723
+ function transformToc(toc, pathToFileDirectory) {
724
+ if (!toc) {
725
+ return null;
726
+ }
727
+ const localToc = JSON.parse(JSON.stringify(toc));
728
+ if (localToc.items) {
729
+ localToc.items = filterFiles(localToc.items, "items", {}, {
730
+ removeHiddenTocItems: true
731
+ });
732
+ }
733
+ const baseTocPath = localToc.base || "";
734
+ const navigationItemQueue = [localToc];
735
+ while (navigationItemQueue.length) {
736
+ const navigationItem = navigationItemQueue.shift();
737
+ if (!navigationItem) {
738
+ continue;
739
+ }
740
+ const { items, href } = navigationItem;
741
+ if (items) {
742
+ navigationItemQueue.push(...navigationItem.items);
743
+ }
744
+ if (href && !isExternalHref(href)) {
745
+ const pathToIndexDirectory = (0, import_path5.relative)(pathToFileDirectory, baseTocPath);
746
+ const fileExtension = (0, import_path5.extname)(href);
747
+ const filename = (0, import_path5.basename)(href, fileExtension);
748
+ const transformedFilename = (0, import_path5.format)({
749
+ name: filename,
750
+ ext: ".html"
751
+ });
752
+ navigationItem.href = (0, import_path5.join)(pathToIndexDirectory, (0, import_path5.dirname)(href), transformedFilename);
753
+ }
754
+ }
755
+ return localToc;
756
+ }
757
+ function transformTocForSinglePage(toc, options) {
758
+ const { root, currentPath } = options;
759
+ if (!toc) {
760
+ return null;
761
+ }
762
+ const localToc = JSON.parse(JSON.stringify(toc));
763
+ if (localToc.items) {
764
+ localToc.items = filterFiles(localToc.items, "items", {}, {
765
+ removeHiddenTocItems: true
766
+ });
767
+ }
768
+ function processItems(items) {
769
+ items.forEach((item) => {
770
+ if (item.items) {
771
+ processItems(item.items);
772
+ }
773
+ if (item.href && !isExternalHref(item.href)) {
774
+ item.href = getSinglePageAnchorId({ root, currentPath, pathname: item.href });
775
+ }
776
+ });
777
+ }
778
+ processItems(localToc.items);
779
+ localToc.singlePage = true;
780
+ return localToc;
781
+ }
782
+
783
+ // src/utils/presets.ts
784
+ var import_path6 = require("path");
785
+ function getVarsPerFile(filePath) {
786
+ const { vars: argVars } = argv_default.getConfig();
787
+ return __spreadValues(__spreadValues({}, preset_default.get((0, import_path6.dirname)(filePath))), argVars);
788
+ }
789
+ function getVarsPerRelativeFile(filePath) {
790
+ const { input } = argv_default.getConfig();
791
+ const root = (0, import_path6.resolve)(input);
792
+ const relativeFilePath = (0, import_path6.relative)(root, filePath);
793
+ return getVarsPerFile(relativeFilePath);
794
+ }
795
+
796
+ // src/utils/glob.ts
797
+ var import_glob = __toESM(require("glob"));
798
+ var glob = (pattern, options) => __async(void 0, null, function* () {
799
+ return new Promise((res, rej) => {
800
+ const state = (0, import_glob.default)(
801
+ pattern,
802
+ options,
803
+ (err) => err ? rej(err) : res({ state })
804
+ );
805
+ });
806
+ });
807
+
808
+ // src/utils/file.ts
809
+ var import_path7 = require("path");
810
+ var import_shelljs = __toESM(require("shelljs"));
811
+ var import_fs2 = require("fs");
812
+ function copyFiles(inputFolderPath, outputFolderPath, files) {
813
+ for (const pathToAsset of files) {
814
+ const outputDir = (0, import_path7.resolve)(outputFolderPath, (0, import_path7.dirname)(pathToAsset));
815
+ const from = (0, import_path7.resolve)(inputFolderPath, pathToAsset);
816
+ const to = (0, import_path7.resolve)(outputFolderPath, pathToAsset);
817
+ import_shelljs.default.mkdir("-p", outputDir);
818
+ (0, import_fs2.copyFileSync)(from, to);
819
+ logger.copy(pathToAsset);
820
+ }
821
+ }
822
+
823
+ // src/services/authors.ts
824
+ function updateAuthorMetadataStringByAuthorLogin(authorLogin, vcsConnector) {
825
+ return __async(this, null, function* () {
826
+ if (!vcsConnector) {
827
+ return "";
828
+ }
829
+ const user = yield getAuthorDetails(vcsConnector, authorLogin);
830
+ if (user) {
831
+ return user;
832
+ }
833
+ return "";
834
+ });
835
+ }
836
+ function updateAuthorMetadataStringByFilePath(filePath, vcsConnector) {
837
+ return __async(this, null, function* () {
838
+ if (!vcsConnector) {
839
+ return "";
840
+ }
841
+ const user = vcsConnector.getExternalAuthorByPath(filePath);
842
+ if (user) {
843
+ const author = replaceDoubleToSingleQuotes(JSON.stringify(user));
844
+ return author;
845
+ }
846
+ return "";
847
+ });
848
+ }
849
+ function getAuthorDetails(vcsConnector, author) {
850
+ return __async(this, null, function* () {
851
+ if (typeof author === "object") {
852
+ return replaceDoubleToSingleQuotes(JSON.stringify(author));
853
+ }
854
+ try {
855
+ JSON.parse(author);
856
+ return replaceDoubleToSingleQuotes(author);
857
+ } catch (e) {
858
+ const user = yield vcsConnector.getUserByLogin(author);
859
+ if (user) {
860
+ return replaceDoubleToSingleQuotes(JSON.stringify(user));
861
+ }
862
+ return null;
863
+ }
864
+ });
865
+ }
866
+
867
+ // src/services/contributors.ts
868
+ var import_promises = require("fs/promises");
869
+ var import_path8 = require("path");
870
+ function getFileContributorsMetadata(fileData, vcsConnector) {
871
+ return __async(this, null, function* () {
872
+ const contributors = yield getFileContributorsString(fileData, vcsConnector);
873
+ return `contributors: ${contributors}`;
874
+ });
875
+ }
876
+ function getFileContributorsString(fileData, vcsConnector) {
877
+ return __async(this, null, function* () {
878
+ const { tmpInputFilePath, inputFolderPathLength } = fileData;
879
+ const relativeFilePath = tmpInputFilePath.substring(inputFolderPathLength);
880
+ const fileContributors = yield vcsConnector.getContributorsByPath(relativeFilePath);
881
+ let nestedContributors = {};
882
+ if (!fileContributors.hasIncludes) {
883
+ nestedContributors = yield getContributorsForNestedFiles(fileData, vcsConnector);
884
+ vcsConnector.addNestedContributorsForPath(relativeFilePath, nestedContributors);
885
+ }
886
+ const fileContributorsWithContributorsIncludedFiles = __spreadValues(__spreadValues({}, fileContributors.contributors), nestedContributors);
887
+ const contributorsArray = Object.entries(fileContributorsWithContributorsIncludedFiles).map(([, contributor]) => contributor);
888
+ return replaceDoubleToSingleQuotes(JSON.stringify(contributorsArray));
889
+ });
890
+ }
891
+ function getContributorsForNestedFiles(fileData, vcsConnector) {
892
+ return __async(this, null, function* () {
893
+ const { fileContent, inputFolderPathLength } = fileData;
894
+ const includeContents = fileContent.match(REGEXP_INCLUDE_CONTENTS);
895
+ if (!includeContents || includeContents.length === 0) {
896
+ return {};
897
+ }
898
+ const includesContributors = [];
899
+ const relativeIncludeFilePaths = getRelativeIncludeFilePaths(fileData, includeContents);
900
+ for (const relativeIncludeFilePath of relativeIncludeFilePaths.values()) {
901
+ const relativeFilePath = relativeIncludeFilePath.substring(inputFolderPathLength);
902
+ const includeContributors = yield vcsConnector.getContributorsByPath(relativeFilePath);
903
+ let nestedContributors = {};
904
+ if (!includeContributors.hasIncludes) {
905
+ let contentIncludeFile;
906
+ try {
907
+ contentIncludeFile = yield (0, import_promises.readFile)(relativeIncludeFilePath, "utf8");
908
+ } catch (err) {
909
+ if (err.code === "ENOENT") {
910
+ continue;
911
+ }
912
+ throw err;
913
+ }
914
+ const newFileData = __spreadProps(__spreadValues({}, fileData), {
915
+ fileContent: contentIncludeFile,
916
+ tmpInputFilePath: relativeIncludeFilePath
917
+ });
918
+ nestedContributors = yield getContributorsForNestedFiles(newFileData, vcsConnector);
919
+ vcsConnector.addNestedContributorsForPath(relativeFilePath, nestedContributors);
920
+ }
921
+ includesContributors.push(includeContributors.contributors);
922
+ includesContributors.push(nestedContributors);
923
+ }
924
+ return Object.assign({}, ...includesContributors);
925
+ });
926
+ }
927
+ function getRelativeIncludeFilePaths(fileData, includeContents) {
928
+ const { tmpInputFilePath } = fileData;
929
+ const relativeIncludeFilePaths = /* @__PURE__ */ new Set();
930
+ includeContents.forEach((includeContent) => {
931
+ const relativeIncludeFilePath = includeContent.match(REGEXP_INCLUDE_FILE_PATH);
932
+ if (relativeIncludeFilePath && relativeIncludeFilePath.length !== 0) {
933
+ const relativeIncludeFilePathWithoutHash = relativeIncludeFilePath[0].split("#");
934
+ const includeFilePath = (0, import_path8.join)((0, import_path8.dirname)(tmpInputFilePath), relativeIncludeFilePathWithoutHash[0]);
935
+ relativeIncludeFilePaths.add(includeFilePath);
936
+ }
937
+ });
938
+ return relativeIncludeFilePaths;
939
+ }
940
+
941
+ // src/services/metadata.ts
942
+ var import_path9 = require("path");
943
+ function getContentWithUpdatedMetadata(fileContent, options, systemVars) {
944
+ return __async(this, null, function* () {
945
+ var _a;
946
+ let result;
947
+ result = getContentWithUpdatedStaticMetadata({
948
+ fileContent,
949
+ sourcePath: (_a = options == null ? void 0 : options.fileData) == null ? void 0 : _a.sourcePath,
950
+ addSystemMeta: options == null ? void 0 : options.addSystemMeta,
951
+ addSourcePath: options == null ? void 0 : options.addSourcePath,
952
+ resources: options == null ? void 0 : options.resources,
953
+ systemVars
954
+ });
955
+ result = yield getContentWithUpdatedDynamicMetadata(result, options);
956
+ return result;
957
+ });
958
+ }
959
+ function getContentWithUpdatedStaticMetadata({
960
+ fileContent,
961
+ sourcePath,
962
+ addSystemMeta,
963
+ addSourcePath,
964
+ resources,
965
+ systemVars
966
+ }) {
967
+ const newMetadatas = [];
968
+ if ((!addSystemMeta || !systemVars) && !addSourcePath && !resources) {
969
+ return fileContent;
970
+ }
971
+ const matches = matchMetadata(fileContent);
972
+ if (addSystemMeta && systemVars && isObject(systemVars)) {
973
+ newMetadatas.push(getSystemVarsMetadataString(systemVars));
974
+ }
975
+ if (resources) {
976
+ newMetadatas.push((0, import_js_yaml2.dump)(resources));
977
+ }
978
+ if (addSourcePath && sourcePath) {
979
+ const sourcePathMetadataString = `sourcePath: ${sourcePath}`;
980
+ newMetadatas.push(sourcePathMetadataString);
981
+ }
982
+ if (matches && matches.length > 0) {
983
+ const [, fileMetadata, , fileMainContent] = matches;
984
+ return `${getUpdatedMetadataString(newMetadatas, fileMetadata)}${fileMainContent}`;
985
+ }
986
+ return `${getUpdatedMetadataString(newMetadatas)}${fileContent}`;
987
+ }
988
+ function getContentWithUpdatedDynamicMetadata(fileContent, options) {
989
+ return __async(this, null, function* () {
990
+ if (!options || !(options == null ? void 0 : options.isContributorsEnabled)) {
991
+ return fileContent;
992
+ }
993
+ let fileMetadata, fileMainContent;
994
+ const matches = matchMetadata(fileContent);
995
+ if (matches && matches.length > 0) {
996
+ const [, matchedFileMetadata, , matchedFileMainContent] = matches;
997
+ fileMetadata = matchedFileMetadata;
998
+ fileMainContent = matchedFileMainContent;
999
+ }
1000
+ const newMetadatas = [];
1001
+ const { isContributorsEnabled } = options;
1002
+ if (isContributorsEnabled) {
1003
+ const contributorsMetaData = yield getContributorsMetadataString(options, fileContent);
1004
+ if (contributorsMetaData) {
1005
+ newMetadatas.push(contributorsMetaData);
1006
+ }
1007
+ let authorMetadata = "";
1008
+ if (fileMetadata) {
1009
+ const matchAuthor = fileMetadata.match(REGEXP_AUTHOR);
1010
+ if (matchAuthor) {
1011
+ const matchedAuthor = matchAuthor[0];
1012
+ authorMetadata = yield updateAuthorMetadataStringByAuthorLogin(matchedAuthor, options.vcsConnector);
1013
+ }
1014
+ }
1015
+ if (!authorMetadata) {
1016
+ const { fileData: { tmpInputFilePath, inputFolderPathLength } } = options;
1017
+ const relativeFilePath = tmpInputFilePath.substring(inputFolderPathLength);
1018
+ authorMetadata = yield updateAuthorMetadataStringByFilePath(relativeFilePath, options.vcsConnector);
1019
+ }
1020
+ if (authorMetadata) {
1021
+ newMetadatas.push(`author: ${authorMetadata}`);
1022
+ }
1023
+ }
1024
+ if (fileMetadata && fileMainContent) {
1025
+ let updatedFileMetadata = fileMetadata;
1026
+ const matchAuthor = fileMetadata.match(REGEXP_AUTHOR);
1027
+ const isNewMetadataIncludesAuthor = newMetadatas.some((item) => /^author: /.test(item));
1028
+ if (matchAuthor && isNewMetadataIncludesAuthor) {
1029
+ updatedFileMetadata = updatedFileMetadata.replace(`author: ${matchAuthor[0]}`, "");
1030
+ }
1031
+ return `${getUpdatedMetadataString(newMetadatas, updatedFileMetadata)}${fileMainContent}`;
1032
+ }
1033
+ return `${getUpdatedMetadataString(newMetadatas)}${fileContent}`;
1034
+ });
1035
+ }
1036
+ function matchMetadata(fileContent) {
1037
+ if (!fileContent.startsWith("---")) {
1038
+ return null;
1039
+ }
1040
+ const regexpMetadata = "(?<=-{3}\\r?\\n)((.*\\r?\\n)*?)(?=-{3}\\r?\\n)";
1041
+ const regexpFileContent = "-{3}((.*[\r?\n]*)*)";
1042
+ const regexpParseFileContent = new RegExp(`${regexpMetadata}${regexpFileContent}`, "gm");
1043
+ return regexpParseFileContent.exec(fileContent);
1044
+ }
1045
+ function getContributorsMetadataString(options, fileContent) {
1046
+ return __async(this, null, function* () {
1047
+ const { isContributorsEnabled, vcsConnector, fileData } = options;
1048
+ if (isContributorsEnabled && vcsConnector) {
1049
+ const updatedFileData = __spreadProps(__spreadValues({}, fileData), {
1050
+ fileContent
1051
+ });
1052
+ return getFileContributorsMetadata(updatedFileData, vcsConnector);
1053
+ }
1054
+ return void 0;
1055
+ });
1056
+ }
1057
+ function getUpdatedMetadataString(newMetadatas, defaultMetadata = "") {
1058
+ const newMetadata = newMetadatas.join(\u0441arriage) + (newMetadatas.length ? \u0441arriage : "");
1059
+ const preparedDefaultMetadata = defaultMetadata.trimRight();
1060
+ const defaultMetadata\u0421arriage = preparedDefaultMetadata ? \u0441arriage : "";
1061
+ const updatedMetadata = `${preparedDefaultMetadata}${defaultMetadata\u0421arriage}${newMetadata}`;
1062
+ return `${metadataBorder}${\u0441arriage}${updatedMetadata}${metadataBorder}${defaultMetadata.length ? "" : \u0441arriage}`;
1063
+ }
1064
+ function getUpdatedMetadata(options, fileContent, meta2) {
1065
+ return __async(this, null, function* () {
1066
+ const { vcsConnector } = options;
1067
+ const newMetadata = {
1068
+ contributors: yield getContributorsMetadata(options, fileContent)
1069
+ };
1070
+ if (!meta2) {
1071
+ return newMetadata;
1072
+ }
1073
+ const updatedAuthor = yield getAuthorMetadata(meta2, vcsConnector);
1074
+ return __spreadProps(__spreadValues(__spreadValues({}, meta2), newMetadata), {
1075
+ author: updatedAuthor
1076
+ });
1077
+ });
1078
+ }
1079
+ function getContributorsMetadata(options, fileContent) {
1080
+ return __async(this, null, function* () {
1081
+ const { isContributorsEnabled, vcsConnector, fileData } = options;
1082
+ if (isContributorsEnabled && vcsConnector) {
1083
+ const updatedFileData = __spreadProps(__spreadValues({}, fileData), {
1084
+ fileContent
1085
+ });
1086
+ return getFileContributorsString(updatedFileData, vcsConnector);
1087
+ }
1088
+ return JSON.stringify([]);
1089
+ });
1090
+ }
1091
+ function getAuthorMetadata(meta2, vcsConnector) {
1092
+ return __async(this, null, function* () {
1093
+ if (meta2.author && vcsConnector) {
1094
+ const updatedAuthor = yield getAuthorDetails(vcsConnector, meta2.author);
1095
+ return updatedAuthor;
1096
+ }
1097
+ return null;
1098
+ });
1099
+ }
1100
+ function getSystemVarsMetadataString(systemVars) {
1101
+ return `__system: ${JSON.stringify(systemVars)}`;
1102
+ }
1103
+ function getAssetsPublicPath(filePath) {
1104
+ const { input } = argv_default.getConfig();
1105
+ const path = (0, import_path9.resolve)(input, filePath);
1106
+ return (0, import_path9.relative)((0, import_path9.dirname)(path), (0, import_path9.resolve)(input));
1107
+ }
1108
+
1109
+ // src/services/includers/index.ts
1110
+ var includers_exports = {};
1111
+ __export(includers_exports, {
1112
+ IncludersError: () => IncludersError,
1113
+ applyIncluders: () => applyIncluders,
1114
+ init: () => init
1115
+ });
1116
+ var import_path12 = require("path");
1117
+ var import_lodash3 = require("lodash");
1118
+
1119
+ // src/services/includers/batteries/generic.ts
1120
+ var generic_exports = {};
1121
+ __export(generic_exports, {
1122
+ default: () => generic_default,
1123
+ includerFunction: () => includerFunction,
1124
+ name: () => name
1125
+ });
1126
+ var import_promises2 = require("fs/promises");
1127
+ var import_path10 = require("path");
1128
+ var import_lodash2 = require("lodash");
1129
+ var import_js_yaml3 = require("js-yaml");
1130
+ var GenericIncluderError = class extends Error {
1131
+ constructor(message, path) {
1132
+ super(message);
1133
+ this.name = "GenericIncluderError";
1134
+ this.path = path;
1135
+ }
1136
+ };
1137
+ var name = "generic";
1138
+ var MD_GLOB = "**/*.md";
1139
+ function includerFunction(params) {
1140
+ return __async(this, null, function* () {
1141
+ var _a, _b;
1142
+ const { readBasePath, writeBasePath, tocPath, item, passedParams: { input, leadingPage }, index } = params;
1143
+ if (!(input == null ? void 0 : input.length) || !((_a = item.include) == null ? void 0 : _a.path)) {
1144
+ throw new GenericIncluderError("provide includer with input parameter", tocPath);
1145
+ }
1146
+ try {
1147
+ const leadingPageName = (_b = leadingPage == null ? void 0 : leadingPage.name) != null ? _b : "Overview";
1148
+ const tocDirPath = (0, import_path10.dirname)(tocPath);
1149
+ const contentPath = index === 0 ? (0, import_path10.join)(writeBasePath, tocDirPath, input) : (0, import_path10.join)(readBasePath, tocDirPath, input);
1150
+ let cache = {};
1151
+ let found = [];
1152
+ ({ state: { found, cache } } = yield glob(MD_GLOB, {
1153
+ cwd: contentPath,
1154
+ nosort: true,
1155
+ nocase: true,
1156
+ cache
1157
+ }));
1158
+ const writePath = (0, import_path10.join)(writeBasePath, tocDirPath, item.include.path);
1159
+ yield (0, import_promises2.mkdir)(writePath, { recursive: true });
1160
+ for (const filePath of found) {
1161
+ const file = yield (0, import_promises2.readFile)((0, import_path10.join)(contentPath, filePath));
1162
+ yield (0, import_promises2.mkdir)((0, import_path10.dirname)((0, import_path10.join)(writePath, filePath)), { recursive: true });
1163
+ yield (0, import_promises2.writeFile)((0, import_path10.join)(writePath, filePath), file);
1164
+ }
1165
+ const graph = createGraphFromPaths(found);
1166
+ const toc = createToc(leadingPageName, item.include.path)(graph, []);
1167
+ yield (0, import_promises2.writeFile)((0, import_path10.join)(writePath, "toc.yaml"), (0, import_js_yaml3.dump)(toc));
1168
+ } catch (err) {
1169
+ throw new GenericIncluderError(err.toString(), tocPath);
1170
+ }
1171
+ });
1172
+ }
1173
+ function createGraphFromPaths(paths) {
1174
+ const graph = {};
1175
+ for (const path of paths) {
1176
+ const chunks = path.split("/").filter(Boolean);
1177
+ if (chunks.length < 2) {
1178
+ if (chunks.length === 1) {
1179
+ graph.files = chunks;
1180
+ }
1181
+ continue;
1182
+ }
1183
+ const file = chunks.pop();
1184
+ (0, import_lodash2.updateWith)(graph, chunks, (old) => {
1185
+ return old ? { files: [...old.files, file] } : { files: [file] };
1186
+ }, Object);
1187
+ }
1188
+ return graph;
1189
+ }
1190
+ function createToc(leadingPageName, tocName) {
1191
+ return function createTocRec(graph, cursor) {
1192
+ var _a, _b;
1193
+ const handler6 = (file) => ({
1194
+ name: (0, import_path10.parse)(file).name === "index" ? leadingPageName : file,
1195
+ href: (0, import_path10.join)(...cursor, file)
1196
+ });
1197
+ const recurse = (key) => createTocRec(graph[key], [...cursor, key]);
1198
+ const current = {
1199
+ name: (_a = cursor[cursor.length - 1]) != null ? _a : tocName,
1200
+ items: [
1201
+ ...((_b = graph.files) != null ? _b : []).map(handler6),
1202
+ ...Object.keys(graph).filter((key) => key !== "files").map(recurse)
1203
+ ]
1204
+ };
1205
+ return current;
1206
+ };
1207
+ }
1208
+ var generic_default = { name, includerFunction };
1209
+
1210
+ // src/services/includers/batteries/sourcedocs.ts
1211
+ var sourcedocs_exports = {};
1212
+ __export(sourcedocs_exports, {
1213
+ default: () => sourcedocs_default,
1214
+ includerFunction: () => includerFunction2,
1215
+ name: () => name2
1216
+ });
1217
+ var name2 = "sourcedocs";
1218
+ var usage = `include:
1219
+ path: <path-where-to-include>
1220
+ includers:
1221
+ - name: generic
1222
+ input: <path-to-directory-with-markdown>
1223
+ leadingPage:
1224
+ name: <leading-page-name>
1225
+ `;
1226
+ function includerFunction2(params) {
1227
+ return __async(this, null, function* () {
1228
+ logger.warn(params.tocPath, `sourcedocs inlcuder is getting depricated in favor of generic includer
1229
+ ${usage}`);
1230
+ yield generic_default.includerFunction(params);
1231
+ });
1232
+ }
1233
+ var sourcedocs_default = { name: name2, includerFunction: includerFunction2 };
1234
+
1235
+ // src/services/includers/batteries/unarchive.ts
1236
+ var unarchive_exports = {};
1237
+ __export(unarchive_exports, {
1238
+ default: () => unarchive_default,
1239
+ includerFunction: () => includerFunction3,
1240
+ name: () => name3
1241
+ });
1242
+ var import_fs3 = require("fs");
1243
+ var import_path11 = require("path");
1244
+ var import_tar_stream = require("tar-stream");
1245
+ var name3 = "unarchive";
1246
+ var UnarchiveIncluderError = class extends Error {
1247
+ constructor(message, path) {
1248
+ super(message);
1249
+ this.name = "UnarchiveIncluderError";
1250
+ this.path = path;
1251
+ }
1252
+ };
1253
+ function pipeline(readPath, writeBasePath) {
1254
+ return new Promise((res, rej) => {
1255
+ const reader3 = (0, import_fs3.createReadStream)(readPath);
1256
+ reader3.on("error", (err) => {
1257
+ rej(err);
1258
+ });
1259
+ const extractor2 = (0, import_tar_stream.extract)();
1260
+ extractor2.on("error", (err) => {
1261
+ rej(err);
1262
+ });
1263
+ (0, import_fs3.mkdirSync)(writeBasePath, { recursive: true });
1264
+ extractor2.on("entry", (header, stream, next) => {
1265
+ const { type, name: name4 } = header;
1266
+ const writePath = (0, import_path11.join)(writeBasePath, name4);
1267
+ const writeDirPath = type === "directory" ? writePath : (0, import_path11.dirname)(writePath);
1268
+ (0, import_fs3.mkdirSync)(writeDirPath, { recursive: true });
1269
+ if (type !== "directory") {
1270
+ const writer3 = (0, import_fs3.createWriteStream)(writePath, { flags: "w" });
1271
+ writer3.on("error", (err) => {
1272
+ rej(err);
1273
+ });
1274
+ stream.pipe(writer3);
1275
+ }
1276
+ stream.on("end", () => {
1277
+ next();
1278
+ });
1279
+ stream.resume();
1280
+ });
1281
+ reader3.pipe(extractor2).on("finish", () => {
1282
+ res();
1283
+ });
1284
+ });
1285
+ }
1286
+ function includerFunction3(params) {
1287
+ return __async(this, null, function* () {
1288
+ const { readBasePath, writeBasePath, tocPath, passedParams: { input, output }, index } = params;
1289
+ if (!(input == null ? void 0 : input.length) || !(output == null ? void 0 : output.length)) {
1290
+ throw new UnarchiveIncluderError("provide includer with input parameter", tocPath);
1291
+ }
1292
+ const contentPath = index === 0 ? (0, import_path11.join)(writeBasePath, input) : (0, import_path11.join)(readBasePath, input);
1293
+ const writePath = (0, import_path11.join)(writeBasePath, output);
1294
+ try {
1295
+ yield pipeline(contentPath, writePath);
1296
+ } catch (err) {
1297
+ throw new UnarchiveIncluderError(err.toString(), tocPath);
1298
+ }
1299
+ });
1300
+ }
1301
+ var unarchive_default = { name: name3, includerFunction: includerFunction3 };
1302
+
1303
+ // src/services/includers/index.ts
1304
+ var includersUsage = `include:
1305
+ path: <path-where-to-include>
1306
+ includers:
1307
+ - name: <includer-name-0>
1308
+ <includer-parameter>: <value-for-includer-parameter>
1309
+ - name: <includer-name-1>
1310
+ <includer-parameter>: <value-for-includer-parameter>
1311
+ `;
1312
+ var includersMap;
1313
+ var IncludersError = class extends Error {
1314
+ constructor(message, path) {
1315
+ super(message);
1316
+ this.name = "IncludersError";
1317
+ this.path = path;
1318
+ }
1319
+ };
1320
+ function init(custom = []) {
1321
+ if (includersMap) {
1322
+ return;
1323
+ }
1324
+ includersMap = { generic: generic_exports, sourcedocs: sourcedocs_exports, unarchive: unarchive_exports };
1325
+ for (const includer of custom) {
1326
+ includersMap[includer.name] = includer;
1327
+ }
1328
+ }
1329
+ function applyIncluders(path, item, vars) {
1330
+ return __async(this, null, function* () {
1331
+ var _a;
1332
+ if (!((_a = item.include) == null ? void 0 : _a.includers)) {
1333
+ return;
1334
+ }
1335
+ if (!includeValid(item.include)) {
1336
+ throw new IncludersError("include doesn't comply with includers standard", path);
1337
+ }
1338
+ item.include.mode = "link" /* LINK */;
1339
+ const { status, message } = includersValid(item.include.includers);
1340
+ if (!status) {
1341
+ throw new IncludersError(message != null ? message : "", path);
1342
+ }
1343
+ let index = 0;
1344
+ for (const _b of item.include.includers) {
1345
+ const _c = _b, { name: name4 } = _c, rest = __objRest(_c, ["name"]);
1346
+ const includer = getIncluder(name4);
1347
+ const passedParams = __spreadValues({}, rest);
1348
+ yield applyIncluder({ path, item, includer, passedParams, index, vars });
1349
+ }
1350
+ item.include.path = (0, import_path12.join)(item.include.path, "toc.yaml");
1351
+ index++;
1352
+ });
1353
+ }
1354
+ function includeValid(include) {
1355
+ var _a;
1356
+ return (include.mode === "link" /* LINK */ || !include.mode) && ((_a = include.path) == null ? void 0 : _a.length);
1357
+ }
1358
+ function includersValid(includers) {
1359
+ for (const includer of includers) {
1360
+ const { status, message } = includerValid(includer);
1361
+ if (!status) {
1362
+ return { status, message };
1363
+ }
1364
+ }
1365
+ return { status: true };
1366
+ }
1367
+ function includerValid(includer) {
1368
+ if ((0, import_lodash3.isObject)(includer)) {
1369
+ if (typeof includer.name !== "string") {
1370
+ return {
1371
+ status: false,
1372
+ message: "use string in the includer.name to specify includers name"
1373
+ };
1374
+ }
1375
+ if (includerExists(includer)) {
1376
+ return { status: true };
1377
+ }
1378
+ return { status: false, message: `includer ${includer.name} not implemented` };
1379
+ }
1380
+ return {
1381
+ status: false,
1382
+ message: `use appropriate includers format:
1383
+ ${includersUsage}`
1384
+ };
1385
+ }
1386
+ function getIncluder(includerName) {
1387
+ return includersMap[includerName];
1388
+ }
1389
+ function includerExists(includer) {
1390
+ return includersMap[includer.name];
1391
+ }
1392
+ function applyIncluder(args) {
1393
+ return __async(this, null, function* () {
1394
+ const { rootInput: readBasePath, input: writeBasePath } = argv_default.getConfig();
1395
+ const { path, item, includer, passedParams, index, vars } = args;
1396
+ const params = {
1397
+ tocPath: path,
1398
+ passedParams,
1399
+ index,
1400
+ item,
1401
+ readBasePath,
1402
+ writeBasePath,
1403
+ vars
1404
+ };
1405
+ return yield includer.includerFunction(params);
1406
+ });
1407
+ }
1408
+
1409
+ // src/services/tocs.ts
1410
+ var storage = /* @__PURE__ */ new Map();
1411
+ var navigationPaths = [];
1412
+ var includedTocPaths = /* @__PURE__ */ new Set();
1413
+ function add(path) {
1414
+ return __async(this, null, function* () {
1415
+ const {
1416
+ input: inputFolderPath,
1417
+ output: outputFolderPath,
1418
+ outputFormat,
1419
+ ignoreStage,
1420
+ vars
1421
+ } = argv_default.getConfig();
1422
+ const pathToDir = (0, import_path13.dirname)(path);
1423
+ const content = (0, import_fs4.readFileSync)((0, import_path13.resolve)(inputFolderPath, path), "utf8");
1424
+ const parsedToc = (0, import_js_yaml4.load)(content);
1425
+ if (parsedToc.stage === ignoreStage) {
1426
+ return;
1427
+ }
1428
+ const combinedVars = __spreadValues(__spreadValues({}, preset_default.get(pathToDir)), vars);
1429
+ if (parsedToc.title) {
1430
+ parsedToc.title = firstFilterTextItems(
1431
+ parsedToc.title,
1432
+ combinedVars,
1433
+ { resolveConditions: true }
1434
+ );
1435
+ }
1436
+ if (typeof parsedToc.title === "string") {
1437
+ parsedToc.title = liquidField(parsedToc.title, combinedVars, path);
1438
+ }
1439
+ parsedToc.items = yield processTocItems(
1440
+ path,
1441
+ parsedToc.items,
1442
+ (0, import_path13.join)(inputFolderPath, pathToDir),
1443
+ (0, import_path13.resolve)(inputFolderPath),
1444
+ combinedVars
1445
+ );
1446
+ storage.set(path, parsedToc);
1447
+ parsedToc.base = pathToDir;
1448
+ if (outputFormat === "md") {
1449
+ const outputPath = (0, import_path13.resolve)(outputFolderPath, path);
1450
+ const outputToc = (0, import_js_yaml4.dump)(parsedToc);
1451
+ import_shelljs2.default.mkdir("-p", (0, import_path13.dirname)(outputPath));
1452
+ (0, import_fs4.writeFileSync)(outputPath, outputToc);
1453
+ }
1454
+ prepareNavigationPaths(parsedToc, pathToDir);
1455
+ });
1456
+ }
1457
+ function processTocItems(path, items, tocDir, sourcesDir, vars) {
1458
+ return __async(this, null, function* () {
1459
+ const {
1460
+ resolveConditions,
1461
+ removeHiddenTocItems
1462
+ } = argv_default.getConfig();
1463
+ let preparedItems = items;
1464
+ if (resolveConditions || removeHiddenTocItems) {
1465
+ try {
1466
+ preparedItems = filterFiles(items, "items", vars, {
1467
+ resolveConditions,
1468
+ removeHiddenTocItems
1469
+ });
1470
+ } catch (error) {
1471
+ import_log3.default.error(`Error while filtering toc file: ${path}. Error message: ${error}`);
1472
+ }
1473
+ }
1474
+ return _replaceIncludes(path, preparedItems, tocDir, sourcesDir, vars);
1475
+ });
1476
+ }
1477
+ function getForPath(path) {
1478
+ return storage.get(path);
1479
+ }
1480
+ function getNavigationPaths() {
1481
+ return [...navigationPaths];
1482
+ }
1483
+ function getIncludedTocPaths() {
1484
+ return [...includedTocPaths];
1485
+ }
1486
+ function prepareNavigationPaths(parsedToc, dirPath) {
1487
+ function processItems(items, pathToDir) {
1488
+ items.forEach((item) => {
1489
+ if (!parsedToc.singlePage && item.items) {
1490
+ const preparedSubItems = item.items.map((yfmToc, index) => {
1491
+ yfmToc.id = `${yfmToc.name}-${index}-${Math.random()}`;
1492
+ return yfmToc;
1493
+ });
1494
+ processItems(preparedSubItems, pathToDir);
1495
+ }
1496
+ if (item.href && !isExternalHref(item.href)) {
1497
+ const href = (0, import_path13.join)(pathToDir, item.href);
1498
+ storage.set(href, parsedToc);
1499
+ const navigationPath = _normalizeHref(href);
1500
+ navigationPaths.push(navigationPath);
1501
+ }
1502
+ });
1503
+ }
1504
+ processItems([parsedToc], dirPath);
1505
+ }
1506
+ function _normalizeHref(href) {
1507
+ const preparedHref = (0, import_path13.normalize)(href);
1508
+ if (preparedHref.endsWith(".md") || preparedHref.endsWith(".yaml")) {
1509
+ return preparedHref;
1510
+ }
1511
+ if (preparedHref.endsWith(import_path13.sep)) {
1512
+ return `${preparedHref}index.yaml`;
1513
+ }
1514
+ return `${preparedHref}.md`;
1515
+ }
1516
+ function _copyTocDir(tocPath, destDir) {
1517
+ const { input: inputFolderPath } = argv_default.getConfig();
1518
+ const { dir: tocDir } = (0, import_path13.parse)(tocPath);
1519
+ const files = (0, import_walk_sync.default)(tocDir, {
1520
+ globs: ["**/*.*"],
1521
+ ignore: ["**/toc.yaml"],
1522
+ directories: false
1523
+ });
1524
+ files.forEach((relPath) => {
1525
+ const from = (0, import_path13.resolve)(tocDir, relPath);
1526
+ const to = (0, import_path13.resolve)(destDir, relPath);
1527
+ const fileExtension = (0, import_path13.extname)(relPath);
1528
+ const isMdFile = fileExtension === ".md";
1529
+ import_shelljs2.default.mkdir("-p", (0, import_path13.parse)(to).dir);
1530
+ if (isMdFile) {
1531
+ const fileContent = (0, import_fs4.readFileSync)(from, "utf8");
1532
+ const sourcePath = (0, import_path13.relative)(inputFolderPath, from);
1533
+ const updatedFileContent = getContentWithUpdatedStaticMetadata({
1534
+ fileContent,
1535
+ sourcePath,
1536
+ addSourcePath: true
1537
+ });
1538
+ (0, import_fs4.writeFileSync)(to, updatedFileContent);
1539
+ } else {
1540
+ (0, import_fs4.copyFileSync)(from, to);
1541
+ }
1542
+ });
1543
+ }
1544
+ function _replaceIncludesHrefs(items, includeTocDir, tocDir) {
1545
+ return items.reduce((acc, tocItem) => {
1546
+ if (tocItem.href) {
1547
+ tocItem.href = (0, import_path13.relative)(tocDir, (0, import_path13.resolve)(includeTocDir, tocItem.href));
1548
+ }
1549
+ if (tocItem.items) {
1550
+ tocItem.items = _replaceIncludesHrefs(tocItem.items, includeTocDir, tocDir);
1551
+ }
1552
+ if (tocItem.include) {
1553
+ const { path } = tocItem.include;
1554
+ tocItem.include.path = (0, import_path13.relative)(tocDir, (0, import_path13.resolve)(includeTocDir, path));
1555
+ }
1556
+ return acc.concat(tocItem);
1557
+ }, []);
1558
+ }
1559
+ function _liquidSubstitutions(input, vars, path) {
1560
+ const { outputFormat, applyPresets } = argv_default.getConfig();
1561
+ if (outputFormat === "md" && !applyPresets) {
1562
+ return input;
1563
+ }
1564
+ return (0, import_liquid2.default)(input, vars, path, {
1565
+ conditions: false,
1566
+ substitutions: true
1567
+ });
1568
+ }
1569
+ function addIncludeTocPath(includeTocPath) {
1570
+ includedTocPaths.add(includeTocPath);
1571
+ }
1572
+ function _replaceIncludes(path, items, tocDir, sourcesDir, vars) {
1573
+ return __async(this, null, function* () {
1574
+ const result = [];
1575
+ for (const item of items) {
1576
+ let includedInlineItems = null;
1577
+ if (item.name) {
1578
+ const tocPath = (0, import_path13.join)(tocDir, "toc.yaml");
1579
+ item.name = _liquidSubstitutions(item.name, vars, tocPath);
1580
+ }
1581
+ try {
1582
+ yield applyIncluders(path, item, vars);
1583
+ } catch (err) {
1584
+ if (err instanceof Error || err instanceof IncludersError) {
1585
+ const message = err.toString();
1586
+ const file = err instanceof IncludersError ? err.path : path;
1587
+ logger.error(file, message);
1588
+ }
1589
+ }
1590
+ if (item.include) {
1591
+ const { mode = "root_merge" /* ROOT_MERGE */ } = item.include;
1592
+ const includeTocPath = mode === "root_merge" /* ROOT_MERGE */ ? (0, import_path13.resolve)(sourcesDir, item.include.path) : (0, import_path13.resolve)(tocDir, item.include.path);
1593
+ const includeTocDir = (0, import_path13.dirname)(includeTocPath);
1594
+ try {
1595
+ const includeToc = (0, import_js_yaml4.load)((0, import_fs4.readFileSync)(includeTocPath, "utf8"));
1596
+ if (includeToc.stage === "tech-preview" /* TECH_PREVIEW */) {
1597
+ continue;
1598
+ }
1599
+ if (mode === "merge" /* MERGE */ || mode === "root_merge" /* ROOT_MERGE */) {
1600
+ _copyTocDir(includeTocPath, tocDir);
1601
+ }
1602
+ addIncludeTocPath(includeTocPath);
1603
+ let includedTocItems = (item.items || []).concat(includeToc.items);
1604
+ const baseTocDir = mode === "link" /* LINK */ ? includeTocDir : tocDir;
1605
+ includedTocItems = yield processTocItems(path, includedTocItems, baseTocDir, sourcesDir, vars);
1606
+ if (mode === "link" /* LINK */) {
1607
+ includedTocItems = _replaceIncludesHrefs(includedTocItems, includeTocDir, tocDir);
1608
+ }
1609
+ if (item.name) {
1610
+ item.items = includedTocItems;
1611
+ } else {
1612
+ includedInlineItems = includedTocItems;
1613
+ }
1614
+ } catch (err) {
1615
+ const message = `Error while including toc: ${(0, import_chalk2.bold)(includeTocPath)} to ${(0, import_chalk2.bold)((0, import_path13.join)(tocDir, "toc.yaml"))}`;
1616
+ import_log3.default.error(message);
1617
+ continue;
1618
+ } finally {
1619
+ delete item.include;
1620
+ }
1621
+ } else if (item.items) {
1622
+ item.items = yield processTocItems(path, item.items, tocDir, sourcesDir, vars);
1623
+ }
1624
+ if (includedInlineItems) {
1625
+ result.push(...includedInlineItems);
1626
+ } else {
1627
+ result.push(item);
1628
+ }
1629
+ }
1630
+ return result;
1631
+ });
1632
+ }
1633
+ function getTocDir(pagePath) {
1634
+ const { input: inputFolderPath } = argv_default.getConfig();
1635
+ const tocDir = (0, import_path13.dirname)(pagePath);
1636
+ const tocPath = (0, import_path13.resolve)(tocDir, "toc.yaml");
1637
+ if (!tocDir.includes(inputFolderPath)) {
1638
+ throw new Error("Error while finding toc dir");
1639
+ }
1640
+ if ((0, import_fs4.existsSync)(tocPath)) {
1641
+ return tocDir;
1642
+ }
1643
+ return getTocDir(tocDir);
1644
+ }
1645
+ function setNavigationPaths(paths) {
1646
+ navigationPaths = paths;
1647
+ }
1648
+ var tocs_default = {
1649
+ add,
1650
+ getForPath,
1651
+ getNavigationPaths,
1652
+ getTocDir,
1653
+ getIncludedTocPaths,
1654
+ setNavigationPaths
1655
+ };
1656
+
1657
+ // src/services/preset.ts
1658
+ var import_path14 = require("path");
1659
+ var presetStorage = /* @__PURE__ */ new Map();
1660
+ function add2(parsedPreset, path, varsPreset) {
1661
+ const combinedValues = __spreadValues(__spreadValues({}, parsedPreset.default || {}), parsedPreset[varsPreset] || {});
1662
+ const key = (0, import_path14.dirname)((0, import_path14.normalize)(path));
1663
+ presetStorage.set(key, combinedValues);
1664
+ }
1665
+ function get(path) {
1666
+ let combinedValues = {};
1667
+ let localPath = (0, import_path14.normalize)(path);
1668
+ while (localPath !== ".") {
1669
+ const presetValues = presetStorage.get(localPath) || {};
1670
+ localPath = (0, import_path14.dirname)(localPath);
1671
+ combinedValues = __spreadValues(__spreadValues({}, presetValues), combinedValues);
1672
+ }
1673
+ combinedValues = __spreadValues(__spreadValues({}, presetStorage.get(".")), combinedValues);
1674
+ return combinedValues;
1675
+ }
1676
+ function getPresetStorage() {
1677
+ return presetStorage;
1678
+ }
1679
+ function setPresetStorage(preset) {
1680
+ presetStorage = preset;
1681
+ }
1682
+ var preset_default = {
1683
+ add: add2,
1684
+ get,
1685
+ getPresetStorage,
1686
+ setPresetStorage
1687
+ };
1688
+
1689
+ // src/services/argv.ts
1690
+ var import_path15 = require("path");
1691
+ var import_fs5 = require("fs");
1692
+ var _argv;
1693
+ function getConfig() {
1694
+ return _argv;
1695
+ }
1696
+ function init2(argv) {
1697
+ _argv = __spreadProps(__spreadValues({}, argv), {
1698
+ ignore: Array.isArray(argv.ignore) ? argv.ignore : []
1699
+ });
1700
+ if (argv.vars) {
1701
+ _argv.vars = JSON.parse(argv.vars);
1702
+ }
1703
+ try {
1704
+ const ignorefile = (0, import_fs5.readFileSync)((0, import_path15.join)(_argv.rootInput, ".yfmignore"), "utf8");
1705
+ const ignore = ignorefile.split("\n");
1706
+ _argv.ignore = _argv.ignore.concat(ignore);
1707
+ } catch (e) {
1708
+ }
1709
+ }
1710
+ function set(argv) {
1711
+ _argv = argv;
1712
+ }
1713
+ var argv_default = {
1714
+ getConfig,
1715
+ init: init2,
1716
+ set
1717
+ };
1718
+
1719
+ // src/services/leading.ts
1720
+ var import_path16 = require("path");
1721
+ var import_fs6 = require("fs");
1722
+ var import_js_yaml5 = require("js-yaml");
1723
+ var import_log4 = __toESM(require("@doc-tools/transform/lib/log"));
1724
+ function filterFile(path) {
1725
+ var _a, _b;
1726
+ const {
1727
+ input: inputFolderPath,
1728
+ vars
1729
+ } = argv_default.getConfig();
1730
+ const pathToDir = (0, import_path16.dirname)(path);
1731
+ const filePath = (0, import_path16.resolve)(inputFolderPath, path);
1732
+ const content = (0, import_fs6.readFileSync)(filePath, "utf8");
1733
+ const parsedIndex = (0, import_js_yaml5.load)(content);
1734
+ const combinedVars = __spreadValues(__spreadValues({}, preset_default.get(pathToDir)), vars);
1735
+ try {
1736
+ const title = firstFilterTextItems(
1737
+ parsedIndex.title,
1738
+ combinedVars,
1739
+ { resolveConditions: true }
1740
+ );
1741
+ parsedIndex.title = liquidField(title, combinedVars, path);
1742
+ const description6 = filterTextItems(
1743
+ parsedIndex.description,
1744
+ combinedVars,
1745
+ { resolveConditions: true }
1746
+ );
1747
+ parsedIndex.description = liquidFields(description6, combinedVars, path);
1748
+ if ((_a = parsedIndex.meta) == null ? void 0 : _a.title) {
1749
+ const metaTitle = firstFilterTextItems(
1750
+ parsedIndex.meta.title,
1751
+ combinedVars,
1752
+ { resolveConditions: true }
1753
+ );
1754
+ parsedIndex.meta.title = liquidField(metaTitle, combinedVars, path);
1755
+ }
1756
+ if ((_b = parsedIndex.meta) == null ? void 0 : _b.description) {
1757
+ const metaDescription = firstFilterTextItems(
1758
+ parsedIndex.meta.description,
1759
+ combinedVars,
1760
+ { resolveConditions: true }
1761
+ );
1762
+ parsedIndex.meta.description = liquidField(metaDescription, combinedVars, path);
1763
+ }
1764
+ if (parsedIndex.nav) {
1765
+ const navTitle = firstFilterTextItems(
1766
+ parsedIndex.nav.title,
1767
+ combinedVars,
1768
+ { resolveConditions: true }
1769
+ );
1770
+ parsedIndex.nav.title = liquidField(navTitle, combinedVars, path);
1771
+ }
1772
+ parsedIndex.links = filterFiles(parsedIndex.links, "links", combinedVars, { resolveConditions: true });
1773
+ parsedIndex.links.forEach((link) => {
1774
+ if (link.title) {
1775
+ link.title = liquidField(link.title, combinedVars, path);
1776
+ }
1777
+ if (link.description) {
1778
+ link.description = liquidField(link.description, combinedVars, path);
1779
+ }
1780
+ });
1781
+ (0, import_fs6.writeFileSync)(filePath, (0, import_js_yaml5.dump)(parsedIndex));
1782
+ } catch (error) {
1783
+ import_log4.default.error(`Error while filtering index file: ${path}. Error message: ${error}`);
1784
+ }
1785
+ }
1786
+ var leading_default = {
1787
+ filterFile
1788
+ };
1789
+
1790
+ // src/services/plugins.ts
1791
+ var plugins_exports = {};
1792
+ __export(plugins_exports, {
1793
+ getCollectOfPlugins: () => getCollectOfPlugins,
1794
+ getCustomLintRules: () => getCustomLintRules,
1795
+ getDefaultLintConfig: () => getDefaultLintConfig,
1796
+ getHeadContent: () => getHeadContent,
1797
+ getPlugins: () => getPlugins,
1798
+ setPlugins: () => setPlugins
1799
+ });
1800
+ var plugins;
1801
+ var collectionOfPlugins;
1802
+ function setPlugins() {
1803
+ plugins = getAllPlugins();
1804
+ collectionOfPlugins = makeCollectOfPlugins();
1805
+ }
1806
+ function getPlugins() {
1807
+ return plugins;
1808
+ }
1809
+ function getCollectOfPlugins() {
1810
+ return collectionOfPlugins;
1811
+ }
1812
+ function makeCollectOfPlugins() {
1813
+ const pluginsWithCollect = plugins.filter((plugin) => {
1814
+ return typeof plugin.collect === "function";
1815
+ });
1816
+ return (output, options) => {
1817
+ let collectsOutput = output;
1818
+ pluginsWithCollect.forEach((plugin) => {
1819
+ const collectOutput = plugin.collect(collectsOutput, options);
1820
+ collectsOutput = typeof collectOutput === "string" ? collectOutput : collectsOutput;
1821
+ });
1822
+ return collectsOutput;
1823
+ };
1824
+ }
1825
+ function getAllPlugins() {
1826
+ const customPlugins = getCustomPlugins();
1827
+ return [...YFM_PLUGINS, ...customPlugins];
1828
+ }
1829
+ function getCustomPlugins() {
1830
+ try {
1831
+ const customPlugins = require(require.resolve("./plugins"));
1832
+ return Array.isArray(customPlugins) ? customPlugins : [];
1833
+ } catch (e) {
1834
+ return [];
1835
+ }
1836
+ }
1837
+ function getHeadContent() {
1838
+ try {
1839
+ return require(require.resolve("./head-content.js"));
1840
+ } catch (e) {
1841
+ return "";
1842
+ }
1843
+ }
1844
+ function getCustomLintRules() {
1845
+ try {
1846
+ return require(require.resolve("./lint-rules"));
1847
+ } catch (e) {
1848
+ return [];
1849
+ }
1850
+ }
1851
+ function getDefaultLintConfig() {
1852
+ try {
1853
+ return require(require.resolve("./default-lint-config"));
1854
+ } catch (e) {
1855
+ return void 0;
1856
+ }
1857
+ }
1858
+
1859
+ // src/cmd/build/index.ts
1860
+ var import_includer = __toESM(require("@diplodoc/openapi-extension/includer"));
1861
+
1862
+ // src/steps/processAssets.ts
1863
+ var import_walk_sync2 = __toESM(require("walk-sync"));
1864
+ var import_shelljs3 = __toESM(require("shelljs"));
1865
+ var import_client3 = __toESM(require_client());
1866
+ function processAssets(outputBundlePath) {
1867
+ const {
1868
+ input: inputFolderPath,
1869
+ output: outputFolderPath
1870
+ } = argv_default.getConfig();
1871
+ const assetFilePath = (0, import_walk_sync2.default)(inputFolderPath, {
1872
+ directories: false,
1873
+ includeBasePath: false,
1874
+ ignore: [
1875
+ "**/*.yaml",
1876
+ "**/*.md"
1877
+ ]
1878
+ });
1879
+ copyFiles(inputFolderPath, outputFolderPath, assetFilePath);
1880
+ import_shelljs3.default.mkdir("-p", outputBundlePath);
1881
+ for (const path of Object.values(import_client3.default.dst)) {
1882
+ import_shelljs3.default.cp(path, outputBundlePath);
1883
+ }
1884
+ }
1885
+
1886
+ // src/steps/processExcludedFiles.ts
1887
+ var import_path17 = require("path");
1888
+ var import_walk_sync3 = __toESM(require("walk-sync"));
1889
+ var import_shelljs4 = __toESM(require("shelljs"));
1890
+ function processExcludedFiles() {
1891
+ const {
1892
+ input: inputFolderPath,
1893
+ output: outputFolderPath,
1894
+ ignore
1895
+ } = argv_default.getConfig();
1896
+ const allContentFiles = (0, import_walk_sync3.default)(inputFolderPath, {
1897
+ directories: false,
1898
+ includeBasePath: true,
1899
+ globs: [
1900
+ "**/*.md",
1901
+ "**/index.yaml",
1902
+ ...ignore
1903
+ ],
1904
+ // Ignores service directories like "_includes", "_templates" and etc.
1905
+ ignore: ["**/_*/**/*"]
1906
+ });
1907
+ const navigationPaths2 = tocs_default.getNavigationPaths().map((filePath) => convertBackSlashToSlash((0, import_path17.resolve)(inputFolderPath, filePath)));
1908
+ const tocSpecifiedFiles = new Set(navigationPaths2);
1909
+ const excludedFiles = allContentFiles.filter((filePath) => !tocSpecifiedFiles.has(filePath));
1910
+ import_shelljs4.default.rm("-f", excludedFiles);
1911
+ const includedTocPaths2 = tocs_default.getIncludedTocPaths().map((filePath) => {
1912
+ const relativeTocPath = (0, import_path17.relative)(inputFolderPath, filePath);
1913
+ const destTocPath = (0, import_path17.resolve)(outputFolderPath, relativeTocPath);
1914
+ return convertBackSlashToSlash(destTocPath);
1915
+ });
1916
+ import_shelljs4.default.rm("-rf", includedTocPaths2);
1917
+ }
1918
+
1919
+ // src/steps/processLogs.ts
1920
+ var import_log5 = __toESM(require("@doc-tools/transform/lib/log"));
1921
+ var import_uniq = __toESM(require("lodash/uniq"));
1922
+ function processLogs(inputFolder) {
1923
+ const replacementRegExp = new RegExp(inputFolder, "ig");
1924
+ const { info, warn, error } = import_log5.default.get();
1925
+ const outputLogs = (0, import_uniq.default)([
1926
+ "",
1927
+ ...info,
1928
+ "",
1929
+ ...warn,
1930
+ "",
1931
+ ...error,
1932
+ ""
1933
+ ]);
1934
+ for (const outputLog of outputLogs) {
1935
+ const preparedLog = outputLog.replace(replacementRegExp, "");
1936
+ console.log(preparedLog);
1937
+ }
1938
+ }
1939
+
1940
+ // src/steps/processPages.ts
1941
+ var import_path22 = require("path");
1942
+ var import_shelljs6 = __toESM(require("shelljs"));
1943
+ var import_fs10 = require("fs");
1944
+ var import_chalk4 = require("chalk");
1945
+ var import_js_yaml7 = require("js-yaml");
1946
+ var import_async = require("async");
1947
+ var import_log11 = __toESM(require("@doc-tools/transform/lib/log"));
1948
+
1949
+ // src/resolvers/md2md.ts
1950
+ var import_fs7 = require("fs");
1951
+ var import_path18 = require("path");
1952
+ var import_shelljs5 = __toESM(require("shelljs"));
1953
+ var import_log6 = __toESM(require("@doc-tools/transform/lib/log"));
1954
+ var import_liquid3 = __toESM(require("@doc-tools/transform/lib/liquid"));
1955
+ function resolveMd2Md(options) {
1956
+ return __async(this, null, function* () {
1957
+ const { inputPath, outputPath, metadata } = options;
1958
+ const { input, output } = argv_default.getConfig();
1959
+ const resolvedInputPath = (0, import_path18.resolve)(input, inputPath);
1960
+ const vars = getVarsPerFile(inputPath);
1961
+ const content = yield getContentWithUpdatedMetadata(
1962
+ (0, import_fs7.readFileSync)(resolvedInputPath, "utf8"),
1963
+ metadata,
1964
+ vars.__system
1965
+ );
1966
+ const { result, changelogs } = transformMd2Md(content, {
1967
+ path: resolvedInputPath,
1968
+ destPath: outputPath,
1969
+ root: (0, import_path18.resolve)(input),
1970
+ destRoot: (0, import_path18.resolve)(output),
1971
+ collectOfPlugins: plugins_exports.getCollectOfPlugins(),
1972
+ vars,
1973
+ log: import_log6.default,
1974
+ copyFile
1975
+ });
1976
+ (0, import_fs7.writeFileSync)(outputPath, result);
1977
+ if (changelogs == null ? void 0 : changelogs.length) {
1978
+ const mdFilename = (0, import_path18.basename)(outputPath, (0, import_path18.extname)(outputPath));
1979
+ const outputDir = (0, import_path18.dirname)(outputPath);
1980
+ changelogs.forEach((changes, index) => {
1981
+ let changesName;
1982
+ const changesDate = changes.date;
1983
+ const changesIdx = changes.index;
1984
+ if (typeof changesIdx === "number") {
1985
+ changesName = String(changesIdx);
1986
+ }
1987
+ if (!changesName && changesDate && /^\d{4}/.test(changesDate)) {
1988
+ changesName = Math.trunc(new Date(changesDate).getTime() / 1e3);
1989
+ }
1990
+ if (!changesName) {
1991
+ changesName = `name-${mdFilename}-${String(changelogs.length - index).padStart(3, "0")}`;
1992
+ }
1993
+ const changesPath = (0, import_path18.join)(outputDir, `changes-${changesName}.json`);
1994
+ if ((0, import_fs7.existsSync)(changesPath)) {
1995
+ throw new Error(`Changelog ${changesPath} already exists!`);
1996
+ }
1997
+ (0, import_fs7.writeFileSync)(changesPath, JSON.stringify(__spreadProps(__spreadValues({}, changes), {
1998
+ source: mdFilename
1999
+ })));
2000
+ });
2001
+ }
2002
+ logger.info(inputPath, PROCESSING_FINISHED);
2003
+ return void 0;
2004
+ });
2005
+ }
2006
+ function copyFile(targetPath, targetDestPath, options) {
2007
+ import_shelljs5.default.mkdir("-p", (0, import_path18.dirname)(targetDestPath));
2008
+ if (options) {
2009
+ const sourceIncludeContent = (0, import_fs7.readFileSync)(targetPath, "utf8");
2010
+ const { result } = transformMd2Md(sourceIncludeContent, options);
2011
+ (0, import_fs7.writeFileSync)(targetDestPath, result);
2012
+ } else {
2013
+ import_shelljs5.default.cp(targetPath, targetDestPath);
2014
+ }
2015
+ }
2016
+ function liquidMd2Md(input, vars, path) {
2017
+ const {
2018
+ applyPresets,
2019
+ resolveConditions,
2020
+ conditionsInCode
2021
+ } = argv_default.getConfig();
2022
+ return (0, import_liquid3.default)(input, vars, path, {
2023
+ conditions: resolveConditions,
2024
+ substitutions: applyPresets,
2025
+ conditionsInCode,
2026
+ withSourceMap: true,
2027
+ keepNotVar: true
2028
+ });
2029
+ }
2030
+ function transformMd2Md(input, options) {
2031
+ const {
2032
+ disableLiquid
2033
+ } = argv_default.getConfig();
2034
+ const {
2035
+ vars = {},
2036
+ path,
2037
+ root,
2038
+ destPath,
2039
+ destRoot,
2040
+ collectOfPlugins,
2041
+ log: pluginLog,
2042
+ copyFile: pluginCopyFile
2043
+ } = options;
2044
+ let output = input;
2045
+ const changelogs = [];
2046
+ if (!disableLiquid) {
2047
+ const liquidResult = liquidMd2Md(input, vars, path);
2048
+ output = liquidResult.output;
2049
+ }
2050
+ if (collectOfPlugins) {
2051
+ output = collectOfPlugins(output, {
2052
+ vars,
2053
+ path,
2054
+ root,
2055
+ destPath,
2056
+ destRoot,
2057
+ log: pluginLog,
2058
+ copyFile: pluginCopyFile,
2059
+ collectOfPlugins,
2060
+ changelogs,
2061
+ extractChangelogs: true
2062
+ });
2063
+ }
2064
+ return {
2065
+ result: output,
2066
+ changelogs,
2067
+ logs: pluginLog.get()
2068
+ };
2069
+ }
2070
+
2071
+ // src/resolvers/md2html.ts
2072
+ var import_path19 = require("path");
2073
+ var import_fs8 = require("fs");
2074
+ var import_js_yaml6 = __toESM(require("js-yaml"));
2075
+ var import_transform = __toESM(require("@doc-tools/transform"));
2076
+ var import_log7 = __toESM(require("@doc-tools/transform/lib/log"));
2077
+ var import_liquid4 = __toESM(require("@doc-tools/transform/lib/liquid"));
2078
+ var FileTransformer = {
2079
+ ".yaml": YamlFileTransformer,
2080
+ ".md": MdFileTransformer
2081
+ };
2082
+ var fixRelativePath = (relativeTo) => (path) => {
2083
+ return (0, import_path19.join)(getAssetsPublicPath(relativeTo), path);
2084
+ };
2085
+ function resolveMd2HTML(options) {
2086
+ return __async(this, null, function* () {
2087
+ var _a;
2088
+ const { inputPath, fileExtension, outputPath, outputBundlePath, metadata } = options;
2089
+ const pathToDir = (0, import_path19.dirname)(inputPath);
2090
+ const toc = tocs_default.getForPath(inputPath) || null;
2091
+ const tocBase = toc && toc.base ? toc.base : "";
2092
+ const pathToFileDir = pathToDir === tocBase ? "" : pathToDir.replace(`${tocBase}${import_path19.sep}`, "");
2093
+ const relativePathToIndex = (0, import_path19.relative)(pathToDir, `${tocBase}${import_path19.sep}`);
2094
+ const { input, lang, allowCustomResources } = argv_default.getConfig();
2095
+ const resolvedPath = (0, import_path19.resolve)(input, inputPath);
2096
+ const content = (0, import_fs8.readFileSync)(resolvedPath, "utf8");
2097
+ const transformFn = FileTransformer[fileExtension];
2098
+ const { result } = transformFn(content, { path: inputPath });
2099
+ const updatedMetadata = metadata && metadata.isContributorsEnabled ? yield getUpdatedMetadata(metadata, content, result == null ? void 0 : result.meta) : result.meta;
2100
+ const fileMeta = fileExtension === ".yaml" ? (_a = result.data.meta) != null ? _a : {} : updatedMetadata;
2101
+ if (allowCustomResources) {
2102
+ const { script, style } = (metadata == null ? void 0 : metadata.resources) || {};
2103
+ fileMeta.style = (fileMeta.style || []).concat(style || []).map(fixRelativePath(inputPath));
2104
+ fileMeta.script = (fileMeta.script || []).concat(script || []).map(fixRelativePath(inputPath));
2105
+ } else {
2106
+ fileMeta.style = [];
2107
+ fileMeta.script = [];
2108
+ }
2109
+ const props = {
2110
+ data: __spreadProps(__spreadValues({
2111
+ leading: inputPath.endsWith(".yaml"),
2112
+ toc: transformToc(toc, pathToDir) || {}
2113
+ }, result), {
2114
+ meta: fileMeta
2115
+ }),
2116
+ router: {
2117
+ pathname: (0, import_path19.join)(relativePathToIndex, pathToFileDir, (0, import_path19.basename)(outputPath))
2118
+ },
2119
+ lang: lang || "ru" /* RU */
2120
+ };
2121
+ const outputDir = (0, import_path19.dirname)(outputPath);
2122
+ const relativePathToBundle = (0, import_path19.relative)((0, import_path19.resolve)(outputDir), (0, import_path19.resolve)(outputBundlePath));
2123
+ const outputFileContent = generateStaticMarkup(props, relativePathToBundle);
2124
+ (0, import_fs8.writeFileSync)(outputPath, outputFileContent);
2125
+ logger.info(inputPath, PROCESSING_FINISHED);
2126
+ return props;
2127
+ });
2128
+ }
2129
+ function YamlFileTransformer(content) {
2130
+ var _a;
2131
+ let data = null;
2132
+ try {
2133
+ data = import_js_yaml6.default.load(content);
2134
+ } catch (error) {
2135
+ import_log7.default.error(`Yaml transform has been failed. Error: ${error}`);
2136
+ }
2137
+ if (!data) {
2138
+ return {
2139
+ result: { data: {} }
2140
+ };
2141
+ }
2142
+ const links2 = (_a = data == null ? void 0 : data.links) == null ? void 0 : _a.map(
2143
+ (link) => link.href ? __spreadProps(__spreadValues({}, link), { href: link.href.replace(/.md$/gmu, ".html") }) : link
2144
+ );
2145
+ if (links2) {
2146
+ data.links = links2;
2147
+ }
2148
+ return {
2149
+ result: { data }
2150
+ };
2151
+ }
2152
+ function liquidMd2Html(input, vars, path) {
2153
+ const { conditionsInCode } = argv_default.getConfig();
2154
+ return (0, import_liquid4.default)(input, vars, path, {
2155
+ conditionsInCode,
2156
+ withSourceMap: true
2157
+ });
2158
+ }
2159
+ function MdFileTransformer(content, transformOptions) {
2160
+ const _a = argv_default.getConfig(), { input } = _a, options = __objRest(_a, ["input"]);
2161
+ const { path: filePath } = transformOptions;
2162
+ const plugins2 = plugins_exports.getPlugins();
2163
+ const vars = getVarsPerFile(filePath);
2164
+ const root = (0, import_path19.resolve)(input);
2165
+ const path = (0, import_path19.resolve)(input, filePath);
2166
+ return (0, import_transform.default)(content, __spreadProps(__spreadValues({}, options), {
2167
+ plugins: plugins2,
2168
+ vars,
2169
+ root,
2170
+ path,
2171
+ assetsPublicPath: getAssetsPublicPath(filePath),
2172
+ getVarsPerFile: getVarsPerRelativeFile,
2173
+ extractTitle: true
2174
+ }));
2175
+ }
2176
+
2177
+ // src/resolvers/lintPage.ts
2178
+ var import_path20 = require("path");
2179
+ var import_log8 = __toESM(require("@doc-tools/transform/lib/log"));
2180
+ var import_yfmlint = __toESM(require("@doc-tools/transform/lib/yfmlint"));
2181
+ var import_fs9 = require("fs");
2182
+ var import_chalk3 = require("chalk");
2183
+ var FileLinter = {
2184
+ ".md": MdFileLinter
2185
+ };
2186
+ function lintPage(options) {
2187
+ const { inputPath, fileExtension, onFinish } = options;
2188
+ const { input } = argv_default.getConfig();
2189
+ const resolvedPath = (0, import_path20.resolve)(input, inputPath);
2190
+ try {
2191
+ const content = (0, import_fs9.readFileSync)(resolvedPath, "utf8");
2192
+ const lintFn = FileLinter[fileExtension];
2193
+ if (!lintFn) {
2194
+ return;
2195
+ }
2196
+ lintFn(content, { path: inputPath });
2197
+ } catch (e) {
2198
+ const message = `No such file or has no access to ${(0, import_chalk3.bold)(resolvedPath)}`;
2199
+ console.error(message, e);
2200
+ import_log8.default.error(message);
2201
+ }
2202
+ if (onFinish) {
2203
+ onFinish();
2204
+ }
2205
+ }
2206
+ function MdFileLinter(content, lintOptions) {
2207
+ const _a = argv_default.getConfig(), {
2208
+ input,
2209
+ lintConfig,
2210
+ disableLiquid,
2211
+ outputFormat
2212
+ } = _a, options = __objRest(_a, [
2213
+ "input",
2214
+ "lintConfig",
2215
+ "disableLiquid",
2216
+ "outputFormat"
2217
+ ]);
2218
+ const { path: filePath } = lintOptions;
2219
+ const plugins2 = outputFormat === "md" ? [] : plugins_exports.getPlugins();
2220
+ const vars = getVarsPerFile(filePath);
2221
+ const root = (0, import_path20.resolve)(input);
2222
+ const path = (0, import_path20.resolve)(input, filePath);
2223
+ let preparedContent = content;
2224
+ const assetsPublicPath = (0, import_path20.relative)((0, import_path20.dirname)(path), root);
2225
+ const lintMarkdown = function lintMarkdown2(opts) {
2226
+ const { input: localInput, path: localPath, sourceMap: sourceMap2 } = opts;
2227
+ const pluginOptions = __spreadProps(__spreadValues({}, options), {
2228
+ vars,
2229
+ root,
2230
+ path: localPath,
2231
+ lintMarkdown: lintMarkdown2,
2232
+ // Should pass the function for linting included files
2233
+ assetsPublicPath,
2234
+ disableLiquid,
2235
+ log: import_log8.default,
2236
+ getVarsPerFile: getVarsPerRelativeFile
2237
+ });
2238
+ (0, import_yfmlint.default)({
2239
+ input: localInput,
2240
+ lintConfig,
2241
+ pluginOptions,
2242
+ plugins: plugins2,
2243
+ defaultLintConfig: plugins_exports.getDefaultLintConfig(),
2244
+ customLintRules: plugins_exports.getCustomLintRules(),
2245
+ sourceMap: sourceMap2
2246
+ });
2247
+ };
2248
+ let sourceMap;
2249
+ if (!disableLiquid) {
2250
+ let liquidResult;
2251
+ if (outputFormat === "md") {
2252
+ liquidResult = liquidMd2Md(content, vars, path);
2253
+ } else {
2254
+ liquidResult = liquidMd2Html(content, vars, path);
2255
+ }
2256
+ preparedContent = liquidResult.output;
2257
+ sourceMap = liquidResult.sourceMap;
2258
+ }
2259
+ lintMarkdown({
2260
+ input: preparedContent,
2261
+ path,
2262
+ sourceMap
2263
+ });
2264
+ }
2265
+
2266
+ // src/vcs-connector/github.ts
2267
+ var import_core = require("@octokit/core");
2268
+ var import_path21 = require("path");
2269
+ var import_simple_git = __toESM(require("simple-git"));
2270
+ var import_minimatch = require("minimatch");
2271
+
2272
+ // src/vcs-connector/client/github.ts
2273
+ var import_log10 = __toESM(require("@doc-tools/transform/lib/log"));
2274
+
2275
+ // src/vcs-connector/connector-validator.ts
2276
+ var import_log9 = __toESM(require("@doc-tools/transform/lib/log"));
2277
+ var githubConnectorValidator = {
2278
+ ["endpoint" /* ENDPOINT */]: {
2279
+ warnMessage: `'${"endpoint" /* ENDPOINT */}' must be provided for GitHub repo.`,
2280
+ validateFn: notEmptyValue,
2281
+ defaultValue: process.env.GITHUB_BASE_URL
2282
+ },
2283
+ ["token" /* TOKEN */]: {
2284
+ warnMessage: `'${"token" /* TOKEN */}' must be provided for GitHub repo.`,
2285
+ validateFn: notEmptyValue,
2286
+ defaultValue: process.env.GITHUB_TOKEN
2287
+ },
2288
+ ["owner" /* OWNER */]: {
2289
+ warnMessage: `'${"owner" /* OWNER */}' must be provided for GitHub repo.`,
2290
+ validateFn: notEmptyValue,
2291
+ defaultValue: process.env.GITHUB_OWNER
2292
+ },
2293
+ ["repo" /* REPO */]: {
2294
+ warnMessage: `'${"repo" /* REPO */}' must be provided for GitHub repo.`,
2295
+ validateFn: notEmptyValue,
2296
+ defaultValue: process.env.GITHUB_REPO
2297
+ }
2298
+ };
2299
+ var connectorValidator = {
2300
+ "type": {
2301
+ warnMessage: "'type' must be provided for repo.",
2302
+ validateFn: notEmptyValue
2303
+ },
2304
+ ["github" /* GITHUB */]: {
2305
+ warnMessage: `'${"github" /* GITHUB */}' object must be filled needed fields.`,
2306
+ validateFn: notEmptyObject,
2307
+ relatedValidator: githubConnectorValidator
2308
+ }
2309
+ };
2310
+ function notEmptyObject(filed) {
2311
+ if (typeof filed === "object") {
2312
+ return Boolean(filed && Object.getOwnPropertyNames(filed).length);
2313
+ }
2314
+ return false;
2315
+ }
2316
+ function notEmptyValue(value) {
2317
+ if (typeof value === "string") {
2318
+ return Boolean(value);
2319
+ }
2320
+ return false;
2321
+ }
2322
+ function validateConnectorFields(sourceType, fieldNames, repoProperties) {
2323
+ var _a;
2324
+ const repoValidator = connectorValidator[sourceType];
2325
+ if (!repoValidator) {
2326
+ import_log9.default.error(`Invalid repo type: ${repoValidator}`);
2327
+ return {};
2328
+ }
2329
+ const isValidRepo = repoValidator.validateFn(repoProperties && repoProperties[sourceType]);
2330
+ const relatedRepoValidator = repoValidator.relatedValidator;
2331
+ if (!repoProperties || !isValidRepo || !relatedRepoValidator) {
2332
+ createLog(repoValidator);
2333
+ return {};
2334
+ }
2335
+ let isValidProperties = true;
2336
+ const validatedFields = {};
2337
+ for (const property of fieldNames) {
2338
+ const propertyValidator = relatedRepoValidator[property];
2339
+ if (!propertyValidator) {
2340
+ import_log9.default.warn(`The property '${property}' doesn't exist in ${sourceType} repo.`);
2341
+ continue;
2342
+ }
2343
+ const propertyValue = propertyValidator.defaultValue || ((_a = repoProperties[sourceType]) == null ? void 0 : _a[property]);
2344
+ if (!propertyValidator.validateFn(propertyValue)) {
2345
+ createLog(propertyValidator);
2346
+ isValidProperties = false;
2347
+ }
2348
+ validatedFields[property] = propertyValue;
2349
+ }
2350
+ if (isValidProperties) {
2351
+ return validatedFields;
2352
+ }
2353
+ import_log9.default.warn(getMsg\u0421onfigurationMustBeProvided(sourceType));
2354
+ return {};
2355
+ }
2356
+ function createLog(validator) {
2357
+ if (validator.errorMessage) {
2358
+ return import_log9.default.error(validator.errorMessage);
2359
+ }
2360
+ if (validator.warnMessage) {
2361
+ return import_log9.default.warn(validator.warnMessage);
2362
+ }
2363
+ throw new Error(`Invalid validator: ${JSON.stringify(validator)}.`);
2364
+ }
2365
+
2366
+ // src/vcs-connector/client/github.ts
2367
+ function getRepoUser(octokit, username) {
2368
+ return __async(this, null, function* () {
2369
+ try {
2370
+ const user = yield octokit.request("GET /users/{username}", {
2371
+ username
2372
+ });
2373
+ return user.data;
2374
+ } catch (error) {
2375
+ import_log10.default.warn(`Getting user for GitHub has been failed. Username: ${username}. Error: ${error}`);
2376
+ return null;
2377
+ }
2378
+ });
2379
+ }
2380
+ function getRepoCommitByHash(httpClientByToken, hashCommit) {
2381
+ return __async(this, null, function* () {
2382
+ const { connector } = argv_default.getConfig();
2383
+ const neededProperties = ["owner" /* OWNER */, "repo" /* REPO */];
2384
+ const validatedFileds = validateConnectorFields("github" /* GITHUB */, neededProperties, connector);
2385
+ if (Object.keys(validatedFileds).length === 0) {
2386
+ return null;
2387
+ }
2388
+ try {
2389
+ const commit = yield httpClientByToken.request("GET /repos/{owner}/{repo}/commits/{commit_sha}", {
2390
+ owner: validatedFileds["owner" /* OWNER */],
2391
+ repo: validatedFileds["repo" /* REPO */],
2392
+ commit_sha: hashCommit
2393
+ });
2394
+ return commit.data;
2395
+ } catch (error) {
2396
+ import_log10.default.warn(`Getting commit by sha has been failed for GitHub. SHA commit: ${hashCommit}. Error: ${error}`);
2397
+ return null;
2398
+ }
2399
+ });
2400
+ }
2401
+ var github_default = {
2402
+ getRepoUser,
2403
+ getRepoCommitByHash
2404
+ };
2405
+
2406
+ // src/vcs-connector/github.ts
2407
+ var import_process2 = __toESM(require("process"));
2408
+ var authorByGitEmail = /* @__PURE__ */ new Map();
2409
+ var authorByPath = /* @__PURE__ */ new Map();
2410
+ var contributorsByPath = /* @__PURE__ */ new Map();
2411
+ var contributorsData = /* @__PURE__ */ new Map();
2412
+ function getGitHubVCSConnector() {
2413
+ return __async(this, null, function* () {
2414
+ const { contributors } = argv_default.getConfig();
2415
+ const httpClientByToken = getHttpClientByToken();
2416
+ if (!httpClientByToken) {
2417
+ return void 0;
2418
+ }
2419
+ let addNestedContributorsForPath = () => {
2420
+ };
2421
+ let getContributorsByPath = () => Promise.resolve({});
2422
+ const getExternalAuthorByPath = (path) => {
2423
+ var _a;
2424
+ return (_a = authorByPath.get(path)) != null ? _a : null;
2425
+ };
2426
+ if (contributors) {
2427
+ yield getAllContributorsTocFiles(httpClientByToken);
2428
+ addNestedContributorsForPath = (path, nestedContributors) => addNestedContributorsForPathFunction(path, nestedContributors);
2429
+ getContributorsByPath = (path) => __async(this, null, function* () {
2430
+ return getFileContributorsByPath(path);
2431
+ });
2432
+ }
2433
+ return {
2434
+ getExternalAuthorByPath,
2435
+ addNestedContributorsForPath,
2436
+ getContributorsByPath,
2437
+ getUserByLogin: (login) => getUserByLogin(httpClientByToken, login)
2438
+ };
2439
+ });
2440
+ }
2441
+ function getHttpClientByToken() {
2442
+ const { connector, contributors } = argv_default.getConfig();
2443
+ if (!contributors) {
2444
+ return null;
2445
+ }
2446
+ const neededProperties = ["token" /* TOKEN */, "endpoint" /* ENDPOINT */];
2447
+ const validatedFileds = validateConnectorFields("github" /* GITHUB */, neededProperties, connector);
2448
+ if (Object.keys(validatedFileds).length === 0) {
2449
+ return null;
2450
+ }
2451
+ const octokit = new import_core.Octokit({
2452
+ auth: validatedFileds["token" /* TOKEN */],
2453
+ baseUrl: validatedFileds["endpoint" /* ENDPOINT */]
2454
+ });
2455
+ return octokit;
2456
+ }
2457
+ function getAllContributorsTocFiles(httpClientByToken) {
2458
+ return __async(this, null, function* () {
2459
+ const { rootInput } = argv_default.getConfig();
2460
+ const options = {
2461
+ baseDir: rootInput
2462
+ };
2463
+ logger.info("", GETTING_ALL_CONTRIBUTORS);
2464
+ const masterDir = "./_yfm-master";
2465
+ const tmpMasterBranch = "yfm-tmp-master";
2466
+ try {
2467
+ yield (0, import_simple_git.default)(options).raw("worktree", "add", "-b", tmpMasterBranch, masterDir, "origin/master");
2468
+ const fullRepoLogString = yield (0, import_simple_git.default)({
2469
+ baseDir: (0, import_path21.join)(rootInput, masterDir)
2470
+ }).raw(
2471
+ "log",
2472
+ `${FIRST_COMMIT_FROM_ROBOT_IN_GITHUB}..HEAD`,
2473
+ "--pretty=format:%ae, %an, %H",
2474
+ "--name-only"
2475
+ );
2476
+ const repoLogs = fullRepoLogString.split("\n\n");
2477
+ if (import_process2.default.env.ENABLE_EXPERIMANTAL_AUTHORS) {
2478
+ const fullAuthorRepoLogString = yield (0, import_simple_git.default)({
2479
+ baseDir: (0, import_path21.join)(rootInput, masterDir)
2480
+ }).raw(
2481
+ "log",
2482
+ `${FIRST_COMMIT_FROM_ROBOT_IN_GITHUB}..HEAD`,
2483
+ "--diff-filter=A",
2484
+ "--pretty=format:%ae;%an;%H",
2485
+ "--name-only"
2486
+ );
2487
+ const authorRepoLog = fullAuthorRepoLogString.split("\n\n");
2488
+ yield matchAuthorsForEachPath(authorRepoLog, httpClientByToken);
2489
+ }
2490
+ yield matchContributionsForEachPath(repoLogs, httpClientByToken);
2491
+ } finally {
2492
+ yield (0, import_simple_git.default)(options).raw("worktree", "remove", masterDir);
2493
+ yield (0, import_simple_git.default)(options).raw("branch", "-d", tmpMasterBranch);
2494
+ }
2495
+ logger.info("", ALL_CONTRIBUTORS_RECEIVED);
2496
+ });
2497
+ }
2498
+ function matchContributionsForEachPath(repoLogs, httpClientByToken) {
2499
+ return __async(this, null, function* () {
2500
+ for (const repoLog of repoLogs) {
2501
+ if (!repoLog) {
2502
+ continue;
2503
+ }
2504
+ const dataArray = repoLog.split("\n");
2505
+ const userData = dataArray[0];
2506
+ const [email, name4, hashCommit] = userData.split(", ");
2507
+ if (shouldAuthorBeIgnored({ email, name: name4 })) {
2508
+ continue;
2509
+ }
2510
+ const hasContributorData = contributorsData.get(email);
2511
+ let contributorDataByHash;
2512
+ if (hasContributorData === void 0) {
2513
+ logger.info("Contributors: Getting data for", email);
2514
+ contributorDataByHash = yield getContributorDataByHashCommit(httpClientByToken, hashCommit);
2515
+ if (contributorDataByHash) {
2516
+ const paths = dataArray.splice(1);
2517
+ addContributorForPath(paths, {
2518
+ [email]: contributorDataByHash
2519
+ });
2520
+ }
2521
+ contributorsData.set(email, contributorDataByHash);
2522
+ } else if (hasContributorData) {
2523
+ const paths = dataArray.splice(1);
2524
+ addContributorForPath(paths, {
2525
+ [email]: hasContributorData
2526
+ });
2527
+ }
2528
+ }
2529
+ });
2530
+ }
2531
+ function matchAuthorsForEachPath(authorRepoLogs, httpClientByToken) {
2532
+ return __async(this, null, function* () {
2533
+ for (const repoLog of authorRepoLogs) {
2534
+ if (!repoLog) {
2535
+ continue;
2536
+ }
2537
+ const dataArray = repoLog.split("\n");
2538
+ const [userData, ...paths] = dataArray;
2539
+ const [email, name4, hashCommit] = userData.split(";");
2540
+ if (shouldAuthorBeIgnored({ email, name: name4 })) {
2541
+ continue;
2542
+ }
2543
+ yield getAuthorByPaths({ email, hashCommit }, paths, httpClientByToken);
2544
+ }
2545
+ });
2546
+ }
2547
+ function getContributorDataByHashCommit(httpClientByToken, hashCommit) {
2548
+ return __async(this, null, function* () {
2549
+ const repoCommit = yield github_default.getRepoCommitByHash(httpClientByToken, hashCommit);
2550
+ if (!repoCommit) {
2551
+ return null;
2552
+ }
2553
+ const { author, commit } = repoCommit;
2554
+ if (!author) {
2555
+ return null;
2556
+ }
2557
+ const { avatar_url: avatar, html_url: url2, login } = author;
2558
+ return {
2559
+ avatar,
2560
+ email: commit.author.email,
2561
+ login,
2562
+ name: commit.author.name,
2563
+ url: url2
2564
+ };
2565
+ });
2566
+ }
2567
+ function getAuthorByPaths(commitInfo, paths, httpClientByToken) {
2568
+ return __async(this, null, function* () {
2569
+ for (const path of paths) {
2570
+ if (!path) {
2571
+ continue;
2572
+ }
2573
+ const normalizePath = (0, import_path21.normalize)(addSlashPrefix(path));
2574
+ const { email, hashCommit } = commitInfo;
2575
+ let authorToReturn = authorByGitEmail.get(email) || null;
2576
+ if (!authorToReturn) {
2577
+ logger.info("Authors: Getting data for", email);
2578
+ const repoCommit = yield github_default.getRepoCommitByHash(httpClientByToken, hashCommit);
2579
+ if (!repoCommit) {
2580
+ continue;
2581
+ }
2582
+ const { author, commit } = repoCommit;
2583
+ if (!author) {
2584
+ continue;
2585
+ }
2586
+ const { avatar_url: avatar, html_url: url2, login } = author;
2587
+ authorToReturn = {
2588
+ avatar,
2589
+ email: commit.author.email,
2590
+ login,
2591
+ name: commit.author.name,
2592
+ url: url2
2593
+ };
2594
+ authorByGitEmail.set(email, authorToReturn);
2595
+ }
2596
+ authorByPath.set(normalizePath, authorToReturn);
2597
+ }
2598
+ });
2599
+ }
2600
+ function getFileContributorsByPath(path) {
2601
+ return __async(this, null, function* () {
2602
+ if (contributorsData.size === 0 || !contributorsByPath.has(path)) {
2603
+ return {};
2604
+ }
2605
+ return contributorsByPath.get(path);
2606
+ });
2607
+ }
2608
+ function getUserByLogin(octokit, userLogin) {
2609
+ return __async(this, null, function* () {
2610
+ const user = yield github_default.getRepoUser(octokit, userLogin);
2611
+ if (!user) {
2612
+ return null;
2613
+ }
2614
+ const { avatar_url: avatar, html_url: url2, email, login, name: name4 } = user;
2615
+ return {
2616
+ avatar,
2617
+ email,
2618
+ login,
2619
+ name: name4,
2620
+ url: url2
2621
+ };
2622
+ });
2623
+ }
2624
+ function addNestedContributorsForPathFunction(path, nestedContributors) {
2625
+ addContributorForPath([path], nestedContributors, true);
2626
+ }
2627
+ function addContributorForPath(paths, newContributor, hasIncludes = false) {
2628
+ paths.forEach((path) => {
2629
+ const normalizePath = (0, import_path21.normalize)(addSlashPrefix(path));
2630
+ if (!contributorsByPath.has(normalizePath)) {
2631
+ contributorsByPath.set(normalizePath, {
2632
+ contributors: newContributor,
2633
+ hasIncludes
2634
+ });
2635
+ return;
2636
+ }
2637
+ const oldContributors = contributorsByPath.get(normalizePath);
2638
+ contributorsByPath.set(normalizePath, {
2639
+ contributors: __spreadValues(__spreadValues({}, oldContributors == null ? void 0 : oldContributors.contributors), newContributor),
2640
+ hasIncludes
2641
+ });
2642
+ });
2643
+ }
2644
+ function shouldAuthorBeIgnored({ email, name: name4 }) {
2645
+ if (!(email || name4)) {
2646
+ return false;
2647
+ }
2648
+ const { ignoreAuthorPatterns } = argv_default.getConfig();
2649
+ if (!ignoreAuthorPatterns) {
2650
+ return false;
2651
+ }
2652
+ for (const pattern of ignoreAuthorPatterns) {
2653
+ if (email && (0, import_minimatch.minimatch)(email, pattern)) {
2654
+ return true;
2655
+ }
2656
+ if (name4 && (0, import_minimatch.minimatch)(name4, pattern)) {
2657
+ return true;
2658
+ }
2659
+ }
2660
+ return false;
2661
+ }
2662
+ var github_default2 = getGitHubVCSConnector;
2663
+
2664
+ // src/vcs-connector/index.ts
2665
+ function getVCSConnector() {
2666
+ return __async(this, null, function* () {
2667
+ const { connector } = argv_default.getConfig();
2668
+ const connectorType = process.env.VCS_CONNECTOR_TYPE || connector && connector.type;
2669
+ switch (connectorType) {
2670
+ case "github" /* GITHUB */:
2671
+ return github_default2();
2672
+ default:
2673
+ return void 0;
2674
+ }
2675
+ });
2676
+ }
2677
+
2678
+ // src/steps/processPages.ts
2679
+ var singlePageResults = {};
2680
+ var singlePagePaths = {};
2681
+ function processPages(outputBundlePath) {
2682
+ return __async(this, null, function* () {
2683
+ const {
2684
+ input: inputFolderPath,
2685
+ output: outputFolderPath,
2686
+ outputFormat,
2687
+ singlePage,
2688
+ resolveConditions
2689
+ } = argv_default.getConfig();
2690
+ const vcsConnector = yield getVCSConnector();
2691
+ plugins_exports.setPlugins();
2692
+ const navigationPaths2 = tocs_default.getNavigationPaths();
2693
+ const concurrency = 500;
2694
+ yield (0, import_async.mapLimit)(navigationPaths2, concurrency, (0, import_async.asyncify)((pathToFile) => __async(this, null, function* () {
2695
+ const pathData = getPathData(pathToFile, inputFolderPath, outputFolderPath, outputFormat, outputBundlePath);
2696
+ logger.proc(pathToFile);
2697
+ const metaDataOptions = getMetaDataOptions(pathData, inputFolderPath.length, vcsConnector);
2698
+ yield preparingPagesByOutputFormat(pathData, metaDataOptions, resolveConditions, singlePage);
2699
+ })));
2700
+ if (singlePage) {
2701
+ yield saveSinglePages(outputBundlePath);
2702
+ }
2703
+ });
2704
+ }
2705
+ function getPathData(pathToFile, inputFolderPath, outputFolderPath, outputFormat, outputBundlePath) {
2706
+ const pathToDir = (0, import_path22.dirname)(pathToFile);
2707
+ const filename = (0, import_path22.basename)(pathToFile);
2708
+ const fileExtension = (0, import_path22.extname)(pathToFile);
2709
+ const fileBaseName = (0, import_path22.basename)(filename, fileExtension);
2710
+ const outputDir = (0, import_path22.resolve)(outputFolderPath, pathToDir);
2711
+ const outputFileName = `${fileBaseName}.${outputFormat}`;
2712
+ const outputPath = (0, import_path22.resolve)(outputDir, outputFileName);
2713
+ const resolvedPathToFile = (0, import_path22.resolve)(inputFolderPath, pathToFile);
2714
+ const outputTocDir = tocs_default.getTocDir(resolvedPathToFile);
2715
+ const pathData = {
2716
+ pathToFile,
2717
+ resolvedPathToFile,
2718
+ filename,
2719
+ fileBaseName,
2720
+ fileExtension,
2721
+ outputDir,
2722
+ outputPath,
2723
+ outputFormat,
2724
+ outputBundlePath,
2725
+ outputTocDir,
2726
+ inputFolderPath,
2727
+ outputFolderPath
2728
+ };
2729
+ return pathData;
2730
+ }
2731
+ function saveSinglePages(outputBundlePath) {
2732
+ return __async(this, null, function* () {
2733
+ const {
2734
+ input: inputFolderPath,
2735
+ output: outputFolderPath,
2736
+ lang,
2737
+ resources
2738
+ } = argv_default.getConfig();
2739
+ try {
2740
+ yield Promise.all(Object.keys(singlePageResults).map((tocDir) => __async(this, null, function* () {
2741
+ if (!singlePageResults[tocDir].length) {
2742
+ return;
2743
+ }
2744
+ const singlePageBody = joinSinglePageResults(singlePageResults[tocDir], inputFolderPath, tocDir);
2745
+ const tocPath = (0, import_path22.join)((0, import_path22.relative)(inputFolderPath, tocDir), "toc.yaml");
2746
+ const toc = tocs_default.getForPath(tocPath) || null;
2747
+ const preparedToc = transformTocForSinglePage(toc, {
2748
+ root: inputFolderPath,
2749
+ currentPath: (0, import_path22.join)(tocDir, SINGLE_PAGE_FILENAME)
2750
+ });
2751
+ const pageData = {
2752
+ data: {
2753
+ leading: false,
2754
+ html: singlePageBody,
2755
+ headings: [],
2756
+ meta: resources || {},
2757
+ toc: preparedToc
2758
+ },
2759
+ router: {
2760
+ pathname: SINGLE_PAGE_FILENAME
2761
+ },
2762
+ lang: lang || "ru" /* RU */
2763
+ };
2764
+ const outputTocDir = (0, import_path22.resolve)(outputFolderPath, (0, import_path22.relative)(inputFolderPath, tocDir));
2765
+ const relativeOutputBundlePath = (0, import_path22.relative)(outputTocDir, outputBundlePath);
2766
+ const singlePageFn = (0, import_path22.join)(tocDir, SINGLE_PAGE_FILENAME);
2767
+ const singlePageDataFn = (0, import_path22.join)(tocDir, SINGLE_PAGE_DATA_FILENAME);
2768
+ const singlePageContent = generateStaticMarkup(pageData, relativeOutputBundlePath);
2769
+ (0, import_fs10.writeFileSync)(singlePageFn, singlePageContent);
2770
+ (0, import_fs10.writeFileSync)(singlePageDataFn, JSON.stringify(pageData));
2771
+ })));
2772
+ } catch (error) {
2773
+ console.log(error);
2774
+ }
2775
+ });
2776
+ }
2777
+ function savePageResultForSinglePage(pageProps, pathData) {
2778
+ const { pathToFile, outputTocDir } = pathData;
2779
+ if (pageProps.data.leading) {
2780
+ return;
2781
+ }
2782
+ singlePagePaths[outputTocDir] = singlePagePaths[outputTocDir] || /* @__PURE__ */ new Set();
2783
+ if (singlePagePaths[outputTocDir].has(pathToFile)) {
2784
+ return;
2785
+ }
2786
+ singlePagePaths[outputTocDir].add(pathToFile);
2787
+ singlePageResults[outputTocDir] = singlePageResults[outputTocDir] || [];
2788
+ singlePageResults[outputTocDir].push({
2789
+ path: pathToFile,
2790
+ content: pageProps.data.html,
2791
+ title: pageProps.data.title
2792
+ });
2793
+ }
2794
+ function getMetaDataOptions(pathData, inputFolderPathLength, vcsConnector) {
2795
+ const { contributors, addSystemMeta, resources, allowCustomResources } = argv_default.getConfig();
2796
+ const metaDataOptions = {
2797
+ vcsConnector,
2798
+ fileData: {
2799
+ tmpInputFilePath: pathData.resolvedPathToFile,
2800
+ inputFolderPathLength,
2801
+ fileContent: ""
2802
+ },
2803
+ isContributorsEnabled: Boolean(contributors && vcsConnector),
2804
+ addSystemMeta
2805
+ };
2806
+ if (allowCustomResources && resources) {
2807
+ const allowedResources = Object.entries(resources).reduce((acc, [key, val]) => {
2808
+ if (Object.keys(ResourceType).includes(key)) {
2809
+ acc[key] = val;
2810
+ }
2811
+ return acc;
2812
+ }, {});
2813
+ metaDataOptions.resources = allowedResources;
2814
+ }
2815
+ return metaDataOptions;
2816
+ }
2817
+ function preparingPagesByOutputFormat(path, metaDataOptions, resolveConditions, singlePage) {
2818
+ return __async(this, null, function* () {
2819
+ const {
2820
+ filename,
2821
+ fileExtension,
2822
+ fileBaseName,
2823
+ outputDir,
2824
+ resolvedPathToFile,
2825
+ outputFormat,
2826
+ pathToFile
2827
+ } = path;
2828
+ const { allowCustomResources } = argv_default.getConfig();
2829
+ try {
2830
+ import_shelljs6.default.mkdir("-p", outputDir);
2831
+ const isYamlFileExtension = fileExtension === ".yaml";
2832
+ if (resolveConditions && fileBaseName === "index" && isYamlFileExtension) {
2833
+ leading_default.filterFile(pathToFile);
2834
+ }
2835
+ if (outputFormat === "md" && isYamlFileExtension && allowCustomResources) {
2836
+ processingYamlFile(path, metaDataOptions);
2837
+ return;
2838
+ }
2839
+ if (outputFormat === "md" && isYamlFileExtension || outputFormat === "html" && !isYamlFileExtension && fileExtension !== ".md") {
2840
+ copyFileWithoutChanges(resolvedPathToFile, outputDir, filename);
2841
+ return;
2842
+ }
2843
+ switch (outputFormat) {
2844
+ case "md":
2845
+ yield processingFileToMd(path, metaDataOptions);
2846
+ return;
2847
+ case "html": {
2848
+ const resolvedFileProps = yield processingFileToHtml(path, metaDataOptions);
2849
+ if (singlePage) {
2850
+ savePageResultForSinglePage(resolvedFileProps, path);
2851
+ }
2852
+ return;
2853
+ }
2854
+ }
2855
+ } catch (e) {
2856
+ const message = `No such file or has no access to ${(0, import_chalk4.bold)(resolvedPathToFile)}`;
2857
+ console.log(message, e);
2858
+ import_log11.default.error(message);
2859
+ }
2860
+ });
2861
+ }
2862
+ function processingYamlFile(path, metaDataOptions) {
2863
+ const { pathToFile, outputFolderPath, inputFolderPath } = path;
2864
+ const filePath = (0, import_path22.resolve)(inputFolderPath, pathToFile);
2865
+ const content = (0, import_fs10.readFileSync)(filePath, "utf8");
2866
+ const parsedContent = (0, import_js_yaml7.load)(content);
2867
+ if (metaDataOptions.resources) {
2868
+ parsedContent.meta = __spreadValues(__spreadValues({}, parsedContent.meta), metaDataOptions.resources);
2869
+ }
2870
+ (0, import_fs10.writeFileSync)((0, import_path22.resolve)(outputFolderPath, pathToFile), (0, import_js_yaml7.dump)(parsedContent));
2871
+ }
2872
+ function copyFileWithoutChanges(resolvedPathToFile, outputDir, filename) {
2873
+ const from = resolvedPathToFile;
2874
+ const to = (0, import_path22.resolve)(outputDir, filename);
2875
+ (0, import_fs10.copyFileSync)(from, to);
2876
+ }
2877
+ function processingFileToMd(path, metaDataOptions) {
2878
+ return __async(this, null, function* () {
2879
+ const { outputPath, pathToFile } = path;
2880
+ yield resolveMd2Md({
2881
+ inputPath: pathToFile,
2882
+ outputPath,
2883
+ metadata: metaDataOptions
2884
+ });
2885
+ });
2886
+ }
2887
+ function processingFileToHtml(path, metaDataOptions) {
2888
+ return __async(this, null, function* () {
2889
+ const {
2890
+ outputBundlePath,
2891
+ filename,
2892
+ fileExtension,
2893
+ outputPath,
2894
+ pathToFile
2895
+ } = path;
2896
+ return resolveMd2HTML({
2897
+ inputPath: pathToFile,
2898
+ outputBundlePath,
2899
+ fileExtension,
2900
+ outputPath,
2901
+ filename,
2902
+ metadata: metaDataOptions
2903
+ });
2904
+ });
2905
+ }
2906
+
2907
+ // src/steps/processLinter.ts
2908
+ var import_log12 = __toESM(require("@doc-tools/transform/lib/log"));
2909
+ var import_threads = require("threads");
2910
+ var import_path23 = require("path");
2911
+
2912
+ // src/utils/worker.ts
2913
+ function splitOnChunks(array, chunkSize = 1e3) {
2914
+ const chunks = [];
2915
+ for (let i = 0, j = array.length; i < j; i += chunkSize) {
2916
+ const chunk = array.slice(i, i + chunkSize);
2917
+ chunks.push(chunk);
2918
+ }
2919
+ return chunks;
2920
+ }
2921
+
2922
+ // src/steps/processLinter.ts
2923
+ var processLinterWorkers;
2924
+ var navigationPathsChunks;
2925
+ function processLinter() {
2926
+ return __async(this, null, function* () {
2927
+ const argvConfig = argv_default.getConfig();
2928
+ const navigationPaths2 = tocs_default.getNavigationPaths();
2929
+ if (!processLinterWorkers) {
2930
+ lintPagesFallback(navigationPaths2);
2931
+ return;
2932
+ }
2933
+ const presetStorage2 = preset_default.getPresetStorage();
2934
+ processLinterWorkers.forEach((worker) => {
2935
+ worker.getProcessedPages().subscribe((pathToFile) => {
2936
+ logger.info(pathToFile, LINTING_FINISHED);
2937
+ });
2938
+ });
2939
+ yield Promise.all(
2940
+ processLinterWorkers.map((worker, i) => {
2941
+ const navigationPathsChunk = navigationPathsChunks[i];
2942
+ return worker.run({
2943
+ argvConfig,
2944
+ presetStorage: presetStorage2,
2945
+ navigationPaths: navigationPathsChunk
2946
+ });
2947
+ })
2948
+ );
2949
+ yield Promise.all(
2950
+ processLinterWorkers.map((worker) => {
2951
+ return worker.finish().then((logs) => {
2952
+ import_log12.default.add(logs);
2953
+ });
2954
+ })
2955
+ );
2956
+ yield Promise.all(
2957
+ processLinterWorkers.map((worker) => {
2958
+ return import_threads.Thread.terminate(worker);
2959
+ })
2960
+ );
2961
+ });
2962
+ }
2963
+ function initLinterWorkers() {
2964
+ return __async(this, null, function* () {
2965
+ const navigationPaths2 = tocs_default.getNavigationPaths();
2966
+ const chunkSize = getChunkSize(navigationPaths2);
2967
+ if (process.env.DISABLE_PARALLEL_BUILD || chunkSize < MIN_CHUNK_SIZE || WORKERS_COUNT <= 0) {
2968
+ return;
2969
+ }
2970
+ navigationPathsChunks = splitOnChunks(navigationPaths2, chunkSize).filter((arr) => arr.length);
2971
+ const workersCount = navigationPathsChunks.length;
2972
+ processLinterWorkers = yield Promise.all(new Array(workersCount).fill(null).map(() => {
2973
+ return (0, import_threads.spawn)(new import_threads.Worker("./linter"), { timeout: 6e4 });
2974
+ }));
2975
+ });
2976
+ }
2977
+ function getChunkSize(arr) {
2978
+ return Math.ceil(arr.length / WORKERS_COUNT);
2979
+ }
2980
+ function lintPagesFallback(navigationPaths2) {
2981
+ plugins_exports.setPlugins();
2982
+ navigationPaths2.forEach((pathToFile) => {
2983
+ lintPage({
2984
+ inputPath: pathToFile,
2985
+ fileExtension: (0, import_path23.extname)(pathToFile),
2986
+ onFinish: () => {
2987
+ logger.info(pathToFile, LINTING_FINISHED);
2988
+ }
2989
+ });
2990
+ });
2991
+ }
2992
+
2993
+ // src/steps/processServiceFiles.ts
2994
+ var import_path24 = require("path");
2995
+ var import_walk_sync4 = __toESM(require("walk-sync"));
2996
+ var import_fs11 = require("fs");
2997
+ var import_js_yaml8 = require("js-yaml");
2998
+ var import_log13 = __toESM(require("@doc-tools/transform/lib/log"));
2999
+ var import_shelljs7 = __toESM(require("shelljs"));
3000
+ function processServiceFiles() {
3001
+ return __async(this, null, function* () {
3002
+ const { input: inputFolderPath, ignore = [] } = argv_default.getConfig();
3003
+ const getFilePathsByGlobals = (globs) => {
3004
+ return (0, import_walk_sync4.default)(inputFolderPath, {
3005
+ directories: false,
3006
+ includeBasePath: false,
3007
+ globs,
3008
+ ignore
3009
+ });
3010
+ };
3011
+ preparingPresetFiles(getFilePathsByGlobals);
3012
+ yield preparingTocFiles(getFilePathsByGlobals);
3013
+ });
3014
+ }
3015
+ function preparingPresetFiles(getFilePathsByGlobals) {
3016
+ const {
3017
+ input: inputFolderPath,
3018
+ varsPreset = "",
3019
+ outputFormat,
3020
+ applyPresets,
3021
+ resolveConditions
3022
+ } = argv_default.getConfig();
3023
+ try {
3024
+ const presetsFilePaths = getFilePathsByGlobals(["**/presets.yaml"]);
3025
+ for (const path of presetsFilePaths) {
3026
+ logger.proc(path);
3027
+ const pathToPresetFile = (0, import_path24.resolve)(inputFolderPath, path);
3028
+ const content = (0, import_fs11.readFileSync)(pathToPresetFile, "utf8");
3029
+ const parsedPreset = (0, import_js_yaml8.load)(content);
3030
+ preset_default.add(parsedPreset, path, varsPreset);
3031
+ if (outputFormat === "md" && (!applyPresets || !resolveConditions)) {
3032
+ saveFilteredPresets(path, parsedPreset);
3033
+ }
3034
+ }
3035
+ } catch (error) {
3036
+ import_log13.default.error(`Preparing presets.yaml files failed. Error: ${error}`);
3037
+ throw error;
3038
+ }
3039
+ }
3040
+ function saveFilteredPresets(path, parsedPreset) {
3041
+ const { output: outputFolderPath, varsPreset = "" } = argv_default.getConfig();
3042
+ const outputPath = (0, import_path24.resolve)(outputFolderPath, path);
3043
+ const filteredPreset = {
3044
+ default: parsedPreset.default
3045
+ };
3046
+ if (parsedPreset[varsPreset]) {
3047
+ filteredPreset[varsPreset] = parsedPreset[varsPreset];
3048
+ }
3049
+ const outputPreset = (0, import_js_yaml8.dump)(filteredPreset, {
3050
+ lineWidth: 120
3051
+ });
3052
+ import_shelljs7.default.mkdir("-p", (0, import_path24.dirname)(outputPath));
3053
+ (0, import_fs11.writeFileSync)(outputPath, outputPreset);
3054
+ }
3055
+ function preparingTocFiles(getFilePathsByGlobals) {
3056
+ return __async(this, null, function* () {
3057
+ try {
3058
+ const tocFilePaths = getFilePathsByGlobals(["**/toc.yaml"]);
3059
+ for (const path of tocFilePaths) {
3060
+ logger.proc(path);
3061
+ yield tocs_default.add(path);
3062
+ }
3063
+ } catch (error) {
3064
+ import_log13.default.error(`Preparing toc.yaml files failed. Error: ${error}`);
3065
+ throw error;
3066
+ }
3067
+ });
3068
+ }
3069
+
3070
+ // src/steps/processMapFile.ts
3071
+ var import_fs12 = require("fs");
3072
+ var import_path25 = require("path");
3073
+ function prepareMapFile() {
3074
+ const {
3075
+ output: outputFolderPath
3076
+ } = argv_default.getConfig();
3077
+ const navigationPathsWithoutExtensions = tocs_default.getNavigationPaths().map((path) => {
3078
+ let preparedPath = convertBackSlashToSlash(path.replace((0, import_path25.extname)(path), ""));
3079
+ if (preparedPath.endsWith("/index")) {
3080
+ preparedPath = preparedPath.substring(0, preparedPath.length - 5);
3081
+ }
3082
+ return preparedPath;
3083
+ });
3084
+ const navigationPaths2 = { files: [...new Set(navigationPathsWithoutExtensions)] };
3085
+ const filesMapBuffer = Buffer.from(JSON.stringify(navigationPaths2, null, " "), "utf8");
3086
+ const mapFile = (0, import_path25.join)(outputFolderPath, "files.json");
3087
+ (0, import_fs12.writeFileSync)(mapFile, filesMapBuffer);
3088
+ }
3089
+
3090
+ // src/cmd/build/index.ts
3091
+ var import_shelljs8 = __toESM(require("shelljs"));
3092
+
3093
+ // src/cmd/publish/upload.ts
3094
+ var import_fs13 = require("fs");
3095
+ var import_walk_sync5 = __toESM(require("walk-sync"));
3096
+ var import_path26 = require("path");
3097
+ var import_client_s3 = require("@aws-sdk/client-s3");
3098
+ var import_mime_types = __toESM(require("mime-types"));
3099
+ var import_async2 = require("async");
3100
+ function upload(props) {
3101
+ return __async(this, null, function* () {
3102
+ const {
3103
+ input,
3104
+ ignore = [],
3105
+ endpoint,
3106
+ region,
3107
+ bucket,
3108
+ prefix,
3109
+ accessKeyId,
3110
+ secretAccessKey
3111
+ } = props;
3112
+ const s3Client = new import_client_s3.S3Client({
3113
+ endpoint,
3114
+ region,
3115
+ credentials: { accessKeyId, secretAccessKey }
3116
+ });
3117
+ const filesToPublish = (0, import_walk_sync5.default)((0, import_path26.resolve)(input), {
3118
+ directories: false,
3119
+ includeBasePath: false,
3120
+ ignore
3121
+ });
3122
+ yield (0, import_async2.mapLimit)(filesToPublish, 100, (0, import_async2.asyncify)((pathToFile) => __async(this, null, function* () {
3123
+ const mimeType = import_mime_types.default.lookup(pathToFile);
3124
+ logger.upload(pathToFile);
3125
+ try {
3126
+ yield s3Client.send(new import_client_s3.PutObjectCommand({
3127
+ ContentType: mimeType ? mimeType : void 0,
3128
+ Bucket: bucket,
3129
+ Key: convertBackSlashToSlash((0, import_path26.join)(prefix, pathToFile)),
3130
+ Body: (0, import_fs13.createReadStream)((0, import_path26.resolve)(input, pathToFile))
3131
+ }));
3132
+ } catch (error) {
3133
+ logger.error(pathToFile, error.message);
3134
+ }
3135
+ })));
3136
+ });
3137
+ }
3138
+
3139
+ // src/cmd/build/index.ts
3140
+ var import_glob3 = __toESM(require("glob"));
3141
+ var build = {
3142
+ command: ["build", "$0"],
3143
+ description: "Build documentation in target directory",
3144
+ handler,
3145
+ builder
3146
+ };
3147
+ function builder(argv) {
3148
+ return argv.option("input", {
3149
+ alias: "i",
3150
+ describe: "Path to input folder with .md files",
3151
+ type: "string",
3152
+ group: "Build options:"
3153
+ }).option("output", {
3154
+ alias: "o",
3155
+ describe: "Path to output folder",
3156
+ type: "string",
3157
+ group: "Build options:"
3158
+ }).option("varsPreset", {
3159
+ default: "default",
3160
+ describe: "Target vars preset of documentation <external|internal>",
3161
+ group: "Build options:"
3162
+ }).option("output-format", {
3163
+ default: "html",
3164
+ describe: "Format of output file <html|md>",
3165
+ group: "Build options:"
3166
+ }).option("vars", {
3167
+ alias: "v",
3168
+ default: "{}",
3169
+ describe: "List of markdown variables",
3170
+ group: "Build options:"
3171
+ }).option("apply-presets", {
3172
+ default: true,
3173
+ describe: "Should apply presets. Only for --output-format=md",
3174
+ type: "boolean",
3175
+ group: "Build options:"
3176
+ }).option("resolve-conditions", {
3177
+ default: true,
3178
+ describe: "Should resolve conditions. Only for --output-format=md",
3179
+ type: "boolean",
3180
+ group: "Build options:"
3181
+ }).option("conditions-in-code", {
3182
+ default: false,
3183
+ describe: "Meet conditions in code blocks",
3184
+ type: "boolean",
3185
+ group: "Build options:"
3186
+ }).option("disable-liquid", {
3187
+ default: false,
3188
+ describe: "Disable template engine",
3189
+ type: "boolean",
3190
+ group: "Build options:"
3191
+ }).option("allowHTML", {
3192
+ default: false,
3193
+ describe: "Allow to use HTML in Markdown files",
3194
+ type: "boolean",
3195
+ group: "Build options:"
3196
+ }).option("ignore-stage", {
3197
+ default: "skip" /* SKIP */,
3198
+ describe: "Ignore tocs with stage",
3199
+ group: "Build options:"
3200
+ }).option("ignore-author-patterns", {
3201
+ default: [],
3202
+ describe: "Ignore authors if they contain passed string",
3203
+ group: "Build options:",
3204
+ type: "array"
3205
+ }).option("contributors", {
3206
+ default: false,
3207
+ describe: "Should attach contributors into files",
3208
+ type: "boolean",
3209
+ group: "Build options:"
3210
+ }).option("add-system-meta", {
3211
+ default: false,
3212
+ describe: "Should add system section variables form presets into files meta data",
3213
+ type: "boolean",
3214
+ group: "Build options:"
3215
+ }).option("add-map-file", {
3216
+ default: false,
3217
+ describe: "Should add all paths of documentation into file.json",
3218
+ type: "boolean",
3219
+ group: "Build options:"
3220
+ }).option("single-page", {
3221
+ default: false,
3222
+ describe: "Beta functionality: Build a single page in the output folder also",
3223
+ type: "boolean",
3224
+ group: "Build options:"
3225
+ }).option("publish", {
3226
+ default: false,
3227
+ describe: "Should upload output files to S3 storage",
3228
+ type: "boolean",
3229
+ group: "Build options:"
3230
+ }).option("remove-hidden-toc-items", {
3231
+ default: false,
3232
+ describe: "Remove hidden toc items",
3233
+ type: "boolean",
3234
+ group: "Build options:"
3235
+ }).option("lint-disabled", {
3236
+ default: false,
3237
+ describe: "Disable linting",
3238
+ type: "boolean",
3239
+ group: "Build options:"
3240
+ }).option("build-disabled", {
3241
+ default: false,
3242
+ describe: "Disable building",
3243
+ type: "boolean",
3244
+ group: "Build options:"
3245
+ }).option("allow-custom-resources", {
3246
+ default: false,
3247
+ describe: "Allow loading custom resources",
3248
+ type: "boolean",
3249
+ group: "Build options:"
3250
+ }).option("static-content", {
3251
+ default: false,
3252
+ describe: "Include static content in the page",
3253
+ type: "boolean",
3254
+ group: "Build options:"
3255
+ }).check(argvValidator).example("yfm -i ./input -o ./output", "").demandOption(["input", "output"], "Please provide input and output arguments to work with this tool");
3256
+ }
3257
+ function handler(args) {
3258
+ return __async(this, null, function* () {
3259
+ var _a;
3260
+ const userOutputFolder = (0, import_path27.resolve)(args.output);
3261
+ const tmpInputFolder = (0, import_path27.resolve)(args.output, TMP_INPUT_FOLDER);
3262
+ const tmpOutputFolder = (0, import_path27.resolve)(args.output, TMP_OUTPUT_FOLDER);
3263
+ try {
3264
+ argv_default.init(__spreadProps(__spreadValues({}, args), {
3265
+ rootInput: args.input,
3266
+ input: tmpInputFolder,
3267
+ output: tmpOutputFolder
3268
+ }));
3269
+ includers_exports.init([import_includer.default]);
3270
+ const {
3271
+ output: outputFolderPath,
3272
+ outputFormat,
3273
+ publish: publish2,
3274
+ lintDisabled,
3275
+ buildDisabled,
3276
+ addMapFile,
3277
+ allowCustomResources,
3278
+ resources
3279
+ } = argv_default.getConfig();
3280
+ preparingTemporaryFolders(userOutputFolder);
3281
+ yield processServiceFiles();
3282
+ processExcludedFiles();
3283
+ if (addMapFile) {
3284
+ prepareMapFile();
3285
+ }
3286
+ const outputBundlePath = (0, import_path27.join)(outputFolderPath, BUNDLE_FOLDER);
3287
+ const pathToConfig = args.config || (0, import_path27.join)(args.input, YFM_CONFIG_FILENAME);
3288
+ const pathToRedirects = (0, import_path27.join)(args.input, REDIRECTS_FILENAME);
3289
+ const pathToLintConfig = (0, import_path27.join)(args.input, LINT_CONFIG_FILENAME);
3290
+ if (!lintDisabled) {
3291
+ yield initLinterWorkers();
3292
+ }
3293
+ const processes = [
3294
+ !lintDisabled && processLinter(),
3295
+ !buildDisabled && processPages(outputBundlePath)
3296
+ ].filter(Boolean);
3297
+ yield Promise.all(processes);
3298
+ if (!buildDisabled) {
3299
+ switch (outputFormat) {
3300
+ case "html":
3301
+ processAssets(outputBundlePath);
3302
+ break;
3303
+ case "md": {
3304
+ import_shelljs8.default.cp((0, import_path27.resolve)(pathToConfig), tmpOutputFolder);
3305
+ import_shelljs8.default.cp((0, import_path27.resolve)(pathToRedirects), tmpOutputFolder);
3306
+ import_shelljs8.default.cp((0, import_path27.resolve)(pathToLintConfig), tmpOutputFolder);
3307
+ if (resources && allowCustomResources) {
3308
+ const resourcePaths = [];
3309
+ Object.keys(resources).forEach((type) => {
3310
+ var _a2;
3311
+ return (_a2 = resources[type]) == null ? void 0 : _a2.forEach((path) => resourcePaths.push(path));
3312
+ });
3313
+ copyFiles(args.input, tmpOutputFolder, resourcePaths);
3314
+ }
3315
+ break;
3316
+ }
3317
+ }
3318
+ import_shelljs8.default.cp("-r", [(0, import_path27.join)(tmpOutputFolder, "*"), (0, import_path27.join)(tmpOutputFolder, ".*")], userOutputFolder);
3319
+ if (publish2) {
3320
+ const DEFAULT_PREFIX = (_a = process.env.YFM_STORAGE_PREFIX) != null ? _a : "";
3321
+ const {
3322
+ ignore = [],
3323
+ storageRegion,
3324
+ storageEndpoint: endpoint,
3325
+ storageBucket: bucket,
3326
+ storagePrefix: prefix = DEFAULT_PREFIX,
3327
+ storageKeyId: accessKeyId,
3328
+ storageSecretKey: secretAccessKey
3329
+ } = argv_default.getConfig();
3330
+ yield upload({
3331
+ input: userOutputFolder,
3332
+ region: storageRegion,
3333
+ ignore,
3334
+ endpoint,
3335
+ bucket,
3336
+ prefix,
3337
+ accessKeyId,
3338
+ secretAccessKey
3339
+ });
3340
+ }
3341
+ }
3342
+ } catch (err) {
3343
+ logger.error("", err.message);
3344
+ } finally {
3345
+ processLogs(tmpInputFolder);
3346
+ import_shelljs8.default.rm("-rf", tmpInputFolder, tmpOutputFolder);
3347
+ }
3348
+ });
3349
+ }
3350
+ function preparingTemporaryFolders(userOutputFolder) {
3351
+ const args = argv_default.getConfig();
3352
+ import_shelljs8.default.mkdir("-p", userOutputFolder);
3353
+ import_shelljs8.default.rm("-rf", args.input, args.output);
3354
+ import_shelljs8.default.mkdir(args.input, args.output);
3355
+ import_shelljs8.default.chmod("-R", "u+w", args.input);
3356
+ copyFiles(args.rootInput, args.input, import_glob3.default.sync("**", {
3357
+ cwd: args.rootInput,
3358
+ nodir: true,
3359
+ follow: true,
3360
+ ignore: [
3361
+ "node_modules/**",
3362
+ "*/node_modules/**"
3363
+ ]
3364
+ }));
3365
+ }
3366
+
3367
+ // src/cmd/publish/index.ts
3368
+ var import_path28 = require("path");
3369
+ var command = "publish";
3370
+ var description = "Upload builded documentation to target S3 bucket";
3371
+ var publish = {
3372
+ command,
3373
+ description,
3374
+ handler: handler2,
3375
+ builder: builder2
3376
+ };
3377
+ function builder2(argv) {
3378
+ return argv.option("strict", {
3379
+ default: true
3380
+ }).option("input", {
3381
+ alias: "i",
3382
+ describe: "Path to folder with builded files",
3383
+ type: "string",
3384
+ required: true,
3385
+ group: "Upload options"
3386
+ }).option("endpoint", {
3387
+ describe: "S3 bucket endpoint",
3388
+ default: "https://s3.amazonaws.com",
3389
+ type: "string",
3390
+ group: "Upload options"
3391
+ }).option("region", {
3392
+ describe: "S3 bucket region",
3393
+ default: "eu-central-1",
3394
+ type: "string",
3395
+ group: "Upload options"
3396
+ }).option("bucket", {
3397
+ describe: "S3 bucket name",
3398
+ type: "string",
3399
+ required: true,
3400
+ group: "Upload options"
3401
+ }).option("prefix", {
3402
+ describe: "S3 bucket ",
3403
+ default: "",
3404
+ type: "string",
3405
+ group: "Upload options"
3406
+ }).option("access-key-id", {
3407
+ describe: "S3 bucket AccessKeyId",
3408
+ type: "string",
3409
+ required: true,
3410
+ group: "Upload options"
3411
+ }).option("secret-access-key", {
3412
+ describe: "S3 bucket SecretAccessKey",
3413
+ type: "string",
3414
+ required: true,
3415
+ group: "Upload options"
3416
+ });
3417
+ }
3418
+ function handler2(args) {
3419
+ return __async(this, null, function* () {
3420
+ argv_default.init(__spreadValues({}, args));
3421
+ const {
3422
+ input,
3423
+ endpoint,
3424
+ bucket,
3425
+ prefix
3426
+ } = argv_default.getConfig();
3427
+ logger.info("", `Upload artifacts from ${input} to ${(0, import_path28.join)(endpoint, bucket, prefix)}`);
3428
+ try {
3429
+ yield upload(argv_default.getConfig());
3430
+ } catch (error) {
3431
+ logger.error("", error.message);
3432
+ }
3433
+ });
3434
+ }
3435
+
3436
+ // src/cmd/xliff/extract.ts
3437
+ var import_path29 = require("path");
3438
+ var import_markdown_translation = __toESM(require("@diplodoc/markdown-translation"));
3439
+ var import_async3 = require("async");
3440
+ var { promises: { readFile: readFile3, writeFile: writeFile2, mkdir: mkdir2 } } = require("fs");
3441
+ var command2 = "extract";
3442
+ var description2 = "extract xliff and skeleton from yfm documentation";
3443
+ var extract2 = { command: command2, description: description2, handler: handler3, builder: builder3 };
3444
+ var MD_GLOB2 = "**/*.md";
3445
+ var MAX_CONCURRENCY = 50;
3446
+ var ExtractError = class extends Error {
3447
+ constructor(message, path) {
3448
+ super(message);
3449
+ this.path = path;
3450
+ }
3451
+ };
3452
+ var USAGE = `yfm xliff extract --input <folder-with-markdown> --output <folder-to-store-xlff-and-skeleton> --sll <source-language>-<source-locale> --tll <target-language>-<target-locale>
3453
+
3454
+ where <source/target-language> is the language code, as described in ISO 639-1.
3455
+
3456
+ where <source/target-locale> is the locale code in alpha-2 format, as described in ISO 3166-1`;
3457
+ function builder3(argv) {
3458
+ return argv.option("source-language-locale", {
3459
+ alias: "sll",
3460
+ describe: "source language and locale",
3461
+ type: "string"
3462
+ }).option("target-language-locale", {
3463
+ alias: "tll",
3464
+ describe: "target language and locale",
3465
+ type: "string"
3466
+ }).option("input", {
3467
+ alias: "i",
3468
+ describe: "input folder with markdown files",
3469
+ type: "string"
3470
+ }).option("output", {
3471
+ alias: "o",
3472
+ describe: "output folder to store xliff and skeleton files",
3473
+ type: "string"
3474
+ }).demandOption(["source-language-locale", "target-language-locale", "input", "output"], USAGE);
3475
+ }
3476
+ function handler3(args) {
3477
+ return __async(this, null, function* () {
3478
+ argv_default.init(__spreadValues({}, args));
3479
+ const { input, output, sourceLanguageLocale, targetLanguageLocale } = args;
3480
+ let source;
3481
+ let target;
3482
+ try {
3483
+ source = parseLanguageLocale(sourceLanguageLocale);
3484
+ target = parseLanguageLocale(targetLanguageLocale);
3485
+ } catch (err) {
3486
+ if (err instanceof Error) {
3487
+ logger.error(input, err.message);
3488
+ }
3489
+ }
3490
+ let cache = {};
3491
+ let found = [];
3492
+ try {
3493
+ ({ state: { found, cache } } = yield glob((0, import_path29.join)(input, MD_GLOB2), {
3494
+ nosort: true,
3495
+ cache
3496
+ }));
3497
+ } catch (err) {
3498
+ if (err instanceof Error) {
3499
+ logger.error(input, err.message);
3500
+ }
3501
+ }
3502
+ const pipelineParameters = { source, target, input, output };
3503
+ const configuredPipeline = pipeline2(pipelineParameters);
3504
+ try {
3505
+ logger.info(input, "starting xliff and skeleton generation pipeline");
3506
+ yield (0, import_async3.eachLimit)(found, MAX_CONCURRENCY, (0, import_async3.asyncify)(configuredPipeline));
3507
+ logger.info(input, "finished xliff and skeleton generation pipeline");
3508
+ } catch (err) {
3509
+ if (err instanceof Error || err instanceof ExtractError) {
3510
+ const file = err instanceof ExtractError ? err.path : input;
3511
+ logger.error(file, err.message);
3512
+ }
3513
+ }
3514
+ });
3515
+ }
3516
+ function parseLanguageLocale(languageLocale) {
3517
+ const [language, locale] = languageLocale.split("-");
3518
+ if ((language == null ? void 0 : language.length) && (locale == null ? void 0 : locale.length)) {
3519
+ return { language, locale };
3520
+ }
3521
+ throw new Error("invalid language-locale string");
3522
+ }
3523
+ function pipeline2(params) {
3524
+ const { input, output, source, target } = params;
3525
+ return (markdownPath) => __async(this, null, function* () {
3526
+ const markdown = yield reader({ path: markdownPath });
3527
+ const extension = (0, import_path29.extname)(markdownPath);
3528
+ const outputRelativePath = markdownPath.replace(extension, "").slice(input.length);
3529
+ const outputPath = (0, import_path29.join)(output, outputRelativePath);
3530
+ const xlfPath = outputPath + ".xliff";
3531
+ const skeletonPath = outputPath + ".skl.md";
3532
+ const extractParameters = {
3533
+ markdownPath,
3534
+ skeletonPath,
3535
+ markdown,
3536
+ source,
3537
+ target
3538
+ };
3539
+ const extracted = yield extractor(extractParameters);
3540
+ const writerParameters = __spreadProps(__spreadValues({}, extracted), {
3541
+ xlfPath,
3542
+ skeletonPath
3543
+ });
3544
+ yield writer(writerParameters);
3545
+ });
3546
+ }
3547
+ function reader(params) {
3548
+ return __async(this, null, function* () {
3549
+ const { path } = params;
3550
+ let markdown;
3551
+ try {
3552
+ logger.info(path, "reading markdown file");
3553
+ markdown = yield readFile3(path, { encoding: "utf-8" });
3554
+ logger.info(path, "finished reading markdown file");
3555
+ } catch (err) {
3556
+ if (err instanceof Error) {
3557
+ throw new ExtractError(err.message, path);
3558
+ }
3559
+ }
3560
+ return markdown;
3561
+ });
3562
+ }
3563
+ function extractor(params) {
3564
+ return __async(this, null, function* () {
3565
+ let extracted;
3566
+ logger.info(params.markdownPath, "generating skeleton and xliff from markdown");
3567
+ try {
3568
+ extracted = import_markdown_translation.default.extract(params);
3569
+ } catch (err) {
3570
+ if (err instanceof Error) {
3571
+ throw new ExtractError(err.message, params.markdownPath);
3572
+ }
3573
+ }
3574
+ logger.info(params.markdownPath, "finished generating skeleton and xliff from markdown");
3575
+ return extracted;
3576
+ });
3577
+ }
3578
+ function writer(params) {
3579
+ return __async(this, null, function* () {
3580
+ const { xlfPath, skeletonPath, xlf, skeleton } = params;
3581
+ logger.info(params.xlfPath, "writing xliff file");
3582
+ logger.info(params.skeletonPath, "writing skeleton file");
3583
+ yield mkdir2((0, import_path29.dirname)(xlfPath), { recursive: true });
3584
+ yield Promise.all([writeFile2(skeletonPath, skeleton), writeFile2(xlfPath, xlf)]);
3585
+ logger.info(params.xlfPath, "finished writing xliff file");
3586
+ logger.info(params.skeletonPath, "finished writing skeleton file");
3587
+ });
3588
+ }
3589
+
3590
+ // src/cmd/xliff/compose.ts
3591
+ var import_path30 = require("path");
3592
+ var import_markdown_translation2 = __toESM(require("@diplodoc/markdown-translation"));
3593
+ var import_async4 = require("async");
3594
+ var { promises: { readFile: readFile4, writeFile: writeFile3, mkdir: mkdir3 } } = require("fs");
3595
+ var command3 = "compose";
3596
+ var description3 = "compose xliff and skeleton into documentation";
3597
+ var compose = { command: command3, description: description3, handler: handler4, builder: builder4 };
3598
+ var SKL_MD_GLOB = "**/*.skl.md";
3599
+ var XLF_GLOB = "**/*.xliff";
3600
+ var MAX_CONCURRENCY2 = 50;
3601
+ var ComposeError = class extends Error {
3602
+ constructor(message, path) {
3603
+ super(message);
3604
+ this.path = path;
3605
+ }
3606
+ };
3607
+ var USAGE2 = "yfm xliff compose --input <folder-with-xliff-and-skeleton> --ouput <folder-to-store-translated-markdown>";
3608
+ function builder4(argv) {
3609
+ return argv.option("input", {
3610
+ alias: "i",
3611
+ describe: "input folder with xliff and skeleton files",
3612
+ type: "string"
3613
+ }).option("output", {
3614
+ alias: "o",
3615
+ describe: "output folder where translated markdown will be stored",
3616
+ type: "string"
3617
+ }).demandOption(["input", "output"], USAGE2);
3618
+ }
3619
+ function handler4(args) {
3620
+ return __async(this, null, function* () {
3621
+ argv_default.init(__spreadValues({}, args));
3622
+ const { input, output } = args;
3623
+ let cache = {};
3624
+ let skeletonPaths = [];
3625
+ let xliffPaths = [];
3626
+ try {
3627
+ ({ state: { found: skeletonPaths, cache } } = yield glob((0, import_path30.join)(input, SKL_MD_GLOB), {
3628
+ nosort: false,
3629
+ cache
3630
+ }));
3631
+ ({ state: { found: xliffPaths, cache } } = yield glob((0, import_path30.join)(input, XLF_GLOB), {
3632
+ nosort: false,
3633
+ cache
3634
+ }));
3635
+ if (xliffPaths.length !== skeletonPaths.length) {
3636
+ throw new ComposeError("number of xliff and skeleton files does'not match", input);
3637
+ }
3638
+ } catch (err) {
3639
+ if (err instanceof Error || err instanceof ComposeError) {
3640
+ const file = err instanceof ComposeError ? err.path : input;
3641
+ logger.error(file, err.message);
3642
+ }
3643
+ }
3644
+ const pipelineParameters = { input, output };
3645
+ const configuredPipeline = pipeline3(pipelineParameters);
3646
+ try {
3647
+ logger.info(input, "staring translated markdown composition pipeline");
3648
+ yield (0, import_async4.eachLimit)(xliffPaths, MAX_CONCURRENCY2, configuredPipeline);
3649
+ logger.info(input, "finished translated markdown composition pipeline");
3650
+ } catch (err) {
3651
+ if (err instanceof Error || err instanceof ComposeError) {
3652
+ const file = err instanceof ComposeError ? err.path : input;
3653
+ logger.error(file, err.message);
3654
+ }
3655
+ }
3656
+ });
3657
+ }
3658
+ function pipeline3(params) {
3659
+ const { input, output } = params;
3660
+ return (xliffPath) => __async(this, null, function* () {
3661
+ const extension = (0, import_path30.extname)(xliffPath);
3662
+ const extensionLessPath = xliffPath.replace(extension, "");
3663
+ const skeletonPath = extensionLessPath + ".skl.md";
3664
+ const readerParameters = { xliffPath, skeletonPath };
3665
+ const read = yield reader2(readerParameters);
3666
+ const composerParameters = __spreadProps(__spreadValues({}, read), {
3667
+ skeletonPath,
3668
+ xliffPath
3669
+ });
3670
+ const { markdown } = yield composer(composerParameters);
3671
+ const inputRelativePath = extensionLessPath.slice(input.length);
3672
+ const markdownPath = (0, import_path30.join)(output, inputRelativePath) + ".md";
3673
+ const writerParameters = {
3674
+ markdown,
3675
+ markdownPath
3676
+ };
3677
+ yield writer2(writerParameters);
3678
+ });
3679
+ }
3680
+ function reader2(params) {
3681
+ return __async(this, null, function* () {
3682
+ const { skeletonPath, xliffPath } = params;
3683
+ let skeleton;
3684
+ let xlf;
3685
+ try {
3686
+ logger.info(skeletonPath, "reading skeleton file");
3687
+ skeleton = yield readFile4(skeletonPath, { encoding: "utf-8" });
3688
+ logger.info(skeletonPath, "finished reading skeleton file");
3689
+ } catch (err) {
3690
+ if (err instanceof Error) {
3691
+ throw new ComposeError(err.message, skeletonPath);
3692
+ }
3693
+ }
3694
+ try {
3695
+ logger.info(xliffPath, "reading xliff file");
3696
+ xlf = yield readFile4(xliffPath, { encoding: "utf-8" });
3697
+ logger.info(xliffPath, "finished reading xliff file");
3698
+ } catch (err) {
3699
+ if (err instanceof Error) {
3700
+ throw new ComposeError(err.message, xliffPath);
3701
+ }
3702
+ }
3703
+ return { skeleton, xlf };
3704
+ });
3705
+ }
3706
+ function composer(params) {
3707
+ return __async(this, null, function* () {
3708
+ const { skeletonPath, xliffPath } = params;
3709
+ let markdown;
3710
+ try {
3711
+ logger.info(skeletonPath, "composing markdown from xliff and skeleton");
3712
+ logger.info(xliffPath, "composing markdown from xliff and skeleton");
3713
+ markdown = import_markdown_translation2.default.compose(params);
3714
+ logger.info(skeletonPath, "finished composing markdown from xliff and skeleton");
3715
+ logger.info(xliffPath, "finished composing markdown from xliff and skeleton");
3716
+ } catch (err) {
3717
+ if (err instanceof Error) {
3718
+ throw new ComposeError(err.message, `${xliffPath} ${skeletonPath}`);
3719
+ }
3720
+ }
3721
+ return { markdown };
3722
+ });
3723
+ }
3724
+ function writer2(params) {
3725
+ return __async(this, null, function* () {
3726
+ const { markdown, markdownPath } = params;
3727
+ try {
3728
+ logger.info(markdownPath, "writing markdown file");
3729
+ yield mkdir3((0, import_path30.dirname)(markdownPath), { recursive: true });
3730
+ yield writeFile3(markdownPath, markdown);
3731
+ logger.info(markdownPath, "finished writing markdown file");
3732
+ } catch (err) {
3733
+ if (err instanceof Error) {
3734
+ throw new ComposeError(err.message, markdownPath);
3735
+ }
3736
+ }
3737
+ });
3738
+ }
3739
+
3740
+ // src/cmd/xliff/index.ts
3741
+ var command4 = "xliff";
3742
+ var description4 = "extract xliff and skeleton from documentation files\ncompose xliff and skeleton into documentation";
3743
+ var xliff = {
3744
+ command: command4,
3745
+ description: description4,
3746
+ handler: () => {
3747
+ },
3748
+ builder: builder5
3749
+ };
3750
+ function builder5(argv) {
3751
+ return argv.command(extract2).command(compose).demandCommand(1, `provide one of the folowing ${command4} commands: ${extract2.command}, ${compose.command}`);
3752
+ }
3753
+
3754
+ // src/cmd/translate/index.ts
3755
+ var import_async5 = require("async");
3756
+ var import_path32 = require("path");
3757
+ var import_promises4 = require("fs/promises");
3758
+ var import_fast_xml_parser = require("fast-xml-parser");
3759
+ var import_session = require("@yandex-cloud/nodejs-sdk/dist/session");
3760
+ var import_service_clients = require("@yandex-cloud/nodejs-sdk/dist/generated/yandex/cloud/service_clients");
3761
+ var import_translation_service = require("@yandex-cloud/nodejs-sdk/dist/generated/yandex/cloud/ai/translate/v2/translation_service");
3762
+
3763
+ // src/packages/credentials/yandex-oauth.ts
3764
+ var import_promises3 = require("fs/promises");
3765
+ var import_process3 = require("process");
3766
+ var import_os = require("os");
3767
+ var import_path31 = require("path");
3768
+ var YANDEX_OAUTH_TOKEN_FILENAME = ".ya_oauth_token";
3769
+ function getYandexOAuthToken() {
3770
+ return __async(this, null, function* () {
3771
+ const { YANDEX_OAUTH_TOKEN } = import_process3.env;
3772
+ return YANDEX_OAUTH_TOKEN != null ? YANDEX_OAUTH_TOKEN : getYandexOAuthTokenFromHomeDir();
3773
+ });
3774
+ }
3775
+ function getYandexOAuthTokenFromHomeDir() {
3776
+ return __async(this, null, function* () {
3777
+ const error = "failed reading yandex oauth token";
3778
+ const path = (0, import_path31.join)((0, import_os.homedir)(), YANDEX_OAUTH_TOKEN_FILENAME);
3779
+ let token;
3780
+ try {
3781
+ token = yield (0, import_promises3.readFile)(path, { encoding: "utf8" });
3782
+ token = token.trim();
3783
+ if (!(token == null ? void 0 : token.length)) {
3784
+ throw new Error(error);
3785
+ }
3786
+ } catch (err) {
3787
+ logger.error(error);
3788
+ throw err;
3789
+ }
3790
+ return token;
3791
+ });
3792
+ }
3793
+
3794
+ // src/cmd/translate/index.ts
3795
+ var yfm2xliff = require("@doc-tools/yfm2xliff/lib/cjs");
3796
+ var composer2 = (xliff2, skeleton) => __async(void 0, null, function* () {
3797
+ return new Promise((res, rej) => yfm2xliff.compose(xliff2, skeleton, (err, composed) => {
3798
+ if (err) {
3799
+ rej(err);
3800
+ }
3801
+ return res(composed);
3802
+ }));
3803
+ });
3804
+ var command5 = "translate";
3805
+ var description5 = "translate documentation with Yandex.Cloud Translator API";
3806
+ var translate = {
3807
+ command: command5,
3808
+ description: description5,
3809
+ handler: handler5,
3810
+ builder: builder6
3811
+ };
3812
+ var MD_GLOB3 = "**/*.md";
3813
+ var REQUESTS_LIMIT = 20;
3814
+ var RETRY_LIMIT = 8;
3815
+ var MTRANS_LOCALE = "MTRANS";
3816
+ function builder6(argv) {
3817
+ return argv.option("source-language", {
3818
+ alias: "sl",
3819
+ describe: "source language code",
3820
+ type: "string"
3821
+ }).option("target-language", {
3822
+ alias: "tl",
3823
+ describe: "target language code",
3824
+ type: "string"
3825
+ }).demandOption(
3826
+ ["source-language", "target-language"],
3827
+ "command requires to specify source and target languages"
3828
+ );
3829
+ }
3830
+ var TranslatorError = class extends Error {
3831
+ constructor(message, path) {
3832
+ super(message);
3833
+ this.path = path;
3834
+ }
3835
+ };
3836
+ function handler5(args) {
3837
+ return __async(this, null, function* () {
3838
+ argv_default.init(__spreadValues({}, args));
3839
+ const {
3840
+ input,
3841
+ output,
3842
+ yandexCloudTranslateFolderId,
3843
+ yandexCloudTranslateGlossaryPairs,
3844
+ sl: sourceLanguage,
3845
+ tl: targetLanguage
3846
+ } = args;
3847
+ logger.info(input, `translating documentation from ${sourceLanguage} to ${targetLanguage} language`);
3848
+ try {
3849
+ let found = [];
3850
+ ({ state: { found } } = yield glob((0, import_path32.join)(input, MD_GLOB3), {
3851
+ nosort: true
3852
+ }));
3853
+ const oauthToken = yield getYandexOAuthToken();
3854
+ const translatorParams = {
3855
+ input,
3856
+ output,
3857
+ sourceLanguage,
3858
+ targetLanguage,
3859
+ yandexCloudTranslateGlossaryPairs,
3860
+ folderId: yandexCloudTranslateFolderId,
3861
+ oauthToken
3862
+ };
3863
+ const translateFn = translator(translatorParams);
3864
+ yield (0, import_async5.eachLimit)(found, REQUESTS_LIMIT, (0, import_async5.asyncify)(translateFn));
3865
+ } catch (err) {
3866
+ if (err instanceof Error || err instanceof TranslatorError) {
3867
+ const message = err.message;
3868
+ const file = err instanceof TranslatorError ? err.path : "";
3869
+ logger.error(file, message);
3870
+ }
3871
+ }
3872
+ logger.info(output, `translated documentation from ${sourceLanguage} to ${targetLanguage} language`);
3873
+ });
3874
+ }
3875
+ function translator(params) {
3876
+ const {
3877
+ oauthToken,
3878
+ folderId,
3879
+ input,
3880
+ output,
3881
+ sourceLanguage,
3882
+ targetLanguage,
3883
+ yandexCloudTranslateGlossaryPairs
3884
+ } = params;
3885
+ const session = new import_session.Session({ oauthToken });
3886
+ const client3 = session.client(import_service_clients.TranslationServiceClient);
3887
+ return (mdPath) => __async(this, null, function* () {
3888
+ try {
3889
+ logger.info(mdPath, "translating");
3890
+ const md = yield (0, import_promises4.readFile)((0, import_path32.resolve)(mdPath), { encoding: "utf-8" });
3891
+ const extracted = yield yfm2xliff.extract({
3892
+ md,
3893
+ mdPath,
3894
+ source: sourceLanguage,
3895
+ target: targetLanguage,
3896
+ sklPath: "",
3897
+ xlfPath: ""
3898
+ });
3899
+ const texts = parseSourcesFromXLIFF(extracted.xliff);
3900
+ const machineTranslateParams = import_translation_service.TranslateRequest.fromPartial({
3901
+ texts,
3902
+ folderId,
3903
+ sourceLanguageCode: sourceLanguage,
3904
+ targetLanguageCode: targetLanguage,
3905
+ glossaryConfig: {
3906
+ glossaryData: {
3907
+ glossaryPairs: yandexCloudTranslateGlossaryPairs
3908
+ }
3909
+ },
3910
+ format: import_translation_service.TranslateRequest_Format.PLAIN_TEXT
3911
+ });
3912
+ const translations = yield (0, import_async5.retry)({ times: RETRY_LIMIT, interval: (count) => {
3913
+ return (1 << count) * 1e3;
3914
+ } }, (0, import_async5.asyncify)(
3915
+ () => __async(this, null, function* () {
3916
+ return yield client3.translate(machineTranslateParams).then((results) => results.translations.map(({ text }) => text));
3917
+ })
3918
+ ));
3919
+ const createXLIFFDocumentParams = {
3920
+ sourceLanguage: sourceLanguage + "-" + MTRANS_LOCALE,
3921
+ targetLanguage: targetLanguage + "-" + MTRANS_LOCALE,
3922
+ sources: texts,
3923
+ targets: translations
3924
+ };
3925
+ const translatedXLIFF = createXLIFFDocument(createXLIFFDocumentParams);
3926
+ const composed = yield composer2(translatedXLIFF, extracted.skeleton);
3927
+ const outputPath = mdPath.replace(input, output);
3928
+ yield (0, import_promises4.mkdir)((0, import_path32.dirname)(outputPath), { recursive: true });
3929
+ yield (0, import_promises4.writeFile)(outputPath, composed);
3930
+ logger.info(outputPath, "finished translating");
3931
+ } catch (err) {
3932
+ if (err instanceof Error) {
3933
+ throw new TranslatorError(err.toString(), mdPath);
3934
+ }
3935
+ }
3936
+ });
3937
+ }
3938
+ function parseSourcesFromXLIFF(xliff2) {
3939
+ var _a, _b, _c, _d;
3940
+ const parser = new import_fast_xml_parser.XMLParser();
3941
+ const inputs = (_d = (_c = (_b = (_a = parser.parse(xliff2)) == null ? void 0 : _a.xliff) == null ? void 0 : _b.file) == null ? void 0 : _c.body["trans-unit"]) != null ? _d : [];
3942
+ return Array.isArray(inputs) ? inputs.map(({ source }) => source) : [inputs.source];
3943
+ }
3944
+ function createXLIFFDocument(params) {
3945
+ const { sourceLanguage, targetLanguage, sources, targets } = params;
3946
+ const unit = (text, i) => `
3947
+ <trans-unit id="${i + 1}">
3948
+ <source xml:lang="${sourceLanguage}">${sources[i]}</source>
3949
+ <target xml:lang="${targetLanguage}">${text}</target>
3950
+ </trans-unit>`;
3951
+ const doc = `
3952
+ <?xml version="1.0" encoding="UTF-8"?>
3953
+ <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
3954
+ <file original="" source-language="${sourceLanguage}" target-language="${targetLanguage}">
3955
+ <header>
3956
+ <skl><external-file href="" /></skl>
3957
+ </header>
3958
+ <body>${targets.map(unit)}</body>
3959
+ </file>
3960
+ </xliff>`;
3961
+ return doc;
3962
+ }
3963
+
3964
+ // src/index.ts
3965
+ console.time(MAIN_TIMER_ID);
3966
+ import_yargs.default.command(build).command(publish).command(xliff).command(translate).option("config", {
3967
+ alias: "c",
3968
+ describe: "YFM configuration file",
3969
+ type: "string"
3970
+ }).option("strict", {
3971
+ alias: "s",
3972
+ default: false,
3973
+ describe: "Run in strict mode",
3974
+ type: "boolean"
3975
+ }).option("quiet", {
3976
+ alias: "q",
3977
+ default: false,
3978
+ describe: "Run in quiet mode. Don't write logs to stdout",
3979
+ type: "boolean"
3980
+ }).group(["config", "strict", "quiet", "help", "version"], "Common options:").version(true ? "4.0.0" : "").help().parse((0, import_helpers.hideBin)(process.argv), {}, (err, { strict }, output) => {
3981
+ console.timeEnd(MAIN_TIMER_ID);
3982
+ if (err) {
3983
+ console.error(err);
3984
+ process.exit(1);
3985
+ }
3986
+ const { warn, error } = import_log14.default.get();
3987
+ if (strict && warn.length || error.length) {
3988
+ process.exit(1);
3989
+ }
3990
+ console.log(output);
3991
+ process.exit(0);
3992
+ });
3993
+ //# sourceMappingURL=index.js.map