@backstage/plugin-techdocs-node 2.0.3-next.2 → 2.2.0-next.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # @backstage/plugin-techdocs-node
2
2
 
3
+ ## 2.2.0-next.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a4604d2: Added a new `@backstage/plugin-techdocs-node/alpha` entry point with building blocks for implementing additional documentation engines in separate modules: `createDockerContainerRunner`, `createOrUpdateMetadata`, `storeEtagMetadata`, `runCommand`, `validateInputDirectory`, `patchIndexPreBuild`, and the `mkdocs.yml` helpers `MKDOCS_SCHEMA`, `validateMkdocsYaml` and `sanitizeMkdocsYml`. These are alpha and may change in minor releases.
8
+
9
+ ### Patch Changes
10
+
11
+ - 686d3cb: Fixed TechDocs served from Azure Blob Storage or Google Cloud Storage keeping storage connections open when a browser navigates away before a file is fully loaded. Errors that occur while streaming a file from Azure Blob Storage are now also logged and handled, instead of being left unhandled.
12
+ - 2e98895: Fixed TechDocs served from AWS S3 leaking S3 connections when a browser navigates away before a file is fully loaded. Over time the connection pool was exhausted and all TechDocs pages failed to load with `Socket timed out without establishing a connection` errors until the backend was restarted.
13
+ - Updated dependencies
14
+ - @backstage/backend-plugin-api@1.11.1-next.0
15
+
16
+ ## 2.1.0
17
+
18
+ ### Minor Changes
19
+
20
+ - 4d4f987: Add engine abstraction layer for multi-engine TechDocs support. Introduces `--engine` flag, engine config map, generator registry with `backstage.io/techdocs-engine` annotation support, `engine` field in `techdocs_metadata.json`, `serve:raw` command, and live-reload adapter interface. MkDocs remains the default with no behavior change.
21
+
22
+ The built-in generator is now registered under `mkdocs`; the previous `techdocs` key is kept as an alias, so existing `generators.register('techdocs', ...)` calls continue to work. The CLI's `--engine` flag takes precedence over the `backstage.io/techdocs-engine` annotation for all commands, and `serve:mkdocs` and the `--mkdocs-parameter-*` flags now print deprecation warnings.
23
+
24
+ ### Patch Changes
25
+
26
+ - 9fc5387: Improved handling of mapping-style Markdown extension configuration.
27
+ - 0fd5fe5: Fixed TechDocs allowing `custom_icons` paths in `mkdocs.yml` that resolve outside the documentation input directory. A `custom_icons` option with such a path is now removed from the configuration with a warning.
28
+ - 8a37336: Fixed TechDocs generation rejecting `mkdocs.yml` files that use the emoji indexes and generators or the `pymdownx.superfences` custom fence formats documented by mkdocs-material, pymdown-extensions and mkdocs-mermaid2.
29
+ - 76ac6ed: Updated dependency `js-yaml` to `^5.0.0`.
30
+ - Updated dependencies
31
+ - @backstage/integration@2.1.3
32
+ - @backstage/backend-plugin-api@1.11.0
33
+ - @backstage/config@1.3.10
34
+ - @backstage/errors@1.3.2
35
+ - @backstage/plugin-techdocs-common@0.1.2
36
+ - @backstage/catalog-model@1.10.2
37
+ - @backstage/integration-aws-node@0.2.3
38
+ - @backstage/plugin-search-common@1.2.26
39
+
3
40
  ## 2.0.3-next.2
4
41
 
5
42
  ### Patch Changes
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ var DockerContainerRunner = require('./stages/generate/DockerContainerRunner.cjs.js');
4
+ var mkdocsPatchers = require('./stages/generate/mkdocsPatchers.cjs.js');
5
+ var helpers = require('./stages/generate/helpers.cjs.js');
6
+
7
+ function createDockerContainerRunner() {
8
+ return new DockerContainerRunner.DockerContainerRunner();
9
+ }
10
+
11
+ exports.sanitizeMkdocsYml = mkdocsPatchers.sanitizeMkdocsYml;
12
+ exports.MKDOCS_SCHEMA = helpers.MKDOCS_SCHEMA;
13
+ exports.createOrUpdateMetadata = helpers.createOrUpdateMetadata;
14
+ exports.patchIndexPreBuild = helpers.patchIndexPreBuild;
15
+ exports.runCommand = helpers.runCommand;
16
+ exports.storeEtagMetadata = helpers.storeEtagMetadata;
17
+ exports.validateInputDirectory = helpers.validateInputDirectory;
18
+ exports.validateMkdocsYaml = helpers.validateMkdocsYaml;
19
+ exports.createDockerContainerRunner = createDockerContainerRunner;
20
+ //# sourceMappingURL=alpha.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"alpha.cjs.js","sources":["../src/alpha.ts"],"sourcesContent":["/*\n * Copyright 2026 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Building blocks for implementing additional TechDocs generators. These are\n// alpha while the set of engines settles and may change in minor releases.\nimport type { TechDocsContainerRunner } from '@backstage/plugin-techdocs-node';\nimport { DockerContainerRunner } from './stages/generate/DockerContainerRunner';\n\nexport { sanitizeMkdocsYml } from './stages/generate/mkdocsPatchers';\nexport {\n createOrUpdateMetadata,\n storeEtagMetadata,\n runCommand,\n validateInputDirectory,\n patchIndexPreBuild,\n validateMkdocsYaml,\n MKDOCS_SCHEMA,\n} from './stages/generate/helpers';\nexport type { RunCommandOptions } from './stages/generate/helpers';\n\n/**\n * Creates a container runner that uses the local Docker daemon, the same one\n * the built-in MkDocs generator uses.\n *\n * @alpha\n */\nexport function createDockerContainerRunner(): TechDocsContainerRunner {\n return new DockerContainerRunner();\n}\n"],"names":["DockerContainerRunner"],"mappings":";;;;;;AAuCO,SAAS,2BAAA,GAAuD;AACrE,EAAA,OAAO,IAAIA,2CAAA,EAAsB;AACnC;;;;;;;;;;"}
@@ -0,0 +1,35 @@
1
+ import { TechDocsContainerRunner } from '@backstage/plugin-techdocs-node';
2
+ import { LoggerService } from '@backstage/backend-plugin-api';
3
+ export { M as MKDOCS_SCHEMA, R as RunCommandOptions, c as createOrUpdateMetadata, p as patchIndexPreBuild, r as runCommand, s as storeEtagMetadata, v as validateInputDirectory, a as validateMkdocsYaml } from './types/helpers.d-DkvPJaTo.js';
4
+ import 'node:child_process';
5
+ import 'js-yaml';
6
+ import 'node:stream';
7
+
8
+ /**
9
+ * Sanitize mkdocs.yml by keeping only allowed configuration keys.
10
+ *
11
+ * TechDocs only supports a subset of MkDocs configuration options.
12
+ * This function reconstructs the config with only allowed keys,
13
+ * discarding everything else. This approach ensures that any unknown
14
+ * or potentially dangerous configuration options are not passed to MkDocs.
15
+ *
16
+ * The file is always rewritten to ensure YAML features like merge keys
17
+ * and anchors are resolved into plain configuration.
18
+ *
19
+ * @param mkdocsYmlPath - Absolute path to mkdocs.yml or equivalent of a docs site
20
+ * @param logger - A logger instance
21
+ * @param additionalAllowedKeys - Optional array of additional keys to allow beyond the default allowlist
22
+ * @param additionalAllowedPlugins - Optional array of additional plugins to allow beyond the default set
23
+ * @alpha
24
+ */
25
+ declare const sanitizeMkdocsYml: (mkdocsYmlPath: string, logger: LoggerService, additionalAllowedKeys?: string[], additionalAllowedPlugins?: string[]) => Promise<void>;
26
+
27
+ /**
28
+ * Creates a container runner that uses the local Docker daemon, the same one
29
+ * the built-in MkDocs generator uses.
30
+ *
31
+ * @alpha
32
+ */
33
+ declare function createDockerContainerRunner(): TechDocsContainerRunner;
34
+
35
+ export { createDockerContainerRunner, sanitizeMkdocsYml };
@@ -1 +1 @@
1
- {"version":3,"file":"extensions.cjs.js","sources":["../src/extensions.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { createExtensionPoint } from '@backstage/backend-plugin-api';\nimport { DocsBuildStrategy } from './techdocsTypes';\nimport {\n PreparerBase,\n PublisherBase,\n PublisherType,\n RemoteProtocol,\n TechdocsGenerator,\n} from './stages';\nimport * as winston from 'winston';\nimport { PublisherSettings } from './stages/publish/types';\n\n/**\n * Extension point type for configuring TechDocs builds.\n *\n * @public\n */\nexport interface TechdocsBuildsExtensionPoint {\n setBuildStrategy(buildStrategy: DocsBuildStrategy): void;\n setBuildLogTransport(transport: winston.transport): void;\n}\n\n/**\n * Extension point for configuring TechDocs builds.\n *\n * @public\n */\nexport const techdocsBuildsExtensionPoint =\n createExtensionPoint<TechdocsBuildsExtensionPoint>({\n id: 'techdocs.builds',\n });\n\n/**\n * Extension point type for configuring a custom TechDocs generator\n *\n * @public\n */\nexport interface TechdocsGeneratorExtensionPoint {\n setTechdocsGenerator(generator: TechdocsGenerator): void;\n}\n\n/**\n * Extension point for configuring a custom TechDocs generator\n *\n * @public\n */\nexport const techdocsGeneratorExtensionPoint =\n createExtensionPoint<TechdocsGeneratorExtensionPoint>({\n id: 'techdocs.generator',\n });\n\n/**\n * Extension point type for configuring a custom TechDocs preparer\n *\n * @public\n */\nexport interface TechdocsPreparerExtensionPoint {\n registerPreparer(protocol: RemoteProtocol, preparer: PreparerBase): void;\n}\n\n/**\n * Extension point for configuring a custom TechDocs preparer\n *\n * @public\n */\nexport const techdocsPreparerExtensionPoint =\n createExtensionPoint<TechdocsPreparerExtensionPoint>({\n id: 'techdocs.preparer',\n });\n\n/**\n * Extension point type for configuring a custom TechDocs publisher\n *\n * @public\n */\nexport interface TechdocsPublisherExtensionPoint {\n registerPublisher(type: PublisherType, publisher: PublisherBase): void;\n registerPublisherSettings<T extends keyof PublisherSettings>(\n publisher: T,\n settings: PublisherSettings[T],\n ): void;\n}\n\n/**\n * Extension point for configuring a custom TechDocs publisher\n *\n * @public\n */\nexport const techdocsPublisherExtensionPoint =\n createExtensionPoint<TechdocsPublisherExtensionPoint>({\n id: 'techdocs.publisher',\n });\n"],"names":["createExtensionPoint"],"mappings":";;;;AA0CO,MAAM,+BACXA,qCAAA,CAAmD;AAAA,EACjD,EAAA,EAAI;AACN,CAAC;AAgBI,MAAM,kCACXA,qCAAA,CAAsD;AAAA,EACpD,EAAA,EAAI;AACN,CAAC;AAgBI,MAAM,iCACXA,qCAAA,CAAqD;AAAA,EACnD,EAAA,EAAI;AACN,CAAC;AAoBI,MAAM,kCACXA,qCAAA,CAAsD;AAAA,EACpD,EAAA,EAAI;AACN,CAAC;;;;;"}
1
+ {"version":3,"file":"extensions.cjs.js","sources":["../src/extensions.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { createExtensionPoint } from '@backstage/backend-plugin-api';\nimport { DocsBuildStrategy } from './techdocsTypes';\nimport {\n GeneratorBase,\n PreparerBase,\n PublisherBase,\n PublisherType,\n RemoteProtocol,\n SupportedGeneratorKey,\n} from './stages';\nimport * as winston from 'winston';\nimport { PublisherSettings } from './stages/publish/types';\n\n/**\n * Extension point type for configuring TechDocs builds.\n *\n * @public\n */\nexport interface TechdocsBuildsExtensionPoint {\n setBuildStrategy(buildStrategy: DocsBuildStrategy): void;\n setBuildLogTransport(transport: winston.transport): void;\n}\n\n/**\n * Extension point for configuring TechDocs builds.\n *\n * @public\n */\nexport const techdocsBuildsExtensionPoint =\n createExtensionPoint<TechdocsBuildsExtensionPoint>({\n id: 'techdocs.builds',\n });\n\n/**\n * Extension point type for configuring TechDocs generators.\n *\n * Use `registerGenerator` to add an engine-specific generator from a backend\n * module (e.g. `plugin-techdocs-backend-module-zensical`). The key corresponds\n * to the `backstage.io/techdocs-engine` entity annotation value.\n *\n * `setTechdocsGenerator` is kept for backwards compatibility — it replaces the\n * default MkDocs generator.\n *\n * @public\n */\nexport interface TechdocsGeneratorExtensionPoint {\n setTechdocsGenerator(generator: GeneratorBase): void;\n registerGenerator(key: SupportedGeneratorKey, generator: GeneratorBase): void;\n}\n\n/**\n * Extension point for configuring a custom TechDocs generator\n *\n * @public\n */\nexport const techdocsGeneratorExtensionPoint =\n createExtensionPoint<TechdocsGeneratorExtensionPoint>({\n id: 'techdocs.generator',\n });\n\n/**\n * Extension point type for configuring a custom TechDocs preparer\n *\n * @public\n */\nexport interface TechdocsPreparerExtensionPoint {\n registerPreparer(protocol: RemoteProtocol, preparer: PreparerBase): void;\n}\n\n/**\n * Extension point for configuring a custom TechDocs preparer\n *\n * @public\n */\nexport const techdocsPreparerExtensionPoint =\n createExtensionPoint<TechdocsPreparerExtensionPoint>({\n id: 'techdocs.preparer',\n });\n\n/**\n * Extension point type for configuring a custom TechDocs publisher\n *\n * @public\n */\nexport interface TechdocsPublisherExtensionPoint {\n registerPublisher(type: PublisherType, publisher: PublisherBase): void;\n registerPublisherSettings<T extends keyof PublisherSettings>(\n publisher: T,\n settings: PublisherSettings[T],\n ): void;\n}\n\n/**\n * Extension point for configuring a custom TechDocs publisher\n *\n * @public\n */\nexport const techdocsPublisherExtensionPoint =\n createExtensionPoint<TechdocsPublisherExtensionPoint>({\n id: 'techdocs.publisher',\n });\n"],"names":["createExtensionPoint"],"mappings":";;;;AA2CO,MAAM,+BACXA,qCAAA,CAAmD;AAAA,EACjD,EAAA,EAAI;AACN,CAAC;AAwBI,MAAM,kCACXA,qCAAA,CAAsD;AAAA,EACpD,EAAA,EAAI;AACN,CAAC;AAgBI,MAAM,iCACXA,qCAAA,CAAqD;AAAA,EACnD,EAAA,EAAI;AACN,CAAC;AAoBI,MAAM,kCACXA,qCAAA,CAAsD;AAAA,EACpD,EAAA,EAAI;AACN,CAAC;;;;;"}
package/dist/index.cjs.js CHANGED
@@ -6,6 +6,7 @@ var url = require('./stages/prepare/url.cjs.js');
6
6
  var preparers = require('./stages/prepare/preparers.cjs.js');
