@backstage/plugin-scaffolder-backend-module-confluence-to-markdown 0.3.1-next.1 → 0.3.1-next.2

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,17 @@
1
1
  # @backstage/plugin-scaffolder-backend-module-confluence-to-markdown
2
2
 
3
+ ## 0.3.1-next.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 720a2f9: Updated dependency `git-url-parse` to `^15.0.0`.
8
+ - Updated dependencies
9
+ - @backstage/integration@1.15.1-next.1
10
+ - @backstage/plugin-scaffolder-node@0.5.0-next.2
11
+ - @backstage/backend-plugin-api@1.0.1-next.1
12
+ - @backstage/config@1.2.0
13
+ - @backstage/errors@1.2.4
14
+
3
15
  ## 0.3.1-next.1
4
16
 
5
17
  ### Patch Changes
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ var pluginScaffolderNode = require('@backstage/plugin-scaffolder-node');
4
+ var errors = require('@backstage/errors');
5
+ var nodeHtmlMarkdown = require('node-html-markdown');
6
+ var fs = require('fs-extra');
7
+ var parseGitUrl = require('git-url-parse');
8
+ var YAML = require('yaml');
9
+ var helpers = require('./helpers.cjs.js');
10
+ var confluenceToMarkdown_examples = require('./confluenceToMarkdown.examples.cjs.js');
11
+
12
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
13
+
14
+ var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
15
+ var parseGitUrl__default = /*#__PURE__*/_interopDefaultCompat(parseGitUrl);
16
+ var YAML__default = /*#__PURE__*/_interopDefaultCompat(YAML);
17
+
18
+ const createConfluenceToMarkdownAction = (options) => {
19
+ const { config, reader, integrations } = options;
20
+ return pluginScaffolderNode.createTemplateAction({
21
+ id: "confluence:transform:markdown",
22
+ description: "Transforms Confluence content to Markdown",
23
+ examples: confluenceToMarkdown_examples.examples,
24
+ schema: {
25
+ input: {
26
+ properties: {
27
+ confluenceUrls: {
28
+ type: "array",
29
+ title: "Confluence URL",
30
+ description: "Paste your Confluence url. Ensure it follows this format: https://{confluence+base+url}/display/{spacekey}/{page+title} or https://{confluence+base+url}/spaces/{spacekey}/pages/1234567/{page+title} for Confluence Cloud",
31
+ items: {
32
+ type: "string",
33
+ default: "Confluence URL"
34
+ }
35
+ },
36
+ repoUrl: {
37
+ type: "string",
38
+ title: "GitHub Repo Url",
39
+ description: "mkdocs.yml file location inside the github repo you want to store the document"
40
+ }
41
+ }
42
+ }
43
+ },
44
+ async handler(ctx) {
45
+ const confluenceConfig = helpers.getConfluenceConfig(config);
46
+ const { confluenceUrls, repoUrl } = ctx.input;
47
+ const parsedRepoUrl = parseGitUrl__default.default(repoUrl);
48
+ const filePathToMkdocs = parsedRepoUrl.filepath.substring(
49
+ 0,
50
+ parsedRepoUrl.filepath.lastIndexOf("/") + 1
51
+ );
52
+ const dirPath = ctx.workspacePath;
53
+ const repoFileDir = `${dirPath}/${parsedRepoUrl.filepath}`;
54
+ let productArray = [];
55
+ ctx.logger.info(`Fetching the mkdocs.yml catalog from ${repoUrl}`);
56
+ await pluginScaffolderNode.fetchContents({
57
+ reader,
58
+ integrations,
59
+ baseUrl: ctx.templateInfo?.baseUrl,
60
+ fetchUrl: `https://${parsedRepoUrl.resource}/${parsedRepoUrl.owner}/${parsedRepoUrl.name}`,
61
+ outputPath: ctx.workspacePath
62
+ });
63
+ for (const url of confluenceUrls) {
64
+ const { spacekey, title, titleWithSpaces } = helpers.createConfluenceVariables(url);
65
+ ctx.logger.info(`Fetching the Confluence content for ${url}`);
66
+ const getConfluenceDoc = await helpers.fetchConfluence(
67
+ `/rest/api/content?title=${title}&spaceKey=${spacekey}&expand=body.export_view`,
68
+ confluenceConfig
69
+ );
70
+ if (getConfluenceDoc.results.length === 0) {
71
+ throw new errors.InputError(
72
+ `Could not find document ${url}. Please check your input.`
73
+ );
74
+ }
75
+ const getDocAttachments = await helpers.fetchConfluence(
76
+ `/rest/api/content/${getConfluenceDoc.results[0].id}/child/attachment`,
77
+ confluenceConfig
78
+ );
79
+ if (getDocAttachments.results.length) {
80
+ fs__default.default.mkdirSync(`${dirPath}/${filePathToMkdocs}docs/img`, {
81
+ recursive: true
82
+ });
83
+ productArray = await helpers.getAndWriteAttachments(
84
+ getDocAttachments,
85
+ dirPath,
86
+ confluenceConfig,
87
+ filePathToMkdocs
88
+ );
89
+ }
90
+ ctx.logger.info(
91
+ `starting action for converting ${titleWithSpaces} from Confluence To Markdown`
92
+ );
93
+ const mkdocsFileContent = await helpers.readFileAsString(repoFileDir);
94
+ const mkdocsFile = await YAML__default.default.parse(mkdocsFileContent);
95
+ ctx.logger.info(
96
+ `Adding new file - ${titleWithSpaces} to the current mkdocs.yml file`
97
+ );
98
+ if (mkdocsFile !== void 0 && mkdocsFile.hasOwnProperty("nav")) {
99
+ const { nav } = mkdocsFile;
100
+ if (!nav.some((i) => i.hasOwnProperty(titleWithSpaces))) {
101
+ nav.push({
102
+ [titleWithSpaces]: `${titleWithSpaces.replace(/\s+/g, "-")}.md`
103
+ });
104
+ mkdocsFile.nav = nav;
105
+ } else {
106
+ throw new errors.ConflictError(
107
+ "This document looks to exist inside the GitHub repo. Will end the action."
108
+ );
109
+ }
110
+ }
111
+ await fs__default.default.writeFile(repoFileDir, YAML__default.default.stringify(mkdocsFile));
112
+ const html = getConfluenceDoc.results[0].body.export_view.value;
113
+ const markdownToPublish = nodeHtmlMarkdown.NodeHtmlMarkdown.translate(html);
114
+ let newString = markdownToPublish;
115
+ productArray.forEach((product) => {
116
+ const regex = product[0].includes(".pdf") ? new RegExp(`(\\[.*?\\]\\()(.*?${product[0]}.*?)(\\))`, "gi") : new RegExp(`(\\!\\[.*?\\]\\()(.*?${product[0]}.*?)(\\))`, "gi");
117
+ newString = newString.replace(regex, `$1./img/${product[1]}$3`);
118
+ });
119
+ ctx.logger.info(`Adding new file to repo.`);
120
+ await fs__default.default.outputFile(
121
+ `${dirPath}/${filePathToMkdocs}docs/${titleWithSpaces.replace(
122
+ /\s+/g,
123
+ "-"
124
+ )}.md`,
125
+ newString
126
+ );
127
+ }
128
+ ctx.output("repo", parsedRepoUrl.name);
129
+ ctx.output("owner", parsedRepoUrl.owner);
130
+ }
131
+ });
132
+ };
133
+
134
+ exports.createConfluenceToMarkdownAction = createConfluenceToMarkdownAction;
135
+ //# sourceMappingURL=confluenceToMarkdown.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"confluenceToMarkdown.cjs.js","sources":["../../../src/actions/confluence/confluenceToMarkdown.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 { Config } from '@backstage/config';\nimport { ScmIntegrations } from '@backstage/integration';\nimport {\n createTemplateAction,\n fetchContents,\n} from '@backstage/plugin-scaffolder-node';\nimport { InputError, ConflictError } from '@backstage/errors';\nimport { NodeHtmlMarkdown } from 'node-html-markdown';\nimport fs from 'fs-extra';\nimport parseGitUrl from 'git-url-parse';\nimport YAML from 'yaml';\nimport {\n readFileAsString,\n fetchConfluence,\n getAndWriteAttachments,\n createConfluenceVariables,\n getConfluenceConfig,\n} from './helpers';\nimport { examples } from './confluenceToMarkdown.examples';\nimport { UrlReaderService } from '@backstage/backend-plugin-api';\n\n/**\n * @public\n */\n\nexport const createConfluenceToMarkdownAction = (options: {\n reader: UrlReaderService;\n integrations: ScmIntegrations;\n config: Config;\n}) => {\n const { config, reader, integrations } = options;\n type Obj = {\n [key: string]: string;\n };\n\n return createTemplateAction<{\n confluenceUrls: string[];\n repoUrl: string;\n }>({\n id: 'confluence:transform:markdown',\n description: 'Transforms Confluence content to Markdown',\n examples,\n schema: {\n input: {\n properties: {\n confluenceUrls: {\n type: 'array',\n title: 'Confluence URL',\n description:\n 'Paste your Confluence url. Ensure it follows this format: https://{confluence+base+url}/display/{spacekey}/{page+title} or https://{confluence+base+url}/spaces/{spacekey}/pages/1234567/{page+title} for Confluence Cloud',\n items: {\n type: 'string',\n default: 'Confluence URL',\n },\n },\n repoUrl: {\n type: 'string',\n title: 'GitHub Repo Url',\n description:\n 'mkdocs.yml file location inside the github repo you want to store the document',\n },\n },\n },\n },\n async handler(ctx) {\n const confluenceConfig = getConfluenceConfig(config);\n const { confluenceUrls, repoUrl } = ctx.input;\n const parsedRepoUrl = parseGitUrl(repoUrl);\n const filePathToMkdocs = parsedRepoUrl.filepath.substring(\n 0,\n parsedRepoUrl.filepath.lastIndexOf('/') + 1,\n );\n const dirPath = ctx.workspacePath;\n const repoFileDir = `${dirPath}/${parsedRepoUrl.filepath}`;\n let productArray: string[][] = [];\n\n ctx.logger.info(`Fetching the mkdocs.yml catalog from ${repoUrl}`);\n\n // This grabs the files from Github\n await fetchContents({\n reader,\n integrations,\n baseUrl: ctx.templateInfo?.baseUrl,\n fetchUrl: `https://${parsedRepoUrl.resource}/${parsedRepoUrl.owner}/${parsedRepoUrl.name}`,\n outputPath: ctx.workspacePath,\n });\n\n for (const url of confluenceUrls) {\n const { spacekey, title, titleWithSpaces } =\n createConfluenceVariables(url);\n // This calls confluence to get the page html and page id\n ctx.logger.info(`Fetching the Confluence content for ${url}`);\n const getConfluenceDoc = await fetchConfluence(\n `/rest/api/content?title=${title}&spaceKey=${spacekey}&expand=body.export_view`,\n confluenceConfig,\n );\n if (getConfluenceDoc.results.length === 0) {\n throw new InputError(\n `Could not find document ${url}. Please check your input.`,\n );\n }\n // This gets attachments for the confluence page if they exist\n const getDocAttachments = await fetchConfluence(\n `/rest/api/content/${getConfluenceDoc.results[0].id}/child/attachment`,\n confluenceConfig,\n );\n\n if (getDocAttachments.results.length) {\n fs.mkdirSync(`${dirPath}/${filePathToMkdocs}docs/img`, {\n recursive: true,\n });\n productArray = await getAndWriteAttachments(\n getDocAttachments,\n dirPath,\n confluenceConfig,\n filePathToMkdocs,\n );\n }\n\n ctx.logger.info(\n `starting action for converting ${titleWithSpaces} from Confluence To Markdown`,\n );\n\n // This reads mkdocs.yml file\n const mkdocsFileContent = await readFileAsString(repoFileDir);\n const mkdocsFile = await YAML.parse(mkdocsFileContent);\n ctx.logger.info(\n `Adding new file - ${titleWithSpaces} to the current mkdocs.yml file`,\n );\n\n // This modifies the mkdocs.yml file\n if (mkdocsFile !== undefined && mkdocsFile.hasOwnProperty('nav')) {\n const { nav } = mkdocsFile;\n if (!nav.some((i: Obj) => i.hasOwnProperty(titleWithSpaces))) {\n nav.push({\n [titleWithSpaces]: `${titleWithSpaces.replace(/\\s+/g, '-')}.md`,\n });\n mkdocsFile.nav = nav;\n } else {\n throw new ConflictError(\n 'This document looks to exist inside the GitHub repo. Will end the action.',\n );\n }\n }\n\n await fs.writeFile(repoFileDir, YAML.stringify(mkdocsFile));\n\n // This grabs the confluence html and converts it to markdown and adds attachments\n const html = getConfluenceDoc.results[0].body.export_view.value;\n const markdownToPublish = NodeHtmlMarkdown.translate(html);\n let newString: string = markdownToPublish;\n productArray.forEach((product: string[]) => {\n // This regex is looking for either [](link to confluence) or ![](link to confluence) in the newly created markdown doc and updating it to point to the versions saved(in ./docs/img) in the local version of GitHub Repo during getAndWriteAttachments\n const regex = product[0].includes('.pdf')\n ? new RegExp(`(\\\\[.*?\\\\]\\\\()(.*?${product[0]}.*?)(\\\\))`, 'gi')\n : new RegExp(`(\\\\!\\\\[.*?\\\\]\\\\()(.*?${product[0]}.*?)(\\\\))`, 'gi');\n newString = newString.replace(regex, `$1./img/${product[1]}$3`);\n });\n\n ctx.logger.info(`Adding new file to repo.`);\n await fs.outputFile(\n `${dirPath}/${filePathToMkdocs}docs/${titleWithSpaces.replace(\n /\\s+/g,\n '-',\n )}.md`,\n newString,\n );\n }\n\n ctx.output('repo', parsedRepoUrl.name);\n ctx.output('owner', parsedRepoUrl.owner);\n },\n });\n};\n"],"names":["createTemplateAction","examples","getConfluenceConfig","parseGitUrl","fetchContents","createConfluenceVariables","fetchConfluence","InputError","fs","getAndWriteAttachments","readFileAsString","YAML","ConflictError","NodeHtmlMarkdown"],"mappings":";;;;;;;;;;;;;;;;;AAyCa,MAAA,gCAAA,GAAmC,CAAC,OAI3C,KAAA;AACJ,EAAA,MAAM,EAAE,MAAA,EAAQ,MAAQ,EAAA,YAAA,EAAiB,GAAA,OAAA,CAAA;AAKzC,EAAA,OAAOA,yCAGJ,CAAA;AAAA,IACD,EAAI,EAAA,+BAAA;AAAA,IACJ,WAAa,EAAA,2CAAA;AAAA,cACbC,sCAAA;AAAA,IACA,MAAQ,EAAA;AAAA,MACN,KAAO,EAAA;AAAA,QACL,UAAY,EAAA;AAAA,UACV,cAAgB,EAAA;AAAA,YACd,IAAM,EAAA,OAAA;AAAA,YACN,KAAO,EAAA,gBAAA;AAAA,YACP,WACE,EAAA,4NAAA;AAAA,YACF,KAAO,EAAA;AAAA,cACL,IAAM,EAAA,QAAA;AAAA,cACN,OAAS,EAAA,gBAAA;AAAA,aACX;AAAA,WACF;AAAA,UACA,OAAS,EAAA;AAAA,YACP,IAAM,EAAA,QAAA;AAAA,YACN,KAAO,EAAA,iBAAA;AAAA,YACP,WACE,EAAA,gFAAA;AAAA,WACJ;AAAA,SACF;AAAA,OACF;AAAA,KACF;AAAA,IACA,MAAM,QAAQ,GAAK,EAAA;AACjB,MAAM,MAAA,gBAAA,GAAmBC,4BAAoB,MAAM,CAAA,CAAA;AACnD,MAAA,MAAM,EAAE,cAAA,EAAgB,OAAQ,EAAA,GAAI,GAAI,CAAA,KAAA,CAAA;AACxC,MAAM,MAAA,aAAA,GAAgBC,6BAAY,OAAO,CAAA,CAAA;AACzC,MAAM,MAAA,gBAAA,GAAmB,cAAc,QAAS,CAAA,SAAA;AAAA,QAC9C,CAAA;AAA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A;AAAA,YACpD,MAAA;AAAA,YACA,GAAA;AAAA,WACD,CAAA,GAAA,CAAA;AAAA,UACD,SAAA;AAAA,SACF,CAAA;AAAA,OACF;AAEA,MAAI,GAAA,CAAA,MAAA,CAAO,MAAQ,EAAA,aAAA,CAAc,IAAI,CAAA,CAAA;AACrC,MAAI,GAAA,CAAA,MAAA,CAAO,OAAS,EAAA,aAAA,CAAc,KAAK,CAAA,CAAA;AAAA,KACzC;AAAA,GACD,CAAA,CAAA;AACH;;;;"}
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ var YAML = require('yaml');
4
+
5
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
6
+
7
+ var YAML__default = /*#__PURE__*/_interopDefaultCompat(YAML);
8
+
9
+ const examples = [
10
+ {
11
+ description: "Downloads content from provided Confluence URLs and converts it to Markdown.",
12
+ example: YAML__default.default.stringify({
13
+ steps: [
14
+ {
15
+ action: "confluence:transform:markdown",
16
+ id: "confluence-transform-markdown",
17
+ name: "Transform Confluence content to Markdown",
18
+ input: {
19
+ confluenceUrls: [
20
+ "https://confluence.example.com/display/SPACEKEY/Page+Title"
21
+ ],
22
+ repoUrl: "https://github.com/organization-name/repo-name/blob/main/mkdocs.yml"
23
+ }
24
+ }
25
+ ]
26
+ })
27
+ }
28
+ ];
29
+
30
+ exports.examples = examples;
31
+ //# sourceMappingURL=confluenceToMarkdown.examples.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"confluenceToMarkdown.examples.cjs.js","sources":["../../../src/actions/confluence/confluenceToMarkdown.examples.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 { TemplateExample } from '@backstage/plugin-scaffolder-node';\nimport yaml from 'yaml';\n\nexport const examples: TemplateExample[] = [\n {\n description:\n 'Downloads content from provided Confluence URLs and converts it to Markdown.',\n example: yaml.stringify({\n steps: [\n {\n action: 'confluence:transform:markdown',\n id: 'confluence-transform-markdown',\n name: 'Transform Confluence content to Markdown',\n input: {\n confluenceUrls: [\n 'https://confluence.example.com/display/SPACEKEY/Page+Title',\n ],\n repoUrl:\n 'https://github.com/organization-name/repo-name/blob/main/mkdocs.yml',\n },\n },\n ],\n }),\n },\n];\n"],"names":["yaml"],"mappings":";;;;;;;;AAmBO,MAAM,QAA8B,GAAA;AAAA,EACzC;AAAA,IACE,WACE,EAAA,8EAAA;AAAA,IACF,OAAA,EAASA,sBAAK,SAAU,CAAA;AAAA,MACtB,KAAO,EAAA;AAAA,QACL;AAAA,UACE,MAAQ,EAAA,+BAAA;AAAA,UACR,EAAI,EAAA,+BAAA;AAAA,UACJ,IAAM,EAAA,0CAAA;AAAA,UACN,KAAO,EAAA;AAAA,YACL,cAAgB,EAAA;AAAA,cACd,4DAAA;AAAA,aACF;AAAA,YACA,OACE,EAAA,qEAAA;AAAA,WACJ;AAAA,SACF;AAAA,OACF;AAAA,KACD,CAAA;AAAA,GACH;AACF;;;;"}
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+
3
+ var errors = require('@backstage/errors');
4
+ var fs = require('fs-extra');
5
+ var fetch = require('node-fetch');
6
+
7
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
8
+
9
+ var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
10
+ var fetch__default = /*#__PURE__*/_interopDefaultCompat(fetch);
11
+
12
+ const getConfluenceConfig = (config) => {
13
+ const confluenceConfig = {
14
+ baseUrl: config.getString("confluence.baseUrl"),
15
+ auth: config.getOptionalString("confluence.auth.type") ?? "bearer",
16
+ token: config.getOptionalString("confluence.auth.token"),
17
+ email: config.getOptionalString("confluence.auth.email"),
18
+ username: config.getOptionalString("confluence.auth.username"),
19
+ password: config.getOptionalString("confluence.auth.password")
20
+ };
21
+ if ((confluenceConfig.auth === "basic" || confluenceConfig.auth === "bearer") && !confluenceConfig.token) {
22
+ throw new Error(
23
+ `No token provided for the configured '${confluenceConfig.auth}' auth method`
24
+ );
25
+ }
26
+ if (confluenceConfig.auth === "basic" && !confluenceConfig.email) {
27
+ throw new Error(
28
+ `No email provided for the configured '${confluenceConfig.auth}' auth method`
29
+ );
30
+ }
31
+ if (confluenceConfig.auth === "userpass" && (!confluenceConfig.username || !confluenceConfig.password)) {
32
+ throw new Error(
33
+ `No username/password provided for the configured '${confluenceConfig.auth}' auth method`
34
+ );
35
+ }
36
+ return confluenceConfig;
37
+ };
38
+ const getAuthorizationHeaderValue = (config) => {
39
+ switch (config.auth) {
40
+ case "bearer":
41
+ return `Bearer ${config.token}`;
42
+ case "basic": {
43
+ const buffer = Buffer.from(`${config.email}:${config.token}`, "utf8");
44
+ return `Basic ${buffer.toString("base64")}`;
45
+ }
46
+ case "userpass": {
47
+ const buffer = Buffer.from(
48
+ `${config.username}:${config.password}`,
49
+ "utf8"
50
+ );
51
+ return `Basic ${buffer.toString("base64")}`;
52
+ }
53
+ default:
54
+ throw new Error(`Unknown auth method '${config.auth}' provided`);
55
+ }
56
+ };
57
+ const readFileAsString = async (fileDir) => {
58
+ const content = await fs__default.default.readFile(fileDir, "utf-8");
59
+ return content.toString();
60
+ };
61
+ const fetchConfluence = async (relativeUrl, config) => {
62
+ const baseUrl = config.baseUrl;
63
+ const authHeaderValue = getAuthorizationHeaderValue(config);
64
+ const url = `${baseUrl}${relativeUrl}`;
65
+ const response = await fetch__default.default(url, {
66
+ method: "GET",
67
+ headers: {
68
+ Authorization: authHeaderValue
69
+ }
70
+ });
71
+ if (!response.ok) {
72
+ throw await errors.ResponseError.fromResponse(response);
73
+ }
74
+ return response.json();
75
+ };
76
+ const getAndWriteAttachments = async (arr, workspace, config, mkdocsDir) => {
77
+ const productArr = [];
78
+ const baseUrl = config.baseUrl;
79
+ const authHeaderValue = getAuthorizationHeaderValue(config);
80
+ await Promise.all(
81
+ await arr.results.map(async (result) => {
82
+ const downloadLink = result._links.download;
83
+ const downloadTitle = result.title.replace(/ /g, "-");
84
+ if (result.metadata.mediaType !== "application/gliffy+json") {
85
+ productArr.push([result.title.replace(/ /g, "%20"), downloadTitle]);
86
+ }
87
+ const url = `${baseUrl}${downloadLink}`;
88
+ const res = await fetch__default.default(url, {
89
+ method: "GET",
90
+ headers: {
91
+ Authorization: authHeaderValue
92
+ }
93
+ });
94
+ if (!res.ok) {
95
+ throw await errors.ResponseError.fromResponse(res);
96
+ } else if (res.body !== null) {
97
+ fs__default.default.openSync(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`, "w");
98
+ const writeStream = fs__default.default.createWriteStream(
99
+ `${workspace}/${mkdocsDir}docs/img/${downloadTitle}`
100
+ );
101
+ res.body.pipe(writeStream);
102
+ await new Promise((resolve, reject) => {
103
+ writeStream.on("finish", () => {
104
+ resolve(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`);
105
+ });
106
+ writeStream.on("error", reject);
107
+ });
108
+ } else {
109
+ throw new errors.ConflictError(
110
+ "No Body on the response. Can not save images from Confluence Doc"
111
+ );
112
+ }
113
+ })
114
+ );
115
+ return productArr;
116
+ };
117
+ const createConfluenceVariables = (url) => {
118
+ let spacekey = void 0;
119
+ let title = void 0;
120
+ let titleWithSpaces = "";
121
+ const params = new URL(url);
122
+ if (params.pathname.split("/")[1] === "display") {
123
+ spacekey = params.pathname.split("/")[2];
124
+ title = params.pathname.split("/")[3];
125
+ titleWithSpaces = title?.replace(/\+/g, " ");
126
+ return { spacekey, title, titleWithSpaces };
127
+ } else if (params.pathname.split("/")[2] === "display") {
128
+ spacekey = params.pathname.split("/")[3];
129
+ title = params.pathname.split("/")[4];
130
+ titleWithSpaces = title?.replace(/\+/g, " ");
131
+ return { spacekey, title, titleWithSpaces };
132
+ } else if (params.pathname.split("/")[2] === "spaces") {
133
+ spacekey = params.pathname.split("/")[3];
134
+ title = params.pathname.split("/")[6];
135
+ titleWithSpaces = title?.replace(/\+/g, " ");
136
+ return { spacekey, title, titleWithSpaces };
137
+ }
138
+ throw new errors.InputError(
139
+ "The Url format for Confluence is incorrect. Acceptable format is `<CONFLUENCE_BASE_URL>/display/<SPACEKEY>/<PAGE+TITLE>` or `<CONFLUENCE_BASE_URL>/spaces/<SPACEKEY>/pages/<PAGEID>/<PAGE+TITLE>` for Confluence cloud"
140
+ );
141
+ };
142
+
143
+ exports.createConfluenceVariables = createConfluenceVariables;
144
+ exports.fetchConfluence = fetchConfluence;
145
+ exports.getAndWriteAttachments = getAndWriteAttachments;
146
+ exports.getAuthorizationHeaderValue = getAuthorizationHeaderValue;
147
+ exports.getConfluenceConfig = getConfluenceConfig;
148
+ exports.readFileAsString = readFileAsString;
149
+ //# sourceMappingURL=helpers.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.cjs.js","sources":["../../../src/actions/confluence/helpers.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 { Config } from '@backstage/config';\nimport { ResponseError, ConflictError, InputError } from '@backstage/errors';\nimport fs from 'fs-extra';\nimport fetch, { Response } from 'node-fetch';\n\ninterface Links {\n webui: string;\n download: string;\n thumbnail: string;\n self: string;\n}\n\ninterface Metadata {\n mediaType: string;\n}\n\nexport interface Result {\n id: string;\n type: string;\n status: string;\n title: string;\n metadata: Metadata;\n _links: Links;\n}\n\nexport interface Results {\n results: Result[];\n}\n\nexport type LocalConfluenceConfig = {\n baseUrl: string;\n auth: string;\n token?: string;\n email?: string;\n username?: string;\n password?: string;\n};\n\nexport const getConfluenceConfig = (config: Config) => {\n const confluenceConfig = {\n baseUrl: config.getString('confluence.baseUrl'),\n auth: config.getOptionalString('confluence.auth.type') ?? 'bearer',\n token: config.getOptionalString('confluence.auth.token'),\n email: config.getOptionalString('confluence.auth.email'),\n username: config.getOptionalString('confluence.auth.username'),\n password: config.getOptionalString('confluence.auth.password'),\n };\n\n if (\n (confluenceConfig.auth === 'basic' || confluenceConfig.auth === 'bearer') &&\n !confluenceConfig.token\n ) {\n throw new Error(\n `No token provided for the configured '${confluenceConfig.auth}' auth method`,\n );\n }\n\n if (confluenceConfig.auth === 'basic' && !confluenceConfig.email) {\n throw new Error(\n `No email provided for the configured '${confluenceConfig.auth}' auth method`,\n );\n }\n\n if (\n confluenceConfig.auth === 'userpass' &&\n (!confluenceConfig.username || !confluenceConfig.password)\n ) {\n throw new Error(\n `No username/password provided for the configured '${confluenceConfig.auth}' auth method`,\n );\n }\n\n return confluenceConfig;\n};\n\nexport const getAuthorizationHeaderValue = (config: LocalConfluenceConfig) => {\n switch (config.auth) {\n case 'bearer':\n return `Bearer ${config.token}`;\n case 'basic': {\n const buffer = Buffer.from(`${config.email}:${config.token}`, 'utf8');\n return `Basic ${buffer.toString('base64')}`;\n }\n case 'userpass': {\n const buffer = Buffer.from(\n `${config.username}:${config.password}`,\n 'utf8',\n );\n return `Basic ${buffer.toString('base64')}`;\n }\n default:\n throw new Error(`Unknown auth method '${config.auth}' provided`);\n }\n};\n\nexport const readFileAsString = async (fileDir: string) => {\n const content = await fs.readFile(fileDir, 'utf-8');\n return content.toString();\n};\n\nexport const fetchConfluence = async (\n relativeUrl: string,\n config: LocalConfluenceConfig,\n) => {\n const baseUrl = config.baseUrl;\n const authHeaderValue = getAuthorizationHeaderValue(config);\n const url = `${baseUrl}${relativeUrl}`;\n const response: Response = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: authHeaderValue,\n },\n });\n if (!response.ok) {\n throw await ResponseError.fromResponse(response);\n }\n\n return response.json();\n};\n\nexport const getAndWriteAttachments = async (\n arr: Results,\n workspace: string,\n config: LocalConfluenceConfig,\n mkdocsDir: string,\n) => {\n const productArr: string[][] = [];\n const baseUrl = config.baseUrl;\n const authHeaderValue = getAuthorizationHeaderValue(config);\n await Promise.all(\n await arr.results.map(async (result: Result) => {\n const downloadLink = result._links.download;\n const downloadTitle = result.title.replace(/ /g, '-');\n if (result.metadata.mediaType !== 'application/gliffy+json') {\n productArr.push([result.title.replace(/ /g, '%20'), downloadTitle]);\n }\n const url = `${baseUrl}${downloadLink}`;\n const res = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: authHeaderValue,\n },\n });\n if (!res.ok) {\n throw await ResponseError.fromResponse(res);\n } else if (res.body !== null) {\n fs.openSync(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`, 'w');\n const writeStream = fs.createWriteStream(\n `${workspace}/${mkdocsDir}docs/img/${downloadTitle}`,\n );\n res.body.pipe(writeStream);\n await new Promise((resolve, reject) => {\n writeStream.on('finish', () => {\n resolve(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`);\n });\n writeStream.on('error', reject);\n });\n } else {\n throw new ConflictError(\n 'No Body on the response. Can not save images from Confluence Doc',\n );\n }\n }),\n );\n return productArr;\n};\n\nexport const createConfluenceVariables = (url: string) => {\n let spacekey: string | undefined = undefined;\n let title: string | undefined = undefined;\n let titleWithSpaces: string | undefined = '';\n const params = new URL(url);\n if (params.pathname.split('/')[1] === 'display') {\n // https://confluence.example.com/display/SPACEKEY/Page+Title\n spacekey = params.pathname.split('/')[2];\n title = params.pathname.split('/')[3];\n titleWithSpaces = title?.replace(/\\+/g, ' ');\n return { spacekey, title, titleWithSpaces };\n } else if (params.pathname.split('/')[2] === 'display') {\n // https://confluence.example.com/prefix/display/SPACEKEY/Page+Title\n spacekey = params.pathname.split('/')[3];\n title = params.pathname.split('/')[4];\n titleWithSpaces = title?.replace(/\\+/g, ' ');\n return { spacekey, title, titleWithSpaces };\n } else if (params.pathname.split('/')[2] === 'spaces') {\n // https://example.atlassian.net/wiki/spaces/SPACEKEY/pages/1234567/Page+Title\n spacekey = params.pathname.split('/')[3];\n title = params.pathname.split('/')[6];\n titleWithSpaces = title?.replace(/\\+/g, ' ');\n return { spacekey, title, titleWithSpaces };\n }\n throw new InputError(\n 'The Url format for Confluence is incorrect. Acceptable format is `<CONFLUENCE_BASE_URL>/display/<SPACEKEY>/<PAGE+TITLE>` or `<CONFLUENCE_BASE_URL>/spaces/<SPACEKEY>/pages/<PAGEID>/<PAGE+TITLE>` for Confluence cloud',\n );\n};\n"],"names":["fs","fetch","ResponseError","ConflictError","InputError"],"mappings":";;;;;;;;;;;AAsDa,MAAA,mBAAA,GAAsB,CAAC,MAAmB,KAAA;AACrD,EAAA,MAAM,gBAAmB,GAAA;AAAA,IACvB,OAAA,EAAS,MAAO,CAAA,SAAA,CAAU,oBAAoB,CAAA;AAAA,IAC9C,IAAM,EAAA,MAAA,CAAO,iBAAkB,CAAA,sBAAsB,CAAK,IAAA,QAAA;AAAA,IAC1D,KAAA,EAAO,MAAO,CAAA,iBAAA,CAAkB,uBAAuB,CAAA;AAAA,IACvD,KAAA,EAAO,MAAO,CAAA,iBAAA,CAAkB,uBAAuB,CAAA;AAAA,IACvD,QAAA,EAAU,MAAO,CAAA,iBAAA,CAAkB,0BAA0B,CAAA;AAAA,IAC7D,QAAA,EAAU,MAAO,CAAA,iBAAA,CAAkB,0BAA0B,CAAA;AAAA,GAC/D,CAAA;AAEA,EACG,IAAA,CAAA,gBAAA,CAAiB,SAAS,OAAW,IAAA,gBAAA,CAAiB,SAAS,QAChE,KAAA,CAAC,iBAAiB,KAClB,EAAA;AACA,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,sCAAA,EAAyC,iBAAiB,IAAI,CA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EAAA;AAEtD,IAAA,QAAA,GAAW,MAAO,CAAA,QAAA,CAAS,KAAM,CAAA,GAAG,EAAE,CAAC,CAAA,CAAA;AACvC,IAAA,KAAA,GAAQ,MAAO,CAAA,QAAA,CAAS,KAAM,CAAA,GAAG,EAAE,CAAC,CAAA,CAAA;AACpC,IAAkB,eAAA,GAAA,KAAA,EAAO,OAAQ,CAAA,KAAA,EAAO,GAAG,CAAA,CAAA;AAC3C,IAAO,OAAA,EAAE,QAAU,EAAA,KAAA,EAAO,eAAgB,EAAA,CAAA;AAAA,GAC5C,MAAA,IAAW,OAAO,QAAS,CAAA,KAAA,CAAM,GAAG,CAAE,CAAA,CAAC,MAAM,QAAU,EAAA;AAErD,IAAA,QAAA,GAAW,MAAO,CAAA,QAAA,CAAS,KAAM,CAAA,GAAG,EAAE,CAAC,CAAA,CAAA;AACvC,IAAA,KAAA,GAAQ,MAAO,CAAA,QAAA,CAAS,KAAM,CAAA,GAAG,EAAE,CAAC,CAAA,CAAA;AACpC,IAAkB,eAAA,GAAA,KAAA,EAAO,OAAQ,CAAA,KAAA,EAAO,GAAG,CAAA,CAAA;AAC3C,IAAO,OAAA,EAAE,QAAU,EAAA,KAAA,EAAO,eAAgB,EAAA,CAAA;AAAA,GAC5C;AACA,EAAA,MAAM,IAAIC,iBAAA;AAAA,IACR,wNAAA;AAAA,GACF,CAAA;AACF;;;;;;;;;"}
package/dist/index.cjs.js CHANGED
@@ -2,316 +2,11 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var pluginScaffolderNode = require('@backstage/plugin-scaffolder-node');
6
- var errors = require('@backstage/errors');
7
- var nodeHtmlMarkdown = require('node-html-markdown');
8
- var fs = require('fs-extra');
9
- var parseGitUrl = require('git-url-parse');
10
- var YAML = require('yaml');
11
- var fetch = require('node-fetch');
12
- var backendPluginApi = require('@backstage/backend-plugin-api');
13
- var alpha = require('@backstage/plugin-scaffolder-node/alpha');
14
- var integration = require('@backstage/integration');
5
+ var confluenceToMarkdown = require('./actions/confluence/confluenceToMarkdown.cjs.js');
6
+ var module$1 = require('./module.cjs.js');
15
7
 
