@tryghost/mg-linkfixer 0.2.8 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/LinkFixer.js +42 -2
  2. package/package.json +2 -2
package/lib/LinkFixer.js CHANGED
@@ -1,3 +1,4 @@
1
+ const path = require('path');
1
2
  const _ = require('lodash');
2
3
  const cheerio = require('cheerio');
3
4
 
@@ -11,6 +12,31 @@ class LinkFixer {
11
12
  this.linkMap = {};
12
13
  }
13
14
 
15
+ /**
16
+ * Clean the URL
17
+ * @param {String} url The given URL
18
+ * @returns {String} A cleaned URL with no protocol or parameters
19
+ *
20
+ * @example
21
+ * cleanURL('https://exampleurl.com/sample-page/child-sample-page/?dolor=simet');
22
+ * => exampleurl.com/sample-page/child-sample-page/
23
+ *
24
+ * @example
25
+ * cleanURL('https://exampleurl.com/sample-page/');
26
+ * => exampleurl.com/sample-page/
27
+ */
28
+ cleanURL(url) {
29
+ try {
30
+ const urlParts = new URL(url);
31
+ const cleanedURL = path.join(urlParts.host, urlParts.pathname);
32
+
33
+ return cleanedURL;
34
+ } catch (error) {
35
+ // If it's an invalid URL, return the original string
36
+ return url;
37
+ }
38
+ }
39
+
14
40
  buildMap(ctx) {
15
41
  if (!ctx.result.posts) {
16
42
  return;
@@ -41,6 +67,12 @@ class LinkFixer {
41
67
  this.linkMap[data.author.url] = `/author/${data.author.data.slug}/`;
42
68
  }
43
69
  });
70
+
71
+ // Remove the protocol, ensuring we treat `http` and `https` sites in the same way
72
+ Object.keys(this.linkMap).forEach((key) => {
73
+ let updatedURL = this.cleanURL(key);
74
+ this.linkMap[updatedURL] = this.linkMap[key];
75
+ });
44
76
  }
45
77
 
46
78
  async processHTML(html) {
@@ -48,8 +80,16 @@ class LinkFixer {
48
80
 
49
81
  let links = $('a').map(async (i, el) => {
50
82
  let href = $(el).attr('href');
51
- if (this.linkMap[href]) {
52
- $(el).attr('href', this.linkMap[href]);
83
+
84
+ if (!href) {
85
+ return;
86
+ }
87
+
88
+ // Clean the URL, matching the links stored in the linkMap
89
+ let updatedURL = this.cleanURL(href);
90
+
91
+ if (this.linkMap[updatedURL]) {
92
+ $(el).attr('href', this.linkMap[updatedURL]);
53
93
  }
54
94
  }).get();
55
95
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryghost/mg-linkfixer",
3
- "version": "0.2.8",
3
+ "version": "0.3.1",
4
4
  "repository": "https://github.com/TryGhost/migrate/tree/main/packages/mg-linkfixer",
5
5
  "author": "Ghost Foundation",
6
6
  "license": "MIT",
@@ -27,5 +27,5 @@
27
27
  "cheerio": "^1.0.0-rc.3",
28
28
  "lodash": "4.17.21"
29
29
  },
30
- "gitHead": "68aae057039319cd550afe37426c0db4145bd29e"
30
+ "gitHead": "370c7f9973e7518cfb6433e694c8fbbf022c32cf"
31
31
  }