7
7
  var publish = require('./stages/publish/publish.cjs.js');
8
8
  var helpers = require('./helpers.cjs.js');
9
+ var techdocsTypes = require('./techdocsTypes.cjs.js');
9
10
  var extensions = require('./extensions.cjs.js');
10
11
  var generators = require('./stages/generate/generators.cjs.js');
11
12
  var techdocs = require('./stages/generate/techdocs.cjs.js');
@@ -22,6 +23,7 @@ exports.getDocFilesFromRepository = helpers.getDocFilesFromRepository;
22
23
  exports.getLocationForEntity = helpers.getLocationForEntity;
23
24
  exports.parseReferenceAnnotation = helpers.parseReferenceAnnotation;
24
25
  exports.transformDirLocation = helpers.transformDirLocation;
26
+ exports.TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY = techdocsTypes.TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY;
25
27
  exports.techdocsBuildsExtensionPoint = extensions.techdocsBuildsExtensionPoint;
26
28
  exports.techdocsGeneratorExtensionPoint = extensions.techdocsGeneratorExtensionPoint;
27
29
  exports.techdocsPreparerExtensionPoint = extensions.techdocsPreparerExtensionPoint;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.d.ts CHANGED
@@ -9,6 +9,9 @@ import { IndexableDocument } from '@backstage/plugin-search-common';
9
9
  import { Writable } from 'node:stream';
10
10
  import * as winston from 'winston';
11
11
  import { Logger } from 'winston';
12
+ export { g as getMkdocsYml } from './types/helpers.d-DkvPJaTo.js';
13
+ import 'node:child_process';
14
+ import 'js-yaml';
12
15
 
13
16
  /**
14
17
  * A unique identifier of the tree blob, usually the commit SHA or etag from the target.
@@ -273,6 +276,7 @@ declare class TechdocsGenerator implements GeneratorBase {
273
276
  */