16
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
17
8
 
18
- var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
19
- var parseGitUrl__default = /*#__PURE__*/_interopDefaultCompat(parseGitUrl);
20
- var YAML__default = /*#__PURE__*/_interopDefaultCompat(YAML);
21
- var fetch__default = /*#__PURE__*/_interopDefaultCompat(fetch);
22
9
 
23
- const getConfluenceConfig = (config) => {
24
- const confluenceConfig = {
25
- baseUrl: config.getString("confluence.baseUrl"),
26
- auth: config.getOptionalString("confluence.auth.type") ?? "bearer",
27
- token: config.getOptionalString("confluence.auth.token"),
28
- email: config.getOptionalString("confluence.auth.email"),
29
- username: config.getOptionalString("confluence.auth.username"),
30
- password: config.getOptionalString("confluence.auth.password")
31
- };
32
- if ((confluenceConfig.auth === "basic" || confluenceConfig.auth === "bearer") && !confluenceConfig.token) {
33
- throw new Error(
34
- `No token provided for the configured '${confluenceConfig.auth}' auth method`
35
- );
36
- }
37
- if (confluenceConfig.auth === "basic" && !confluenceConfig.email) {
38
- throw new Error(
39
- `No email provided for the configured '${confluenceConfig.auth}' auth method`
40
- );
41
- }
42
- if (confluenceConfig.auth === "userpass" && (!confluenceConfig.username || !confluenceConfig.password)) {
43
- throw new Error(
44
- `No username/password provided for the configured '${confluenceConfig.auth}' auth method`
45
- );
46
- }
47
- return confluenceConfig;
48
- };
49
- const getAuthorizationHeaderValue = (config) => {
50
- switch (config.auth) {
51
- case "bearer":
52
- return `Bearer ${config.token}`;
53
- case "basic": {
54
- const buffer = Buffer.from(`${config.email}:${config.token}`, "utf8");
55
- return `Basic ${buffer.toString("base64")}`;
56
- }
57
- case "userpass": {
58
- const buffer = Buffer.from(
59
- `${config.username}:${config.password}`,
60
- "utf8"
61
- );
62
- return `Basic ${buffer.toString("base64")}`;
63
- }
64
- default:
65
- throw new Error(`Unknown auth method '${config.auth}' provided`);
66
- }
67
- };
68
- const readFileAsString = async (fileDir) => {
69
- const content = await fs__default.default.readFile(fileDir, "utf-8");
70
- return content.toString();
71
- };
72
- const fetchConfluence = async (relativeUrl, config) => {
73
- const baseUrl = config.baseUrl;
74
- const authHeaderValue = getAuthorizationHeaderValue(config);
75
- const url = `${baseUrl}${relativeUrl}`;
76
- const response = await fetch__default.default(url, {
77
- method: "GET",
78
- headers: {
79
- Authorization: authHeaderValue
80
- }
81
- });
82
- if (!response.ok) {
83
- throw await errors.ResponseError.fromResponse(response);
84
- }
85
- return response.json();
86
- };
87
- const getAndWriteAttachments = async (arr, workspace, config, mkdocsDir) => {
88
- const productArr = [];
89
- const baseUrl = config.baseUrl;
90
- const authHeaderValue = getAuthorizationHeaderValue(config);
91
- await Promise.all(
92
- await arr.results.map(async (result) => {
93
- const downloadLink = result._links.download;
94
- const downloadTitle = result.title.replace(/ /g, "-");
95
- if (result.metadata.mediaType !== "application/gliffy+json") {
96
- productArr.push([result.title.replace(/ /g, "%20"), downloadTitle]);
97
- }
98
- const url = `${baseUrl}${downloadLink}`;
99
- const res = await fetch__default.default(url, {
100
- method: "GET",
101
- headers: {
102
- Authorization: authHeaderValue
103
- }
104
- });
105
- if (!res.ok) {
106
- throw await errors.ResponseError.fromResponse(res);
107
- } else if (res.body !== null) {
108
- fs__default.default.openSync(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`, "w");
109
- const writeStream = fs__default.default.createWriteStream(
110
- `${workspace}/${mkdocsDir}docs/img/${downloadTitle}`
111
- );
112
- res.body.pipe(writeStream);
113
- await new Promise((resolve, reject) => {
114
- writeStream.on("finish", () => {
115
- resolve(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`);
116
- });
117
- writeStream.on("error", reject);
118
- });
119
- } else {
120
- throw new errors.ConflictError(
121
- "No Body on the response. Can not save images from Confluence Doc"
122
- );
123
- }
124
- })
125
- );
126
- return productArr;
127
- };
128
- const createConfluenceVariables = (url) => {
129
- let spacekey = void 0;
130
- let title = void 0;
131
- let titleWithSpaces = "";
132
- const params = new URL(url);
133
- if (params.pathname.split("/")[1] === "display") {
134
- spacekey = params.pathname.split("/")[2];
135
- title = params.pathname.split("/")[3];
136
- titleWithSpaces = title?.replace(/\+/g, " ");
137
- return { spacekey, title, titleWithSpaces };
138
- } else if (params.pathname.split("/")[2] === "display") {
139
- spacekey = params.pathname.split("/")[3];
140
- title = params.pathname.split("/")[4];
141
- titleWithSpaces = title?.replace(/\+/g, " ");
142
- return { spacekey, title, titleWithSpaces };
143
- } else if (params.pathname.split("/")[2] === "spaces") {
144
- spacekey = params.pathname.split("/")[3];
145
- title = params.pathname.split("/")[6];
146
- titleWithSpaces = title?.replace(/\+/g, " ");
147
- return { spacekey, title, titleWithSpaces };
148
- }
149
- throw new errors.InputError(
150
- "The Url format for Confluence is incorrect. Acceptable format is `<CONFLUENCE_BASE_URL>/display/<SPACEKEY>/<PAGE+TITLE>` or `<CONFLUENCE_BASE_URL>/spaces/<SPACEKEY>/pages/<PAGEID>/<PAGE+TITLE>` for Confluence cloud"
151
- );
152
- };
153
-
154
- const examples = [
155
- {
156
- description: "Downloads content from provided Confluence URLs and converts it to Markdown.",
157
- example: YAML__default.default.stringify({
158
- steps: [
159
- {
160
- action: "confluence:transform:markdown",
161
- id: "confluence-transform-markdown",
162
- name: "Transform Confluence content to Markdown",
163
- input: {
164
- confluenceUrls: [
165
- "https://confluence.example.com/display/SPACEKEY/Page+Title"
166
- ],
167
- repoUrl: "https://github.com/organization-name/repo-name/blob/main/mkdocs.yml"
168
- }
169
- }
170
- ]
171
- })
172
- }
173
- ];
174
-
175
- const createConfluenceToMarkdownAction = (options) => {
176
- const { config, reader, integrations } = options;
177
- return pluginScaffolderNode.createTemplateAction({
178
- id: "confluence:transform:markdown",
179
- description: "Transforms Confluence content to Markdown",
180
- examples,
181
- schema: {
182
- input: {
183
- properties: {
184
- confluenceUrls: {
185
- type: "array",
186
- title: "Confluence URL",
187
- description: "Paste your Confluence url. Ensure it follows this format: https://{confluence+base+url}/display/{spacekey}/{page+title} or https://{confluence+base+url}/spaces/{spacekey}/pages/1234567/{page+title} for Confluence Cloud",
188
- items: {
189
- type: "string",
190
- default: "Confluence URL"
191
- }
192
- },
193
- repoUrl: {
194
- type: "string",
195
- title: "GitHub Repo Url",
196
- description: "mkdocs.yml file location inside the github repo you want to store the document"
197
- }
198
- }
199
- }
200
- },
201
- async handler(ctx) {
202
- const confluenceConfig = getConfluenceConfig(config);
203
- const { confluenceUrls, repoUrl } = ctx.input;
204
- const parsedRepoUrl = parseGitUrl__default.default(repoUrl);
205
- const filePathToMkdocs = parsedRepoUrl.filepath.substring(
206
- 0,
207
- parsedRepoUrl.filepath.lastIndexOf("/") + 1
208
- );
209
- const dirPath = ctx.workspacePath;
210
- const repoFileDir = `${dirPath}/${parsedRepoUrl.filepath}`;
211
- let productArray = [];
212
- ctx.logger.info(`Fetching the mkdocs.yml catalog from ${repoUrl}`);
213
- await pluginScaffolderNode.fetchContents({
214
- reader,
215
- integrations,
216
- baseUrl: ctx.templateInfo?.baseUrl,
217
- fetchUrl: `https://${parsedRepoUrl.resource}/${parsedRepoUrl.owner}/${parsedRepoUrl.name}`,
218
- outputPath: ctx.workspacePath
219
- });
220
- for (const url of confluenceUrls) {
221
- const { spacekey, title, titleWithSpaces } = createConfluenceVariables(url);
222
- ctx.logger.info(`Fetching the Confluence content for ${url}`);
223
- const getConfluenceDoc = await fetchConfluence(
224
- `/rest/api/content?title=${title}&spaceKey=${spacekey}&expand=body.export_view`,
225
- confluenceConfig
226
- );
227
- if (getConfluenceDoc.results.length === 0) {
228
- throw new errors.InputError(
229
- `Could not find document ${url}. Please check your input.`
230
- );
231
- }
232
- const getDocAttachments = await fetchConfluence(
233
- `/rest/api/content/${getConfluenceDoc.results[0].id}/child/attachment`,
234
- confluenceConfig
235
- );
236
- if (getDocAttachments.results.length) {
237
- fs__default.default.mkdirSync(`${dirPath}/${filePathToMkdocs}docs/img`, {
238
- recursive: true
239
- });
240
- productArray = await getAndWriteAttachments(
241
- getDocAttachments,
242
- dirPath,
243
- confluenceConfig,
244
- filePathToMkdocs
245
- );
246
- }
247
- ctx.logger.info(
248
- `starting action for converting ${titleWithSpaces} from Confluence To Markdown`
249
- );
250
- const mkdocsFileContent = await readFileAsString(repoFileDir);
251
- const mkdocsFile = await YAML__default.default.parse(mkdocsFileContent);
252
- ctx.logger.info(
253
- `Adding new file - ${titleWithSpaces} to the current mkdocs.yml file`
254
- );
255
- if (mkdocsFile !== void 0 && mkdocsFile.hasOwnProperty("nav")) {
256
- const { nav } = mkdocsFile;
257
- if (!nav.some((i) => i.hasOwnProperty(titleWithSpaces))) {
258
- nav.push({
259
- [titleWithSpaces]: `${titleWithSpaces.replace(/\s+/g, "-")}.md`
260
- });
261
- mkdocsFile.nav = nav;
262
- } else {
263
- throw new errors.ConflictError(
264
- "This document looks to exist inside the GitHub repo. Will end the action."
265
- );
266
- }
267
- }
268
- await fs__default.default.writeFile(repoFileDir, YAML__default.default.stringify(mkdocsFile));
269
- const html = getConfluenceDoc.results[0].body.export_view.value;
270
- const markdownToPublish = nodeHtmlMarkdown.NodeHtmlMarkdown.translate(html);
271
- let newString = markdownToPublish;
272
- productArray.forEach((product) => {
273
- const regex = product[0].includes(".pdf") ? new RegExp(`(\\[.*?\\]\\()(.*?${product[0]}.*?)(\\))`, "gi") : new RegExp(`(\\!\\[.*?\\]\\()(.*?${product[0]}.*?)(\\))`, "gi");
274
- newString = newString.replace(regex, `$1./img/${product[1]}$3`);
275
- });
276
- ctx.logger.info(`Adding new file to repo.`);
277
- await fs__default.default.outputFile(
278
- `${dirPath}/${filePathToMkdocs}docs/${titleWithSpaces.replace(
279
- /\s+/g,
280
- "-"
281
- )}.md`,
282
- newString
283
- );
284
- }
285
- ctx.output("repo", parsedRepoUrl.name);
286
- ctx.output("owner", parsedRepoUrl.owner);
287
- }
288
- });
289
- };
290
-
291
- const confluenceToMarkdownModule = backendPluginApi.createBackendModule({
292
- pluginId: "scaffolder",
293
- moduleId: "confluence-to-markdown",
294
- register({ registerInit }) {
295
- registerInit({
296
- deps: {
297
- scaffolder: alpha.scaffolderActionsExtensionPoint,
298
- config: backendPluginApi.coreServices.rootConfig,
299
- reader: backendPluginApi.coreServices.urlReader
300
- },
301
- async init({ scaffolder, config, reader }) {
302
- const integrations = integration.ScmIntegrations.fromConfig(config);
303
- scaffolder.addActions(
304
- createConfluenceToMarkdownAction({
305
- config,
306
- integrations,
307
- reader
308
- })
309
- );
310
- }
311
- });
312
- }
313
- });
314
-
315
- exports.createConfluenceToMarkdownAction = createConfluenceToMarkdownAction;
316
- exports.default = confluenceToMarkdownModule;
10
+ exports.createConfluenceToMarkdownAction = confluenceToMarkdown.createConfluenceToMarkdownAction;
11
+ exports.default = module$1.confluenceToMarkdownModule;
317
12
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/actions/confluence/helpers.ts","../src/actions/confluence/confluenceToMarkdown.examples.ts","../src/actions/confluence/confluenceToMarkdown.ts","../src/module.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 { Config } from '@backstage/config';\nimport { ResponseError, ConflictError, InputError } from '@backstage/errors';\nimport fs from 'fs-extra';\nimport fetch, { Response } from 'node-fetch';\n\ninterface Links {\n webui: string;\n download: string;\n thumbnail: string;\n self: string;\n}\n\ninterface Metadata {\n mediaType: string;\n}\n\nexport interface Result {\n id: string;\n type: string;\n status: string;\n title: string;\n metadata: Metadata;\n _links: Links;\n}\n\nexport interface Results {\n results: Result[];\n}\n\nexport type LocalConfluenceConfig = {\n baseUrl: string;\n auth: string;\n token?: string;\n email?: string;\n username?: string;\n password?: string;\n};\n\nexport const getConfluenceConfig = (config: Config) => {\n const confluenceConfig = {\n baseUrl: config.getString('confluence.baseUrl'),\n auth: config.getOptionalString('confluence.auth.type') ?? 'bearer',\n token: config.getOptionalString('confluence.auth.token'),\n email: config.getOptionalString('confluence.auth.email'),\n username: config.getOptionalString('confluence.auth.username'),\n password: config.getOptionalString('confluence.auth.password'),\n };\n\n if (\n (confluenceConfig.auth === 'basic' || confluenceConfig.auth === 'bearer') &&\n !confluenceConfig.token\n ) {\n throw new Error(\n `No token provided for the configured '${confluenceConfig.auth}' auth method`,\n );\n }\n\n if (confluenceConfig.auth === 'basic' && !confluenceConfig.email) {\n throw new Error(\n `No email provided for the configured '${confluenceConfig.auth}' auth method`,\n );\n }\n\n if (\n confluenceConfig.auth === 'userpass' &&\n (!confluenceConfig.username || !confluenceConfig.password)\n ) {\n throw new Error(\n `No username/password provided for the configured '${confluenceConfig.auth}' auth method`,\n );\n }\n\n return confluenceConfig;\n};\n\nexport const getAuthorizationHeaderValue = (config: LocalConfluenceConfig) => {\n switch (config.auth) {\n case 'bearer':\n return `Bearer ${config.token}`;\n case 'basic': {\n const buffer = Buffer.from(`${config.email}:${config.token}`, 'utf8');\n return `Basic ${buffer.toString('base64')}`;\n }\n case 'userpass': {\n const buffer = Buffer.from(\n `${config.username}:${config.password}`,\n 'utf8',\n );\n return `Basic ${buffer.toString('base64')}`;\n }\n default:\n throw new Error(`Unknown auth method '${config.auth}' provided`);\n }\n};\n\nexport const readFileAsString = async (fileDir: string) => {\n const content = await fs.readFile(fileDir, 'utf-8');\n return content.toString();\n};\n\nexport const fetchConfluence = async (\n relativeUrl: string,\n config: LocalConfluenceConfig,\n) => {\n const baseUrl = config.baseUrl;\n const authHeaderValue = getAuthorizationHeaderValue(config);\n const url = `${baseUrl}${relativeUrl}`;\n const response: Response = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: authHeaderValue,\n },\n });\n if (!response.ok) {\n throw await ResponseError.fromResponse(response);\n }\n\n return response.json();\n};\n\nexport const getAndWriteAttachments = async (\n arr: Results,\n workspace: string,\n config: LocalConfluenceConfig,\n mkdocsDir: string,\n) => {\n const productArr: string[][] = [];\n const baseUrl = config.baseUrl;\n const authHeaderValue = getAuthorizationHeaderValue(config);\n await Promise.all(\n await arr.results.map(async (result: Result) => {\n const downloadLink = result._links.download;\n const downloadTitle = result.title.replace(/ /g, '-');\n if (result.metadata.mediaType !== 'application/gliffy+json') {\n productArr.push([result.title.replace(/ /g, '%20'), downloadTitle]);\n }\n const url = `${baseUrl}${downloadLink}`;\n const res = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: authHeaderValue,\n },\n });\n if (!res.ok) {\n throw await ResponseError.fromResponse(res);\n } else if (res.body !== null) {\n fs.openSync(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`, 'w');\n const writeStream = fs.createWriteStream(\n `${workspace}/${mkdocsDir}docs/img/${downloadTitle}`,\n );\n res.body.pipe(writeStream);\n await new Promise((resolve, reject) => {\n writeStream.on('finish', () => {\n resolve(`${workspace}/${mkdocsDir}docs/img/${downloadTitle}`);\n });\n writeStream.on('error', reject);\n });\n } else {\n throw new ConflictError(\n 'No Body on the response. Can not save images from Confluence Doc',\n );\n }\n }),\n );\n return productArr;\n};\n\nexport const createConfluenceVariables = (url: string) => {\n let spacekey: string | undefined = undefined;\n let title: string | undefined = undefined;\n let titleWithSpaces: string | undefined = '';\n const params = new URL(url);\n if (params.pathname.split('/')[1] === 'display') {\n // https://confluence.example.com/display/SPACEKEY/Page+Title\n spacekey = params.pathname.split('/')[2];\n title = params.pathname.split('/')[3];\n titleWithSpaces = title?.replace(/\\+/g, ' ');\n return { spacekey, title, titleWithSpaces };\n } else if (params.pathname.split('/')[2] === 'display') {\n // https://confluence.example.com/prefix/display/SPACEKEY/Page+Title\n spacekey = params.pathname.split('/')[3];\n title = params.pathname.split('/')[4];\n titleWithSpaces = title?.replace(/\\+/g, ' ');\n return { spacekey, title, titleWithSpaces };\n } else if (params.pathname.split('/')[2] === 'spaces') {\n // https://example.atlassian.net/wiki/spaces/SPACEKEY/pages/1234567/Page+Title\n spacekey = params.pathname.split('/')[3];\n title = params.pathname.split('/')[6];\n titleWithSpaces = title?.replace(/\\+/g, ' ');\n return { spacekey, title, titleWithSpaces };\n }\n throw new InputError(\n 'The Url format for Confluence is incorrect. Acceptable format is `<CONFLUENCE_BASE_URL>/display/<SPACEKEY>/<PAGE+TITLE>` or `<CONFLUENCE_BASE_URL>/spaces/<SPACEKEY>/pages/<PAGEID>/<PAGE+TITLE>` for Confluence cloud',\n );\n};\n","/*\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 { TemplateExample } from '@backstage/plugin-scaffolder-node';\nimport yaml from 'yaml';\n\nexport const examples: TemplateExample[] = [\n {\n description:\n 'Downloads content from provided Confluence URLs and converts it to Markdown.',\n example: yaml.stringify({\n steps: [\n {\n action: 'confluence:transform:markdown',\n id: 'confluence-transform-markdown',\n name: 'Transform Confluence content to Markdown',\n input: {\n confluenceUrls: [\n 'https://confluence.example.com/display/SPACEKEY/Page+Title',\n ],\n repoUrl:\n 'https://github.com/organization-name/repo-name/blob/main/mkdocs.yml',\n },\n },\n ],\n }),\n },\n];\n","/*\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 { Config } from '@backstage/config';\nimport { ScmIntegrations } from '@backstage/integration';\nimport {\n createTemplateAction,\n fetchContents,\n} from '@backstage/plugin-scaffolder-node';\nimport { InputError, ConflictError } from '@backstage/errors';\nimport { NodeHtmlMarkdown } from 'node-html-markdown';\nimport fs from 'fs-extra';\nimport parseGitUrl from 'git-url-parse';\nimport YAML from 'yaml';\nimport {\n readFileAsString,\n fetchConfluence,\n getAndWriteAttachments,\n createConfluenceVariables,\n getConfluenceConfig,\n} from './helpers';\nimport { examples } from './confluenceToMarkdown.examples';\nimport { UrlReaderService } from '@backstage/backend-plugin-api';\n\n/**\n * @public\n */\n\nexport const createConfluenceToMarkdownAction = (options: {\n reader: UrlReaderService;\n integrations: ScmIntegrations;\n config: Config;\n}) => {\n const { config, reader, integrations } = options;\n type Obj = {\n [key: string]: string;\n };\n\n return createTemplateAction<{\n confluenceUrls: string[];\n repoUrl: string;\n }>({\n id: 'confluence:transform:markdown',\n description: 'Transforms Confluence content to Markdown',\n examples,\n schema: {\n input: {\n properties: {\n confluenceUrls: {\n type: 'array',\n title: 'Confluence URL',\n description:\n 'Paste your Confluence url. Ensure it follows this format: https://{confluence+base+url}/display/{spacekey}/{page+title} or https://{confluence+base+url}/spaces/{spacekey}/pages/1234567/{page+title} for Confluence Cloud',\n items: {\n type: 'string',\n default: 'Confluence URL',\n },\n },\n repoUrl: {\n type: 'string',\n title: 'GitHub Repo Url',\n description:\n 'mkdocs.yml file location inside the github repo you want to store the document',\n },\n },\n },\n },\n async handler(ctx) {\n const confluenceConfig = getConfluenceConfig(config);\n const { confluenceUrls, repoUrl } = ctx.input;\n const parsedRepoUrl = parseGitUrl(repoUrl);\n const filePathToMkdocs = parsedRepoUrl.filepath.substring(\n 0,\n parsedRepoUrl.filepath.lastIndexOf('/') + 1,\n );\n const dirPath = ctx.workspacePath;\n const repoFileDir = `${dirPath}/${parsedRepoUrl.filepath}`;\n let productArray: string[][] = [];\n\n ctx.logger.info(`Fetching the mkdocs.yml catalog from ${repoUrl}`);\n\n // This grabs the files from Github\n await fetchContents({\n reader,\n integrations,\n baseUrl: ctx.templateInfo?.baseUrl,\n fetchUrl: `https://${parsedRepoUrl.resource}/${parsedRepoUrl.owner}/${parsedRepoUrl.name}`,\n outputPath: ctx.workspacePath,\n });\n\n for (const url of confluenceUrls) {\n const { spacekey, title, titleWithSpaces } =\n createConfluenceVariables(url);\n // This calls confluence to get the page html and page id\n ctx.logger.info(`Fetching the Confluence content for ${url}`);\n const getConfluenceDoc = await fetchConfluence(\n `/rest/api/content?title=${title}&spaceKey=${spacekey}&expand=body.export_view`,\n confluenceConfig,\n );\n if (getConfluenceDoc.results.length === 0) {\n throw new InputError(\n `Could not find document ${url}. Please check your input.`,\n );\n }\n // This gets attachments for the confluence page if they exist\n const getDocAttachments = await fetchConfluence(\n `/rest/api/content/${getConfluenceDoc.results[0].id}/child/attachment`,\n confluenceConfig,\n );\n\n if (getDocAttachments.results.length) {\n fs.mkdirSync(`${dirPath}/${filePathToMkdocs}docs/img`, {\n recursive: true,\n });\n productArray = await getAndWriteAttachments(\n getDocAttachments,\n dirPath,\n confluenceConfig,\n filePathToMkdocs,\n );\n }\n\n ctx.logger.info(\n `starting action for converting ${titleWithSpaces} from Confluence To Markdown`,\n );\n\n // This reads mkdocs.yml file\n const mkdocsFileContent = await readFileAsString(repoFileDir);\n const mkdocsFile = await YAML.parse(mkdocsFileContent);\n ctx.logger.info(\n `Adding new file - ${titleWithSpaces} to the current mkdocs.yml file`,\n );\n\n // This modifies the mkdocs.yml file\n if (mkdocsFile !== undefined && mkdocsFile.hasOwnProperty('nav')) {\n const { nav } = mkdocsFile;\n if (!nav.some((i: Obj) => i.hasOwnProperty(titleWithSpaces))) {\n nav.push({\n [titleWithSpaces]: `${titleWithSpaces.replace(/\\s+/g, '-')}.md`,\n });\n mkdocsFile.nav = nav;\n } else {\n throw new ConflictError(\n 'This document looks to exist inside the GitHub repo. Will end the action.',\n );\n }\n }\n\n await fs.writeFile(repoFileDir, YAML.stringify(mkdocsFile));\n\n // This grabs the confluence html and converts it to markdown and adds attachments\n const html = getConfluenceDoc.results[0].body.export_view.value;\n const markdownToPublish = NodeHtmlMarkdown.translate(html);\n let newString: string = markdownToPublish;\n productArray.forEach((product: string[]) => {\n // This regex is looking for either [](link to confluence) or ![](link to confluence) in the newly created markdown doc and updating it to point to the versions saved(in ./docs/img) in the local version of GitHub Repo during getAndWriteAttachments\n const regex = product[0].includes('.pdf')\n ? new RegExp(`(\\\\[.*?\\\\]\\\\()(.*?${product[0]}.*?)(\\\\))`, 'gi')\n : new RegExp(`(\\\\!\\\\[.*?\\\\]\\\\()(.*?${product[0]}.*?)(\\\\))`, 'gi');\n newString = newString.replace(regex, `$1./img/${product[1]}$3`);\n });\n\n ctx.logger.info(`Adding new file to repo.`);\n await fs.outputFile(\n `${dirPath}/${filePathToMkdocs}docs/${titleWithSpaces.replace(\n /\\s+/g,\n '-',\n )}.md`,\n newString,\n );\n }\n\n ctx.output('repo', parsedRepoUrl.name);\n ctx.output('owner', parsedRepoUrl.owner);\n },\n });\n};\n","/*\n * Copyright 2024 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 createBackendModule,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { scaffolderActionsExtensionPoint } from '@backstage/plugin-scaffolder-node/alpha';\nimport { createConfluenceToMarkdownAction } from './actions';\nimport { ScmIntegrations } from '@backstage/integration';\n\n/**\n * @public\n * The Confluence to Markdown Module for the Scaffolder Backend\n */\nexport const confluenceToMarkdownModule = createBackendModule({\n pluginId: 'scaffolder',\n moduleId: 'confluence-to-markdown',\n register({ registerInit }) {\n registerInit({\n deps: {\n scaffolder: scaffolderActionsExtensionPoint,\n config: coreServices.rootConfig,\n reader: coreServices.urlReader,\n },\n async init({ scaffolder, config, reader }) {\n const integrations = ScmIntegrations.fromConfig(config);\n scaffolder.addActions(\n createConfluenceToMarkdownAction({\n config,\n integrations,\n reader,\n }),\n );\n },\n });\n },\n});\n"],"names":["fs","fetch","ResponseError","ConflictError","InputError","yaml","createTemplateAction","parseGitUrl","fetchContents","YAML","NodeHtmlMarkdown","createBackendModule","scaffolderActionsExtensionPoint","coreServices","ScmIntegrations"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsDa,MAAA,mBAAA,GAAsB,CAAC,MAAmB,KAAA;AACrD,EAAA,MAAM,gBAAmB,GAAA;AAAA,IACvB,OAAA,EAAS,MAAO,CAAA,SAAA,CAAU,oBAAoB,CAAA;AAAA,IAC9C,IAAM,EAAA,MAAA,CAAO,iBAAkB,CAAA,sBAAsB,CAAK,IAAA,QAAA;AAAA,IAC1D,KAAA,EAAO,MAAO,CAAA,iBAAA,CAAkB,uBAAuB,CAAA;AAAA,IACvD,KAAA,EAAO,MAAO,CAAA,iBAAA,CAAkB,uBAAuB,CAAA;AAAA,IACvD,QAAA,EAAU,MAAO,CAAA,iBAAA,CAAkB,0BAA0B,CAAA;AAAA,IAC7D,QAAA,EAAU,MAAO,CAAA,iBAAA,CAAkB,0BAA0B,CAAA;AAAA,GAC/D,CAAA;AAEA,EACG,IAAA,CAAA,gBAAA,CAAiB,SAAS,OAAW,IAAA,gBAAA,CAAiB,SAAS,QAChE,KAAA,CAAC,iBAAiB,KAClB,EAAA;AACA,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,sCAAA,EAAyC,iBAAiB,IAAI,CAAA,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,CAAA,CAAA;AACrC,MAAI,GAAA,CAAA,MAAA,CAAO,OAAS,EAAA,aAAA,CAAc,KAAK,CAAA,CAAA;AAAA,KACzC;AAAA,GACD,CAAA,CAAA;AACH;;AClKO,MAAM,6BAA6BW,oCAAoB,CAAA;AAAA,EAC5D,QAAU,EAAA,YAAA;AAAA,EACV,QAAU,EAAA,wBAAA;AAAA,EACV,QAAA,CAAS,EAAE,YAAA,EAAgB,EAAA;AACzB,IAAa,YAAA,CAAA;AAAA,MACX,IAAM,EAAA;AAAA,QACJ,UAAY,EAAAC,qCAAA;AAAA,QACZ,QAAQC,6BAAa,CAAA,UAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,SAAA;AAAA,OACvB;AAAA,MACA,MAAM,IAAK,CAAA,EAAE,UAAY,EAAA,MAAA,EAAQ,QAAU,EAAA;AACzC,QAAM,MAAA,YAAA,GAAeC,2BAAgB,CAAA,UAAA,CAAW,MAAM,CAAA,CAAA;AACtD,QAAW,UAAA,CAAA,UAAA;AAAA,UACT,gCAAiC,CAAA;AAAA,YAC/B,MAAA;AAAA,YACA,YAAA;AAAA,YACA,MAAA;AAAA,WACD,CAAA;AAAA,SACH,CAAA;AAAA,OACF;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ var backendPluginApi = require('@backstage/backend-plugin-api');
4
+ var alpha = require('@backstage/plugin-scaffolder-node/alpha');
5
+ var confluenceToMarkdown = require('./actions/confluence/confluenceToMarkdown.cjs.js');
6
+ var integration = require('@backstage/integration');
7
+
8
+ const confluenceToMarkdownModule = backendPluginApi.createBackendModule({
9
+ pluginId: "scaffolder",
10
+ moduleId: "confluence-to-markdown",
11
+ register({ registerInit }) {
12
+ registerInit({
13
+ deps: {
14
+ scaffolder: alpha.scaffolderActionsExtensionPoint,
15
+ config: backendPluginApi.coreServices.rootConfig,
16
+ reader: backendPluginApi.coreServices.urlReader
17
+ },
18
+ async init({ scaffolder, config, reader }) {
19
+ const integrations = integration.ScmIntegrations.fromConfig(config);
20
+ scaffolder.addActions(
21
+ confluenceToMarkdown.createConfluenceToMarkdownAction({
22
+ config,
23
+ integrations,
24
+ reader
25
+ })
26
+ );
27
+ }
28
+ });
29
+ }
30
+ });
31
+
32
+ exports.confluenceToMarkdownModule = confluenceToMarkdownModule;
33
+ //# sourceMappingURL=module.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.cjs.js","sources":["../src/module.ts"],"sourcesContent":["/*\n * Copyright 2024 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 createBackendModule,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { scaffolderActionsExtensionPoint } from '@backstage/plugin-scaffolder-node/alpha';\nimport { createConfluenceToMarkdownAction } from './actions';\nimport { ScmIntegrations } from '@backstage/integration';\n\n/**\n * @public\n * The Confluence to Markdown Module for the Scaffolder Backend\n */\nexport const confluenceToMarkdownModule = createBackendModule({\n pluginId: 'scaffolder',\n moduleId: 'confluence-to-markdown',\n register({ registerInit }) {\n registerInit({\n deps: {\n scaffolder: scaffolderActionsExtensionPoint,\n config: coreServices.rootConfig,\n reader: coreServices.urlReader,\n },\n async init({ scaffolder, config, reader }) {\n const integrations = ScmIntegrations.fromConfig(config);\n scaffolder.addActions(\n createConfluenceToMarkdownAction({\n config,\n integrations,\n reader,\n }),\n );\n },\n });\n },\n});\n"],"names":["createBackendModule","scaffolderActionsExtensionPoint","coreServices","ScmIntegrations","createConfluenceToMarkdownAction"],"mappings":";;;;;;;AA2BO,MAAM,6BAA6BA,oCAAoB,CAAA;AAAA,EAC5D,QAAU,EAAA,YAAA;AAAA,EACV,QAAU,EAAA,wBAAA;AAAA,EACV,QAAA,CAAS,EAAE,YAAA,EAAgB,EAAA;AACzB,IAAa,YAAA,CAAA;AAAA,MACX,IAAM,EAAA;AAAA,QACJ,UAAY,EAAAC,qCAAA;AAAA,QACZ,QAAQC,6BAAa,CAAA,UAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,SAAA;AAAA,OACvB;AAAA,MACA,MAAM,IAAK,CAAA,EAAE,UAAY,EAAA,MAAA,EAAQ,QAAU,EAAA;AACzC,QAAM,MAAA,YAAA,GAAeC,2BAAgB,CAAA,UAAA,CAAW,MAAM,CAAA,CAAA;AACtD,QAAW,UAAA,CAAA,UAAA;AAAA,UACTC,qDAAiC,CAAA;AAAA,YAC/B,MAAA;AAAA,YACA,YAAA;AAAA,YACA,MAAA;AAAA,WACD,CAAA;AAAA,SACH,CAAA;AAAA,OACF;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-scaffolder-backend-module-confluence-to-markdown",
3
- "version": "0.3.1-next.1",
3
+ "version": "0.3.1-next.2",
4
4
  "description": "The confluence-to-markdown module for @backstage/plugin-scaffolder-backend",
5
5
  "backstage": {
6
6
  "role": "backend-plugin-module",
@@ -44,21 +44,21 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@backstage/backend-common": "^0.25.0",
47
- "@backstage/backend-plugin-api": "1.0.1-next.0",
47
+ "@backstage/backend-plugin-api": "1.0.1-next.1",
48
48
  "@backstage/config": "1.2.0",
49
49
  "@backstage/errors": "1.2.4",
50
- "@backstage/integration": "1.15.1-next.0",
51
- "@backstage/plugin-scaffolder-node": "0.5.0-next.1",
50
+ "@backstage/integration": "1.15.1-next.1",
51
+ "@backstage/plugin-scaffolder-node": "0.5.0-next.2",
52
52
  "fs-extra": "^11.2.0",
53
- "git-url-parse": "^14.0.0",
53
+ "git-url-parse": "^15.0.0",
54
54
  "node-fetch": "^2.7.0",
55
55
  "node-html-markdown": "^1.3.0",
56
56
  "yaml": "^2.0.0"
57
57
  },
58
58
  "devDependencies": {
59
- "@backstage/backend-test-utils": "1.0.1-next.1",
60
- "@backstage/cli": "0.28.0-next.1",
61
- "@backstage/plugin-scaffolder-node-test-utils": "0.1.13-next.1",
59
+ "@backstage/backend-test-utils": "1.0.1-next.2",
60
+ "@backstage/cli": "0.28.0-next.2",
61
+ "@backstage/plugin-scaffolder-node-test-utils": "0.1.13-next.2",
62
62
  "msw": "^1.0.0"
63
63
  },
64
64
  "configSchema": "config.d.ts"