discord-message-transcript 1.3.1-dev.3.35 → 1.3.2-dev.0.49

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 (88) hide show
  1. package/dist/core/assetResolver/base64/imageToBase64.d.ts +2 -0
  2. package/dist/core/{imageToBase64.js → assetResolver/base64/imageToBase64.js} +18 -4
  3. package/dist/core/assetResolver/cdn/cdnCustomError.d.ts +16 -0
  4. package/dist/core/assetResolver/cdn/cdnCustomError.js +28 -0
  5. package/dist/core/assetResolver/cdn/cdnResolver.d.ts +3 -0
  6. package/dist/core/assetResolver/cdn/cdnResolver.js +90 -0
  7. package/dist/core/assetResolver/cdn/cloudinaryCdnResolver.d.ts +1 -0
  8. package/dist/core/assetResolver/cdn/cloudinaryCdnResolver.js +120 -0
  9. package/dist/core/assetResolver/cdn/sanitizeFileName.d.ts +1 -0
  10. package/dist/core/assetResolver/cdn/sanitizeFileName.js +17 -0
  11. package/dist/core/assetResolver/cdn/uploadCareCdnResolver.d.ts +1 -0
  12. package/dist/core/assetResolver/cdn/uploadCareCdnResolver.js +137 -0
  13. package/dist/core/assetResolver/cdn/validateCdnUrl.d.ts +1 -0
  14. package/dist/core/assetResolver/cdn/validateCdnUrl.js +8 -0
  15. package/dist/core/assetResolver/contants.d.ts +1 -0
  16. package/dist/core/assetResolver/contants.js +1 -0
  17. package/dist/core/assetResolver/index.d.ts +7 -0
  18. package/dist/core/assetResolver/index.js +22 -0
  19. package/dist/core/assetResolver/url/authorUrlResolver.d.ts +3 -0
  20. package/dist/core/assetResolver/url/authorUrlResolver.js +10 -0
  21. package/dist/core/assetResolver/url/imageUrlResolver.d.ts +4 -0
  22. package/dist/core/assetResolver/url/imageUrlResolver.js +20 -0
  23. package/dist/core/assetResolver/url/messageUrlResolver.d.ts +3 -0
  24. package/dist/core/{urlResolver.js → assetResolver/url/messageUrlResolver.js} +17 -43
  25. package/dist/core/assetResolver/url/urlResolver.d.ts +3 -0
  26. package/dist/core/assetResolver/url/urlResolver.js +24 -0
  27. package/dist/core/{componentToJson.d.ts → discordParser/componentToJson.d.ts} +1 -1
  28. package/dist/core/discordParser/componentToJson.js +159 -0
  29. package/dist/core/discordParser/fetchMessages.d.ts +7 -0
  30. package/dist/core/{fetchMessages.js → discordParser/fetchMessages.js} +1 -1
  31. package/dist/core/{getMentions.d.ts → discordParser/getMentions.d.ts} +1 -1
  32. package/dist/core/{getMentions.js → discordParser/getMentions.js} +1 -1
  33. package/dist/core/discordParser/index.d.ts +4 -0
  34. package/dist/core/discordParser/index.js +33 -0
  35. package/dist/core/mappers.d.ts +1 -1
  36. package/dist/core/mappers.js +1 -1
  37. package/dist/core/networkSecurity/constants.d.ts +3 -0
  38. package/dist/core/networkSecurity/constants.js +3 -0
  39. package/dist/core/networkSecurity/dns.d.ts +2 -0
  40. package/dist/core/networkSecurity/dns.js +29 -0
  41. package/dist/core/networkSecurity/index.d.ts +2 -0
  42. package/dist/core/networkSecurity/index.js +2 -0
  43. package/dist/core/networkSecurity/ip.d.ts +1 -0
  44. package/dist/core/networkSecurity/ip.js +110 -0
  45. package/dist/core/networkSecurity/lookup.d.ts +2 -0
  46. package/dist/core/networkSecurity/lookup.js +14 -0
  47. package/dist/core/networkSecurity/urlSafety.d.ts +3 -0
  48. package/dist/core/networkSecurity/urlSafety.js +71 -0
  49. package/dist/index.d.ts +3 -3
  50. package/dist/index.js +13 -56
  51. package/dist/renderers/json/json.d.ts +1 -1
  52. package/dist/renderers/json/json.js +3 -4
  53. package/dist/types/types.d.ts +36 -2
  54. package/dist/utils/sleep.d.ts +1 -0
  55. package/dist/utils/sleep.js +3 -0
  56. package/package.json +4 -7
  57. package/dist/core/cdnResolver.d.ts +0 -5
  58. package/dist/core/cdnResolver.js +0 -210
  59. package/dist/core/clientManager.d.ts +0 -3
  60. package/dist/core/clientManager.js +0 -9
  61. package/dist/core/componentHelpers.d.ts +0 -3
  62. package/dist/core/componentHelpers.js +0 -175
  63. package/dist/core/componentToJson.js +0 -145
  64. package/dist/core/error.d.ts +0 -3
  65. package/dist/core/error.js +0 -7
  66. package/dist/core/fetchMessages.d.ts +0 -19
  67. package/dist/core/imageToBase64.d.ts +0 -1
  68. package/dist/core/markdown.d.ts +0 -2
  69. package/dist/core/markdown.js +0 -175
  70. package/dist/core/urlResolver.d.ts +0 -5
  71. package/dist/renderers/html/clientRenderer.d.ts +0 -0
  72. package/dist/renderers/html/clientRenderer.js +0 -73
  73. package/dist/renderers/html/css.d.ts +0 -11
  74. package/dist/renderers/html/css.js +0 -663
  75. package/dist/renderers/html/html copy.d.ts +0 -19
  76. package/dist/renderers/html/html copy.js +0 -371
  77. package/dist/renderers/html/html-backup.d.ts +0 -19
  78. package/dist/renderers/html/html-backup.js +0 -371
  79. package/dist/renderers/html/html.d.ts +0 -19
  80. package/dist/renderers/html/html.js +0 -415
  81. package/dist/renderers/html/html2.d.ts +0 -8
  82. package/dist/renderers/html/html2.js +0 -233
  83. package/dist/renderers/html/js.d.ts +0 -4
  84. package/dist/renderers/html/js.js +0 -174
  85. package/dist/types/types copy.d.ts +0 -284
  86. package/dist/types/types copy.js +0 -35
  87. /package/dist/core/{limiter.d.ts → assetResolver/limiter.d.ts} +0 -0
  88. /package/dist/core/{limiter.js → assetResolver/limiter.js} +0 -0