274
277
  declare class Generators implements GeneratorBuilder {
275
278
  private generatorMap;
279
+ private defaultEngine;
276
280
  /**
277
281
  * Returns a generators instance containing a generator for TechDocs
278
282
  * @param config - A Backstage configuration
@@ -281,7 +285,7 @@ declare class Generators implements GeneratorBuilder {
281
285
  static fromConfig(config: Config, options: {
282
286
  logger: LoggerService;
283
287
  containerRunner?: TechDocsContainerRunner;
284
- customGenerator?: TechdocsGenerator;
288
+ customGenerator?: GeneratorBase;
285
289
  }): Promise<GeneratorBuilder>;
286
290
  /**
287
291
  * Register a generator in the generators collection
@@ -296,24 +300,6 @@ declare class Generators implements GeneratorBuilder {
296
300
  get(entity: Entity): GeneratorBase;
297
301
  }
298
302
 
299
- /**
300
- * Finds and loads the contents of an mkdocs.yml, mkdocs.yaml file, a file
301
- * with a specified name or an ad-hoc created file with minimal config.
302
- * @public
303
- *
304
- * @param inputDir - base dir to be searched for either an mkdocs.yml or mkdocs.yaml file.
305
- * @param options - name: default mkdocs site_name to be used with a ad hoc file default value is "Documentation Site"
306
- * mkdocsConfigFileName (optional): a non-default file name to be used as the config
307
- */
308
- declare const getMkdocsYml: (inputDir: string, options?: {
309
- name?: string;
310
- mkdocsConfigFileName?: string;
311
- }) => Promise<{
312
- path: string;
313
- content: string;
314
- configIsTemporary: boolean;
315
- }>;
316
-
317
303
  /**
318
304
  * @public
319
305
  * @deprecated
@@ -587,6 +573,12 @@ interface DocsBuildStrategy {
587
573
  entity: Entity;
588
574
  }): Promise<boolean>;
589
575
  }
576
+ /**
577
+ * A catalog annotation key indicating which TechDoc Generation Engine to use
578
+ *
579
+ * @public
580
+ */
581
+ declare const TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY = "backstage.io/techdocs-engine";
590
582
 
591
583
  /**
592
584
  * Extension point type for configuring TechDocs builds.
@@ -604,12 +596,20 @@ interface TechdocsBuildsExtensionPoint {
604
596
  */
605
597
  declare const techdocsBuildsExtensionPoint: _backstage_backend_plugin_api.ExtensionPoint<TechdocsBuildsExtensionPoint>;
606
598
  /**
607
- * Extension point type for configuring a custom TechDocs generator
599
+ * Extension point type for configuring TechDocs generators.
600
+ *
601
+ * Use `registerGenerator` to add an engine-specific generator from a backend
602
+ * module (e.g. `plugin-techdocs-backend-module-zensical`). The key corresponds
603
+ * to the `backstage.io/techdocs-engine` entity annotation value.
604
+ *
605
+ * `setTechdocsGenerator` is kept for backwards compatibility — it replaces the
606
+ * default MkDocs generator.
608
607
  *
609
608
  * @public
610
609
  */
611
610
  interface TechdocsGeneratorExtensionPoint {
612
- setTechdocsGenerator(generator: TechdocsGenerator): void;
611
+ setTechdocsGenerator(generator: GeneratorBase): void;
612
+ registerGenerator(key: SupportedGeneratorKey, generator: GeneratorBase): void;
613
613
  }
614
614
  /**
615
615
  * Extension point for configuring a custom TechDocs generator
@@ -647,5 +647,5 @@ interface TechdocsPublisherExtensionPoint {
647
647
  */
648
648
  declare const techdocsPublisherExtensionPoint: _backstage_backend_plugin_api.ExtensionPoint<TechdocsPublisherExtensionPoint>;
649
649
 
650
- export { DirectoryPreparer, Generators, Preparers, Publisher, TechdocsGenerator, UrlPreparer, getDocFilesFromRepository, getLocationForEntity, getMkDocsYml, getMkdocsYml, parseReferenceAnnotation, techdocsBuildsExtensionPoint, techdocsGeneratorExtensionPoint, techdocsPreparerExtensionPoint, techdocsPublisherExtensionPoint, transformDirLocation };
650
+ export { DirectoryPreparer, Generators, Preparers, Publisher, TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY, TechdocsGenerator, UrlPreparer, getDocFilesFromRepository, getLocationForEntity, getMkDocsYml, parseReferenceAnnotation, techdocsBuildsExtensionPoint, techdocsGeneratorExtensionPoint, techdocsPreparerExtensionPoint, techdocsPublisherExtensionPoint, transformDirLocation };
651
651
  export type { ContainerRunnerPullOptions, DocsBuildStrategy, ETag, GeneratorBase, GeneratorBuilder, GeneratorOptions, GeneratorRunOptions, MigrateRequest, ParsedLocationAnnotation, PreparerBase, PreparerBuilder, PreparerConfig, PreparerOptions, PreparerResponse, PublishRequest, PublishResponse, PublisherBase, PublisherBuilder, PublisherFactory, PublisherSettings, PublisherType, ReadinessResponse, RemoteProtocol, SupportedGeneratorKey, TechDocsContainerRunner, TechDocsDocument, TechDocsMetadata, TechdocsBuildsExtensionPoint, TechdocsGeneratorExtensionPoint, TechdocsPreparerExtensionPoint, TechdocsPublisherExtensionPoint };
@@ -1,10 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var helpers = require('./helpers.cjs.js');
4
3
  var techdocs = require('./techdocs.cjs.js');
4
+ var techdocsTypes = require('../../techdocsTypes.cjs.js');
5
5
 
6
+ function normalizeGeneratorKey(key) {
7
+ return key === "techdocs" ? "mkdocs" : key;
8
+ }
6
9
  class Generators {
7
10
  generatorMap = /* @__PURE__ */ new Map();
11
+ defaultEngine = "mkdocs";
8
12
  /**
9
13
  * Returns a generators instance containing a generator for TechDocs
10
14
  * @param config - A Backstage configuration
@@ -12,8 +16,11 @@ class Generators {
12
16
  */
13
17
  static async fromConfig(config, options) {
14
18
  const generators = new Generators();
15
- const techdocsGenerator = options.customGenerator ?? techdocs.TechdocsGenerator.fromConfig(config, options);
16
- generators.register("techdocs", techdocsGenerator);
19
+ const defaultEngine = config.getOptionalString("techdocs.generator.defaultEngine") ?? "mkdocs";
20
+ generators.defaultEngine = defaultEngine;
21
+ options.logger.info(`TechDocs generator defaultEngine: ${defaultEngine}`);
22
+ const mkdocsGenerator = options.customGenerator ?? techdocs.TechdocsGenerator.fromConfig(config, options);
23
+ generators.register("mkdocs", mkdocsGenerator);
17
24
  return generators;
18
25
  }
19
26
  /**
@@ -22,17 +29,26 @@ class Generators {
22
29
  * @param generator - The generator instance to register
23
30
  */
24
31
  register(generatorKey, generator) {
25
- this.generatorMap.set(generatorKey, generator);
32
+ this.generatorMap.set(normalizeGeneratorKey(generatorKey), generator);
26
33
  }
27
34
  /**
28
35
  * Returns the generator for a given TechDocs entity
29
36
  * @param entity - A TechDocs entity instance
30
37
  */
31
38
  get(entity) {
32
- const generatorKey = helpers.getGeneratorKey(entity);
39
+ if (!entity) {
40
+ throw new Error("No entity provided");
41
+ }
42
+ const annotatedEngine = entity.metadata?.annotations?.[techdocsTypes.TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY];
43
+ const generatorKey = normalizeGeneratorKey(
44
+ annotatedEngine ?? this.defaultEngine
45
+ );
33
46
  const generator = this.generatorMap.get(generatorKey);
34
47
  if (!generator) {
35
- throw new Error(`No generator registered for entity: "${generatorKey}"`);
48
+ const source = annotatedEngine ? `the ${techdocsTypes.TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY} annotation` : "techdocs.generator.defaultEngine";
49
+ throw new Error(
50
+ `No TechDocs generator registered for engine "${generatorKey}" (from ${source}). Registered engines: ${[...this.generatorMap.keys()].join(", ")}`
51
+ );
36
52
  }
37
53
  return generator;
38
54
  }
@@ -1 +1 @@
1
- {"version":3,"file":"generators.cjs.js","sources":["../../../src/stages/generate/generators.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Entity } from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { getGeneratorKey } from './helpers';\nimport { TechdocsGenerator } from './techdocs';\nimport {\n GeneratorBase,\n GeneratorBuilder,\n SupportedGeneratorKey,\n} from './types';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { TechDocsContainerRunner } from './types';\n\n/**\n * Collection of docs generators\n * @public\n */\nexport class Generators implements GeneratorBuilder {\n private generatorMap = new Map<SupportedGeneratorKey, GeneratorBase>();\n\n /**\n * Returns a generators instance containing a generator for TechDocs\n * @param config - A Backstage configuration\n * @param options - Options to configure the TechDocs generator\n */\n static async fromConfig(\n config: Config,\n options: {\n logger: LoggerService;\n containerRunner?: TechDocsContainerRunner;\n customGenerator?: TechdocsGenerator;\n },\n ): Promise<GeneratorBuilder> {\n const generators = new Generators();\n\n const techdocsGenerator =\n options.customGenerator ?? TechdocsGenerator.fromConfig(config, options);\n generators.register('techdocs', techdocsGenerator);\n\n return generators;\n }\n\n /**\n * Register a generator in the generators collection\n * @param generatorKey - Unique identifier for the generator\n * @param generator - The generator instance to register\n */\n register(generatorKey: SupportedGeneratorKey, generator: GeneratorBase) {\n this.generatorMap.set(generatorKey, generator);\n }\n\n /**\n * Returns the generator for a given TechDocs entity\n * @param entity - A TechDocs entity instance\n */\n get(entity: Entity): GeneratorBase {\n const generatorKey = getGeneratorKey(entity);\n const generator = this.generatorMap.get(generatorKey);\n\n if (!generator) {\n throw new Error(`No generator registered for entity: \"${generatorKey}\"`);\n }\n\n return generator;\n }\n}\n"],"names":["TechdocsGenerator","getGeneratorKey"],"mappings":";;;;;AAgCO,MAAM,UAAA,CAAuC;AAAA,EAC1C,YAAA,uBAAmB,GAAA,EAA0C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOrE,aAAa,UAAA,CACX,MAAA,EACA,OAAA,EAK2B;AAC3B,IAAA,MAAM,UAAA,GAAa,IAAI,UAAA,EAAW;AAElC,IAAA,MAAM,oBACJ,OAAA,CAAQ,eAAA,IAAmBA,0BAAA,CAAkB,UAAA,CAAW,QAAQ,OAAO,CAAA;AACzE,IAAA,UAAA,CAAW,QAAA,CAAS,YAAY,iBAAiB,CAAA;AAEjD,IAAA,OAAO,UAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAA,CAAS,cAAqC,SAAA,EAA0B;AACtE,IAAA,IAAA,CAAK,YAAA,CAAa,GAAA,CAAI,YAAA,EAAc,SAAS,CAAA;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,MAAA,EAA+B;AACjC,IAAA,MAAM,YAAA,GAAeC,wBAAgB,MAAM,CAAA;AAC3C,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,YAAA,CAAa,GAAA,CAAI,YAAY,CAAA;AAEpD,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qCAAA,EAAwC,YAAY,CAAA,CAAA,CAAG,CAAA;AAAA,IACzE;AAEA,IAAA,OAAO,SAAA;AAAA,EACT;AACF;;"}
1
+ {"version":3,"file":"generators.cjs.js","sources":["../../../src/stages/generate/generators.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Entity } from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { TechdocsGenerator } from './techdocs';\nimport {\n GeneratorBase,\n GeneratorBuilder,\n SupportedGeneratorKey,\n} from './types';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { TechDocsContainerRunner } from './types';\nimport { TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY } from '../../techdocsTypes';\n\n/**\n * 'techdocs' was the generator key before engines were introduced, and is\n * kept as an alias of 'mkdocs' so that existing registrations keep working.\n */\nfunction normalizeGeneratorKey(key: SupportedGeneratorKey): string {\n return key === 'techdocs' ? 'mkdocs' : key;\n}\n\n/**\n * Collection of docs generators\n * @public\n */\nexport class Generators implements GeneratorBuilder {\n private generatorMap = new Map<SupportedGeneratorKey, GeneratorBase>();\n private defaultEngine: SupportedGeneratorKey = 'mkdocs';\n\n /**\n * Returns a generators instance containing a generator for TechDocs\n * @param config - A Backstage configuration\n * @param options - Options to configure the TechDocs generator\n */\n static async fromConfig(\n config: Config,\n options: {\n logger: LoggerService;\n containerRunner?: TechDocsContainerRunner;\n customGenerator?: GeneratorBase;\n },\n ): Promise<GeneratorBuilder> {\n const generators = new Generators();\n const defaultEngine =\n config.getOptionalString('techdocs.generator.defaultEngine') ?? 'mkdocs';\n\n generators.defaultEngine = defaultEngine;\n\n options.logger.info(`TechDocs generator defaultEngine: ${defaultEngine}`);\n\n const mkdocsGenerator =\n options.customGenerator ?? TechdocsGenerator.fromConfig(config, options);\n generators.register('mkdocs', mkdocsGenerator);\n\n return generators;\n }\n\n /**\n * Register a generator in the generators collection\n * @param generatorKey - Unique identifier for the generator\n * @param generator - The generator instance to register\n */\n register(generatorKey: SupportedGeneratorKey, generator: GeneratorBase) {\n this.generatorMap.set(normalizeGeneratorKey(generatorKey), generator);\n }\n\n /**\n * Returns the generator for a given TechDocs entity\n * @param entity - A TechDocs entity instance\n */\n get(entity: Entity): GeneratorBase {\n if (!entity) {\n throw new Error('No entity provided');\n }\n\n const annotatedEngine =\n entity.metadata?.annotations?.[TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY];\n const generatorKey = normalizeGeneratorKey(\n annotatedEngine ?? this.defaultEngine,\n );\n const generator = this.generatorMap.get(generatorKey);\n\n if (!generator) {\n const source = annotatedEngine\n ? `the ${TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY} annotation`\n : 'techdocs.generator.defaultEngine';\n throw new Error(\n `No TechDocs generator registered for engine \"${generatorKey}\" (from ${source}). ` +\n `Registered engines: ${[...this.generatorMap.keys()].join(', ')}`,\n );\n }\n\n return generator;\n }\n}\n"],"names":["TechdocsGenerator","TECHDOCS_ENGINE_CATALOG_ANNOTATION_KEY"],"mappings":";;;;;AAgCA,SAAS,sBAAsB,GAAA,EAAoC;AACjE,EAAA,OAAO,GAAA,KAAQ,aAAa,QAAA,GAAW,GAAA;AACzC;AAMO,MAAM,UAAA,CAAuC;AAAA,EAC1C,YAAA,uBAAmB,GAAA,EAA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EAAOA,oDAAsC,CAAA,WAAA,CAAA,GAC7C,kCAAA;AACJ,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,6CAAA,EAAgD,YAAY,CAAA,QAAA,EAAW,MAAM,0BACpD,CAAC,GAAG,IAAA,CAAK,YAAA,CAAa,IAAA,EAAM,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,OACnE;AAAA,IACF;AAEA,IAAA,OAAO,SAAA;AAAA,EACT;AACF;;"}
@@ -35,12 +35,6 @@ var gitUrlParse__default = /*#__PURE__*/_interopDefaultCompat(gitUrlParse);
35
35
  var yaml__namespace = /*#__PURE__*/_interopNamespaceCompat(yaml);
36
36
  var path__default = /*#__PURE__*/_interopDefaultCompat(path);
37
37
 
38
- function getGeneratorKey(entity) {
39
- if (!entity) {
40
- throw new Error("No entity provided");
41
- }
42
- return "techdocs";
43
- }
44
38
  const runCommand = async ({
45
39
  command,
46
40
  args,
@@ -345,7 +339,7 @@ const patchIndexPreBuild = async ({
345
339
  ].join(" ")} exists.`
346
340
  );
347
341
  };
348
- const createOrUpdateMetadata = async (techdocsMetadataPath, logger) => {
342
+ const createOrUpdateMetadata = async (techdocsMetadataPath, logger, engine) => {
349
343
  const techdocsMetadataDir = techdocsMetadataPath.split(path__default.default.sep).slice(0, -1).join(path__default.default.sep);
350
344
  try {
351
345
  await fs__default.default.access(techdocsMetadataPath, fs__default.default.constants.F_OK);
@@ -361,6 +355,9 @@ const createOrUpdateMetadata = async (techdocsMetadataPath, logger) => {
361
355
  throw new Error(message);
362
356
  }
363
357
  json.build_timestamp = Date.now();
358
+ if (engine) {
359
+ json.engine = engine;
360
+ }
364
361
  try {
365
362
  json.files = (await helpers.getFileTreeRecursively(techdocsMetadataDir)).map(
366
363
  (file) => file.replace(`${techdocsMetadataDir}${path__default.default.sep}`, "")
@@ -387,7 +384,6 @@ exports.MKDOCS_SCHEMA = MKDOCS_SCHEMA;
387
384
  exports.UnknownTag = UnknownTag;
388
385
  exports.createOrUpdateMetadata = createOrUpdateMetadata;
389
386
  exports.generateMkdocsYml = generateMkdocsYml;
390
- exports.getGeneratorKey = getGeneratorKey;
391
387
  exports.getMkdocsYml = getMkdocsYml;
392
388
  exports.getRepoUrlFromLocationAnnotation = getRepoUrlFromLocationAnnotation;
393
389
  exports.patchIndexPreBuild = patchIndexPreBuild;
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.cjs.js","sources":["../../../src/stages/generate/helpers.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isChildPath, LoggerService } from '@backstage/backend-plugin-api';\nimport { Entity } from '@backstage/catalog-model';\nimport { ForwardedError, NotAllowedError, toError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport { SpawnOptionsWithoutStdio, spawn } from 'node:child_process';\nimport fs from 'fs-extra';\nimport gitUrlParse from 'git-url-parse';\nimport * as yaml from 'js-yaml';\nimport {\n defineMappingTag,\n defineScalarTag,\n defineSequenceTag,\n mapTag,\n YAML11_SCHEMA,\n} from 'js-yaml';\nimport path, { resolve as resolvePath } from 'node:path';\nimport { PassThrough, Writable } from 'node:stream';\nimport { ParsedLocationAnnotation } from '../../helpers';\nimport { DefaultMkdocsContent, SupportedGeneratorKey } from './types';\nimport { getFileTreeRecursively } from '../publish/helpers';\n\n// TODO: Implement proper support for more generators.\nexport function getGeneratorKey(entity: Entity): SupportedGeneratorKey {\n if (!entity) {\n throw new Error('No entity provided');\n }\n\n return 'techdocs';\n}\n\nexport type RunCommandOptions = {\n /** command to run */\n command: string;\n /** arguments to pass the command */\n args: string[];\n /** options to pass to spawn */\n options: SpawnOptionsWithoutStdio;\n /** stream to capture stdout and stderr output */\n logStream?: Writable;\n};\n\n/**\n * Run a command in a sub-process, normally a shell command.\n */\nexport const runCommand = async ({\n command,\n args,\n options,\n logStream = new PassThrough(),\n}: RunCommandOptions) => {\n await new Promise<void>((resolve, reject) => {\n const process = spawn(command, args, options);\n\n process.stdout.on('data', stream => {\n logStream.write(stream);\n });\n\n process.stderr.on('data', stream => {\n logStream.write(stream);\n });\n\n process.on('error', error => {\n return reject(error);\n });\n\n process.on('close', code => {\n if (code !== 0) {\n return reject(`Command ${command} failed, exit code: ${code}`);\n }\n return resolve();\n });\n });\n};\n\n/**\n * Return the source url for MkDocs based on the backstage.io/techdocs-ref annotation.\n * Depending on the type of target, it can either return a repo_url, an edit_uri, both, or none.\n *\n * @param parsedLocationAnnotation - Object with location url and type\n * @param scmIntegrations - the scmIntegration to do url transformations\n * @param docsFolder - the configured docs folder in the mkdocs.yml (defaults to 'docs')\n * @returns the settings for the mkdocs.yml\n */\nexport const getRepoUrlFromLocationAnnotation = (\n parsedLocationAnnotation: ParsedLocationAnnotation,\n scmIntegrations: ScmIntegrationRegistry,\n docsFolder: string = 'docs',\n): { repo_url?: string; edit_uri?: string } => {\n const { type: locationType, target } = parsedLocationAnnotation;\n\n if (locationType === 'url') {\n const integration = scmIntegrations.byUrl(target);\n\n // We only support it for github, gitlab, bitbucketServer and harness for now as the edit_uri\n // is not properly supported for others yet.\n if (\n integration &&\n ['github', 'gitlab', 'bitbucketServer', 'harness'].includes(\n integration.type,\n )\n ) {\n // handle the case where a user manually writes url:https://github.com/backstage/backstage i.e. without /blob/...\n const { filepathtype } = gitUrlParse(target);\n if (filepathtype === '') {\n return { repo_url: target };\n }\n\n const sourceFolder = integration.resolveUrl({\n url: `./${docsFolder}`,\n base: target.endsWith('/') ? target : `${target}/`,\n });\n return {\n repo_url: target,\n edit_uri: integration.resolveEditUrl(sourceFolder),\n };\n }\n }\n\n return {};\n};\n\n// Listed exactly rather than by a `pymdownx.` prefix: resolving one of these\n// tags imports the module it names, and a prefix would accept any module-level\n// attribute of any importable submodule.\nconst ALLOWED_PYTHON_YAML_TAGS = new Set([\n // Emoji indexes; mkdocs-material moved its own from materialx to\n // material.extensions in 9.4.\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.emojione',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.gemoji',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.twemoji',\n 'tag:yaml.org,2002:python/name:materialx.emoji.twemoji',\n 'tag:yaml.org,2002:python/name:material.extensions.emoji.twemoji',\n // Emoji generators\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_alt',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_png',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_png_sprite',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_svg',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_svg_sprite',\n 'tag:yaml.org,2002:python/name:materialx.emoji.to_svg',\n 'tag:yaml.org,2002:python/name:material.extensions.emoji.to_svg',\n // Custom fence formats, used for Mermaid diagrams. The mermaid2 ones come\n // from mkdocs-mermaid2, which mkdocs-techdocs-core does not bundle.\n 'tag:yaml.org,2002:python/name:pymdownx.superfences.fence_code_format',\n 'tag:yaml.org,2002:python/name:pymdownx.superfences.fence_div_format',\n 'tag:yaml.org,2002:python/name:mermaid2.fence_mermaid',\n 'tag:yaml.org,2002:python/name:mermaid2.fence_mermaid_custom',\n // Slug factory for toc and pymdownx.tabbed\n 'tag:yaml.org,2002:python/object/apply:pymdownx.slugs.slugify',\n]);\n\nexport class UnknownTag {\n public readonly data: any;\n public readonly type?: string;\n\n constructor(data: any, type?: string) {\n if (\n type?.startsWith('tag:yaml.org,2002:python/') &&\n !ALLOWED_PYTHON_YAML_TAGS.has(type)\n ) {\n throw new Error(`Unsupported Python YAML tag '${type}'`);\n }\n\n this.data = data;\n this.type = type;\n }\n}\n\n/** Preserve YAML merge keys and MkDocs-specific tags while inspecting config. */\nexport const MKDOCS_SCHEMA = YAML11_SCHEMA.withTags(\n defineScalarTag('', {\n matchByTagPrefix: true,\n resolve: (data, _isExplicit, tagName) => new UnknownTag(data, tagName),\n identify: data =>\n data instanceof UnknownTag && typeof data.data === 'string',\n represent: data => data.data,\n representTagName: data => data.type,\n }),\n defineSequenceTag<UnknownTag>('', {\n matchByTagPrefix: true,\n create: tagName => new UnknownTag([], tagName),\n addItem: (carrier, item) => {\n carrier.data.push(item);\n },\n identify: data => data instanceof UnknownTag && Array.isArray(data.data),\n represent: data => data.data,\n representTagName: data => data.type,\n }),\n defineMappingTag<UnknownTag>('tag:', {\n matchByTagPrefix: true,\n create: tagName => new UnknownTag({}, tagName),\n addPair: (carrier, key, value) => mapTag.addPair(carrier.data, key, value),\n has: (carrier, key) => mapTag.has(carrier.data, key),\n keys: result => mapTag.keys(result.data),\n get: (result, key) => mapTag.get(result.data, key),\n identify: data =>\n data instanceof UnknownTag &&\n typeof data.data === 'object' &&\n data.data !== null &&\n !Array.isArray(data.data),\n represent: data => new Map(Object.entries(data.data)),\n representTagName: data => data.type,\n }),\n);\n\n/**\n * Generates a mkdocs.yml configuration file\n *\n * @param inputDir - base dir to where the mkdocs.yml file will be created\n * @param siteOptions - options for the site: `name` property will be used in mkdocs.yml for the\n * required `site_name` property, default value is \"Documentation Site\"\n */\nexport const generateMkdocsYml = async (\n inputDir: string,\n siteOptions?: { name?: string },\n) => {\n try {\n // TODO(awanlin): Use a provided default mkdocs.yml\n // from config or some specified location. If this is\n // not provided then fall back to generating bare\n // minimum mkdocs.yml file\n\n const mkdocsYmlPath = path.join(inputDir, 'mkdocs.yml');\n const defaultSiteName = siteOptions?.name ?? 'Documentation Site';\n const defaultMkdocsContent: DefaultMkdocsContent = {\n site_name: defaultSiteName,\n docs_dir: 'docs',\n plugins: ['techdocs-core'],\n };\n\n await fs.writeFile(\n mkdocsYmlPath,\n yaml.dump(defaultMkdocsContent, { schema: MKDOCS_SCHEMA }),\n );\n } catch (error) {\n throw new ForwardedError('Could not generate mkdocs.yml file', error);\n }\n};\n\n/**\n * Finds and loads the contents of an mkdocs.yml, mkdocs.yaml file, a file\n * with a specified name or an ad-hoc created file with minimal config.\n * @public\n *\n * @param inputDir - base dir to be searched for either an mkdocs.yml or mkdocs.yaml file.\n * @param options - name: default mkdocs site_name to be used with a ad hoc file default value is \"Documentation Site\"\n * mkdocsConfigFileName (optional): a non-default file name to be used as the config\n */\nexport const getMkdocsYml = async (\n inputDir: string,\n options?: { name?: string; mkdocsConfigFileName?: string },\n): Promise<{ path: string; content: string; configIsTemporary: boolean }> => {\n let mkdocsYmlPath: string;\n let mkdocsYmlFileString: string;\n try {\n if (options?.mkdocsConfigFileName) {\n mkdocsYmlPath = path.join(inputDir, options.mkdocsConfigFileName);\n if (!(await fs.pathExists(mkdocsYmlPath))) {\n throw new Error(`The specified file ${mkdocsYmlPath} does not exist`);\n }\n\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: false,\n };\n }\n\n mkdocsYmlPath = path.join(inputDir, 'mkdocs.yaml');\n if (await fs.pathExists(mkdocsYmlPath)) {\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: false,\n };\n }\n\n mkdocsYmlPath = path.join(inputDir, 'mkdocs.yml');\n if (await fs.pathExists(mkdocsYmlPath)) {\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: false,\n };\n }\n\n // No mkdocs file, generate it\n await generateMkdocsYml(inputDir, options);\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n } catch (error) {\n throw new ForwardedError(\n 'Could not read MkDocs YAML config file mkdocs.yml or mkdocs.yaml or default for validation',\n error,\n );\n }\n\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: true,\n };\n};\n\n/**\n * Allowlist of MkDocs configuration keys supported by TechDocs.\n *\n * @see https://www.mkdocs.org/user-guide/configuration/\n */\nexport const ALLOWED_MKDOCS_KEYS = new Set([\n // Site information\n 'site_name',\n 'site_url',\n 'site_description',\n 'site_author',\n // Repository\n 'repo_url',\n 'repo_name',\n 'edit_uri',\n 'edit_uri_template',\n // Build directories\n 'docs_dir',\n 'site_dir',\n // Documentation layout\n 'nav',\n 'exclude_docs',\n 'not_in_nav',\n // Build settings\n 'theme',\n 'plugins',\n 'markdown_extensions',\n 'extra',\n 'extra_css',\n // Preview controls\n 'use_directory_urls',\n 'strict',\n 'dev_addr',\n 'watch',\n // Metadata\n 'copyright',\n 'remote_branch',\n 'remote_name',\n 'validation',\n // Deprecated\n 'google_analytics',\n]);\n\n/**\n * Denylist of configuration keys that must be stripped from extension\n * configurations nested within `markdown_extensions`.\n */\nexport const DANGEROUS_EXTENSION_CONFIG_KEYS = new Set(['plantuml_cmd']);\n\n/**\n * Allowlist of theme configuration keys supported by TechDocs.\n *\n * @see https://squidfunk.github.io/mkdocs-material/setup/\n */\nexport const ALLOWED_THEME_KEYS = new Set([\n 'name',\n 'font',\n 'icon',\n 'logo',\n 'favicon',\n 'language',\n 'direction',\n 'palette',\n 'features',\n]);\n\n/**\n * Validating mkdocs config file for incorrect/insecure values\n * Throws on invalid configs\n *\n * @param inputDir - base dir to be used as a docs_dir path validity check\n * @param mkdocsYmlFileString - The string contents of the loaded\n * mkdocs.yml or equivalent of a docs site\n * @returns the parsed docs_dir or undefined\n */\nexport const validateMkdocsYaml = async (\n inputDir: string,\n mkdocsYmlFileString: string,\n): Promise<string | undefined> => {\n const mkdocsYml = yaml.load(mkdocsYmlFileString, {\n schema: MKDOCS_SCHEMA,\n });\n\n if (mkdocsYml === null || typeof mkdocsYml !== 'object') {\n return undefined;\n }\n\n const parsedMkdocsYml: Record<string, any> = mkdocsYml;\n\n if (\n parsedMkdocsYml.docs_dir &&\n !isChildPath(inputDir, resolvePath(inputDir, parsedMkdocsYml.docs_dir))\n ) {\n throw new Error(\n `docs_dir configuration value in mkdocs can't be an absolute directory or start with ../ for security reasons.\n Use relative paths instead which are resolved relative to your mkdocs.yml file location.`,\n );\n }\n return parsedMkdocsYml.docs_dir;\n};\n\n/**\n * Validates that the input directory doesn't contain symlinks pointing outside\n * of it. This prevents path traversal attacks where malicious symlinks could be\n * used to read arbitrary files from the host filesystem.\n *\n * The whole input directory is checked rather than only the docs directory,\n * because MkDocs extensions can read files from anywhere in the input directory.\n *\n * @param inputDir - The input directory to validate (absolute path)\n */\nexport const validateInputDirectory = async (\n inputDir: string,\n): Promise<void> => {\n const entries = await fs.readdir(inputDir, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isSymbolicLink()) {\n continue;\n }\n\n const entryPath = path.join(entry.parentPath, entry.name);\n // isChildPath resolves both paths through realpath, so this also catches\n // relative, chained and dangling links\n if (!isChildPath(inputDir, entryPath)) {\n throw new NotAllowedError(\n `Path ${entryPath} is not allowed to refer to a location outside ${inputDir}`,\n );\n }\n }\n};\n\n/**\n * Update docs/index.md file before TechDocs generator uses it to generate docs site,\n * falling back to docs/README.md or README.md in case a default docs/index.md\n * is not provided.\n */\nexport const patchIndexPreBuild = async ({\n inputDir,\n logger,\n docsDir = 'docs',\n}: {\n inputDir: string;\n logger: LoggerService;\n docsDir?: string;\n}) => {\n const docsPath = path.join(inputDir, docsDir);\n const indexMdPath = path.join(docsPath, 'index.md');\n\n if (await fs.pathExists(indexMdPath)) {\n return;\n }\n logger.warn(`${path.join(docsDir, 'index.md')} not found.`);\n const fallbacks = [\n path.join(docsPath, 'README.md'),\n path.join(docsPath, 'readme.md'),\n path.join(inputDir, 'README.md'),\n path.join(inputDir, 'readme.md'),\n ];\n\n if (!isChildPath(inputDir, docsPath)) {\n throw new NotAllowedError(\n `Target path ${docsPath} is not allowed to refer to a location outside ${inputDir}`,\n );\n }\n await fs.ensureDir(docsPath);\n for (const filePath of fallbacks) {\n if (!isChildPath(inputDir, filePath)) {\n throw new NotAllowedError(\n `Source path ${filePath} is not allowed to refer to a location outside ${inputDir}`,\n );\n }\n try {\n await fs.copyFile(filePath, indexMdPath);\n return;\n } catch (error) {\n logger.warn(`${path.relative(inputDir, filePath)} not found.`);\n }\n }\n\n logger.warn(\n `Could not find any techdocs' index file. Please make sure at least one of ${[\n indexMdPath,\n ...fallbacks,\n ].join(' ')} exists.`,\n );\n};\n\n/**\n * Create or update the techdocs_metadata.json. Values initialized/updated are:\n * - The build_timestamp (now)\n * - The list of files generated\n *\n * @param techdocsMetadataPath - File path to techdocs_metadata.json\n */\nexport const createOrUpdateMetadata = async (\n techdocsMetadataPath: string,\n logger: LoggerService,\n): Promise<void> => {\n const techdocsMetadataDir = techdocsMetadataPath\n .split(path.sep)\n .slice(0, -1)\n .join(path.sep);\n // check if file exists, create if it does not.\n try {\n await fs.access(techdocsMetadataPath, fs.constants.F_OK);\n } catch (err) {\n // Bootstrap file with empty JSON\n await fs.writeJson(techdocsMetadataPath, JSON.parse('{}'));\n }\n // check if valid Json\n let json;\n try {\n json = await fs.readJson(techdocsMetadataPath);\n } catch (err) {\n const message = `Invalid JSON at ${techdocsMetadataPath} with error ${\n toError(err).message\n }`;\n logger.error(message);\n throw new Error(message);\n }\n\n json.build_timestamp = Date.now();\n\n // Get and write generated files to the metadata JSON. Each file string is in\n // a form appropriate for invalidating the associated object from cache.\n try {\n json.files = (await getFileTreeRecursively(techdocsMetadataDir)).map(file =>\n file.replace(`${techdocsMetadataDir}${path.sep}`, ''),\n );\n } catch (err) {\n json.files = [];\n logger.warn(\n `Unable to add files list to metadata: ${toError(err).message}`,\n );\n }\n\n await fs.writeJson(techdocsMetadataPath, json);\n return;\n};\n\n/**\n * Update the techdocs_metadata.json to add etag of the prepared tree (e.g. commit SHA or actual Etag of the resource).\n * This is helpful to check if a TechDocs site in storage has gone outdated, without maintaining an in-memory build info\n * per Backstage instance.\n *\n * @param techdocsMetadataPath - File path to techdocs_metadata.json\n * @param etag - The ETag to use\n */\nexport const storeEtagMetadata = async (\n techdocsMetadataPath: string,\n etag: string,\n): Promise<void> => {\n const json = await fs.readJson(techdocsMetadataPath);\n json.etag = etag;\n await fs.writeJson(techdocsMetadataPath, json);\n};\n"],"names":["PassThrough","spawn","gitUrlParse","YAML11_SCHEMA","defineScalarTag","defineSequenceTag","defineMappingTag","mapTag","path","fs","yaml","ForwardedError","isChildPath","resolvePath","NotAllowedError","toError","getFileTreeRecursively"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCO,SAAS,gBAAgB,MAAA,EAAuC;AACrE,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,MAAM,IAAI,MAAM,oBAAoB,CAAA;AAAA,EACtC;AAEA,EAAA,OAAO,UAAA;AACT;AAgBO,MAAM,aAAa,OAAO;AAAA,EAC/B,OAAA;AAAA,EACA,IAAA;AAAA,EACA,OAAA;AAAA,EACA,SAAA,GAAY,IAAIA,uBAAA;AAClB,CAAA,KAAyB;AACvB,EAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC3C,IAAA,MAAM,OAAA,GAAUC,wBAAA,CAAM,OAAA,EAAS,IAAA,EAAM,OAAO,CAAA;AAE5C,IAAA,OAAA,CAAQ,MAAA,CAAO,EAAA,CAAG,MAAA,EAAQ,CAAA,MAAA,KAAU;AAClC,MAAA,SAAA,CAAU,MAAM,MAAM,CAAA;AAAA,IACxB,CAAC,CAAA;AAED,IAAA,OAAA,CAAQ,MAAA,CAAO,EAAA,CAAG,MAAA,EAAQ,CAAA,MAAA,KAAU;AAClC,MAAA,SAAA,CAAU,MAAM,MAAM,CAAA;AAAA,IACxB,CAAC,CAAA;AAED,IAAA,OAAA,CAAQ,EAAA,CAAG,SAAS,CAAA,KAA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AA;AAAA,MACL,CAAA,sCAAA,EAAyCO,cAAA,CAAQ,GAAG,CAAA,CAAE,OAAO,CAAA;AAAA,KAC/D;AAAA,EACF;AAEA,EAAA,MAAMN,mBAAA,CAAG,SAAA,CAAU,oBAAA,EAAsB,IAAI,CAAA;AAC7C,EAAA;AACF;AAUO,MAAM,iBAAA,GAAoB,OAC/B,oBAAA,EACA,IAAA,KACkB;AAClB,EAAA,MAAM,IAAA,GAAO,MAAMA,mBAAA,CAAG,QAAA,CAAS,oBAAoB,CAAA;AACnD,EAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,EAAA,MAAMA,mBAAA,CAAG,SAAA,CAAU,oBAAA,EAAsB,IAAI,CAAA;AAC/C;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"helpers.cjs.js","sources":["../../../src/stages/generate/helpers.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isChildPath, LoggerService } from '@backstage/backend-plugin-api';\nimport { ForwardedError, NotAllowedError, toError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport { SpawnOptionsWithoutStdio, spawn } from 'node:child_process';\nimport fs from 'fs-extra';\nimport gitUrlParse from 'git-url-parse';\nimport * as yaml from 'js-yaml';\nimport {\n defineMappingTag,\n defineScalarTag,\n defineSequenceTag,\n mapTag,\n YAML11_SCHEMA,\n} from 'js-yaml';\nimport path, { resolve as resolvePath } from 'node:path';\nimport { PassThrough, Writable } from 'node:stream';\nimport { ParsedLocationAnnotation } from '../../helpers';\nimport { DefaultMkdocsContent } from './types';\nimport { getFileTreeRecursively } from '../publish/helpers';\n\n/** @alpha */\nexport type RunCommandOptions = {\n /** command to run */\n command: string;\n /** arguments to pass the command */\n args: string[];\n /** options to pass to spawn */\n options: SpawnOptionsWithoutStdio;\n /** stream to capture stdout and stderr output */\n logStream?: Writable;\n};\n\n/**\n * Run a command in a sub-process, normally a shell command.\n * @alpha\n */\nexport const runCommand = async ({\n command,\n args,\n options,\n logStream = new PassThrough(),\n}: RunCommandOptions) => {\n await new Promise<void>((resolve, reject) => {\n const process = spawn(command, args, options);\n\n process.stdout.on('data', stream => {\n logStream.write(stream);\n });\n\n process.stderr.on('data', stream => {\n logStream.write(stream);\n });\n\n process.on('error', error => {\n return reject(error);\n });\n\n process.on('close', code => {\n if (code !== 0) {\n return reject(`Command ${command} failed, exit code: ${code}`);\n }\n return resolve();\n });\n });\n};\n\n/**\n * Return the source url for MkDocs based on the backstage.io/techdocs-ref annotation.\n * Depending on the type of target, it can either return a repo_url, an edit_uri, both, or none.\n *\n * @param parsedLocationAnnotation - Object with location url and type\n * @param scmIntegrations - the scmIntegration to do url transformations\n * @param docsFolder - the configured docs folder in the mkdocs.yml (defaults to 'docs')\n * @returns the settings for the mkdocs.yml\n */\nexport const getRepoUrlFromLocationAnnotation = (\n parsedLocationAnnotation: ParsedLocationAnnotation,\n scmIntegrations: ScmIntegrationRegistry,\n docsFolder: string = 'docs',\n): { repo_url?: string; edit_uri?: string } => {\n const { type: locationType, target } = parsedLocationAnnotation;\n\n if (locationType === 'url') {\n const integration = scmIntegrations.byUrl(target);\n\n // We only support it for github, gitlab, bitbucketServer and harness for now as the edit_uri\n // is not properly supported for others yet.\n if (\n integration &&\n ['github', 'gitlab', 'bitbucketServer', 'harness'].includes(\n integration.type,\n )\n ) {\n // handle the case where a user manually writes url:https://github.com/backstage/backstage i.e. without /blob/...\n const { filepathtype } = gitUrlParse(target);\n if (filepathtype === '') {\n return { repo_url: target };\n }\n\n const sourceFolder = integration.resolveUrl({\n url: `./${docsFolder}`,\n base: target.endsWith('/') ? target : `${target}/`,\n });\n return {\n repo_url: target,\n edit_uri: integration.resolveEditUrl(sourceFolder),\n };\n }\n }\n\n return {};\n};\n\n// Listed exactly rather than by a `pymdownx.` prefix: resolving one of these\n// tags imports the module it names, and a prefix would accept any module-level\n// attribute of any importable submodule.\nconst ALLOWED_PYTHON_YAML_TAGS = new Set([\n // Emoji indexes; mkdocs-material moved its own from materialx to\n // material.extensions in 9.4.\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.emojione',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.gemoji',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.twemoji',\n 'tag:yaml.org,2002:python/name:materialx.emoji.twemoji',\n 'tag:yaml.org,2002:python/name:material.extensions.emoji.twemoji',\n // Emoji generators\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_alt',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_png',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_png_sprite',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_svg',\n 'tag:yaml.org,2002:python/name:pymdownx.emoji.to_svg_sprite',\n 'tag:yaml.org,2002:python/name:materialx.emoji.to_svg',\n 'tag:yaml.org,2002:python/name:material.extensions.emoji.to_svg',\n // Custom fence formats, used for Mermaid diagrams. The mermaid2 ones come\n // from mkdocs-mermaid2, which mkdocs-techdocs-core does not bundle.\n 'tag:yaml.org,2002:python/name:pymdownx.superfences.fence_code_format',\n 'tag:yaml.org,2002:python/name:pymdownx.superfences.fence_div_format',\n 'tag:yaml.org,2002:python/name:mermaid2.fence_mermaid',\n 'tag:yaml.org,2002:python/name:mermaid2.fence_mermaid_custom',\n // Slug factory for toc and pymdownx.tabbed\n 'tag:yaml.org,2002:python/object/apply:pymdownx.slugs.slugify',\n]);\n\nexport class UnknownTag {\n public readonly data: any;\n public readonly type?: string;\n\n constructor(data: any, type?: string) {\n if (\n type?.startsWith('tag:yaml.org,2002:python/') &&\n !ALLOWED_PYTHON_YAML_TAGS.has(type)\n ) {\n throw new Error(`Unsupported Python YAML tag '${type}'`);\n }\n\n this.data = data;\n this.type = type;\n }\n}\n\n/**\n * Preserve YAML merge keys and MkDocs-specific tags while inspecting config.\n *\n * @alpha\n */\nexport const MKDOCS_SCHEMA = YAML11_SCHEMA.withTags(\n defineScalarTag('', {\n matchByTagPrefix: true,\n resolve: (data, _isExplicit, tagName) => new UnknownTag(data, tagName),\n identify: data =>\n data instanceof UnknownTag && typeof data.data === 'string',\n represent: data => data.data,\n representTagName: data => data.type,\n }),\n defineSequenceTag<UnknownTag>('', {\n matchByTagPrefix: true,\n create: tagName => new UnknownTag([], tagName),\n addItem: (carrier, item) => {\n carrier.data.push(item);\n },\n identify: data => data instanceof UnknownTag && Array.isArray(data.data),\n represent: data => data.data,\n representTagName: data => data.type,\n }),\n defineMappingTag<UnknownTag>('tag:', {\n matchByTagPrefix: true,\n create: tagName => new UnknownTag({}, tagName),\n addPair: (carrier, key, value) => mapTag.addPair(carrier.data, key, value),\n has: (carrier, key) => mapTag.has(carrier.data, key),\n keys: result => mapTag.keys(result.data),\n get: (result, key) => mapTag.get(result.data, key),\n identify: data =>\n data instanceof UnknownTag &&\n typeof data.data === 'object' &&\n data.data !== null &&\n !Array.isArray(data.data),\n represent: data => new Map(Object.entries(data.data)),\n representTagName: data => data.type,\n }),\n);\n\n/**\n * Generates a mkdocs.yml configuration file\n *\n * @param inputDir - base dir to where the mkdocs.yml file will be created\n * @param siteOptions - options for the site: `name` property will be used in mkdocs.yml for the\n * required `site_name` property, default value is \"Documentation Site\"\n */\nexport const generateMkdocsYml = async (\n inputDir: string,\n siteOptions?: { name?: string },\n) => {\n try {\n // TODO(awanlin): Use a provided default mkdocs.yml\n // from config or some specified location. If this is\n // not provided then fall back to generating bare\n // minimum mkdocs.yml file\n\n const mkdocsYmlPath = path.join(inputDir, 'mkdocs.yml');\n const defaultSiteName = siteOptions?.name ?? 'Documentation Site';\n const defaultMkdocsContent: DefaultMkdocsContent = {\n site_name: defaultSiteName,\n docs_dir: 'docs',\n plugins: ['techdocs-core'],\n };\n\n await fs.writeFile(\n mkdocsYmlPath,\n yaml.dump(defaultMkdocsContent, { schema: MKDOCS_SCHEMA }),\n );\n } catch (error) {\n throw new ForwardedError('Could not generate mkdocs.yml file', error);\n }\n};\n\n/**\n * Finds and loads the contents of an mkdocs.yml, mkdocs.yaml file, a file\n * with a specified name or an ad-hoc created file with minimal config.\n * @public\n *\n * @param inputDir - base dir to be searched for either an mkdocs.yml or mkdocs.yaml file.\n * @param options - name: default mkdocs site_name to be used with a ad hoc file default value is \"Documentation Site\"\n * mkdocsConfigFileName (optional): a non-default file name to be used as the config\n */\nexport const getMkdocsYml = async (\n inputDir: string,\n options?: { name?: string; mkdocsConfigFileName?: string },\n): Promise<{ path: string; content: string; configIsTemporary: boolean }> => {\n let mkdocsYmlPath: string;\n let mkdocsYmlFileString: string;\n try {\n if (options?.mkdocsConfigFileName) {\n mkdocsYmlPath = path.join(inputDir, options.mkdocsConfigFileName);\n if (!(await fs.pathExists(mkdocsYmlPath))) {\n throw new Error(`The specified file ${mkdocsYmlPath} does not exist`);\n }\n\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: false,\n };\n }\n\n mkdocsYmlPath = path.join(inputDir, 'mkdocs.yaml');\n if (await fs.pathExists(mkdocsYmlPath)) {\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: false,\n };\n }\n\n mkdocsYmlPath = path.join(inputDir, 'mkdocs.yml');\n if (await fs.pathExists(mkdocsYmlPath)) {\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: false,\n };\n }\n\n // No mkdocs file, generate it\n await generateMkdocsYml(inputDir, options);\n mkdocsYmlFileString = await fs.readFile(mkdocsYmlPath, 'utf8');\n } catch (error) {\n throw new ForwardedError(\n 'Could not read MkDocs YAML config file mkdocs.yml or mkdocs.yaml or default for validation',\n error,\n );\n }\n\n return {\n path: mkdocsYmlPath,\n content: mkdocsYmlFileString,\n configIsTemporary: true,\n };\n};\n\n/**\n * Allowlist of MkDocs configuration keys supported by TechDocs.\n *\n * @see https://www.mkdocs.org/user-guide/configuration/\n */\nexport const ALLOWED_MKDOCS_KEYS = new Set([\n // Site information\n 'site_name',\n 'site_url',\n 'site_description',\n 'site_author',\n // Repository\n 'repo_url',\n 'repo_name',\n 'edit_uri',\n 'edit_uri_template',\n // Build directories\n 'docs_dir',\n 'site_dir',\n // Documentation layout\n 'nav',\n 'exclude_docs',\n 'not_in_nav',\n // Build settings\n 'theme',\n 'plugins',\n 'markdown_extensions',\n 'extra',\n 'extra_css',\n // Preview controls\n 'use_directory_urls',\n 'strict',\n 'dev_addr',\n 'watch',\n // Metadata\n 'copyright',\n 'remote_branch',\n 'remote_name',\n 'validation',\n // Deprecated\n 'google_analytics',\n]);\n\n/**\n * Denylist of configuration keys that must be stripped from extension\n * configurations nested within `markdown_extensions`.\n */\nexport const DANGEROUS_EXTENSION_CONFIG_KEYS = new Set(['plantuml_cmd']);\n\n/**\n * Allowlist of theme configuration keys supported by TechDocs.\n *\n * @see https://squidfunk.github.io/mkdocs-material/setup/\n */\nexport const ALLOWED_THEME_KEYS = new Set([\n 'name',\n 'font',\n 'icon',\n 'logo',\n 'favicon',\n 'language',\n 'direction',\n 'palette',\n 'features',\n]);\n\n/**\n * Validating mkdocs config file for incorrect/insecure values\n * Throws on invalid configs\n *\n * @param inputDir - base dir to be used as a docs_dir path validity check\n * @param mkdocsYmlFileString - The string contents of the loaded\n * mkdocs.yml or equivalent of a docs site\n * @returns the parsed docs_dir or undefined\n * @alpha\n */\nexport const validateMkdocsYaml = async (\n inputDir: string,\n mkdocsYmlFileString: string,\n): Promise<string | undefined> => {\n const mkdocsYml = yaml.load(mkdocsYmlFileString, {\n schema: MKDOCS_SCHEMA,\n });\n\n if (mkdocsYml === null || typeof mkdocsYml !== 'object') {\n return undefined;\n }\n\n const parsedMkdocsYml: Record<string, any> = mkdocsYml;\n\n if (\n parsedMkdocsYml.docs_dir &&\n !isChildPath(inputDir, resolvePath(inputDir, parsedMkdocsYml.docs_dir))\n ) {\n throw new Error(\n `docs_dir configuration value in mkdocs can't be an absolute directory or start with ../ for security reasons.\n Use relative paths instead which are resolved relative to your mkdocs.yml file location.`,\n );\n }\n return parsedMkdocsYml.docs_dir;\n};\n\n/**\n * Validates that the input directory doesn't contain symlinks pointing outside\n * of it. This prevents path traversal attacks where malicious symlinks could be\n * used to read arbitrary files from the host filesystem.\n *\n * The whole input directory is checked rather than only the docs directory,\n * because MkDocs extensions can read files from anywhere in the input directory.\n *\n * @param inputDir - The input directory to validate (absolute path)\n * @alpha\n */\nexport const validateInputDirectory = async (\n inputDir: string,\n): Promise<void> => {\n const entries = await fs.readdir(inputDir, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isSymbolicLink()) {\n continue;\n }\n\n const entryPath = path.join(entry.parentPath, entry.name);\n // isChildPath resolves both paths through realpath, so this also catches\n // relative, chained and dangling links\n if (!isChildPath(inputDir, entryPath)) {\n throw new NotAllowedError(\n `Path ${entryPath} is not allowed to refer to a location outside ${inputDir}`,\n );\n }\n }\n};\n\n/**\n * Update docs/index.md file before TechDocs generator uses it to generate docs site,\n * falling back to docs/README.md or README.md in case a default docs/index.md\n * is not provided.\n * @alpha\n */\nexport const patchIndexPreBuild = async ({\n inputDir,\n logger,\n docsDir = 'docs',\n}: {\n inputDir: string;\n logger: LoggerService;\n docsDir?: string;\n}) => {\n const docsPath = path.join(inputDir, docsDir);\n const indexMdPath = path.join(docsPath, 'index.md');\n\n if (await fs.pathExists(indexMdPath)) {\n return;\n }\n logger.warn(`${path.join(docsDir, 'index.md')} not found.`);\n const fallbacks = [\n path.join(docsPath, 'README.md'),\n path.join(docsPath, 'readme.md'),\n path.join(inputDir, 'README.md'),\n path.join(inputDir, 'readme.md'),\n ];\n\n if (!isChildPath(inputDir, docsPath)) {\n throw new NotAllowedError(\n `Target path ${docsPath} is not allowed to refer to a location outside ${inputDir}`,\n );\n }\n await fs.ensureDir(docsPath);\n for (const filePath of fallbacks) {\n if (!isChildPath(inputDir, filePath)) {\n throw new NotAllowedError(\n `Source path ${filePath} is not allowed to refer to a location outside ${inputDir}`,\n );\n }\n try {\n await fs.copyFile(filePath, indexMdPath);\n return;\n } catch (error) {\n logger.warn(`${path.relative(inputDir, filePath)} not found.`);\n }\n }\n\n logger.warn(\n `Could not find any techdocs' index file. Please make sure at least one of ${[\n indexMdPath,\n ...fallbacks,\n ].join(' ')} exists.`,\n );\n};\n\n/**\n * Create or update the techdocs_metadata.json. Values initialized/updated are:\n * - The build_timestamp (now)\n * - The list of files generated\n *\n * @param techdocsMetadataPath - File path to techdocs_metadata.json\n * @alpha\n */\nexport const createOrUpdateMetadata = async (\n techdocsMetadataPath: string,\n logger: LoggerService,\n engine?: string,\n): Promise<void> => {\n const techdocsMetadataDir = techdocsMetadataPath\n .split(path.sep)\n .slice(0, -1)\n .join(path.sep);\n // check if file exists, create if it does not.\n try {\n await fs.access(techdocsMetadataPath, fs.constants.F_OK);\n } catch (err) {\n // Bootstrap file with empty JSON\n await fs.writeJson(techdocsMetadataPath, JSON.parse('{}'));\n }\n // check if valid Json\n let json;\n try {\n json = await fs.readJson(techdocsMetadataPath);\n } catch (err) {\n const message = `Invalid JSON at ${techdocsMetadataPath} with error ${\n toError(err).message\n }`;\n logger.error(message);\n throw new Error(message);\n }\n\n json.build_timestamp = Date.now();\n if (engine) {\n json.engine = engine;\n }\n\n // Get and write generated files to the metadata JSON. Each file string is in\n // a form appropriate for invalidating the associated object from cache.\n try {\n json.files = (await getFileTreeRecursively(techdocsMetadataDir)).map(file =>\n file.replace(`${techdocsMetadataDir}${path.sep}`, ''),\n );\n } catch (err) {\n json.files = [];\n logger.warn(\n `Unable to add files list to metadata: ${toError(err).message}`,\n );\n }\n\n await fs.writeJson(techdocsMetadataPath, json);\n return;\n};\n\n/**\n * Update the techdocs_metadata.json to add etag of the prepared tree (e.g. commit SHA or actual Etag of the resource).\n * This is helpful to check if a TechDocs site in storage has gone outdated, without maintaining an in-memory build info\n * per Backstage instance.\n *\n * @param techdocsMetadataPath - File path to techdocs_metadata.json\n * @param etag - The ETag to use\n * @alpha\n */\nexport const storeEtagMetadata = async (\n techdocsMetadataPath: string,\n etag: string,\n): Promise<void> => {\n const json = await fs.readJson(techdocsMetadataPath);\n json.etag = etag;\n await fs.writeJson(techdocsMetadataPath, json);\n};\n"],"names":["PassThrough","spawn","gitUrlParse","YAML11_SCHEMA","defineScalarTag","defineSequenceTag","defineMappingTag","mapTag","path","fs","yaml","ForwardedError","isChildPath","resolvePath","NotAllowedError","toError","getFileTreeRecursively"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,MAAM,aAAa,OAAO;AAAA,EAC/B,OAAA;AAAA,EACA,IAAA;AAAA,EACA,OAAA;AAAA,EACA,SAAA,GAAY,IAAIA,uBAAA;AAClB,CAAA,KAAyB;AACvB,EAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC3C,IAAA,MAAM,OAAA,GAAUC,wBAAA,CAAM,OAAA,EAAS,IAAA,EAAM,OAAO,CAAA;AAE5C,IAAA,OAAA,CAAQ,MAAA,CAAO,EAAA,CAAG,MAAA,EAAQ,CAAA,MAAA,KAAU;AAClC,MAAA,SAAA,CAAU,MAAM,MAAM,CAAA;AAAA,IACxB,CAAC,CAAA;AAED,IAAA,OAAA,CAAQ,MAAA,CAAO,EAAA,CAAG,MAAA,EAAQ,CAAA,MAAA,KAAU;AAClC,MAAA,SAAA,CAAU,MAAM,MAAM,CAAA;AAAA,IACxB,CAAC,CAAA;AAED,IAAA,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