-
Notifications
You must be signed in to change notification settings - Fork 345
Expand file tree
/
Copy pathexecutors.ts
More file actions
210 lines (189 loc) · 7.16 KB
/
Copy pathexecutors.ts
File metadata and controls
210 lines (189 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import type {
ExecutionContext,
ProviderExecutors,
ProviderProxyExecutor,
TransitFileWriter,
} from "../../core/types.ts";
import type { Docsend2PdfActionName } from "./actions.ts";
import { Buffer } from "node:buffer";
import { compactObject, optionalBoolean, optionalInteger, optionalString } from "../../core/cast.ts";
import { assertPublicHttpUrl, readBoundedResponseBytes } from "../../core/request.ts";
import {
defineProviderExecutors,
defineProviderProxy,
providerUserAgent,
ProviderRequestError,
} from "../provider-runtime.ts";
const service = "docsend_2_pdf";
const convertUrl = "https://docsend2pdf.com/api/convert";
const docsend2PdfApiBaseUrl = "https://docsend2pdf.com/api";
const pdfMimeType = "application/pdf";
interface Docsend2PdfContext {
fetcher: typeof fetch;
signal?: AbortSignal;
transitFiles?: TransitFileWriter;
}
type Handler = (input: Record<string, unknown>, context: Docsend2PdfContext) => Promise<unknown>;
const handlers: Record<Docsend2PdfActionName, Handler> = {
convert(input, context) {
return convert(input, context);
},
};
export const executors: ProviderExecutors = defineProviderExecutors<Docsend2PdfContext>({
service,
handlers,
createContext(context: ExecutionContext, fetcher: typeof fetch): Docsend2PdfContext {
const providerContext: Docsend2PdfContext = { fetcher, signal: context.signal };
if (context.transitFiles) providerContext.transitFiles = context.transitFiles;
return providerContext;
},
});
export const proxy: ProviderProxyExecutor = defineProviderProxy({
service,
baseUrl: docsend2PdfApiBaseUrl,
auth: { type: "none" },
});
async function convert(input: Record<string, unknown>, context: Docsend2PdfContext): Promise<unknown> {
const returnPdfBase64 = optionalBoolean(input.returnPdfBase64) ?? false;
const transitFiles = context.transitFiles;
if (!returnPdfBase64 && !transitFiles) {
throw new ProviderRequestError(
400,
"Transit file storage is not enabled; set returnPdfBase64=true to return PDF bytes inline.",
);
}
const response = await context.fetcher(convertUrl, {
method: "POST",
headers: {
accept: "application/pdf, application/json",
"content-type": "application/json",
"user-agent": providerUserAgent,
},
body: JSON.stringify(buildRequestBody(input)),
signal: context.signal,
});
await assertResponse(response);
const contentType = response.headers.get("content-type") ?? pdfMimeType;
if (!contentType.toLowerCase().includes(pdfMimeType)) {
throw new ProviderRequestError(502, `Docsend2pdf convert returned unexpected content type ${contentType}`);
}
let bytes: Buffer;
if (returnPdfBase64) {
bytes = Buffer.from(await response.arrayBuffer());
} else {
if (!transitFiles) {
throw new ProviderRequestError(400, "Transit file storage is not enabled.");
}
bytes = Buffer.from(
await readBoundedResponseBytes(response, {
maxBytes: transitFiles.maxBytes,
fieldName: "Docsend2pdf converted PDF",
createError: (message) => new ProviderRequestError(413, message),
}),
);
}
const outputName = normalizePdfName(optionalString(input.outputName) ?? readFilename(response));
const pdf = returnPdfBase64
? {
name: outputName,
mimetype: pdfMimeType,
base64: bytes.toString("base64"),
}
: await uploadConvertedPdf(context, outputName, bytes);
return {
succeeded: true,
contentType: pdfMimeType,
contentLength: readHeaderInteger(response.headers, "content-length") ?? bytes.byteLength,
rateLimit: compactObject({
limit: readHeaderInteger(response.headers, "x-ratelimit-limit"),
remaining: readHeaderInteger(response.headers, "x-ratelimit-remaining"),
reset: readHeaderInteger(response.headers, "x-ratelimit-reset"),
retryAfter: readHeaderInteger(response.headers, "retry-after"),
}),
pdf,
};
}
function buildRequestBody(input: Record<string, unknown>): Record<string, unknown> {
const url = readDocsendUrl(input.url);
return compactObject({
url,
email: optionalString(input.email),
passcode: optionalString(input.passcode),
});
}
function readDocsendUrl(value: unknown): string {
const raw = optionalString(value);
if (!raw) throw new ProviderRequestError(400, "url is required");
const url = assertPublicHttpUrl(raw, {
fieldName: "url",
createError: (message) => new ProviderRequestError(400, message),
});
if (url.protocol !== "https:") throw new ProviderRequestError(400, "url must use https");
if (url.username || url.password) throw new ProviderRequestError(400, "url must not include credentials");
const hostname = url.hostname.toLowerCase();
if (hostname !== "docsend.com" && !hostname.endsWith(".docsend.com")) {
throw new ProviderRequestError(400, "url must be a docsend.com URL");
}
return url.toString();
}
async function uploadConvertedPdf(
context: Docsend2PdfContext,
name: string,
bytes: Buffer,
): Promise<Record<string, unknown>> {
if (!context.transitFiles) {
throw new ProviderRequestError(400, "Transit file storage is not enabled.");
}
const file = new File([Uint8Array.from(bytes)], name, { type: pdfMimeType });
const upload = await context.transitFiles.create(file);
return {
name,
mimetype: pdfMimeType,
downloadUrl: upload.downloadUrl,
};
}
async function assertResponse(response: Response): Promise<void> {
if (response.ok) return;
const message = await readError(response);
if (response.status === 429) throw new ProviderRequestError(429, message);
if (response.status >= 400 && response.status < 500) throw new ProviderRequestError(response.status, message);
throw new ProviderRequestError(response.status >= 500 ? response.status : 502, message);
}
async function readError(response: Response): Promise<string> {
const text = await response.text().catch(() => "");
if (!text) return response.statusText || `Docsend2pdf request failed with ${response.status}`;
try {
const payload = JSON.parse(text) as Record<string, unknown>;
return (
optionalString(payload.error) ??
optionalString(payload.message) ??
response.statusText ??
`Docsend2pdf request failed with ${response.status}`
);
} catch {
return text;
}
}
function readHeaderInteger(headers: Headers, name: string): number | undefined {
const value = headers.get(name);
if (!value) return undefined;
return optionalInteger(Number(value));
}
function readFilename(response: Response): string {
const disposition = response.headers.get("content-disposition");
if (!disposition) return "docsend.pdf";
for (const segment of disposition.split(";")) {
const trimmed = segment.trim();
if (trimmed.toLowerCase().startsWith("filename=")) {
return stripWrappingQuotes(trimmed.slice("filename=".length).trim()) || "docsend.pdf";
}
}
return "docsend.pdf";
}
function normalizePdfName(value: string): string {
const trimmed = value.trim() || "docsend.pdf";
return trimmed.toLowerCase().endsWith(".pdf") ? trimmed : `${trimmed}.pdf`;
}
function stripWrappingQuotes(value: string): string {
return value.length >= 2 && value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value;
}