@@ -0,0 +1,2 @@
1
+ import { safeUrlReturn } from '@/types';
2
+ export declare function imageToBase64(safeUrlObject: safeUrlReturn, disableWarnings: boolean): Promise<string>;
@@ -1,13 +1,21 @@
1
+ import { CustomWarn } from 'discord-message-transcript-base';
2
+ import { getBase64Limiter } from '../limiter.js';
1
3
  import https from 'https';
2
4
  import http from 'http';
3
- import { CustomWarn } from 'discord-message-transcript-base';
4
- import { getBase64Limiter } from './limiter.js';
5
- export async function imageToBase64(url, disableWarnings) {
5
+ import { createLookup } from '@/networkSecurity';
6
+ import { USER_AGENT } from '../contants.js';
7
+ const MAX_BYTES = 25 * 1024 * 1024; // 25MB
8
+ export async function imageToBase64(safeUrlObject, disableWarnings) {
9
+ const url = safeUrlObject.url;
6
10
  const limit = getBase64Limiter();
7
11
  return limit(async () => {
8
12
  return new Promise((resolve, reject) => {
9
13
  const client = url.startsWith('https') ? https : http;
10
- const request = client.get(url, { headers: { "User-Agent": "discord-message-transcript" } }, (response) => {
14
+ const lookup = createLookup(safeUrlObject.safeIps);
15
+ const request = client.get(url, {
16
+ headers: { "User-Agent": USER_AGENT },
17
+ lookup: lookup
18
+ }, (response) => {
11
19
  if (response.statusCode !== 200) {
12
20
  response.destroy();
13
21
  CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of converting to base64.
@@ -19,8 +27,14 @@ Failed to fetch image with status code: ${response.statusCode} from ${url}.`, di
19
27
  response.destroy();
20
28
  return resolve(url);
21
29
  }
30
+ let total = 0;
22
31
  const chunks = [];
23
32
  response.on('data', (chunk) => {
33
+ total += chunk.length;
34
+ if (total > MAX_BYTES) {
35
+ response.destroy();
36
+ return resolve(url);
37
+ }
24
38
  chunks.push(chunk);
25
39
  });
26
40
  response.on('end', () => {
@@ -0,0 +1,16 @@
1
+ export declare class CDNProviderError extends Error {
2
+ provider: "CLOUDINARY" | "UPLOADCARE" | "CUSTOM";
3
+ code: string;
4
+ status?: number;
5
+ hint?: string;
6
+ errorMessage?: string;
7
+ constructor(opts: {
8
+ provider: "CLOUDINARY" | "UPLOADCARE" | "CUSTOM";
9
+ message: string;
10
+ code: string;
11
+ status?: number;
12
+ hint?: string;
13
+ errorMessage?: string;
14
+ });
15
+ }
16
+ export declare function warnCdnError(provider: string, url: string, err: any, disableWarnings: boolean): void;
@@ -0,0 +1,28 @@
1
+ import { CustomWarn } from "discord-message-transcript-base";
2
+ export class CDNProviderError extends Error {
3
+ provider;
4
+ code;
5
+ status;
6
+ hint;
7
+ errorMessage;
8
+ constructor(opts) {
9
+ super(opts.message);
10
+ this.provider = opts.provider;
11
+ this.code = opts.code;
12
+ this.status = opts.status;
13
+ this.hint = opts.hint;
14
+ this.errorMessage = opts.errorMessage;
15
+ }
16
+ }
17
+ export function warnCdnError(provider, url, err, disableWarnings) {
18
+ if (err instanceof CDNProviderError) {
19
+ CustomWarn(`[CDN:${err.provider}] Upload failed → fallback to original URL
20
+ URL: ${url}
21
+ Reason: ${err.message}
22
+ Code: ${err.code}${err.status ? ` (HTTP ${err.status})` : ""}${err.hint ? `\nHint: ${err.hint}` : ""} ${err.errorMessage ? `\nError Message: ${err.errorMessage}` : ""}`, disableWarnings);
23
+ return;
24
+ }
25
+ CustomWarn(`[CDN:${provider}] Unknown error → fallback to original URL
26
+ URL: ${url}
27
+ Error: ${err?.message ?? err}`, disableWarnings);
28
+ }
@@ -0,0 +1,3 @@
1
+ import { CDNOptions, safeUrlReturn } from "@/types/types.js";
2
+ import { TranscriptOptionsBase } from "discord-message-transcript-base";
3
+ export declare function cdnResolver(safeUrlObject: safeUrlReturn, options: TranscriptOptionsBase, cdnOptions: CDNOptions): Promise<string>;
@@ -0,0 +1,90 @@
1
+ import { CustomWarn } from "discord-message-transcript-base";
2
+ import { getCDNLimiter } from "../limiter.js";
3
+ import { createLookup } from "@/networkSecurity";
4
+ import https from 'https';
5
+ import http from 'http';
6
+ import { uploadCareCdnResolver } from "./uploadCareCdnResolver.js";
7
+ import { cloudinaryCdnResolver } from "./cloudinaryCdnResolver.js";
8
+ import { validateCdnUrl } from "./validateCdnUrl.js";
9
+ import { USER_AGENT } from "../contants.js";
10
+ export async function cdnResolver(safeUrlObject, options, cdnOptions) {
11
+ const url = safeUrlObject.url;
12
+ const limit = getCDNLimiter();
13
+ return limit(async () => {
14
+ return new Promise((resolve, reject) => {
15
+ const client = safeUrlObject.url.startsWith('https') ? https : http;
16
+ const lookup = createLookup(safeUrlObject.safeIps);
17
+ const request = client.get(url, {
18
+ headers: { "User-Agent": USER_AGENT },
19
+ lookup: lookup
20
+ }, async (response) => {
21
+ if (response.statusCode !== 200) {
22
+ response.destroy();
23
+ CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
24
+ Failed to fetch attachment with status code: ${response.statusCode} from ${safeUrlObject.url}.`, options.disableWarnings);
25
+ return resolve(url);
26
+ }
27
+ const contentType = response.headers["content-type"];
28
+ const splitContentType = contentType ? contentType?.split('/') : [];
29
+ if (!contentType || splitContentType.length != 2 || splitContentType[0].length == 0 || splitContentType[1].length == 0) {
30
+ response.destroy();
31
+ CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
32
+ Failed to receive a valid content-type from ${url}.`, options.disableWarnings);
33
+ return resolve(url);
34
+ }
35
+ response.destroy();
36
+ const isImage = contentType.startsWith('image/') && contentType !== 'image/gif';
37
+ const isAudio = contentType.startsWith('audio/');
38
+ const isVideo = contentType.startsWith('video/') || contentType === 'image/gif';
39
+ if ((cdnOptions.includeImage && isImage) ||
40
+ (cdnOptions.includeAudio && isAudio) ||
41
+ (cdnOptions.includeVideo && isVideo) ||
42
+ (cdnOptions.includeOthers && !isAudio && !isImage && !isVideo)) {
43
+ return resolve(await cdnRedirectType(url, options, contentType, cdnOptions));
44
+ }
45
+ return resolve(url);
46
+ });
47
+ request.on('error', (err) => {
48
+ CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
49
+ Error: ${err.message}`, options.disableWarnings);
50
+ return resolve(url);
51
+ });
52
+ request.setTimeout(15000, () => {
53
+ request.destroy();
54
+ CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
55
+ Request timeout for ${url}.`, options.disableWarnings);
56
+ return resolve(url);
57
+ });
58
+ request.end();
59
+ });
60
+ });
61
+ }
62
+ async function cdnRedirectType(url, options, contentType, cdnOptions) {
63
+ let newUrl;
64
+ switch (cdnOptions.provider) {
65
+ case "CUSTOM": {
66
+ try {
67
+ newUrl = await cdnOptions.resolver(url, contentType, cdnOptions.customData);
68
+ break;
69
+ }
70
+ catch (error) {
71
+ CustomWarn(`Custom CDN resolver threw an error. Falling back to original URL.
72
+ This is most likely an issue in the custom CDN implementation provided by the user.
73
+ URL: ${url}
74
+ Error: ${error?.message ?? error}`, options.disableWarnings);
75
+ return url;
76
+ }
77
+ }
78
+ case "CLOUDINARY": {
79
+ newUrl = await cloudinaryCdnResolver(url, options.fileName, cdnOptions.cloudName, cdnOptions.apiKey, cdnOptions.apiSecret, options.disableWarnings);
80
+ break;
81
+ }
82
+ case "UPLOADCARE": {
83
+ newUrl = await uploadCareCdnResolver(url, cdnOptions.publicKey, cdnOptions.cdnDomain, options.disableWarnings);
84
+ break;
85
+ }
86
+ }
87
+ if (validateCdnUrl(newUrl, options.disableWarnings))
88
+ return newUrl;
89
+ return url;
90
+ }
@@ -0,0 +1 @@
1
+ export declare function cloudinaryCdnResolver(url: string, fileName: string, cloudName: string, apiKey: string, apiSecret: string, disableWarnings: boolean): Promise<string>;
@@ -0,0 +1,120 @@
1
+ import crypto from 'crypto';
2
+ import { CDNProviderError, warnCdnError } from './cdnCustomError.js';
3
+ import { sanitizeFileName } from './sanitizeFileName.js';
4
+ import { USER_AGENT } from '../contants.js';
5
+ // https://cloudinary.com/documentation/upload_images
6
+ export async function cloudinaryCdnResolver(url, fileName, cloudName, apiKey, apiSecret, disableWarnings) {
7
+ try {
8
+ if (!cloudName || !apiKey || !apiSecret) {
9
+ throw new CDNProviderError({
10
+ provider: "CLOUDINARY",
11
+ code: "CONFIG_MISSING",
12
+ message: "Cloudinary configuration is missing required fields.",
13
+ hint: "Verify cloudName, apiKey and apiSecret."
14
+ });
15
+ }
16
+ const paramsToSign = {
17
+ folder: `discord-message-transcript/${sanitizeFileName(fileName)}`,
18
+ timestamp: Math.floor(Date.now() / 1000).toString(),
19
+ unique_filename: "true",
20
+ use_filename: "true",
21
+ };
22
+ const stringToSign = Object.keys(paramsToSign).sort().map(k => `${k}=${paramsToSign[k]}`).join("&");
23
+ // signature SHA256
24
+ const signature = crypto
25
+ .createHash("sha256")
26
+ .update(stringToSign + apiSecret)
27
+ .digest("hex");
28
+ const form = new FormData();
29
+ form.append("folder", paramsToSign.folder);
30
+ form.append("file", url);
31
+ form.append("api_key", apiKey);
32
+ form.append("timestamp", paramsToSign.timestamp);
33
+ form.append("signature", signature);
34
+ form.append("use_filename", paramsToSign.use_filename);
35
+ form.append("unique_filename", paramsToSign.unique_filename);
36
+ let res;
37
+ try {
38
+ res = await fetch(`https://api.cloudinary.com/v1_1/${cloudName}/auto/upload`, {
39
+ method: "POST",
40
+ body: form,
41
+ headers: { "User-Agent": USER_AGENT }
42
+ });
43
+ }
44
+ catch (networkErr) {
45
+ throw new CDNProviderError({
46
+ provider: "CLOUDINARY",
47
+ code: "NETWORK_ERROR",
48
+ message: "Network error while contacting Cloudinary.",
49
+ hint: "Check internet connection, DNS, firewall or proxy.",
50
+ });
51
+ }
52
+ if (!res.ok) {
53
+ let body = {};
54
+ try {
55
+ body = await res.json();
56
+ }
57
+ catch { } // It isn't a problem body be empty
58
+ switch (res.status) {
59
+ case 400:
60
+ throw new CDNProviderError({
61
+ provider: "CLOUDINARY",
62
+ code: "BAD_REQUEST",
63
+ status: res.status,
64
+ message: body?.error?.message ?? "Invalid upload parameters.",
65
+ hint: "Check folder name, file URL accessibility, and signature.",
66
+ errorMessage: body.error.message ? body.error.message : undefined
67
+ });
68
+ case 401:
69
+ case 403:
70
+ throw new CDNProviderError({
71
+ provider: "CLOUDINARY",
72
+ code: "INVALID_CREDENTIALS",
73
+ status: res.status,
74
+ message: "Cloudinary rejected credentials.",
75
+ hint: "Check apiKey/apiSecret and cloudName.",
76
+ errorMessage: body.error.message ? body.error.message : undefined
77
+ });
78
+ case 420:
79
+ throw new CDNProviderError({
80
+ provider: "CLOUDINARY",
81
+ code: "RATE_LIMIT",
82
+ status: res.status,
83
+ message: "Cloudinary rate limit exceeded.",
84
+ hint: "Reduce concurrency.",
85
+ errorMessage: body.error.message ? body.error.message : undefined
86
+ });
87
+ case 500:
88
+ throw new CDNProviderError({
89
+ provider: "CLOUDINARY",
90
+ code: "CLOUDINARY_INTERNAL_ERROR",
91
+ status: res.status,
92
+ message: "Cloudinary has a internal error.",
93
+ hint: "Contact support or check https://status.cloudinary.com.",
94
+ errorMessage: body.error.message ? body.error.message : undefined
95
+ });
96
+ default:
97
+ throw new CDNProviderError({
98
+ provider: "CLOUDINARY",
99
+ code: "HTTP_ERROR",
100
+ status: res.status,
101
+ message: `Unexpected Cloudinary response.`,
102
+ errorMessage: body.error.message ? body.error.message : undefined
103
+ });
104
+ }
105
+ }
106
+ const json = await res.json();
107
+ if (!json.secure_url) {
108
+ throw new CDNProviderError({
109
+ provider: "CLOUDINARY",
110
+ code: "INVALID_RESPONSE",
111
+ message: "Cloudinary response missing secure_url."
112
+ });
113
+ }
114
+ return json.secure_url;
115
+ }
116
+ catch (error) {
117
+ warnCdnError("CLOUDINARY", url, error, disableWarnings);
118
+ return url;
119
+ }
120
+ }
@@ -0,0 +1 @@
1
+ export declare function sanitizeFileName(fileName: string): string;
@@ -0,0 +1,17 @@
1
+ import { randomUUID } from "crypto";
2
+ const INVALID_REGEX = /[<>:"/\\|?*\x00-\x1F]|[^\p{L}\p{N}._ -]/gu;
3
+ const MAX_LENGTH = 100;
4
+ export function sanitizeFileName(fileName) {
5
+ fileName = fileName
6
+ .trim()
7
+ .replace(INVALID_REGEX, "")
8
+ .replace(/\s+/g, " ");
9
+ fileName = fileName.replace(/[. ]+$/, "");
10
+ if (fileName.length > MAX_LENGTH) {
11
+ fileName = fileName.slice(0, MAX_LENGTH);
12
+ }
13
+ if (!fileName.length) {
14
+ fileName = `fallbackFile-${randomUUID()}`;
15
+ }
16
+ return fileName;
17
+ }
@@ -0,0 +1 @@
1
+ export declare function uploadCareCdnResolver(url: string, publicKey: string, cdnDomain: string, disableWarnings: boolean): Promise<string>;
@@ -0,0 +1,137 @@
1
+ import { sleep } from "@/utils/sleep.js";
2
+ import { CDNProviderError, warnCdnError } from "./cdnCustomError.js";
3
+ import { USER_AGENT } from "../contants.js";
4
+ // https://uploadcare.com/api-refs/upload-api/#tag/Upload/operation/fromURLUpload
5
+ export async function uploadCareCdnResolver(url, publicKey, cdnDomain, disableWarnings) {
6
+ try {
7
+ if (!publicKey || !cdnDomain) {
8
+ throw new CDNProviderError({
9
+ provider: "UPLOADCARE",
10
+ code: "CONFIG_MISSING",
11
+ message: "Uploadcare configuration is missing required fields.",
12
+ hint: "Verify cdnDomain and publickey."
13
+ });
14
+ }
15
+ const form = new FormData();
16
+ form.append("pub_key", publicKey);
17
+ form.append("source_url", url);
18
+ form.append("store", "1");
19
+ form.append("check_URL_duplicates", "1");
20
+ form.append("save_URL_duplicates", "1");
21
+ let res;
22
+ try {
23
+ res = await fetch("https://upload.uploadcare.com/from_url/", {
24
+ method: "POST",
25
+ body: form,
26
+ headers: { "User-Agent": USER_AGENT }
27
+ });
28
+ }
29
+ catch {
30
+ throw new CDNProviderError({
31
+ provider: "UPLOADCARE",
32
+ code: "NETWORK_ERROR",
33
+ message: "Network error while contacting Uploadcare.",
34
+ hint: "Check DNS, firewall or internet connection."
35
+ });
36
+ }
37
+ if (!res.ok) {
38
+ let body = {};
39
+ try {
40
+ body = await res.text(); // Uploadcare use text/plain for error messages
41
+ }
42
+ catch { } // It isn't a problem body be empty
43
+ switch (res.status) {
44
+ case 400:
45
+ throw new CDNProviderError({
46
+ provider: "UPLOADCARE",
47
+ code: "BAD_REQUEST",
48
+ status: 400,
49
+ message: "Uploadcare rejected parameters.",
50
+ hint: "Check publickKey, file URL accessibility, and signature.",
51
+ errorMessage: body ?? undefined
52
+ });
53
+ case 403:
54
+ throw new CDNProviderError({
55
+ provider: "UPLOADCARE",
56
+ code: "INVALID_KEY",
57
+ status: 403,
58
+ message: "Uploadcare rejected public key.",
59
+ hint: "Verify public key and project settings.",
60
+ errorMessage: body ?? undefined
61
+ });
62
+ case 429:
63
+ throw new CDNProviderError({
64
+ provider: "UPLOADCARE",
65
+ code: "RATE_LIMIT",
66
+ status: 429,
67
+ message: "Uploadcare rate limit exceeded.",
68
+ hint: "Reduce concurrency.",
69
+ errorMessage: body ?? undefined
70
+ });
71
+ case 500:
72
+ throw new CDNProviderError({
73
+ provider: "UPLOADCARE",
74
+ code: "UPLOADCARE_INTERNAL",
75
+ status: res.status,
76
+ message: "Uploadcare internal error.",
77
+ hint: "Check https://status.uploadcare.com",
78
+ errorMessage: body ?? undefined
79
+ });
80
+ default:
81
+ throw new CDNProviderError({
82
+ provider: "UPLOADCARE",
83
+ code: "HTTP_ERROR",
84
+ status: res.status,
85
+ message: "Unexpected Uploadcare response.",
86
+ errorMessage: body ?? undefined
87
+ });
88
+ }
89
+ }
90
+ const json = await res.json();
91
+ if (json.uuid) {
92
+ return `https://${cdnDomain}/${json.uuid}/`;
93
+ }
94
+ if (!json.token) {
95
+ throw new CDNProviderError({
96
+ provider: "UPLOADCARE",
97
+ code: "INVALID_RESPONSE",
98
+ message: "Uploadcare response missing uuid/token."
99
+ });
100
+ }
101
+ let delay = 200;
102
+ let maxDelay = 2000;
103
+ for (let i = 0; i < 10; i++) {
104
+ await sleep(delay);
105
+ delay = Math.min(delay * 2, maxDelay);
106
+ const resToken = await fetch(`https://upload.uploadcare.com/from_url/status/?token=${json.token}&pub_key=${publicKey}`, { headers: { "User-Agent": USER_AGENT } });
107
+ if (!resToken.ok) {
108
+ throw new CDNProviderError({
109
+ provider: "UPLOADCARE",
110
+ code: "STATUS_ERROR",
111
+ status: resToken.status,
112
+ message: "Uploadcare status endpoint failed."
113
+ });
114
+ }
115
+ const jsonToken = await resToken.json();
116
+ if (jsonToken.status === "success" && jsonToken.file_id) {
117
+ return `https://${cdnDomain}/${jsonToken.file_id}/`;
118
+ }
119
+ if (jsonToken.status === "error") {
120
+ throw new CDNProviderError({
121
+ provider: "UPLOADCARE",
122
+ code: "UPLOAD_FAILED",
123
+ message: jsonToken.error || "Uploadcare processing failed."
124
+ });
125
+ }
126
+ }
127
+ throw new CDNProviderError({
128
+ provider: "UPLOADCARE",
129
+ code: "TIMEOUT",
130
+ message: "Uploadcare polling timeout."
131
+ });
132
+ }
133
+ catch (error) {
134
+ warnCdnError("UPLOADCARE", url, error, disableWarnings);
135
+ return url;
136
+ }
137
+ }
@@ -0,0 +1 @@
1
+ export declare function validateCdnUrl(url: string, disableWarnings: boolean): boolean;
@@ -0,0 +1,8 @@
1
+ import { CustomWarn } from "discord-message-transcript-base";
2
+ export function validateCdnUrl(url, disableWarnings) {
3
+ if (url.includes('"') || url.includes('<') || url.includes('>')) {
4
+ CustomWarn(`Unsafe URL received from CDN, using fallback.\nURL: ${url}`, disableWarnings);
5
+ return false;
6
+ }
7
+ return true;
8
+ }
@@ -0,0 +1 @@
1
+ export declare const USER_AGENT = "discord-message-transcript";
@@ -0,0 +1 @@
1
+ export const USER_AGENT = "discord-message-transcript";
@@ -0,0 +1,7 @@
1
+ import { Json } from "@/renderers/json/json.js";
2
+ import { CDNOptions, Maps } from "@/types/types.js";
3
+ import { TranscriptOptionsBase } from "discord-message-transcript-base";
4
+ export * from "./limiter.js";
5
+ export * from "./url/imageUrlResolver.js";
6
+ export * from "./url/urlResolver.js";
7
+ export declare function jsonAssetResolver(jsonTranscript: Json, maps: Maps, options: TranscriptOptionsBase, cdnOptions: CDNOptions | null): Promise<void>;
@@ -0,0 +1,22 @@
1
+ import { authorUrlResolver } from "./url/authorUrlResolver.js";
2
+ import { messagesUrlResolver } from "./url/messageUrlResolver.js";
3
+ export * from "./limiter.js";
4
+ export * from "./url/imageUrlResolver.js";
5
+ export * from "./url/urlResolver.js";
6
+ export async function jsonAssetResolver(jsonTranscript, maps, options, cdnOptions) {
7
+ await Promise.all([
8
+ (async () => {
9
+ jsonTranscript.setAuthors(await authorUrlResolver(maps.authors, options, cdnOptions, maps.urlCache));
10
+ maps.authors.clear();
11
+ })(),
12
+ (() => {
13
+ jsonTranscript.setMentions({ channels: Array.from(maps.mentions.channels.values()), roles: Array.from(maps.mentions.roles.values()), users: Array.from(maps.mentions.users.values()) });
14
+ maps.mentions.channels.clear();
15
+ maps.mentions.roles.clear();
16
+ maps.mentions.users.clear();
17
+ })(),
18
+ (async () => {
19
+ jsonTranscript.setMessages(await messagesUrlResolver(jsonTranscript.getMessages(), options, cdnOptions, maps.urlCache));
20
+ })()
21
+ ]);
22
+ }
@@ -0,0 +1,3 @@
1
+ import { JsonAuthor, TranscriptOptionsBase } from "discord-message-transcript-base";
2
+ import { CDNOptions } from "@/types/types.js";
3
+ export declare function authorUrlResolver(authors: Map<string, JsonAuthor>, options: TranscriptOptionsBase, cdnOptions: CDNOptions | null, urlCache: Map<string, Promise<string>>): Promise<JsonAuthor[]>;
@@ -0,0 +1,10 @@
1
+ import { imageUrlResolver } from "./imageUrlResolver.js";
2
+ import { urlResolver } from "./urlResolver.js";
3
+ export async function authorUrlResolver(authors, options, cdnOptions, urlCache) {
4
+ return await Promise.all(Array.from(authors.values()).map(async (author) => {
5
+ return {
6
+ ...author,
7
+ avatarURL: await urlResolver((await imageUrlResolver(author.avatarURL, options, false)), options, cdnOptions, urlCache),
8
+ };
9
+ }));
10
+ }
@@ -0,0 +1,4 @@
1
+ import { JsonAttachment, TranscriptOptionsBase } from "discord-message-transcript-base";
2
+ import { safeUrlReturn } from "@/types";
3
+ export declare function imageUrlResolver(url: string, options: TranscriptOptionsBase, canReturnNull: false, attachments?: JsonAttachment[]): Promise<safeUrlReturn>;
4
+ export declare function imageUrlResolver(url: string | null, options: TranscriptOptionsBase, canReturnNull: true, attachments?: JsonAttachment[]): Promise<safeUrlReturn | null>;
@@ -0,0 +1,20 @@
1
+ import { FALLBACK_PIXEL } from "discord-message-transcript-base";
2
+ import { isSafeForHTML } from "@/networkSecurity";
3
+ export async function imageUrlResolver(url, options, canReturnNull, attachments) {
4
+ if (!url)
5
+ return null;
6
+ // Resolve attachment:// references to actual attachment URL
7
+ if (url.startsWith("attachment://")) {
8
+ const name = url.slice("attachment://".length).trim();
9
+ const found = attachments?.find(a => a.name === name);
10
+ if (!found)
11
+ return { safe: true, safeIps: [], url: FALLBACK_PIXEL };
12
+ url = found.url;
13
+ }
14
+ const safeUrlReturn = await isSafeForHTML(url, options);
15
+ if (safeUrlReturn.safe)
16
+ return safeUrlReturn;
17
+ if (canReturnNull)
18
+ return null;
19
+ return { safe: true, safeIps: [], url: FALLBACK_PIXEL };
20
+ }
@@ -0,0 +1,3 @@
1
+ import { CDNOptions } from "@/types/types.js";
2
+ import { JsonMessage, TranscriptOptionsBase } from "discord-message-transcript-base";
3
+ export declare function messagesUrlResolver(messages: JsonMessage[], options: TranscriptOptionsBase, cdnOptions: CDNOptions | null, urlCache: Map<string, Promise<string>>): Promise<JsonMessage[]>;