@backstage/plugin-techdocs-backend 2.0.5-next.1 → 2.0.5

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,18 @@
1
1
  # @backstage/plugin-techdocs-backend
2
2
 
3
+ ## 2.0.5
4
+
5
+ ### Patch Changes
6
+
7
+ - 484e500: Updated CachedEntityLoader to use BackstageCredentials instead of raw tokens for cache key generation. It now uses principal-based identification (user entity ref for users, subject for services) instead of token-based keys, providing more consistent caching behavior.
8
+ - Updated dependencies
9
+ - @backstage/backend-defaults@0.12.0
10
+ - @backstage/catalog-client@1.11.0
11
+ - @backstage/plugin-catalog-node@1.18.0
12
+ - @backstage/backend-plugin-api@1.4.2
13
+ - @backstage/plugin-search-backend-module-techdocs@0.4.5
14
+ - @backstage/plugin-techdocs-node@1.13.6
15
+
3
16
  ## 2.0.5-next.1
4
17
 
5
18
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"BuildMetadataStorage.cjs.js","sources":["../../src/DocsBuilder/BuildMetadataStorage.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\n// Entity uid: unix timestamp\nconst lastUpdatedRecord = {} as Record<string, number>;\n\n/**\n * Store timestamps of the most recent TechDocs update of each Entity. This is\n * used to avoid checking for an update on each and every request to TechDocs.\n */\nexport class BuildMetadataStorage {\n private entityUid: string;\n private lastUpdatedRecord: Record<string, number>;\n\n constructor(entityUid: string) {\n this.entityUid = entityUid;\n this.lastUpdatedRecord = lastUpdatedRecord;\n }\n\n setLastUpdated(): void {\n this.lastUpdatedRecord[this.entityUid] = Date.now();\n }\n\n getLastUpdated(): number | undefined {\n return this.lastUpdatedRecord[this.entityUid];\n }\n}\n\n/**\n * Return false if a check for update has happened in last 60 seconds.\n */\nexport const shouldCheckForUpdate = (entityUid: string) => {\n const lastUpdated = new BuildMetadataStorage(entityUid).getLastUpdated();\n if (lastUpdated) {\n // The difference is in milliseconds\n if (Date.now() - lastUpdated < 60 * 1000) {\n return false;\n }\n }\n return true;\n};\n"],"names":[],"mappings":";;AAiBA,MAAM,oBAAoB,EAAC;AAMpB,MAAM,oBAAqB,CAAA;AAAA,EACxB,SAAA;AAAA,EACA,iBAAA;AAAA,EAER,YAAY,SAAmB,EAAA;AAC7B,IAAA,IAAA,CAAK,SAAY,GAAA,SAAA;AACjB,IAAA,IAAA,CAAK,iBAAoB,GAAA,iBAAA;AAAA;AAC3B,EAEA,cAAuB,GAAA;AACrB,IAAA,IAAA,CAAK,iBAAkB,CAAA,IAAA,CAAK,SAAS,CAAA,GAAI,KAAK,GAAI,EAAA;AAAA;AACpD,EAEA,cAAqC,GAAA;AACnC,IAAO,OAAA,IAAA,CAAK,iBAAkB,CAAA,IAAA,CAAK,SAAS,CAAA;AAAA;AAEhD;AAKa,MAAA,oBAAA,GAAuB,CAAC,SAAsB,KAAA;AACzD,EAAA,MAAM,WAAc,GAAA,IAAI,oBAAqB,CAAA,SAAS,EAAE,cAAe,EAAA;AACvE,EAAA,IAAI,WAAa,EAAA;AAEf,IAAA,IAAI,IAAK,CAAA,GAAA,EAAQ,GAAA,WAAA,GAAc,KAAK,GAAM,EAAA;AACxC,MAAO,OAAA,KAAA;AAAA;AACT;AAEF,EAAO,OAAA,IAAA;AACT;;;;;"}
1
+ {"version":3,"file":"BuildMetadataStorage.cjs.js","sources":["../../src/DocsBuilder/BuildMetadataStorage.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\n// Entity uid: unix timestamp\nconst lastUpdatedRecord = {} as Record<string, number>;\n\n/**\n * Store timestamps of the most recent TechDocs update of each Entity. This is\n * used to avoid checking for an update on each and every request to TechDocs.\n */\nexport class BuildMetadataStorage {\n private entityUid: string;\n private lastUpdatedRecord: Record<string, number>;\n\n constructor(entityUid: string) {\n this.entityUid = entityUid;\n this.lastUpdatedRecord = lastUpdatedRecord;\n }\n\n setLastUpdated(): void {\n this.lastUpdatedRecord[this.entityUid] = Date.now();\n }\n\n getLastUpdated(): number | undefined {\n return this.lastUpdatedRecord[this.entityUid];\n }\n}\n\n/**\n * Return false if a check for update has happened in last 60 seconds.\n */\nexport const shouldCheckForUpdate = (entityUid: string) => {\n const lastUpdated = new BuildMetadataStorage(entityUid).getLastUpdated();\n if (lastUpdated) {\n // The difference is in milliseconds\n if (Date.now() - lastUpdated < 60 * 1000) {\n return false;\n }\n }\n return true;\n};\n"],"names":[],"mappings":";;AAiBA,MAAM,oBAAoB,EAAC;AAMpB,MAAM,oBAAA,CAAqB;AAAA,EACxB,SAAA;AAAA,EACA,iBAAA;AAAA,EAER,YAAY,SAAA,EAAmB;AAC7B,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,iBAAA,GAAoB,iBAAA;AAAA,EAC3B;AAAA,EAEA,cAAA,GAAuB;AACrB,IAAA,IAAA,CAAK,iBAAA,CAAkB,IAAA,CAAK,SAAS,CAAA,GAAI,KAAK,GAAA,EAAI;AAAA,EACpD;AAAA,EAEA,cAAA,GAAqC;AACnC,IAAA,OAAO,IAAA,CAAK,iBAAA,CAAkB,IAAA,CAAK,SAAS,CAAA;AAAA,EAC9C;AACF;AAKO,MAAM,oBAAA,GAAuB,CAAC,SAAA,KAAsB;AACzD,EAAA,MAAM,WAAA,GAAc,IAAI,oBAAA,CAAqB,SAAS,EAAE,cAAA,EAAe;AACvE,EAAA,IAAI,WAAA,EAAa;AAEf,IAAA,IAAI,IAAA,CAAK,GAAA,EAAI,GAAI,WAAA,GAAc,KAAK,GAAA,EAAM;AACxC,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"builder.cjs.js","sources":["../../src/DocsBuilder/builder.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 */\nimport {\n DEFAULT_NAMESPACE,\n Entity,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { assertError, isError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport {\n GeneratorBase,\n GeneratorBuilder,\n getLocationForEntity,\n PreparerBase,\n PreparerBuilder,\n PublisherBase,\n} from '@backstage/plugin-techdocs-node';\nimport fs from 'fs-extra';\nimport os from 'os';\nimport path from 'path';\nimport { Writable } from 'stream';\nimport { Logger } from 'winston';\nimport { BuildMetadataStorage } from './BuildMetadataStorage';\nimport { TechDocsCache } from '../cache';\n\ntype DocsBuilderArguments = {\n preparers: PreparerBuilder;\n generators: GeneratorBuilder;\n publisher: PublisherBase;\n entity: Entity;\n logger: Logger;\n config: Config;\n scmIntegrations: ScmIntegrationRegistry;\n logStream?: Writable;\n cache?: TechDocsCache;\n};\n\nexport class DocsBuilder {\n private preparer: PreparerBase;\n private generator: GeneratorBase;\n private publisher: PublisherBase;\n private entity: Entity;\n private logger: Logger;\n private config: Config;\n private scmIntegrations: ScmIntegrationRegistry;\n private logStream: Writable | undefined;\n private cache?: TechDocsCache;\n\n constructor({\n preparers,\n generators,\n publisher,\n entity,\n logger,\n config,\n scmIntegrations,\n logStream,\n cache,\n }: DocsBuilderArguments) {\n this.preparer = preparers.get(entity);\n this.generator = generators.get(entity);\n this.publisher = publisher;\n this.entity = entity;\n this.logger = logger;\n this.config = config;\n this.scmIntegrations = scmIntegrations;\n this.logStream = logStream;\n this.cache = cache;\n }\n\n /**\n * Build the docs and return whether they have been newly generated or have been cached\n * @returns true, if the docs have been built. false, if the cached docs are still up-to-date.\n */\n public async build(): Promise<boolean> {\n if (!this.entity.metadata.uid) {\n throw new Error(\n 'Trying to build documentation for entity not in software catalog',\n );\n }\n\n /**\n * Prepare (and cache check)\n */\n\n this.logger.info(\n `Step 1 of 3: Preparing docs for entity ${stringifyEntityRef(\n this.entity,\n )}`,\n );\n\n // If available, use the etag stored in techdocs_metadata.json to\n // check if docs are outdated and need to be regenerated.\n let storedEtag: string | undefined;\n if (await this.publisher.hasDocsBeenGenerated(this.entity)) {\n try {\n storedEtag = (\n await this.publisher.fetchTechDocsMetadata({\n namespace: this.entity.metadata.namespace ?? DEFAULT_NAMESPACE,\n kind: this.entity.kind,\n name: this.entity.metadata.name,\n })\n ).etag;\n } catch (err) {\n // Proceed with a fresh build\n this.logger.warn(\n `Unable to read techdocs_metadata.json, proceeding with fresh build, error ${err}.`,\n );\n }\n }\n\n let preparedDir: string | undefined;\n let outputDir: string | undefined;\n\n try {\n let newEtag: string;\n try {\n const preparerResponse = await this.preparer.prepare(this.entity, {\n etag: storedEtag,\n logger: this.logger,\n });\n\n preparedDir = preparerResponse.preparedDir;\n newEtag = preparerResponse.etag;\n } catch (err) {\n if (isError(err) && err.name === 'NotModifiedError') {\n // No need to prepare anymore since cache is valid.\n // Set last check happened to now\n new BuildMetadataStorage(this.entity.metadata.uid).setLastUpdated();\n this.logger.debug(\n `Docs for ${stringifyEntityRef(\n this.entity,\n )} are unmodified. Using cache, skipping generate and prepare`,\n );\n return false;\n }\n throw err;\n }\n\n this.logger.info(\n `Prepare step completed for entity ${stringifyEntityRef(\n this.entity,\n )}, stored at ${preparedDir}`,\n );\n\n /**\n * Generate\n */\n\n this.logger.info(\n `Step 2 of 3: Generating docs for entity ${stringifyEntityRef(\n this.entity,\n )}`,\n );\n\n const workingDir = this.config.getOptionalString(\n 'backend.workingDirectory',\n );\n const tmpdirPath = workingDir || os.tmpdir();\n // Fixes a problem with macOS returning a path that is a symlink\n const tmpdirResolvedPath = fs.realpathSync(tmpdirPath);\n outputDir = await fs.mkdtemp(\n path.join(tmpdirResolvedPath, 'techdocs-tmp-'),\n );\n\n const parsedLocationAnnotation = getLocationForEntity(\n this.entity,\n this.scmIntegrations,\n );\n await this.generator.run({\n inputDir: preparedDir,\n outputDir,\n parsedLocationAnnotation,\n etag: newEtag,\n logger: this.logger,\n logStream: this.logStream,\n siteOptions: {\n name: this.entity.metadata.title ?? this.entity.metadata.name,\n },\n });\n\n /**\n * Publish\n */\n\n this.logger.info(\n `Step 3 of 3: Publishing docs for entity ${stringifyEntityRef(\n this.entity,\n )}`,\n );\n\n const published = await this.publisher.publish({\n entity: this.entity,\n directory: outputDir,\n });\n\n // Invalidate the cache for any published objects.\n if (this.cache && published && published?.objects?.length) {\n this.logger.debug(\n `Invalidating ${published.objects.length} cache objects`,\n );\n await this.cache.invalidateMultiple(published.objects);\n }\n } finally {\n // Remove Prepared directory since it is no longer needed.\n // Caveat: Can not remove prepared directory in case of git preparer since the\n // local git repository is used to get etag on subsequent requests.\n if (preparedDir && this.preparer.shouldCleanPreparedDirectory()) {\n this.logger.debug(`Removing prepared directory ${preparedDir}`);\n try {\n // Not a blocker hence no need to await this.\n fs.remove(preparedDir);\n } catch (error) {\n assertError(error);\n this.logger.debug(\n `Error removing prepared directory ${error.message}`,\n );\n }\n }\n\n if (outputDir) {\n this.logger.debug(`Removing generated directory ${outputDir}`);\n try {\n // Not a blocker hence no need to await this.\n fs.remove(outputDir);\n } catch (error) {\n assertError(error);\n this.logger.debug(\n `Error removing generated directory ${error.message}`,\n );\n }\n }\n }\n\n // Update the last check time for the entity\n new BuildMetadataStorage(this.entity.metadata.uid).setLastUpdated();\n\n return true;\n }\n}\n"],"names":["stringifyEntityRef","DEFAULT_NAMESPACE","isError","BuildMetadataStorage","os","fs","path","getLocationForEntity","assertError"],"mappings":";;;;;;;;;;;;;;;;AAmDO,MAAM,WAAY,CAAA;AAAA,EACf,QAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,eAAA;AAAA,EACA,SAAA;AAAA,EACA,KAAA;AAAA,EAER,WAAY,CAAA;AAAA,IACV,SAAA;AAAA,IACA,UAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,eAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACuB,EAAA;AACvB,IAAK,IAAA,CAAA,QAAA,GAAW,SAAU,CAAA,GAAA,CAAI,MAAM,CAAA;AACpC,IAAK,IAAA,CAAA,SAAA,GAAY,UAAW,CAAA,GAAA,CAAI,MAAM,CAAA;AACtC,IAAA,IAAA,CAAK,SAAY,GAAA,SAAA;AACjB,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAA,IAAA,CAAK,eAAkB,GAAA,eAAA;AACvB,IAAA,IAAA,CAAK,SAAY,GAAA,SAAA;AACjB,IAAA,IAAA,CAAK,KAAQ,GAAA,KAAA;AAAA;AACf;AAAA;AAAA;AAAA;AAAA,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A,IAAI,SAAW,EAAA;AACb,QAAA,IAAA,CAAK,MAAO,CAAA,KAAA,CAAM,CAAgC,6BAAA,EAAA,SAAS,CAAE,CAAA,CAAA;AAC7D,QAAI,IAAA;AAEF,UAAAH,mBAAA,CAAG,OAAO,SAAS,CAAA;AAAA,iBACZ,KAAO,EAAA;AACd,UAAAG,kBAAA,CAAY,KAAK,CAAA;AACjB,UAAA,IAAA,CAAK,MAAO,CAAA,KAAA;AAAA,YACV,CAAA,mCAAA,EAAsC,MAAM,OAAO,CAAA;AAAA,WACrD;AAAA;AACF;AACF;AAIF,IAAA,IAAIL,0CAAqB,IAAK,CAAA,MAAA,CAAO,QAAS,CAAA,GAAG,EAAE,cAAe,EAAA;AAElE,IAAO,OAAA,IAAA;AAAA;AAEX;;;;"}
1
+ {"version":3,"file":"builder.cjs.js","sources":["../../src/DocsBuilder/builder.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 */\nimport {\n DEFAULT_NAMESPACE,\n Entity,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { assertError, isError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport {\n GeneratorBase,\n GeneratorBuilder,\n getLocationForEntity,\n PreparerBase,\n PreparerBuilder,\n PublisherBase,\n} from '@backstage/plugin-techdocs-node';\nimport fs from 'fs-extra';\nimport os from 'os';\nimport path from 'path';\nimport { Writable } from 'stream';\nimport { Logger } from 'winston';\nimport { BuildMetadataStorage } from './BuildMetadataStorage';\nimport { TechDocsCache } from '../cache';\n\ntype DocsBuilderArguments = {\n preparers: PreparerBuilder;\n generators: GeneratorBuilder;\n publisher: PublisherBase;\n entity: Entity;\n logger: Logger;\n config: Config;\n scmIntegrations: ScmIntegrationRegistry;\n logStream?: Writable;\n cache?: TechDocsCache;\n};\n\nexport class DocsBuilder {\n private preparer: PreparerBase;\n private generator: GeneratorBase;\n private publisher: PublisherBase;\n private entity: Entity;\n private logger: Logger;\n private config: Config;\n private scmIntegrations: ScmIntegrationRegistry;\n private logStream: Writable | undefined;\n private cache?: TechDocsCache;\n\n constructor({\n preparers,\n generators,\n publisher,\n entity,\n logger,\n config,\n scmIntegrations,\n logStream,\n cache,\n }: DocsBuilderArguments) {\n this.preparer = preparers.get(entity);\n this.generator = generators.get(entity);\n this.publisher = publisher;\n this.entity = entity;\n this.logger = logger;\n this.config = config;\n this.scmIntegrations = scmIntegrations;\n this.logStream = logStream;\n this.cache = cache;\n }\n\n /**\n * Build the docs and return whether they have been newly generated or have been cached\n * @returns true, if the docs have been built. false, if the cached docs are still up-to-date.\n */\n public async build(): Promise<boolean> {\n if (!this.entity.metadata.uid) {\n throw new Error(\n 'Trying to build documentation for entity not in software catalog',\n );\n }\n\n /**\n * Prepare (and cache check)\n */\n\n this.logger.info(\n `Step 1 of 3: Preparing docs for entity ${stringifyEntityRef(\n this.entity,\n )}`,\n );\n\n // If available, use the etag stored in techdocs_metadata.json to\n // check if docs are outdated and need to be regenerated.\n let storedEtag: string | undefined;\n if (await this.publisher.hasDocsBeenGenerated(this.entity)) {\n try {\n storedEtag = (\n await this.publisher.fetchTechDocsMetadata({\n namespace: this.entity.metadata.namespace ?? DEFAULT_NAMESPACE,\n kind: this.entity.kind,\n name: this.entity.metadata.name,\n })\n ).etag;\n } catch (err) {\n // Proceed with a fresh build\n this.logger.warn(\n `Unable to read techdocs_metadata.json, proceeding with fresh build, error ${err}.`,\n );\n }\n }\n\n let preparedDir: string | undefined;\n let outputDir: string | undefined;\n\n try {\n let newEtag: string;\n try {\n const preparerResponse = await this.preparer.prepare(this.entity, {\n etag: storedEtag,\n logger: this.logger,\n });\n\n preparedDir = preparerResponse.preparedDir;\n newEtag = preparerResponse.etag;\n } catch (err) {\n if (isError(err) && err.name === 'NotModifiedError') {\n // No need to prepare anymore since cache is valid.\n // Set last check happened to now\n new BuildMetadataStorage(this.entity.metadata.uid).setLastUpdated();\n this.logger.debug(\n `Docs for ${stringifyEntityRef(\n this.entity,\n )} are unmodified. Using cache, skipping generate and prepare`,\n );\n return false;\n }\n throw err;\n }\n\n this.logger.info(\n `Prepare step completed for entity ${stringifyEntityRef(\n this.entity,\n )}, stored at ${preparedDir}`,\n );\n\n /**\n * Generate\n */\n\n this.logger.info(\n `Step 2 of 3: Generating docs for entity ${stringifyEntityRef(\n this.entity,\n )}`,\n );\n\n const workingDir = this.config.getOptionalString(\n 'backend.workingDirectory',\n );\n const tmpdirPath = workingDir || os.tmpdir();\n // Fixes a problem with macOS returning a path that is a symlink\n const tmpdirResolvedPath = fs.realpathSync(tmpdirPath);\n outputDir = await fs.mkdtemp(\n path.join(tmpdirResolvedPath, 'techdocs-tmp-'),\n );\n\n const parsedLocationAnnotation = getLocationForEntity(\n this.entity,\n this.scmIntegrations,\n );\n await this.generator.run({\n inputDir: preparedDir,\n outputDir,\n parsedLocationAnnotation,\n etag: newEtag,\n logger: this.logger,\n logStream: this.logStream,\n siteOptions: {\n name: this.entity.metadata.title ?? this.entity.metadata.name,\n },\n });\n\n /**\n * Publish\n */\n\n this.logger.info(\n `Step 3 of 3: Publishing docs for entity ${stringifyEntityRef(\n this.entity,\n )}`,\n );\n\n const published = await this.publisher.publish({\n entity: this.entity,\n directory: outputDir,\n });\n\n // Invalidate the cache for any published objects.\n if (this.cache && published && published?.objects?.length) {\n this.logger.debug(\n `Invalidating ${published.objects.length} cache objects`,\n );\n await this.cache.invalidateMultiple(published.objects);\n }\n } finally {\n // Remove Prepared directory since it is no longer needed.\n // Caveat: Can not remove prepared directory in case of git preparer since the\n // local git repository is used to get etag on subsequent requests.\n if (preparedDir && this.preparer.shouldCleanPreparedDirectory()) {\n this.logger.debug(`Removing prepared directory ${preparedDir}`);\n try {\n // Not a blocker hence no need to await this.\n fs.remove(preparedDir);\n } catch (error) {\n assertError(error);\n this.logger.debug(\n `Error removing prepared directory ${error.message}`,\n );\n }\n }\n\n if (outputDir) {\n this.logger.debug(`Removing generated directory ${outputDir}`);\n try {\n // Not a blocker hence no need to await this.\n fs.remove(outputDir);\n } catch (error) {\n assertError(error);\n this.logger.debug(\n `Error removing generated directory ${error.message}`,\n );\n }\n }\n }\n\n // Update the last check time for the entity\n new BuildMetadataStorage(this.entity.metadata.uid).setLastUpdated();\n\n return true;\n }\n}\n"],"names":["stringifyEntityRef","DEFAULT_NAMESPACE","isError","BuildMetadataStorage","os","fs","path","getLocationForEntity","assertError"],"mappings":";;;;;;;;;;;;;;;;AAmDO,MAAM,WAAA,CAAY;AAAA,EACf,QAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,eAAA;AAAA,EACA,SAAA;AAAA,EACA,KAAA;AAAA,EAER,WAAA,CAAY;AAAA,IACV,SAAA;AAAA,IACA,UAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,eAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF,EAAyB;AACvB,IAAA,IAAA,CAAK,QAAA,GAAW,SAAA,CAAU,GAAA,CAAI,MAAM,CAAA;AACpC,IAAA,IAAA,CAAK,SAAA,GAAY,UAAA,CAAW,GAAA,CAAI,MAAM,CAAA;AACtC,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,eAAA,GAA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A;AAAA,QACvB,SAAS,KAAA,EAAO;AACd,UAAAG,kBAAA,CAAY,KAAK,CAAA;AACjB,UAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,YACV,CAAA,kCAAA,EAAqC,MAAM,OAAO,CAAA;AAAA,WACpD;AAAA,QACF;AAAA,MACF;AAEA,MAAA,IAAI,SAAA,EAAW;AACb,QAAA,IAAA,CAAK,MAAA,CAAO,KAAA,CAAM,CAAA,6BAAA,EAAgC,SAAS,CAAA,CAAE,CAAA;AAC7D,QAAA,IAAI;AAEF,UAAAH,mBAAA,CAAG,OAAO,SAAS,CAAA;AAAA,QACrB,SAAS,KAAA,EAAO;AACd,UAAAG,kBAAA,CAAY,KAAK,CAAA;AACjB,UAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,YACV,CAAA,mCAAA,EAAsC,MAAM,OAAO,CAAA;AAAA,WACrD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,IAAA,IAAIL,0CAAqB,IAAA,CAAK,MAAA,CAAO,QAAA,CAAS,GAAG,EAAE,cAAA,EAAe;AAElE,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"alpha.cjs.js","sources":["../src/alpha.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 */\n\nimport { techdocsPlugin } from './plugin';\n\n/** @alpha */\nconst _feature = techdocsPlugin;\nexport default _feature;\n"],"names":["techdocsPlugin"],"mappings":";;;;;;AAmBA,MAAM,QAAW,GAAAA;;;;"}
1
+ {"version":3,"file":"alpha.cjs.js","sources":["../src/alpha.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 */\n\nimport { techdocsPlugin } from './plugin';\n\n/** @alpha */\nconst _feature = techdocsPlugin;\nexport default _feature;\n"],"names":["techdocsPlugin"],"mappings":";;;;;;AAmBA,MAAM,QAAA,GAAWA;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"TechDocsCache.cjs.js","sources":["../../src/cache/TechDocsCache.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { assertError, CustomErrorBase } from '@backstage/errors';\nimport { Config } from '@backstage/config';\nimport { CacheService, LoggerService } from '@backstage/backend-plugin-api';\n\nexport class CacheInvalidationError extends CustomErrorBase {}\n\nexport class TechDocsCache {\n protected readonly cache: CacheService;\n protected readonly logger: LoggerService;\n protected readonly readTimeout: number;\n\n private constructor({\n cache,\n logger,\n readTimeout,\n }: {\n cache: CacheService;\n logger: LoggerService;\n readTimeout: number;\n }) {\n this.cache = cache;\n this.logger = logger;\n this.readTimeout = readTimeout;\n }\n\n static fromConfig(\n config: Config,\n { cache, logger }: { cache: CacheService; logger: LoggerService },\n ) {\n const timeout = config.getOptionalNumber('techdocs.cache.readTimeout');\n const readTimeout = timeout === undefined ? 1000 : timeout;\n return new TechDocsCache({ cache, logger, readTimeout });\n }\n\n async get(path: string): Promise<Buffer | undefined> {\n try {\n // Promise.race ensures we don't hang the client for long if the cache is\n // temporarily unreachable.\n const response = (await Promise.race([\n this.cache.get(path),\n new Promise(cancelAfter => setTimeout(cancelAfter, this.readTimeout)),\n ])) as string | undefined;\n\n if (response !== undefined) {\n this.logger.debug(`Cache hit: ${path}`);\n return Buffer.from(response, 'base64');\n }\n\n this.logger.debug(`Cache miss: ${path}`);\n return response;\n } catch (e) {\n assertError(e);\n this.logger.warn(`Error getting cache entry ${path}: ${e.message}`);\n this.logger.debug(e.message, e);\n return undefined;\n }\n }\n\n async set(path: string, data: Buffer): Promise<void> {\n this.logger.debug(`Writing cache entry for ${path}`);\n this.cache\n .set(path, data.toString('base64'))\n .catch(e => this.logger.error('write error', e));\n }\n\n async invalidate(path: string): Promise<void> {\n return this.cache.delete(path);\n }\n\n async invalidateMultiple(\n paths: string[],\n ): Promise<PromiseSettledResult<void>[]> {\n const settled = await Promise.allSettled(\n paths.map(path => this.cache.delete(path)),\n );\n const rejected = settled.filter(\n s => s.status === 'rejected',\n ) as PromiseRejectedResult[];\n\n if (rejected.length) {\n throw new CacheInvalidationError(\n 'TechDocs cache invalidation error',\n rejected,\n );\n }\n\n return settled;\n }\n}\n"],"names":["CustomErrorBase","assertError"],"mappings":";;;;AAmBO,MAAM,+BAA+BA,sBAAgB,CAAA;AAAC;AAEtD,MAAM,aAAc,CAAA;AAAA,EACN,KAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAAA,EAEX,WAAY,CAAA;AAAA,IAClB,KAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GAKC,EAAA;AACD,IAAA,IAAA,CAAK,KAAQ,GAAA,KAAA;AACb,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAA,IAAA,CAAK,WAAc,GAAA,WAAA;AAAA;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M,GAAI,CAAA,IAAA,EAAc,IAA6B,EAAA;AACnD,IAAA,IAAA,CAAK,MAAO,CAAA,KAAA,CAAM,CAA2B,wBAAA,EAAA,IAAI,CAAE,CAAA,CAAA;AACnD,IAAA,IAAA,CAAK,KACF,CAAA,GAAA,CAAI,IAAM,EAAA,IAAA,CAAK,SAAS,QAAQ,CAAC,CACjC,CAAA,KAAA,CAAM,OAAK,IAAK,CAAA,MAAA,CAAO,KAAM,CAAA,aAAA,EAAe,CAAC,CAAC,CAAA;AAAA;AACnD,EAEA,MAAM,WAAW,IAA6B,EAAA;AAC5C,IAAO,OAAA,IAAA,CAAK,KAAM,CAAA,MAAA,CAAO,IAAI,CAAA;AAAA;AAC/B,EAEA,MAAM,mBACJ,KACuC,EAAA;AACvC,IAAM,MAAA,OAAA,GAAU,MAAM,OAAQ,CAAA,UAAA;AAAA,MAC5B,MAAM,GAAI,CAAA,CAAA,IAAA,KAAQ,KAAK,KAAM,CAAA,MAAA,CAAO,IAAI,CAAC;AAAA,KAC3C;AACA,IAAA,MAAM,WAAW,OAAQ,CAAA,MAAA;AAAA,MACvB,CAAA,CAAA,KAAK,EAAE,MAAW,KAAA;AAAA,KACpB;AAEA,IAAA,IAAI,SAAS,MAAQ,EAAA;AACnB,MAAA,MAAM,IAAI,sBAAA;AAAA,QACR,mCAAA;AAAA,QACA;AAAA,OACF;AAAA;AAGF,IAAO,OAAA,OAAA;AAAA;AAEX;;;;;"}
1
+ {"version":3,"file":"TechDocsCache.cjs.js","sources":["../../src/cache/TechDocsCache.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { assertError, CustomErrorBase } from '@backstage/errors';\nimport { Config } from '@backstage/config';\nimport { CacheService, LoggerService } from '@backstage/backend-plugin-api';\n\nexport class CacheInvalidationError extends CustomErrorBase {}\n\nexport class TechDocsCache {\n protected readonly cache: CacheService;\n protected readonly logger: LoggerService;\n protected readonly readTimeout: number;\n\n private constructor({\n cache,\n logger,\n readTimeout,\n }: {\n cache: CacheService;\n logger: LoggerService;\n readTimeout: number;\n }) {\n this.cache = cache;\n this.logger = logger;\n this.readTimeout = readTimeout;\n }\n\n static fromConfig(\n config: Config,\n { cache, logger }: { cache: CacheService; logger: LoggerService },\n ) {\n const timeout = config.getOptionalNumber('techdocs.cache.readTimeout');\n const readTimeout = timeout === undefined ? 1000 : timeout;\n return new TechDocsCache({ cache, logger, readTimeout });\n }\n\n async get(path: string): Promise<Buffer | undefined> {\n try {\n // Promise.race ensures we don't hang the client for long if the cache is\n // temporarily unreachable.\n const response = (await Promise.race([\n this.cache.get(path),\n new Promise(cancelAfter => setTimeout(cancelAfter, this.readTimeout)),\n ])) as string | undefined;\n\n if (response !== undefined) {\n this.logger.debug(`Cache hit: ${path}`);\n return Buffer.from(response, 'base64');\n }\n\n this.logger.debug(`Cache miss: ${path}`);\n return response;\n } catch (e) {\n assertError(e);\n this.logger.warn(`Error getting cache entry ${path}: ${e.message}`);\n this.logger.debug(e.message, e);\n return undefined;\n }\n }\n\n async set(path: string, data: Buffer): Promise<void> {\n this.logger.debug(`Writing cache entry for ${path}`);\n this.cache\n .set(path, data.toString('base64'))\n .catch(e => this.logger.error('write error', e));\n }\n\n async invalidate(path: string): Promise<void> {\n return this.cache.delete(path);\n }\n\n async invalidateMultiple(\n paths: string[],\n ): Promise<PromiseSettledResult<void>[]> {\n const settled = await Promise.allSettled(\n paths.map(path => this.cache.delete(path)),\n );\n const rejected = settled.filter(\n s => s.status === 'rejected',\n ) as PromiseRejectedResult[];\n\n if (rejected.length) {\n throw new CacheInvalidationError(\n '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ACnB,MAAA,MAAM,IAAI,sBAAA;AAAA,QACR,mCAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAEA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"cacheMiddleware.cjs.js","sources":["../../src/cache/cacheMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { Router } from 'express';\nimport router from 'express-promise-router';\nimport { TechDocsCache } from './TechDocsCache';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\ntype CacheMiddlewareOptions = {\n cache: TechDocsCache;\n logger: LoggerService;\n};\n\ntype ErrorCallback = (err?: Error) => void;\n\nexport const createCacheMiddleware = ({\n cache,\n}: CacheMiddlewareOptions): Router => {\n const cacheMiddleware = router();\n\n // Middleware that, through socket monkey patching, captures responses as\n // they're sent over /static/docs/* and caches them. Subsequent requests are\n // loaded from cache. Cache key is the object's path (after `/static/docs/`).\n cacheMiddleware.use(async (req, res, next) => {\n const socket = res.socket;\n const isCacheable = req.path.startsWith('/static/docs/');\n const isGetRequest = req.method === 'GET';\n\n // Continue early if this is non-cacheable, or there's no socket.\n if (!isCacheable || !socket) {\n next();\n return;\n }\n\n // Make concrete references to these things.\n const reqPath = decodeURI(req.path.match(/\\/static\\/docs\\/(.*)$/)![1]);\n const realEnd = socket.end.bind(socket);\n const realWrite = socket.write.bind(socket);\n let writeToCache = true;\n const chunks: Buffer[] = [];\n\n // Monkey-patch the response's socket to keep track of chunks as they are\n // written over the wire.\n socket.write = (\n data: string | Uint8Array,\n encoding?: BufferEncoding | ErrorCallback,\n callback?: ErrorCallback,\n ) => {\n // This cast is obviously weird, but it covers a type bug in @types/node\n // which does not gracefully handle union types.\n chunks.push(\n typeof data === 'string' ? Buffer.from(data) : Buffer.from(data),\n );\n if (typeof encoding === 'function') {\n return realWrite(data, encoding);\n }\n return realWrite(data, encoding, callback);\n };\n\n // When a socket is closed, if there were no errors and the data written\n // over the socket should be cached, cache it!\n socket.on('close', async hadError => {\n const content = Buffer.concat(chunks);\n const head = content.toString('utf8', 0, 12);\n if (\n isGetRequest &&\n writeToCache &&\n !hadError &&\n head.match(/HTTP\\/\\d\\.\\d 200/)\n ) {\n await cache.set(reqPath, content);\n }\n });\n\n // Attempt to retrieve data from the cache.\n const cached = await cache.get(reqPath);\n\n // If there is a cache hit, write it out on the socket, ensure we don't re-\n // cache the data, and prevent going back to canonical storage by never\n // calling next().\n if (cached) {\n writeToCache = false;\n realEnd(cached);\n return;\n }\n\n // No data retrieved from cache: allow retrieval from canonical storage.\n next();\n });\n\n return cacheMiddleware;\n};\n"],"names":["router"],"mappings":";;;;;;;;AA2BO,MAAM,wBAAwB,CAAC;AAAA,EACpC;AACF,CAAsC,KAAA;AACpC,EAAA,MAAM,kBAAkBA,uBAAO,EAAA;AAK/B,EAAA,eAAA,CAAgB,GAAI,CAAA,OAAO,GAAK,EAAA,GAAA,EAAK,IAAS,KAAA;AAC5C,IAAA,MAAM,SAAS,GAAI,CAAA,MAAA;AACnB,IAAA,MAAM,WAAc,GAAA,GAAA,CAAI,IAAK,CAAA,UAAA,CAAW,eAAe,CAAA;AACvD,IAAM,MAAA,YAAA,GAAe,IAAI,MAAW,KAAA,KAAA;AAGpC,IAAI,IAAA,CAAC,WAAe,IAAA,CAAC,MAAQ,EAAA;AAC3B,MAAK,IAAA,EAAA;AACL,MAAA;AAAA;AAIF,IAAM,MAAA,OAAA,GAAU,UAAU,GAAI,CAAA,IAAA,CAAK,MAAM,uBAAuB,CAAA,CAAG,CAAC,CAAC,CAAA;AAC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A,GACN,CAAA;AAED,EAAO,OAAA,eAAA;AACT;;;;"}
1
+ {"version":3,"file":"cacheMiddleware.cjs.js","sources":["../../src/cache/cacheMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { Router } from 'express';\nimport router from 'express-promise-router';\nimport { TechDocsCache } from './TechDocsCache';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\ntype CacheMiddlewareOptions = {\n cache: TechDocsCache;\n logger: LoggerService;\n};\n\ntype ErrorCallback = (err?: Error) => void;\n\nexport const createCacheMiddleware = ({\n cache,\n}: CacheMiddlewareOptions): Router => {\n const cacheMiddleware = router();\n\n // Middleware that, through socket monkey patching, captures responses as\n // they're sent over /static/docs/* and caches them. Subsequent requests are\n // loaded from cache. Cache key is the object's path (after `/static/docs/`).\n cacheMiddleware.use(async (req, res, next) => {\n const socket = res.socket;\n const isCacheable = req.path.startsWith('/static/docs/');\n const isGetRequest = req.method === 'GET';\n\n // Continue early if this is non-cacheable, or there's no socket.\n if (!isCacheable || !socket) {\n next();\n return;\n }\n\n // Make concrete references to these things.\n const reqPath = decodeURI(req.path.match(/\\/static\\/docs\\/(.*)$/)![1]);\n const realEnd = socket.end.bind(socket);\n const realWrite = socket.write.bind(socket);\n let writeToCache = true;\n const chunks: Buffer[] = [];\n\n // Monkey-patch the response's socket to keep track of chunks as they are\n // written over the wire.\n socket.write = (\n data: string | Uint8Array,\n encoding?: BufferEncoding | ErrorCallback,\n callback?: ErrorCallback,\n ) => {\n // This cast is obviously weird, but it covers a type bug in @types/node\n // which does not gracefully handle union types.\n chunks.push(\n typeof data === 'string' ? Buffer.from(data) : Buffer.from(data),\n );\n if (typeof encoding === 'function') {\n return realWrite(data, encoding);\n }\n return realWrite(data, encoding, callback);\n };\n\n // When a socket is closed, if there were no errors and the data written\n // over the socket should be cached, cache it!\n socket.on('close', async hadError => {\n const content = Buffer.concat(chunks);\n const head = content.toString('utf8', 0, 12);\n if (\n isGetRequest &&\n writeToCache &&\n !hadError &&\n head.match(/HTTP\\/\\d\\.\\d 200/)\n ) {\n await cache.set(reqPath, content);\n }\n });\n\n // Attempt to retrieve data from the cache.\n const cached = await cache.get(reqPath);\n\n // If there is a cache hit, write it out on the socket, ensure we don't re-\n // cache the data, and prevent going back to canonical storage by never\n // calling next().\n if (cached) {\n writeToCache = false;\n realEnd(cached);\n return;\n }\n\n // No data retrieved from cache: allow retrieval from canonical storage.\n next();\n });\n\n return cacheMiddleware;\n};\n"],"names":["router"],"mappings":";;;;;;;;AA2BO,MAAM,wBAAwB,CAAC;AAAA,EACpC;AACF,CAAA,KAAsC;AACpC,EAAA,MAAM,kBAAkBA,uBAAA,EAAO;AAK/B,EAAA,eAAA,CAAgB,GAAA,CAAI,OAAO,GAAA,EAAK,GAAA,EAAK,IAAA,KAAS;AAC5C,IAAA,MAAM,SAAS,GAAA,CAAI,MAAA;AACnB,IAAA,MAAM,WAAA,GAAc,GAAA,CAAI,IAAA,CAAK,UAAA,CAAW,eAAe,CAAA;AACvD,IAAA,MAAM,YAAA,GAAe,IAAI,MAAA,KAAW,KAAA;AAGpC,IAAA,IAAI,CAAC,WAAA,IAAe,CAAC,MAAA,EAAQ;AAC3B,MAAA,IAAA,EAAK;AACL,MAAA;AAAA,IACF;AAGA,IAAA,MAAM,OAAA,GAAU,UAAU,GAAA,CAAI,IAAA,CAAK,MAAM,uBAAuB,CAAA,CAAG,CAAC,CAAC,CAAA;AACrE,IAAA,MAAM,OAAA,GAAU,MAAA,CAAO,GAAA,CAAI,IAAA,CAAK,MAAM,CAAA;AACtC,IAAA,M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1 @@
1
- {"version":3,"file":"plugin.cjs.js","sources":["../src/plugin.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 */\n\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport {\n DocsBuildStrategy,\n Generators,\n PreparerBase,\n Preparers,\n Publisher,\n PublisherBase,\n PublisherSettings,\n PublisherType,\n RemoteProtocol,\n techdocsBuildsExtensionPoint,\n TechdocsGenerator,\n techdocsGeneratorExtensionPoint,\n techdocsPreparerExtensionPoint,\n techdocsPublisherExtensionPoint,\n} from '@backstage/plugin-techdocs-node';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\nimport * as winston from 'winston';\nimport { createRouter } from './service/router';\n\n/**\n * The TechDocs plugin is responsible for serving and building documentation for any entity.\n * @public\n */\nexport const techdocsPlugin = createBackendPlugin({\n pluginId: 'techdocs',\n register(env) {\n let docsBuildStrategy: DocsBuildStrategy | undefined;\n let buildLogTransport: winston.transport | undefined;\n env.registerExtensionPoint(techdocsBuildsExtensionPoint, {\n setBuildStrategy(buildStrategy: DocsBuildStrategy) {\n if (docsBuildStrategy) {\n throw new Error('DocsBuildStrategy may only be set once');\n }\n docsBuildStrategy = buildStrategy;\n },\n setBuildLogTransport(transport: winston.transport) {\n if (buildLogTransport) {\n throw new Error('BuildLogTransport may only be set once');\n }\n buildLogTransport = transport;\n },\n });\n\n let customTechdocsGenerator: TechdocsGenerator | undefined;\n env.registerExtensionPoint(techdocsGeneratorExtensionPoint, {\n setTechdocsGenerator(generator: TechdocsGenerator) {\n if (customTechdocsGenerator) {\n throw new Error('TechdocsGenerator may only be set once');\n }\n\n customTechdocsGenerator = generator;\n },\n });\n\n const customPreparers = new Map<RemoteProtocol, PreparerBase>();\n env.registerExtensionPoint(techdocsPreparerExtensionPoint, {\n registerPreparer(protocol: RemoteProtocol, preparer: PreparerBase) {\n if (customPreparers.has(protocol)) {\n throw new Error(\n `Preparer for protocol ${protocol} is already registered`,\n );\n }\n customPreparers.set(protocol, preparer);\n },\n });\n\n let customTechdocsPublisher: PublisherBase | undefined;\n const publisherSettings: PublisherSettings = {};\n env.registerExtensionPoint(techdocsPublisherExtensionPoint, {\n registerPublisher(type: PublisherType, publisher: PublisherBase) {\n if (customTechdocsPublisher) {\n throw new Error(`Publisher for type ${type} is already registered`);\n }\n customTechdocsPublisher = publisher;\n },\n registerPublisherSettings<T extends keyof PublisherSettings>(\n publisher: T,\n settings: PublisherSettings[T],\n ) {\n publisherSettings[publisher] = settings;\n },\n });\n\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.logger,\n urlReader: coreServices.urlReader,\n http: coreServices.httpRouter,\n discovery: coreServices.discovery,\n cache: coreServices.cache,\n httpAuth: coreServices.httpAuth,\n auth: coreServices.auth,\n catalog: catalogServiceRef,\n },\n async init({\n config,\n logger,\n urlReader,\n http,\n discovery,\n cache,\n httpAuth,\n auth,\n catalog,\n }) {\n // Preparers are responsible for fetching source files for documentation.\n const preparers = await Preparers.fromConfig(config, {\n reader: urlReader,\n logger: logger,\n });\n for (const [protocol, preparer] of customPreparers.entries()) {\n preparers.register(protocol, preparer);\n }\n\n // Generators are used for generating documentation sites.\n const generators = await Generators.fromConfig(config, {\n logger: logger,\n customGenerator: customTechdocsGenerator,\n });\n\n // Publisher is used for\n // 1. Publishing generated files to storage\n // 2. Fetching files from storage and passing them to TechDocs frontend.\n const publisher = await Publisher.fromConfig(config, {\n logger: logger,\n discovery: discovery,\n customPublisher: customTechdocsPublisher,\n publisherSettings,\n });\n\n // checks if the publisher is working and logs the result\n await publisher.getReadiness();\n\n http.use(\n await createRouter({\n logger: logger,\n cache,\n docsBuildStrategy,\n buildLogTransport,\n preparers,\n generators,\n publisher,\n config,\n discovery,\n httpAuth,\n auth,\n catalogClient: catalog,\n }),\n );\n\n http.addAuthPolicy({\n path: '/static',\n allow: 'user-cookie',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","techdocsBuildsExtensionPoint","techdocsGeneratorExtensionPoint","techdocsPreparerExtensionPoint","techdocsPublisherExtensionPoint","coreServices","catalogServiceRef","Preparers","Generators","Publisher","createRouter"],"mappings":";;;;;;;AA4CO,MAAM,iBAAiBA,oCAAoB,CAAA;AAAA,EAChD,QAAU,EAAA,UAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAI,IAAA,iBAAA;AACJ,IAAI,IAAA,iBAAA;AACJ,IAAA,GAAA,CAAI,uBAAuBC,+CAA8B,EAAA;AAAA,MACvD,iBAAiB,aAAkC,EAAA;AACjD,QAAA,IAAI,iBAAmB,EAAA;AACrB,UAAM,MAAA,IAAI,MAAM,wCAAwC,CAAA;AAAA;AAE1D,QAAoB,iBAAA,GAAA,aAAA;AAAA,OACtB;AAAA,MACA,qBAAqB,SAA8B,EAAA;AACjD,QAAA,IAAI,iBAAmB,EAAA;AACrB,UAAM,MAAA,IAAI,MAAM,wCAAwC,CAAA;AAAA;AAE1D,QAAoB,iBAAA,GAAA,SAAA;AAAA;AACtB,KACD,CAAA;AAED,IAAI,IAAA,uBAAA;AACJ,IAAA,GAAA,CAAI,uBAAuBC,kDAAiC,EAAA;AAAA,MAC1D,qBAAqB,SAA8B,EAAA;AACjD,QAAA,IAAI,uBAAyB,EAAA;AAC3B,UAAM,MAAA,IAAI,MAAM,wCAAwC,CAAA;AAAA;AAG1D,QAA0B,uBAAA,GAAA,SAAA;AAAA;AAC5B,KACD,CAAA;AAED,IAAM,MAAA,eAAA,uBAAsB,GAAkC,EAAA;AAC9D,IAAA,GAAA,CAAI,uBAAuBC,iDAAgC,EA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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 {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport {\n DocsBuildStrategy,\n Generators,\n PreparerBase,\n Preparers,\n Publisher,\n PublisherBase,\n PublisherSettings,\n PublisherType,\n RemoteProtocol,\n techdocsBuildsExtensionPoint,\n TechdocsGenerator,\n techdocsGeneratorExtensionPoint,\n techdocsPreparerExtensionPoint,\n techdocsPublisherExtensionPoint,\n} from '@backstage/plugin-techdocs-node';\nimport { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha';\nimport * as winston from 'winston';\nimport { createRouter } from './service/router';\n\n/**\n * The TechDocs plugin is responsible for serving and building documentation for any entity.\n * @public\n */\nexport const techdocsPlugin = createBackendPlugin({\n pluginId: 'techdocs',\n register(env) {\n let docsBuildStrategy: DocsBuildStrategy | undefined;\n let buildLogTransport: winston.transport | undefined;\n env.registerExtensionPoint(techdocsBuildsExtensionPoint, {\n setBuildStrategy(buildStrategy: DocsBuildStrategy) {\n if (docsBuildStrategy) {\n throw new Error('DocsBuildStrategy may only be set once');\n }\n docsBuildStrategy = buildStrategy;\n },\n setBuildLogTransport(transport: winston.transport) {\n if (buildLogTransport) {\n throw new Error('BuildLogTransport may only be set once');\n }\n buildLogTransport = transport;\n },\n });\n\n let customTechdocsGenerator: TechdocsGenerator | undefined;\n env.registerExtensionPoint(techdocsGeneratorExtensionPoint, {\n setTechdocsGenerator(generator: TechdocsGenerator) {\n if (customTechdocsGenerator) {\n throw new Error('TechdocsGenerator may only be set once');\n }\n\n customTechdocsGenerator = generator;\n },\n });\n\n const customPreparers = new Map<RemoteProtocol, PreparerBase>();\n env.registerExtensionPoint(techdocsPreparerExtensionPoint, {\n registerPreparer(protocol: RemoteProtocol, preparer: PreparerBase) {\n if (customPreparers.has(protocol)) {\n throw new Error(\n `Preparer for protocol ${protocol} is already registered`,\n );\n }\n customPreparers.set(protocol, preparer);\n },\n });\n\n let customTechdocsPublisher: PublisherBase | undefined;\n const publisherSettings: PublisherSettings = {};\n env.registerExtensionPoint(techdocsPublisherExtensionPoint, {\n registerPublisher(type: PublisherType, publisher: PublisherBase) {\n if (customTechdocsPublisher) {\n throw new Error(`Publisher for type ${type} is already registered`);\n }\n customTechdocsPublisher = publisher;\n },\n registerPublisherSettings<T extends keyof PublisherSettings>(\n publisher: T,\n settings: PublisherSettings[T],\n ) {\n publisherSettings[publisher] = settings;\n },\n });\n\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.logger,\n urlReader: coreServices.urlReader,\n http: coreServices.httpRouter,\n discovery: coreServices.discovery,\n cache: coreServices.cache,\n httpAuth: coreServices.httpAuth,\n auth: coreServices.auth,\n catalog: catalogServiceRef,\n },\n async init({\n config,\n logger,\n urlReader,\n http,\n discovery,\n cache,\n httpAuth,\n auth,\n catalog,\n }) {\n // Preparers are responsible for fetching source files for documentation.\n const preparers = await Preparers.fromConfig(config, {\n reader: urlReader,\n logger: logger,\n });\n for (const [protocol, preparer] of customPreparers.entries()) {\n preparers.register(protocol, preparer);\n }\n\n // Generators are used for generating documentation sites.\n const generators = await Generators.fromConfig(config, {\n logger: logger,\n customGenerator: customTechdocsGenerator,\n });\n\n // Publisher is used for\n // 1. Publishing generated files to storage\n // 2. Fetching files from storage and passing them to TechDocs frontend.\n const publisher = await Publisher.fromConfig(config, {\n logger: logger,\n discovery: discovery,\n customPublisher: customTechdocsPublisher,\n publisherSettings,\n });\n\n // checks if the publisher is working and logs the result\n await publisher.getReadiness();\n\n http.use(\n await createRouter({\n logger: logger,\n cache,\n docsBuildStrategy,\n buildLogTransport,\n preparers,\n generators,\n publisher,\n config,\n discovery,\n httpAuth,\n auth,\n catalogClient: catalog,\n }),\n );\n\n http.addAuthPolicy({\n path: '/static',\n allow: 'user-cookie',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","techdocsBuildsExtensionPoint","techdocsGeneratorExtensionPoint","techdocsPreparerExtensionPoint","techdocsPublisherExtensionPoint","coreServices","catalogServiceRef","Preparers","Generators","Publisher","createRouter"],"mappings":";;;;;;;AA4CO,MAAM,iBAAiBA,oCAAA,CAAoB;AAAA,EAChD,QAAA,EAAU,UAAA;AAAA,EACV,SAAS,GAAA,EAAK;AACZ,IAAA,IAAI,iBAAA;AACJ,IAAA,IAAI,iBAAA;AACJ,IAAA,GAAA,CAAI,uBAAuBC,+CAAA,EAA8B;AAAA,MACvD,iBAAiB,aAAA,EAAkC;AACjD,QAAA,IAAI,iBAAA,EAAmB;AACrB,UAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,QAC1D;AACA,QAAA,iBAAA,GAAoB,aAAA;AAAA,MACtB,CAAA;AAAA,MACA,qBAAqB,SAAA,EAA8B;AACjD,QAAA,IAAI,iBAAA,EAAmB;AACrB,UAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,QAC1D;AACA,QAAA,iBAAA,GAAoB,SAAA;AAAA,MACtB;AAAA,KACD,CAAA;AAED,IAAA,IAAI,uBAAA;AACJ,IAAA,GAAA,CAAI,uBAAuBC,kDAAA,EAAiC;AAAA,MAC1D,qBAAqB,SAAA,EAA8B;AACjD,QAAA,IAAI,uBAAA,EAAyB;AAC3B,UAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,QAC1D;AAEA,QAAA,uBAAA,GAA0B,SAAA;AAAA,MAC5B;AAAA,KACD,CAAA;AAED,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAAkC;AAC9D,IAAA,GAAA,CAAI,uBAAuBC,iDAAA,EAAgC;AAAA,MACzD,gBAAA,CAAiB,UAA0B,QAAA,E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"sourcesContent":["/*\n * Copyright 2022 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 {\n AuthService,\n BackstageCredentials,\n CacheService,\n} from '@backstage/backend-plugin-api';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n Entity,\n CompoundEntityRef,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\n\nexport type CachedEntityLoaderOptions = {\n auth: AuthService;\n catalog: CatalogApi;\n cache: CacheService;\n};\n\nexport class CachedEntityLoader {\n private readonly auth: AuthService;\n private readonly catalog: CatalogApi;\n private readonly cache: CacheService;\n private readonly readTimeout = 1000;\n\n constructor({ auth, catalog, cache }: CachedEntityLoaderOptions) {\n this.auth = auth;\n this.catalog = catalog;\n this.cache = cache;\n }\n\n async load(\n credentials: BackstageCredentials,\n entityRef: CompoundEntityRef,\n token: string | undefined,\n ): Promise<Entity | undefined> {\n const cacheKey = this.getCacheKey(entityRef, credentials);\n let result = await this.getFromCache(cacheKey);\n\n if (result) {\n return result;\n }\n\n result = await this.catalog.getEntityByRef(entityRef, { token });\n\n if (result) {\n this.cache.set(cacheKey, result, { ttl: 5000 });\n }\n\n return result;\n }\n\n private async getFromCache(key: string): Promise<Entity | undefined> {\n // Promise.race ensures we don't hang the client for long if the cache is\n // temporarily unreachable.\n return (await Promise.race([\n this.cache.get(key),\n new Promise(cancelAfter => setTimeout(cancelAfter, this.readTimeout)),\n ])) as Entity | undefined;\n }\n\n private getCacheKey(\n entityName: CompoundEntityRef,\n credentials: BackstageCredentials,\n ): string {\n const key = ['catalog', stringifyEntityRef(entityName)];\n\n if (this.auth.isPrincipal(credentials, 'user')) {\n key.push(credentials.principal.userEntityRef);\n } else if (this.auth.isPrincipal(credentials, 'service')) {\n key.push(credentials.principal.subject);\n }\n\n return key.join(':');\n }\n}\n"],"names":["stringifyEntityRef"],"mappings":";;;;AAkCO,MAAM,kBAAmB,CAAA;AAAA,EACb,IAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,WAAc,GAAA,GAAA;AAAA,EAE/B,WAAY,CAAA,EAAE,IAAM,EAAA,OAAA,EAAS,OAAoC,EAAA;AAC/D,IAAA,IAAA,CAAK,IAAO,GAAA,IAAA;AACZ,IAAA,IAAA,CAAK,OAAU,GAAA,OAAA;AACf,IAAA,IAAA,CAAK,KAAQ,GAAA,KAAA;AAAA;AACf,EAEA,MAAM,IAAA,CACJ,WACA,EAAA,SAAA,EACA,KAC6B,EAAA;AAC7B,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,WAAY,CAAA,SAAA,EAAW,WAAW,CAAA;AACxD,IAAA,IAAI,MAAS,GAAA,MAAM,IAAK,CAAA,YAAA,CAAa,QAAQ,CAAA;AAE7C,IAAA,IAAI,MAAQ,EAAA;AACV,MAAO,OAAA,MAAA;AAAA;AAGT,IAAA,MAAA,GAAS,MAAM,IAAK,CAAA,OAAA,CAAQ,eAAe,SAAW,EAAA,EAAE,OAAO,CAAA;AAE/D,IAAA,IAAI,MAAQ,EAAA;AACV,MAAA,IAAA,CAAK,MAAM,GAAI,CAAA,QAAA,EAAU,QAAQ,EAAE,GAAA,EAAK,KAAM,CAAA;AAAA;AAGhD,IAAO,OAAA,MAAA;AAAA;AACT,EAEA,MAAc,aAAa,GAA0C,EAAA;AAGnE,IAAQ,OAAA,MAAM,QAAQ,IAAK,CAAA;AAAA,MACzB,IAAA,CAAK,KAAM,CAAA,GAAA,CAAI,GAAG,CAAA;AAAA,MAClB,IAAI,OAAQ,CAAA,CAAA,WAAA,KAAe,WAAW,WAAa,EAAA,IAAA,CAAK,WAAW,CAAC;AAAA,KACrE,CAAA;AAAA;AACH,EAEQ,WAAA,CACN,YACA,WACQ,EAAA;AACR,IAAA,MAAM,GAAM,GAAA,CAAC,SAAW,EAAAA,+BAAA,CAAmB,UAAU,CAAC,CAAA;AAEtD,IAAA,IAAI,IAAK,CAAA,IAAA,CAAK,WAAY,CAAA,WAAA,EAAa,MAAM,CAAG,EAAA;AAC9C,MAAI,GAAA,CAAA,IAAA,CAAK,WAAY,CAAA,SAAA,CAAU,aAAa,CAAA;AAAA,eACnC,IAAK,CAAA,IAAA,CAAK,WAAY,CAAA,WAAA,EAAa,SAAS,CAAG,EAAA;AACxD,MAAI,GAAA,CAAA,IAAA,CAAK,WAAY,CAAA,SAAA,CAAU,OAAO,CAAA;AAAA;AAGxC,IAAO,OAAA,GAAA,CAAI,KAAK,GAAG,CAAA;AAAA;AAEvB;;;;"}
1
+ {"version":3,"file":"CachedEntityLoader.cjs.js","sources":["../../src/service/CachedEntityLoader.ts"],"sourcesContent":["/*\n * Copyright 2022 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 {\n AuthService,\n BackstageCredentials,\n CacheService,\n} from '@backstage/backend-plugin-api';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n Entity,\n CompoundEntityRef,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\n\nexport type CachedEntityLoaderOptions = {\n auth: AuthService;\n catalog: CatalogApi;\n cache: CacheService;\n};\n\nexport class CachedEntityLoader {\n private readonly auth: AuthService;\n private readonly catalog: CatalogApi;\n private readonly cache: CacheService;\n private readonly readTimeout = 1000;\n\n constructor({ auth, catalog, cache }: CachedEntityLoaderOptions) {\n this.auth = auth;\n this.catalog = catalog;\n this.cache = cache;\n }\n\n async load(\n credentials: BackstageCredentials,\n entityRef: CompoundEntityRef,\n token: string | undefined,\n ): Promise<Entity | undefined> {\n const cacheKey = this.getCacheKey(entityRef, credentials);\n let result = await this.getFromCache(cacheKey);\n\n if (result) {\n return result;\n }\n\n result = await this.catalog.getEntityByRef(entityRef, { token });\n\n if (result) {\n this.cache.set(cacheKey, result, { ttl: 5000 });\n }\n\n return result;\n }\n\n private async getFromCache(key: string): Promise<Entity | undefined> {\n // Promise.race ensures we don't hang the client for long if the cache is\n // temporarily unreachable.\n return (await Promise.race([\n this.cache.get(key),\n new Promise(cancelAfter => setTimeout(cancelAfter, this.readTimeout)),\n ])) as Entity | undefined;\n }\n\n private getCacheKey(\n entityName: CompoundEntityRef,\n credentials: BackstageCredentials,\n ): string {\n const key = ['catalog', stringifyEntityRef(entityName)];\n\n if (this.auth.isPrincipal(credentials, 'user')) {\n key.push(credentials.principal.userEntityRef);\n } else if (this.auth.isPrincipal(credentials, 'service')) {\n key.push(credentials.principal.subject);\n }\n\n return key.join(':');\n }\n}\n"],"names":["stringifyEntityRef"],"mappings":";;;;AAkCO,MAAM,kBAAA,CAAmB;AAAA,EACb,IAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,WAAA,GAAc,GAAA;AAAA,EAE/B,WAAA,CAAY,EAAE,IAAA,EAAM,OAAA,EAAS,OAAM,EAA8B;AAC/D,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AAAA,EAEA,MAAM,IAAA,CACJ,WAAA,EACA,SAAA,EACA,KAAA,EAC6B;AAC7B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,WAAA,CAAY,SAAA,EAAW,WAAW,CAAA;AACxD,IAAA,IAAI,MAAA,GAAS,MAAM,IAAA,CAAK,YAAA,C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/*\n * Copyright 2022 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 { Entity } from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { DocsBuildStrategy } from '@backstage/plugin-techdocs-node';\n\nexport class DefaultDocsBuildStrategy implements DocsBuildStrategy {\n private readonly config: Config;\n\n private constructor(config: Config) {\n this.config = config;\n }\n\n static fromConfig(config: Config): DefaultDocsBuildStrategy {\n return new DefaultDocsBuildStrategy(config);\n }\n\n async shouldBuild(_: { entity: Entity }): Promise<boolean> {\n return [undefined, 'local'].includes(\n this.config.getOptionalString('techdocs.builder'),\n );\n }\n}\n"],"names":[],"mappings":";;AAmBO,MAAM,wBAAsD,CAAA;AAAA,EAChD,MAAA;AAAA,EAET,YAAY,MAAgB,EAAA;AAClC,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AAAA;AAChB,EAEA,OAAO,WAAW,MAA0C,EAAA;AAC1D,IAAO,OAAA,IAAI,yBAAyB,MAAM,CAAA;AAAA;AAC5C,EAEA,MAAM,YAAY,CAAyC,EAAA;AACzD,IAAO,OAAA,CAAC,KAAW,CAAA,EAAA,OAAO,CAAE,CAAA,QAAA;AAAA,MAC1B,IAAA,CAAK,MAAO,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,KAClD;AAAA;AAEJ;;;;"}
1
+ {"version":3,"file":"DefaultDocsBuildStrategy.cjs.js","sources":["../../src/service/DefaultDocsBuildStrategy.ts"],"sourcesContent":["/*\n * Copyright 2022 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 { Entity } from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { DocsBuildStrategy } from '@backstage/plugin-techdocs-node';\n\nexport class DefaultDocsBuildStrategy implements DocsBuildStrategy {\n private readonly config: Config;\n\n private constructor(config: Config) {\n this.config = config;\n }\n\n static fromConfig(config: Config): DefaultDocsBuildStrategy {\n return new DefaultDocsBuildStrategy(config);\n }\n\n async shouldBuild(_: { entity: Entity }): Promise<boolean> {\n return [undefined, 'local'].includes(\n this.config.getOptionalString('techdocs.builder'),\n );\n }\n}\n"],"names":[],"mappings":";;AAmBO,MAAM,wBAAA,CAAsD;AAAA,EAChD,MAAA;AAAA,EAET,YAAY,MAAA,EAAgB;AAClC,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,OAAO,WAAW,MAAA,EAA0C;AAC1D,IAAA,OAAO,IAAI,yBAAyB,MAAM,CAAA;AAAA,EAC5C;AAAA,EAEA,MAAM,YAAY,CAAA,EAAyC;AACzD,IAAA,OAAO,CAAC,MAAA,EAAW,OAAO,CAAA,CAAE,QAAA;AAAA,MAC1B,IAAA,CAAK,MAAA,CAAO,iBAAA,CAAkB,kBAAkB;AAAA,KAClD;AAAA,EACF;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"DocsSynchronizer.cjs.js","sources":["../../src/service/DocsSynchronizer.ts"],"sourcesContent":["/*\n * Copyright 2021 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 {\n DEFAULT_NAMESPACE,\n Entity,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { assertError, NotFoundError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport {\n GeneratorBuilder,\n PreparerBuilder,\n PublisherBase,\n} from '@backstage/plugin-techdocs-node';\nimport pLimit, { Limit } from 'p-limit';\nimport { PassThrough } from 'stream';\nimport * as winston from 'winston';\nimport { TechDocsCache } from '../cache';\nimport {\n BuildMetadataStorage,\n DocsBuilder,\n shouldCheckForUpdate,\n} from '../DocsBuilder';\nimport { DiscoveryService, LoggerService } from '@backstage/backend-plugin-api';\n\nexport type DocsSynchronizerSyncOpts = {\n log: (message: string) => void;\n error: (e: Error) => void;\n finish: (result: { updated: boolean }) => void;\n};\n\nexport class DocsSynchronizer {\n private readonly publisher: PublisherBase;\n private readonly logger: LoggerService;\n private readonly buildLogTransport?: winston.transport;\n private readonly config: Config;\n private readonly scmIntegrations: ScmIntegrationRegistry;\n private readonly cache: TechDocsCache | undefined;\n private readonly buildLimiter: Limit;\n\n constructor({\n publisher,\n logger,\n buildLogTransport,\n config,\n scmIntegrations,\n cache,\n }: {\n publisher: PublisherBase;\n logger: LoggerService;\n buildLogTransport?: winston.transport;\n config: Config;\n scmIntegrations: ScmIntegrationRegistry;\n cache: TechDocsCache | undefined;\n }) {\n this.config = config;\n this.logger = logger;\n this.buildLogTransport = buildLogTransport;\n this.publisher = publisher;\n this.scmIntegrations = scmIntegrations;\n this.cache = cache;\n\n // Single host/process: limit concurrent builds up to 10 at a time.\n this.buildLimiter = pLimit(10);\n }\n\n async doSync({\n responseHandler: { log, error, finish },\n entity,\n preparers,\n generators,\n }: {\n responseHandler: DocsSynchronizerSyncOpts;\n entity: Entity;\n preparers: PreparerBuilder;\n generators: GeneratorBuilder;\n }) {\n // create a new logger to log data to the caller\n const taskLogger = winston.createLogger({\n level: process.env.LOG_LEVEL || 'info',\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.timestamp(),\n winston.format.simple(),\n ),\n defaultMeta: {},\n });\n\n // create an in-memory stream to forward logs to the event-stream\n const logStream = new PassThrough();\n logStream.on('data', async data => {\n log(data.toString().trim());\n });\n\n taskLogger.add(new winston.transports.Stream({ stream: logStream }));\n if (this.buildLogTransport) {\n taskLogger.add(this.buildLogTransport);\n }\n\n // check if the last update check was too recent\n if (!shouldCheckForUpdate(entity.metadata.uid!)) {\n finish({ updated: false });\n return;\n }\n\n let foundDocs = false;\n\n try {\n const docsBuilder = new DocsBuilder({\n preparers,\n generators,\n publisher: this.publisher,\n logger: taskLogger,\n entity,\n config: this.config,\n scmIntegrations: this.scmIntegrations,\n logStream,\n cache: this.cache,\n });\n\n const interval = setInterval(() => {\n taskLogger.info(\n 'The docs building process is taking a little bit longer to process this entity. Please bear with us.',\n );\n }, 10000);\n const updated = await this.buildLimiter(() => docsBuilder.build());\n clearInterval(interval);\n\n if (!updated) {\n finish({ updated: false });\n return;\n }\n } catch (e) {\n assertError(e);\n const msg = `Failed to build the docs page for entity ${stringifyEntityRef(\n entity,\n )}: ${e.message}`;\n taskLogger.error(msg);\n this.logger.error(msg, e);\n error(e);\n return;\n }\n\n // With a maximum of ~5 seconds wait, check if the files got published and if docs will be fetched\n // on the user's page. If not, respond with a message asking them to check back later.\n // The delay here is to make sure GCS/AWS/etc. registers newly uploaded files which is usually <1 second\n for (let attempt = 0; attempt < 5; attempt++) {\n if (await this.publisher.hasDocsBeenGenerated(entity)) {\n foundDocs = true;\n break;\n }\n await new Promise(r => setTimeout(r, 1000));\n }\n if (!foundDocs) {\n this.logger.error(\n 'Published files are taking longer to show up in storage. Something went wrong.',\n );\n error(\n new NotFoundError(\n 'Sorry! It took too long for the generated docs to show up in storage. Are you sure the docs project is generating an `index.html` file? Otherwise, check back later.',\n ),\n );\n return;\n }\n\n finish({ updated: true });\n }\n\n async doCacheSync({\n responseHandler: { finish },\n discovery,\n token,\n entity,\n }: {\n responseHandler: DocsSynchronizerSyncOpts;\n discovery: DiscoveryService;\n token: string | undefined;\n entity: Entity;\n }) {\n // Check if the last update check was too recent.\n if (!shouldCheckForUpdate(entity.metadata.uid!) || !this.cache) {\n finish({ updated: false });\n return;\n }\n\n // Fetch techdocs_metadata.json from the publisher and from cache.\n const baseUrl = await discovery.getBaseUrl('techdocs');\n const namespace = entity.metadata?.namespace || DEFAULT_NAMESPACE;\n const kind = entity.kind;\n const name = entity.metadata.name;\n const legacyPathCasing =\n this.config.getOptionalBoolean(\n 'techdocs.legacyUseCaseSensitiveTripletPaths',\n ) || false;\n const tripletPath = `${namespace}/${kind}/${name}`;\n const entityTripletPath = `${\n legacyPathCasing ? tripletPath : tripletPath.toLocaleLowerCase('en-US')\n }`;\n try {\n const [sourceMetadata, cachedMetadata] = await Promise.all([\n this.publisher.fetchTechDocsMetadata({ namespace, kind, name }),\n fetch(\n `${baseUrl}/static/docs/${entityTripletPath}/techdocs_metadata.json`,\n {\n headers: token ? { Authorization: `Bearer ${token}` } : {},\n },\n ).then(\n f =>\n f.json().catch(() => undefined) as ReturnType<\n PublisherBase['fetchTechDocsMetadata']\n >,\n ),\n ]);\n\n // If build timestamps differ, merge their files[] lists and invalidate all objects.\n if (sourceMetadata.build_timestamp !== cachedMetadata.build_timestamp) {\n const files = [\n ...new Set([\n ...(sourceMetadata.files || []),\n ...(cachedMetadata.files || []),\n ]),\n ].map(f => `${entityTripletPath}/${f}`);\n await this.cache.invalidateMultiple(files);\n finish({ updated: true });\n } else {\n finish({ updated: false });\n }\n } catch (e) {\n assertError(e);\n // In case of error, log and allow the user to go about their business.\n this.logger.error(\n `Error syncing cache for ${entityTripletPath}: ${e.message}`,\n );\n finish({ updated: false });\n } finally {\n // Update the last check time for the entity\n new BuildMetadataStorage(entity.metadata.uid!).setLastUpdated();\n }\n }\n}\n"],"names":["pLimit","winston","PassThrough","shouldCheckForUpdate","DocsBuilder","assertError","stringifyEntityRef","NotFoundError","DEFAULT_NAMESPACE","BuildMetadataStorage"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CO,MAAM,gBAAiB,CAAA;AAAA,EACX,SAAA;AAAA,EACA,MAAA;AAAA,EACA,iBAAA;AAAA,EACA,MAAA;AAAA,EACA,eAAA;AAAA,EACA,KAAA;AAAA,EACA,YAAA;AAAA,EAEjB,WAAY,CAAA;AAAA,IACV,SAAA;AAAA,IACA,MAAA;AAAA,IACA,iBAAA;AAAA,IACA,MAAA;AAAA,IACA,eAAA;AAAA,IACA;AAAA,GAQC,EAAA;AACD,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA;AACd,IAAA,IAAA,CAAK,iBAAoB,GAAA,iBAAA;AACzB,IAAA,IAAA,CAAK,SAAY,GAAA,SAAA;AACjB,IAAA,IAAA,CAAK,eAAkB,GAAA,eAAA;AACvB,IAAA,IAAA,CAAK,KAAQ,GAAA,KAAA;AAGb,IAAK,IAAA,CAAA,YAAA,GAAeA,wBAAO,EAAE,CAAA;AAAA;AAC/B,EAEA,MAAM,MAAO,CAAA;AAAA,IACX,eAAiB,EAAA,EAAE,GAAK,EAAA,KAAA,EAAO,MAAO,EAAA;AAAA,IACtC,MAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GAMC,EAAA;AAED,IAAM,MAAA,UAAA,GAAaC,mBAAQ,YAAa,CAAA;AAAA,MACtC,KAAA,EAAO,OAAQ,CAAA,GAAA,CAAI,SAAa,IAAA,MAAA;AAAA,MAChC,MAAA,EAAQA,mBAAQ,MAAO,CAAA,OAAA;AAAA,QACrBA,kBAAA,CAAQ,OAAO,QAAS,EAAA;AAAA,QACxBA,kBAAA,CAAQ,OAAO,SAAU,EAAA;AAAA,QACzBA,kBAAA,CAAQ,OAAO,MAAO;AAAA,OACxB;AAAA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;AAAA,UACZ,uBAAO,GAAI,CAAA;AAAA,YACT,GAAI,cAAe,CAAA,KAAA,IAAS,EAAC;AAAA,YAC7B,GAAI,cAAe,CAAA,KAAA,IAAS;AAAC,WAC9B;AAAA,UACD,GAAI,CAAA,CAAA,CAAA,KAAK,GAAG,iBAAiB,CAAA,CAAA,EAAI,CAAC,CAAE,CAAA,CAAA;AACtC,QAAM,MAAA,IAAA,CAAK,KAAM,CAAA,kBAAA,CAAmB,KAAK,CAAA;AACzC,QAAO,MAAA,CAAA,EAAE,OAAS,EAAA,IAAA,EAAM,CAAA;AAAA,OACnB,MAAA;AACL,QAAO,MAAA,CAAA,EAAE,OAAS,EAAA,KAAA,EAAO,CAAA;AAAA;AAC3B,aACO,CAAG,EAAA;AACV,MAAAH,kBAAA,CAAY,CAAC,CAAA;AAEb,MAAA,IAAA,CAAK,MAAO,CAAA,KAAA;AAAA,QACV,CAA2B,wBAAA,EAAA,iBAAiB,CAAK,EAAA,EAAA,CAAA,CAAE,OAAO,CAAA;AAAA,OAC5D;AACA,MAAO,MAAA,CAAA,EAAE,OAAS,EAAA,KAAA,EAAO,CAAA;AAAA,KACzB,SAAA;AAEA,MAAA,IAAII,yCAAqB,CAAA,MAAA,CAAO,QAAS,CAAA,GAAI,EAAE,cAAe,EAAA;AAAA;AAChE;AAEJ;;;;"}
1
+ {"version":3,"file":"DocsSynchronizer.cjs.js","sources":["../../src/service/DocsSynchronizer.ts"],"sourcesContent":["/*\n * Copyright 2021 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 {\n DEFAULT_NAMESPACE,\n Entity,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { assertError, NotFoundError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport {\n GeneratorBuilder,\n PreparerBuilder,\n PublisherBase,\n} from '@backstage/plugin-techdocs-node';\nimport pLimit, { Limit } from 'p-limit';\nimport { PassThrough } from 'stream';\nimport * as winston from 'winston';\nimport { TechDocsCache } from '../cache';\nimport {\n BuildMetadataStorage,\n DocsBuilder,\n shouldCheckForUpdate,\n} from '../DocsBuilder';\nimport { DiscoveryService, LoggerService } from '@backstage/backend-plugin-api';\n\nexport type DocsSynchronizerSyncOpts = {\n log: (message: string) => void;\n error: (e: Error) => void;\n finish: (result: { updated: boolean }) => void;\n};\n\nexport class DocsSynchronizer {\n private readonly publisher: PublisherBase;\n private readonly logger: LoggerService;\n private readonly buildLogTransport?: winston.transport;\n private readonly config: Config;\n private readonly scmIntegrations: ScmIntegrationRegistry;\n private readonly cache: TechDocsCache | undefined;\n private readonly buildLimiter: Limit;\n\n constructor({\n publisher,\n logger,\n buildLogTransport,\n config,\n scmIntegrations,\n cache,\n }: {\n publisher: PublisherBase;\n logger: LoggerService;\n buildLogTransport?: winston.transport;\n config: Config;\n scmIntegrations: ScmIntegrationRegistry;\n cache: TechDocsCache | undefined;\n }) {\n this.config = config;\n this.logger = logger;\n this.buildLogTransport = buildLogTransport;\n this.publisher = publisher;\n this.scmIntegrations = scmIntegrations;\n this.cache = cache;\n\n // Single host/process: limit concurrent builds up to 10 at a time.\n this.buildLimiter = pLimit(10);\n }\n\n async doSync({\n responseHandler: { log, error, finish },\n entity,\n preparers,\n generators,\n }: {\n responseHandler: DocsSynchronizerSyncOpts;\n entity: Entity;\n preparers: PreparerBuilder;\n generators: GeneratorBuilder;\n }) {\n // create a new logger to log data to the caller\n const taskLogger = winston.createLogger({\n level: process.env.LOG_LEVEL || 'info',\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.timestamp(),\n winston.format.simple(),\n ),\n defaultMeta: {},\n });\n\n // create an in-memory stream to forward logs to the event-stream\n const logStream = new PassThrough();\n logStream.on('data', async data => {\n log(data.toString().trim());\n });\n\n taskLogger.add(new winston.transports.Stream({ stream: logStream }));\n if (this.buildLogTransport) {\n taskLogger.add(this.buildLogTransport);\n }\n\n // check if the last update check was too recent\n if (!shouldCheckForUpdate(entity.metadata.uid!)) {\n finish({ updated: false });\n return;\n }\n\n let foundDocs = false;\n\n try {\n const docsBuilder = new DocsBuilder({\n preparers,\n generators,\n publisher: this.publisher,\n logger: taskLogger,\n entity,\n config: this.config,\n scmIntegrations: this.scmIntegrations,\n logStream,\n cache: this.cache,\n });\n\n const interval = setInterval(() => {\n taskLogger.info(\n 'The docs building process is taking a little bit longer to process this entity. Please bear with us.',\n );\n }, 10000);\n const updated = await this.buildLimiter(() => docsBuilder.build());\n clearInterval(interval);\n\n if (!updated) {\n finish({ updated: false });\n return;\n }\n } catch (e) {\n assertError(e);\n const msg = `Failed to build the docs page for entity ${stringifyEntityRef(\n entity,\n )}: ${e.message}`;\n taskLogger.error(msg);\n this.logger.error(msg, e);\n error(e);\n return;\n }\n\n // With a maximum of ~5 seconds wait, check if the files got published and if docs will be fetched\n // on the user's page. If not, respond with a message asking them to check back later.\n // The delay here is to make sure GCS/AWS/etc. registers newly uploaded files which is usually <1 second\n for (let attempt = 0; attempt < 5; attempt++) {\n if (await this.publisher.hasDocsBeenGenerated(entity)) {\n foundDocs = true;\n break;\n }\n await new Promise(r => setTimeout(r, 1000));\n }\n if (!foundDocs) {\n this.logger.error(\n 'Published files are taking longer to show up in storage. Something went wrong.',\n );\n error(\n new NotFoundError(\n 'Sorry! It took too long for the generated docs to show up in storage. Are you sure the docs project is generating an `index.html` file? Otherwise, check back later.',\n ),\n );\n return;\n }\n\n finish({ updated: true });\n }\n\n async doCacheSync({\n responseHandler: { finish },\n discovery,\n token,\n entity,\n }: {\n responseHandler: DocsSynchronizerSyncOpts;\n discovery: DiscoveryService;\n token: string | undefined;\n entity: Entity;\n }) {\n // Check if the last update check was too recent.\n if (!shouldCheckForUpdate(entity.metadata.uid!) || !this.cache) {\n finish({ updated: false });\n return;\n }\n\n // Fetch techdocs_metadata.json from the publisher and from cache.\n const baseUrl = await discovery.getBaseUrl('techdocs');\n const namespace = entity.metadata?.namespace || DEFAULT_NAMESPACE;\n const kind = entity.kind;\n const name = entity.metadata.name;\n const legacyPathCasing =\n this.config.getOptionalBoolean(\n 'techdocs.legacyUseCaseSensitiveTripletPaths',\n ) || false;\n const tripletPath = `${namespace}/${kind}/${name}`;\n const entityTripletPath = `${\n legacyPathCasing ? tripletPath : tripletPath.toLocaleLowerCase('en-US')\n }`;\n try {\n const [sourceMetadata, cachedMetadata] = await Promise.all([\n this.publisher.fetchTechDocsMetadata({ namespace, kind, name }),\n fetch(\n `${baseUrl}/static/docs/${entityTripletPath}/techdocs_metadata.json`,\n {\n headers: token ? { Authorization: `Bearer ${token}` } : {},\n },\n ).then(\n f =>\n f.json().catch(() => undefined) as ReturnType<\n PublisherBase['fetchTechDocsMetadata']\n >,\n ),\n ]);\n\n // If build timestamps differ, merge their files[] lists and invalidate all objects.\n if (sourceMetadata.build_timestamp !== cachedMetadata.build_timestamp) {\n const files = [\n ...new Set([\n ...(sourceMetadata.files || []),\n ...(cachedMetadata.files || []),\n ]),\n ].map(f => `${entityTripletPath}/${f}`);\n await this.cache.invalidateMultiple(files);\n finish({ updated: true });\n } else {\n finish({ updated: false });\n }\n } catch (e) {\n assertError(e);\n // In case of error, log and allow the user to go about their business.\n this.logger.error(\n `Error syncing cache for ${entityTripletPath}: ${e.message}`,\n );\n finish({ updated: false });\n } finally {\n // Update the last check time for the entity\n new BuildMetadataStorage(entity.metadata.uid!).setLastUpdated();\n }\n }\n}\n"],"names":["pLimit","winston","PassThrough","shouldCheckForUpdate","DocsBuilder","assertError","stringifyEntityRef","NotFoundError","DEFAULT_NAMESPACE","BuildMetadataStorage"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAA,YAC7B,GAAI,cAAA,CAAe,KAAA,IAAS;AAAC,WAC9B;AAAA,UACD,GAAA,CAAI,CAAA,CAAA,KAAK,GAAG,iBAAiB,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,CAAA;AACtC,QAAA,MAAM,IAAA,CAAK,KAAA,CAAM,kBAAA,CAAmB,KAAK,CAAA;AACzC,QAAA,MAAA,CAAO,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA;AAAA,MAC1B,CAAA,MAAO;AACL,QAAA,MAAA,CAAO,EAAE,OAAA,EAAS,KAAA,EAAO,CAAA;AAAA,MAC3B;AAAA,IACF,SAAS,CAAA,EAAG;AACV,MAAAH,kBAAA,CAAY,CAAC,CAAA;AAEb,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV,CAAA,wBAAA,EAA2B,iBAAiB,CAAA,EAAA,EAAK,CAAA,CAAE,OAAO,CAAA;AAAA,OAC5D;AACA,MAAA,MAAA,CAAO,EAAE,OAAA,EAAS,KAAA,EAAO,CAAA;AAAA,IAC3B,CAAA,SAAE;AAEA,MAAA,IAAII,yCAAA,CAAqB,MAAA,CAAO,QAAA,CAAS,GAAI,EAAE,cAAA,EAAe;AAAA,IAChE;AAAA,EACF;AACF;;;;"}
@@ -179,7 +179,7 @@ async function createRouter(options) {
179
179
  );
180
180
  }
181
181
  if (cache) {
182
- router.use(cacheMiddleware.createCacheMiddleware({ logger, cache }));
182
+ router.use(cacheMiddleware.createCacheMiddleware({ cache }));
183
183
  }
184
184
  router.use("/static/docs", publisher.docsRouter());
185
185
  return router;
@@ -1 +1 @@
1
- {"version":3,"file":"router.cjs.js","sources":["../../src/service/router.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 { CatalogApi, CatalogClient } from '@backstage/catalog-client';\nimport { stringifyEntityRef } from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { NotFoundError } from '@backstage/errors';\nimport {\n DocsBuildStrategy,\n GeneratorBuilder,\n getLocationForEntity,\n PreparerBuilder,\n PublisherBase,\n} from '@backstage/plugin-techdocs-node';\nimport express, { Response } from 'express';\nimport Router from 'express-promise-router';\nimport { Knex } from 'knex';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { DocsSynchronizer, DocsSynchronizerSyncOpts } from './DocsSynchronizer';\nimport { createCacheMiddleware, TechDocsCache } from '../cache';\nimport { CachedEntityLoader } from './CachedEntityLoader';\nimport { DefaultDocsBuildStrategy } from './DefaultDocsBuildStrategy';\nimport * as winston from 'winston';\nimport {\n AuthService,\n CacheService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\n/**\n * Required dependencies for running TechDocs in the \"out-of-the-box\"\n * deployment configuration (prepare/generate/publish all in the Backend).\n *\n * @internal\n */\nexport type OutOfTheBoxDeploymentOptions = {\n preparers: PreparerBuilder;\n generators: GeneratorBuilder;\n publisher: PublisherBase;\n logger: LoggerService;\n discovery: DiscoveryService;\n database?: Knex; // TODO: Make database required when we're implementing database stuff.\n config: Config;\n cache: CacheService;\n docsBuildStrategy?: DocsBuildStrategy;\n buildLogTransport?: winston.transport;\n catalogClient?: CatalogApi;\n httpAuth: HttpAuthService;\n auth: AuthService;\n};\n\n/**\n * Required dependencies for running TechDocs in the \"recommended\" deployment\n * configuration (prepare/generate handled externally in CI/CD).\n *\n * @internal\n */\nexport type RecommendedDeploymentOptions = {\n publisher: PublisherBase;\n logger: LoggerService;\n discovery: DiscoveryService;\n config: Config;\n cache: CacheService;\n docsBuildStrategy?: DocsBuildStrategy;\n buildLogTransport?: winston.transport;\n catalogClient?: CatalogApi;\n httpAuth: HttpAuthService;\n auth: AuthService;\n};\n\n/**\n * One of the two deployment configurations must be provided.\n *\n * @internal\n */\nexport type RouterOptions =\n | RecommendedDeploymentOptions\n | OutOfTheBoxDeploymentOptions;\n\n/**\n * Typeguard to help createRouter() understand when we are in a \"recommended\"\n * deployment vs. when we are in an out-of-the-box deployment configuration.\n *\n * @internal\n */\nfunction isOutOfTheBoxOption(\n opt: RouterOptions,\n): opt is OutOfTheBoxDeploymentOptions {\n return (opt as OutOfTheBoxDeploymentOptions).preparers !== undefined;\n}\n\n/**\n * Creates a techdocs router.\n *\n * @internal\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const router = Router();\n const { publisher, config, logger, discovery, httpAuth, auth } = options;\n\n const catalogClient =\n options.catalogClient ?? new CatalogClient({ discoveryApi: discovery });\n const docsBuildStrategy =\n options.docsBuildStrategy ?? DefaultDocsBuildStrategy.fromConfig(config);\n const buildLogTransport = options.buildLogTransport;\n\n // Entities are cached to optimize the /static/docs request path, which can be called many times\n // when loading a single techdocs page.\n const entityLoader = new CachedEntityLoader({\n auth,\n catalog: catalogClient,\n cache: options.cache,\n });\n\n // Set up a cache client if configured.\n let cache: TechDocsCache | undefined;\n const defaultTtl = config.getOptionalNumber('techdocs.cache.ttl');\n if (defaultTtl) {\n const cacheClient = options.cache.withOptions({ defaultTtl });\n cache = TechDocsCache.fromConfig(config, { cache: cacheClient, logger });\n }\n\n const scmIntegrations = ScmIntegrations.fromConfig(config);\n const docsSynchronizer = new DocsSynchronizer({\n publisher,\n logger,\n buildLogTransport,\n config,\n scmIntegrations,\n cache,\n });\n\n router.get('/metadata/techdocs/:namespace/:kind/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const entityName = { kind, namespace, name };\n\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n // Verify that the related entity exists and the current user has permission to view it.\n const entity = await entityLoader.load(credentials, entityName, token);\n\n if (!entity) {\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n );\n }\n\n try {\n const techdocsMetadata = await publisher.fetchTechDocsMetadata(\n entityName,\n );\n\n res.json(techdocsMetadata);\n } catch (err) {\n logger.info(\n `Unable to get metadata for '${stringifyEntityRef(\n entityName,\n )}' with error ${err}`,\n );\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n err,\n );\n }\n });\n\n router.get('/metadata/entity/:namespace/:kind/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const entityName = { kind, namespace, name };\n\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const entity = await entityLoader.load(credentials, entityName, token);\n\n if (!entity) {\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n );\n }\n\n try {\n const locationMetadata = getLocationForEntity(entity, scmIntegrations);\n res.json({ ...entity, locationMetadata });\n } catch (err) {\n logger.info(\n `Unable to get metadata for '${stringifyEntityRef(\n entityName,\n )}' with error ${err}`,\n );\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n err,\n );\n }\n });\n\n // Check if docs are the latest version and trigger rebuilds if not\n // Responds with an event-stream that closes after the build finished\n // Responds with an immediate success if rebuild not needed\n // If a build is required, responds with a success when finished\n router.get('/sync/:namespace/:kind/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const entity = await entityLoader.load(\n credentials,\n { kind, namespace, name },\n token,\n );\n\n if (!entity?.metadata?.uid) {\n throw new NotFoundError('Entity metadata UID missing');\n }\n\n const responseHandler: DocsSynchronizerSyncOpts = createEventStream(res);\n\n // By default, techdocs-backend will only try to build documentation for an entity if techdocs.builder is set to\n // 'local'. If set to 'external', it will assume that an external process (e.g. CI/CD pipeline\n // of the repository) is responsible for building and publishing documentation to the storage provider.\n // Altering the implementation of the injected docsBuildStrategy allows for more complex behaviours, based on\n // either config or the properties of the entity (e.g. annotations, labels, spec fields etc.).\n const shouldBuild = await docsBuildStrategy.shouldBuild({ entity });\n if (!shouldBuild) {\n // However, if caching is enabled, take the opportunity to check and\n // invalidate stale cache entries.\n if (cache) {\n const { token: techDocsToken } = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId: 'techdocs',\n });\n await docsSynchronizer.doCacheSync({\n responseHandler,\n discovery,\n token: techDocsToken,\n entity,\n });\n return;\n }\n responseHandler.finish({ updated: false });\n return;\n }\n\n // Set the synchronization and build process if \"out-of-the-box\" configuration is provided.\n if (isOutOfTheBoxOption(options)) {\n const { preparers, generators } = options;\n\n await docsSynchronizer.doSync({\n responseHandler,\n entity,\n preparers,\n generators,\n });\n return;\n }\n\n responseHandler.error(\n new Error(\n \"Invalid configuration. docsBuildStrategy.shouldBuild returned 'true', but no 'preparer' was provided to the router initialization.\",\n ),\n );\n });\n\n // Ensures that the related entity exists and the current user has permission to view it.\n if (config.getOptionalBoolean('permission.enabled')) {\n router.use(\n '/static/docs/:namespace/:kind/:name',\n async (req, _res, next) => {\n const { kind, namespace, name } = req.params;\n const entityName = { kind, namespace, name };\n\n const credentials = await httpAuth.credentials(req, {\n allowLimitedAccess: true,\n });\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const entity = await entityLoader.load(credentials, entityName, token);\n\n if (!entity) {\n throw new NotFoundError(\n `Entity not found for ${stringifyEntityRef(entityName)}`,\n );\n }\n\n next();\n },\n );\n }\n\n // If a cache manager was provided, attach the cache middleware.\n if (cache) {\n router.use(createCacheMiddleware({ logger, cache }));\n }\n\n // Route middleware which serves files from the storage set in the publisher.\n router.use('/static/docs', publisher.docsRouter());\n\n return router;\n}\n\n/**\n * Create an event-stream response that emits the events 'log', 'error', and 'finish'.\n *\n * @param res - the response to write the event-stream to\n * @returns A tuple of <log, error, finish> callbacks to emit messages. A call to 'error' or 'finish'\n * will close the event-stream.\n */\nexport function createEventStream(\n res: Response<any, any>,\n): DocsSynchronizerSyncOpts {\n // Mandatory headers and http status to keep connection open\n res.writeHead(200, {\n Connection: 'keep-alive',\n 'Cache-Control': 'no-cache',\n 'Content-Type': 'text/event-stream',\n });\n\n // client closes connection\n res.socket?.on('close', () => {\n res.end();\n });\n\n // write the event to the stream\n const send = (type: 'error' | 'finish' | 'log', data: any) => {\n res.write(`event: ${type}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n\n // res.flush() is only available with the compression middleware\n if (res.flush) {\n res.flush();\n }\n };\n\n return {\n log: data => {\n send('log', data);\n },\n\n error: e => {\n send('error', e.message);\n res.end();\n },\n\n finish: result => {\n send('finish', result);\n res.end();\n },\n };\n}\n"],"names":["Router","catalogClient","CatalogClient","DefaultDocsBuildStrategy","CachedEntityLoader","TechDocsCache","ScmIntegrations","DocsSynchronizer","NotFoundError","stringifyEntityRef","getLocationForEntity","createCacheMiddleware"],"mappings":";;;;;;;;;;;;;;;;;;AAoGA,SAAS,oBACP,GACqC,EAAA;AACrC,EAAA,OAAQ,IAAqC,SAAc,KAAA,KAAA,CAAA;AAC7D;AAOA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAA,MAAM,SAASA,uBAAO,EAAA;AACtB,EAAA,MAAM,EAAE,SAAW,EAAA,MAAA,EAAQ,QAAQ,SAAW,EAAA,QAAA,EAAU,MAAS,GAAA,OAAA;AAEjE,EAAM,MAAAC,eAAA,GACJ,QAAQ,aAAiB,IAAA,IAAIC,4BAAc,EAAE,YAAA,EAAc,WAAW,CAAA;AACxE,EAAA,MAAM,iBACJ,GAAA,OAAA,CAAQ,iBAAqB,IAAAC,iDAAA,CAAyB,WAAW,MAAM,CAAA;AACzE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AAK,SAAU,CAAA,IAAI,CAAC;;AAAA,CAAM,CAAA;AAG7D,IAAA,IAAI,IAAI,KAAO,EAAA;AACb,MAAA,GAAA,CAAI,KAAM,EAAA;AAAA;AACZ,GACF;AAEA,EAAO,OAAA;AAAA,IACL,KAAK,CAAQ,IAAA,KAAA;AACX,MAAA,IAAA,CAAK,OAAO,IAAI,CAAA;AAAA,KAClB;AAAA,IAEA,OAAO,CAAK,CAAA,KAAA;AACV,MAAK,IAAA,CAAA,OAAA,EAAS,EAAE,OAAO,CAAA;AACvB,MAAA,GAAA,CAAI,GAAI,EAAA;AAAA,KACV;AAAA,IAEA,QAAQ,CAAU,MAAA,KAAA;AAChB,MAAA,IAAA,CAAK,UAAU,MAAM,CAAA;AACrB,MAAA,GAAA,CAAI,GAAI,EAAA;AAAA;AACV,GACF;AACF;;;;;"}
1
+ {"version":3,"file":"router.cjs.js","sources":["../../src/service/router.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 { CatalogApi, CatalogClient } from '@backstage/catalog-client';\nimport { stringifyEntityRef } from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { NotFoundError } from '@backstage/errors';\nimport {\n DocsBuildStrategy,\n GeneratorBuilder,\n getLocationForEntity,\n PreparerBuilder,\n PublisherBase,\n} from '@backstage/plugin-techdocs-node';\nimport express, { Response } from 'express';\nimport Router from 'express-promise-router';\nimport { Knex } from 'knex';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { DocsSynchronizer, DocsSynchronizerSyncOpts } from './DocsSynchronizer';\nimport { createCacheMiddleware, TechDocsCache } from '../cache';\nimport { CachedEntityLoader } from './CachedEntityLoader';\nimport { DefaultDocsBuildStrategy } from './DefaultDocsBuildStrategy';\nimport * as winston from 'winston';\nimport {\n AuthService,\n CacheService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\n/**\n * Required dependencies for running TechDocs in the \"out-of-the-box\"\n * deployment configuration (prepare/generate/publish all in the Backend).\n *\n * @internal\n */\nexport type OutOfTheBoxDeploymentOptions = {\n preparers: PreparerBuilder;\n generators: GeneratorBuilder;\n publisher: PublisherBase;\n logger: LoggerService;\n discovery: DiscoveryService;\n database?: Knex; // TODO: Make database required when we're implementing database stuff.\n config: Config;\n cache: CacheService;\n docsBuildStrategy?: DocsBuildStrategy;\n buildLogTransport?: winston.transport;\n catalogClient?: CatalogApi;\n httpAuth: HttpAuthService;\n auth: AuthService;\n};\n\n/**\n * Required dependencies for running TechDocs in the \"recommended\" deployment\n * configuration (prepare/generate handled externally in CI/CD).\n *\n * @internal\n */\nexport type RecommendedDeploymentOptions = {\n publisher: PublisherBase;\n logger: LoggerService;\n discovery: DiscoveryService;\n config: Config;\n cache: CacheService;\n docsBuildStrategy?: DocsBuildStrategy;\n buildLogTransport?: winston.transport;\n catalogClient?: CatalogApi;\n httpAuth: HttpAuthService;\n auth: AuthService;\n};\n\n/**\n * One of the two deployment configurations must be provided.\n *\n * @internal\n */\nexport type RouterOptions =\n | RecommendedDeploymentOptions\n | OutOfTheBoxDeploymentOptions;\n\n/**\n * Typeguard to help createRouter() understand when we are in a \"recommended\"\n * deployment vs. when we are in an out-of-the-box deployment configuration.\n *\n * @internal\n */\nfunction isOutOfTheBoxOption(\n opt: RouterOptions,\n): opt is OutOfTheBoxDeploymentOptions {\n return (opt as OutOfTheBoxDeploymentOptions).preparers !== undefined;\n}\n\n/**\n * Creates a techdocs router.\n *\n * @internal\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const router = Router();\n const { publisher, config, logger, discovery, httpAuth, auth } = options;\n\n const catalogClient =\n options.catalogClient ?? new CatalogClient({ discoveryApi: discovery });\n const docsBuildStrategy =\n options.docsBuildStrategy ?? DefaultDocsBuildStrategy.fromConfig(config);\n const buildLogTransport = options.buildLogTransport;\n\n // Entities are cached to optimize the /static/docs request path, which can be called many times\n // when loading a single techdocs page.\n const entityLoader = new CachedEntityLoader({\n auth,\n catalog: catalogClient,\n cache: options.cache,\n });\n\n // Set up a cache client if configured.\n let cache: TechDocsCache | undefined;\n const defaultTtl = config.getOptionalNumber('techdocs.cache.ttl');\n if (defaultTtl) {\n const cacheClient = options.cache.withOptions({ defaultTtl });\n cache = TechDocsCache.fromConfig(config, { cache: cacheClient, logger });\n }\n\n const scmIntegrations = ScmIntegrations.fromConfig(config);\n const docsSynchronizer = new DocsSynchronizer({\n publisher,\n logger,\n buildLogTransport,\n config,\n scmIntegrations,\n cache,\n });\n\n router.get('/metadata/techdocs/:namespace/:kind/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const entityName = { kind, namespace, name };\n\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n // Verify that the related entity exists and the current user has permission to view it.\n const entity = await entityLoader.load(credentials, entityName, token);\n\n if (!entity) {\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n );\n }\n\n try {\n const techdocsMetadata = await publisher.fetchTechDocsMetadata(\n entityName,\n );\n\n res.json(techdocsMetadata);\n } catch (err) {\n logger.info(\n `Unable to get metadata for '${stringifyEntityRef(\n entityName,\n )}' with error ${err}`,\n );\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n err,\n );\n }\n });\n\n router.get('/metadata/entity/:namespace/:kind/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const entityName = { kind, namespace, name };\n\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const entity = await entityLoader.load(credentials, entityName, token);\n\n if (!entity) {\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n );\n }\n\n try {\n const locationMetadata = getLocationForEntity(entity, scmIntegrations);\n res.json({ ...entity, locationMetadata });\n } catch (err) {\n logger.info(\n `Unable to get metadata for '${stringifyEntityRef(\n entityName,\n )}' with error ${err}`,\n );\n throw new NotFoundError(\n `Unable to get metadata for '${stringifyEntityRef(entityName)}'`,\n err,\n );\n }\n });\n\n // Check if docs are the latest version and trigger rebuilds if not\n // Responds with an event-stream that closes after the build finished\n // Responds with an immediate success if rebuild not needed\n // If a build is required, responds with a success when finished\n router.get('/sync/:namespace/:kind/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const entity = await entityLoader.load(\n credentials,\n { kind, namespace, name },\n token,\n );\n\n if (!entity?.metadata?.uid) {\n throw new NotFoundError('Entity metadata UID missing');\n }\n\n const responseHandler: DocsSynchronizerSyncOpts = createEventStream(res);\n\n // By default, techdocs-backend will only try to build documentation for an entity if techdocs.builder is set to\n // 'local'. If set to 'external', it will assume that an external process (e.g. CI/CD pipeline\n // of the repository) is responsible for building and publishing documentation to the storage provider.\n // Altering the implementation of the injected docsBuildStrategy allows for more complex behaviours, based on\n // either config or the properties of the entity (e.g. annotations, labels, spec fields etc.).\n const shouldBuild = await docsBuildStrategy.shouldBuild({ entity });\n if (!shouldBuild) {\n // However, if caching is enabled, take the opportunity to check and\n // invalidate stale cache entries.\n if (cache) {\n const { token: techDocsToken } = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId: 'techdocs',\n });\n await docsSynchronizer.doCacheSync({\n responseHandler,\n discovery,\n token: techDocsToken,\n entity,\n });\n return;\n }\n responseHandler.finish({ updated: false });\n return;\n }\n\n // Set the synchronization and build process if \"out-of-the-box\" configuration is provided.\n if (isOutOfTheBoxOption(options)) {\n const { preparers, generators } = options;\n\n await docsSynchronizer.doSync({\n responseHandler,\n entity,\n preparers,\n generators,\n });\n return;\n }\n\n responseHandler.error(\n new Error(\n \"Invalid configuration. docsBuildStrategy.shouldBuild returned 'true', but no 'preparer' was provided to the router initialization.\",\n ),\n );\n });\n\n // Ensures that the related entity exists and the current user has permission to view it.\n if (config.getOptionalBoolean('permission.enabled')) {\n router.use(\n '/static/docs/:namespace/:kind/:name',\n async (req, _res, next) => {\n const { kind, namespace, name } = req.params;\n const entityName = { kind, namespace, name };\n\n const credentials = await httpAuth.credentials(req, {\n allowLimitedAccess: true,\n });\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const entity = await entityLoader.load(credentials, entityName, token);\n\n if (!entity) {\n throw new NotFoundError(\n `Entity not found for ${stringifyEntityRef(entityName)}`,\n );\n }\n\n next();\n },\n );\n }\n\n // If a cache manager was provided, attach the cache middleware.\n if (cache) {\n router.use(createCacheMiddleware({ logger, cache }));\n }\n\n // Route middleware which serves files from the storage set in the publisher.\n router.use('/static/docs', publisher.docsRouter());\n\n return router;\n}\n\n/**\n * Create an event-stream response that emits the events 'log', 'error', and 'finish'.\n *\n * @param res - the response to write the event-stream to\n * @returns A tuple of <log, error, finish> callbacks to emit messages. A call to 'error' or 'finish'\n * will close the event-stream.\n */\nexport function createEventStream(\n res: Response<any, any>,\n): DocsSynchronizerSyncOpts {\n // Mandatory headers and http status to keep connection open\n res.writeHead(200, {\n Connection: 'keep-alive',\n 'Cache-Control': 'no-cache',\n 'Content-Type': 'text/event-stream',\n });\n\n // client closes connection\n res.socket?.on('close', () => {\n res.end();\n });\n\n // write the event to the stream\n const send = (type: 'error' | 'finish' | 'log', data: any) => {\n res.write(`event: ${type}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n\n // res.flush() is only available with the compression middleware\n if (res.flush) {\n res.flush();\n }\n };\n\n return {\n log: data => {\n send('log', data);\n },\n\n error: e => {\n send('error', e.message);\n res.end();\n },\n\n finish: result => {\n send('finish', result);\n res.end();\n },\n };\n}\n"],"names":["Router","catalogClient","CatalogClient","DefaultDocsBuildStrategy","CachedEntityLoader","TechDocsCache","ScmIntegrations","DocsSynchronizer","NotFoundError","stringifyEntityRef","getLocationForEntity","createCacheMiddleware"],"mappings":";;;;;;;;;;;;;;;;;;AAoGA,SAAS,oBACP,GAAA,EACqC;AACrC,EAAA,OAAQ,IAAqC,SAAA,KAAc,MAAA;AAC7D;AAOA,eAAsB,aACpB,OAAA,EACyB;AACzB,EAAA,MAAM,SAASA,uBAAA,EAAO;AACtB,EAAA,MAAM,EAAE,SAAA,EAAW,MAAA,EAAQ,QAAQ,SAAA,EAAW,QAAA,EAAU,MAAK,GAAI,OAAA;AAEjE,EAAA,MAAMC,eAAA,GACJ,QAAQ,aAAA,IAAiB,IAAIC,4BAAc,EAAE,YAAA,EAAc,WAAW,CAAA;AACxE,EAAA,MAAM,iBAAA,GACJ,OAAA,CAAQ,iBAAA,IAAqBC,iDAAA,CAAyB,WAAW,MAAM,CAAA;AACzE,EAAA,MAAM,oBAAoB,OAAA,CAAQ,iBAAA;AAIlC,EAAA,MAAM,YAAA,GAAe,IAAIC,qCAAA,CAAmB;AAAA,IAC1C,IAAA;AAAA,IACA,OAAA,EAASH,eAAA;AAAA,IACT,OAAO,OAAA,CAAQ;AAAA,GAChB,CAAA;AAGD,EAAA,IAAI,KAAA;AACJ,EAAA,MAAM,UAAA,GAAa,MAAA,CAAO,iBAAA,CAAkB,oBAAoB,CAAA;AAChE,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,MAAM,cAAc,OAAA,CAAQ,KAAA,CAAM,WAAA,CAAY,EAAE,YAAY,CAAA;AAC5D,IAAA,KAAA,GAAQI,4BAAc,UAAA,CAAW,MAAA,EAAQ,EAAE,KAAA,EAAO,W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I;AAAA,IACV,CAAA;AAAA,IAEA,QAAQ,CAAA,MAAA,KAAU;AAChB,MAAA,IAAA,CAAK,UAAU,MAAM,CAAA;AACrB,MAAA,GAAA,CAAI,GAAA,EAAI;AAAA,IACV;AAAA,GACF;AACF;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-techdocs-backend",
3
- "version": "2.0.5-next.1",
3
+ "version": "2.0.5",
4
4
  "description": "The Backstage backend plugin that renders technical documentation for your components",
5
5
  "backstage": {
6
6
  "role": "backend-plugin",
@@ -72,19 +72,19 @@
72
72
  "test": "backstage-cli package test"
73
73
  },
74
74
  "dependencies": {
75
- "@backstage/backend-defaults": "0.11.2-next.0",
76
- "@backstage/backend-plugin-api": "1.4.2-next.0",
77
- "@backstage/catalog-client": "1.11.0-next.0",
78
- "@backstage/catalog-model": "1.7.5",
79
- "@backstage/config": "1.3.3",
80
- "@backstage/errors": "1.2.7",
81
- "@backstage/integration": "1.17.1",
82
- "@backstage/plugin-catalog-common": "1.1.5",
83
- "@backstage/plugin-catalog-node": "1.18.0-next.0",
84
- "@backstage/plugin-permission-common": "0.9.1",
85
- "@backstage/plugin-search-backend-module-techdocs": "0.4.5-next.0",
86
- "@backstage/plugin-techdocs-common": "0.1.1",
87
- "@backstage/plugin-techdocs-node": "1.13.6-next.0",
75
+ "@backstage/backend-defaults": "^0.12.0",
76
+ "@backstage/backend-plugin-api": "^1.4.2",
77
+ "@backstage/catalog-client": "^1.11.0",
78
+ "@backstage/catalog-model": "^1.7.5",
79
+ "@backstage/config": "^1.3.3",
80
+ "@backstage/errors": "^1.2.7",
81
+ "@backstage/integration": "^1.17.1",
82
+ "@backstage/plugin-catalog-common": "^1.1.5",
83
+ "@backstage/plugin-catalog-node": "^1.18.0",
84
+ "@backstage/plugin-permission-common": "^0.9.1",
85
+ "@backstage/plugin-search-backend-module-techdocs": "^0.4.5",
86
+ "@backstage/plugin-techdocs-common": "^0.1.1",
87
+ "@backstage/plugin-techdocs-node": "^1.13.6",
88
88
  "express": "^4.17.1",
89
89
  "express-promise-router": "^4.1.0",
90
90
  "fs-extra": "^11.2.0",
@@ -94,9 +94,9 @@
94
94
  "winston": "^3.2.1"
95
95
  },
96
96
  "devDependencies": {
97
- "@backstage/backend-defaults": "0.11.2-next.0",
98
- "@backstage/backend-test-utils": "1.7.1-next.0",
99
- "@backstage/cli": "0.34.0-next.1",
97
+ "@backstage/backend-defaults": "^0.12.0",
98
+ "@backstage/backend-test-utils": "^1.8.0",
99
+ "@backstage/cli": "^0.34.0",
100
100
  "@types/express": "^4.17.6",
101
101
  "msw": "^2.0.0",
102
102
  "supertest": "^7.0.0"