@superdurable/connector-dropbox 0.0.0-stage → 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,678 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ ContinueFolderBranch,
6
+ ContinueFolderBranchCursorExpired,
7
+ ContinueFolderBranchDefect,
8
+ ContinueFolderBranchInvalidResponse,
9
+ ContinueFolderBranchListed,
10
+ ContinueFolderBranchProviderRejected,
11
+ ContinueFolderDefinition,
12
+ ContinueFolderInputSchema,
13
+ ContinueFolderMetadata,
14
+ DownloadFileBranch,
15
+ DownloadFileBranchDefect,
16
+ DownloadFileBranchDownloaded,
17
+ DownloadFileBranchInvalidResponse,
18
+ DownloadFileBranchNotFound,
19
+ DownloadFileBranchProviderRejected,
20
+ DownloadFileBranchTooLarge,
21
+ DownloadFileDefinition,
22
+ DownloadFileInputSchema,
23
+ DownloadFileMetadata,
24
+ DownloadedFileSchema,
25
+ EntryMetadataSchema,
26
+ FolderPageSchema,
27
+ GetMetadataBranch,
28
+ GetMetadataBranchDefect,
29
+ GetMetadataBranchFound,
30
+ GetMetadataBranchInvalidResponse,
31
+ GetMetadataBranchNotFound,
32
+ GetMetadataBranchProviderRejected,
33
+ GetMetadataDefinition,
34
+ GetMetadataInputSchema,
35
+ GetMetadataMetadata,
36
+ ListFolderBranch,
37
+ ListFolderBranchDefect,
38
+ ListFolderBranchInvalidResponse,
39
+ ListFolderBranchListed,
40
+ ListFolderBranchNotFound,
41
+ ListFolderBranchProviderRejected,
42
+ ListFolderDefinition,
43
+ ListFolderInputSchema,
44
+ ListFolderMetadata,
45
+ ProviderID,
46
+ UploadFileBranch,
47
+ UploadFileBranchDefect,
48
+ UploadFileBranchInvalidResponse,
49
+ UploadFileBranchProviderRejected,
50
+ UploadFileBranchUploaded,
51
+ UploadFileDefinition,
52
+ UploadFileInputSchema,
53
+ UploadFileMetadata,
54
+ UploadedFileSchema,
55
+ decodeCredentials,
56
+ decodeSharedCredentials,
57
+ emptyDownloadedFile,
58
+ emptyEntryMetadata,
59
+ emptyFolderPage,
60
+ emptyUploadedFile,
61
+ newConnection,
62
+ newConnectionWithOperations,
63
+ newProjectCredentialProvider
64
+ } from "./chunk-OVLMU3VN.js";
65
+
66
+ // src/client.ts
67
+ import {
68
+ ReauthorizationRequiredError,
69
+ SecretString,
70
+ resolveCredential
71
+ } from "@superdurable/connectors-sdk";
72
+ import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
73
+ import {
74
+ BodyTooLargeError,
75
+ isHeaderSafeCredential,
76
+ parseRetryAfter,
77
+ sendProviderRequest,
78
+ validateBaseURL
79
+ } from "@superdurable/connectors-sdk/providerhttp";
80
+
81
+ // src/generated/refresh.ts
82
+ var Authorization = {
83
+ "fields": [
84
+ {
85
+ "name": "oauth_client_id",
86
+ "required": true,
87
+ "type": "string"
88
+ },
89
+ {
90
+ "name": "oauth_client_secret",
91
+ "required": true,
92
+ "type": "secretString"
93
+ },
94
+ {
95
+ "name": "access_token",
96
+ "required": true,
97
+ "type": "secretString"
98
+ },
99
+ {
100
+ "name": "refresh_token",
101
+ "required": true,
102
+ "type": "secretString"
103
+ }
104
+ ],
105
+ "oauth2": {
106
+ "clientIDCredential": "oauth_client_id",
107
+ "clientSecretCredential": "oauth_client_secret",
108
+ "credentialMappings": [
109
+ {
110
+ "credential": "access_token",
111
+ "source": "access_token"
112
+ },
113
+ {
114
+ "credential": "refresh_token",
115
+ "source": "refresh_token"
116
+ }
117
+ ],
118
+ "refresh": {
119
+ "missingExpiry": "reject",
120
+ "requiredScopes": [
121
+ "files.metadata.read",
122
+ "files.content.read",
123
+ "files.content.write"
124
+ ],
125
+ "scopeSeparators": "whitespaceAndComma",
126
+ "storedMissingExpiry": "refresh",
127
+ "terminalErrorCodes": [
128
+ "invalid_grant",
129
+ "invalid_client",
130
+ "unauthorized_client"
131
+ ],
132
+ "tokenExchangeTimeout": "15s"
133
+ },
134
+ "scopes": [
135
+ "files.metadata.read",
136
+ "files.content.read",
137
+ "files.content.write"
138
+ ],
139
+ "tokenEndpoint": "https://api.dropboxapi.com/oauth2/token",
140
+ "tokenEndpointAuthMethod": "client_secret_basic"
141
+ },
142
+ "refreshable": true,
143
+ "type": "oauth2"
144
+ };
145
+ var CredentialFields = {
146
+ "access_token": "accessToken",
147
+ "oauth_client_id": "oauthClientId",
148
+ "oauth_client_secret": "oauthClientSecret",
149
+ "refresh_token": "refreshToken"
150
+ };
151
+
152
+ // src/operations.ts
153
+ import {
154
+ newMutationBranch,
155
+ newMutationRetry,
156
+ newQueryBranch,
157
+ newQueryRetry
158
+ } from "@superdurable/connectors-sdk";
159
+ function failure(operation, kind, message) {
160
+ return { kind, provider: "dropbox", operation, message };
161
+ }
162
+ function queryFailure(operation, branch, kind, message, empty) {
163
+ return newQueryBranch(branch, empty, {}, failure(operation, kind, message));
164
+ }
165
+ function queryRetry(operation, kind, message, delay = 0) {
166
+ return newQueryRetry(failure(operation, kind, message), delay);
167
+ }
168
+ function uploadFailure(branch, kind, message) {
169
+ return newMutationBranch(branch, emptyUploadedFile, {}, failure("uploadFile", kind, message));
170
+ }
171
+ function uploadRetry(kind, message, delay = 0) {
172
+ return newMutationRetry(failure("uploadFile", kind, message), delay);
173
+ }
174
+ function validPath(path, allowRoot) {
175
+ if (!path) return allowRoot;
176
+ if (Buffer.byteLength(path, "utf8") > 4096 || Buffer.from(path, "utf8").toString("utf8") !== path) return false;
177
+ for (const character of path) if (character.codePointAt(0) < 32 || character.codePointAt(0) === 127) return false;
178
+ return ["/", "id:", "ns:", "rev:"].some((prefix) => path.startsWith(prefix));
179
+ }
180
+ function requiredString(object, key) {
181
+ const value = object[key];
182
+ if (value === void 0 || value === null) return "";
183
+ if (typeof value !== "string") throw new TypeError("Dropbox field has an invalid type");
184
+ return value;
185
+ }
186
+ function objectBody(body) {
187
+ const value = JSON.parse(Buffer.from(body).toString("utf8"));
188
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Dropbox object is invalid");
189
+ return value;
190
+ }
191
+ function decodeEntry(value, upload = false) {
192
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Dropbox entry is invalid");
193
+ const record = value;
194
+ const kind = upload ? "file" : requiredString(record, ".tag");
195
+ const entry = {
196
+ id: requiredString(record, "id"),
197
+ name: requiredString(record, "name"),
198
+ pathDisplay: requiredString(record, "path_display"),
199
+ kind
200
+ };
201
+ if (!["file", "folder"].includes(kind) || !entry.id || !entry.name || !entry.pathDisplay) throw new TypeError("Dropbox entry identity is incomplete");
202
+ return entry;
203
+ }
204
+ function decodeFolderPage(body) {
205
+ const record = objectBody(body);
206
+ if (!Array.isArray(record.entries) || typeof record.has_more !== "boolean") throw new TypeError("Dropbox folder page is invalid");
207
+ const cursor = requiredString(record, "cursor");
208
+ if (!cursor) throw new TypeError("Dropbox folder cursor is missing");
209
+ return { entries: record.entries.map((item) => decodeEntry(item)), cursor, hasMore: record.has_more };
210
+ }
211
+ function errorSummary(body) {
212
+ try {
213
+ return requiredString(objectBody(body), "error_summary");
214
+ } catch {
215
+ return "";
216
+ }
217
+ }
218
+ function queryDecision(operation, exchange, empty, notFound = "", cursorExpired = "") {
219
+ if (exchange.error === "credential") return queryFailure(operation, "defect", "AUTHENTICATION", "connection credentials are unavailable or invalid", empty);
220
+ if (exchange.error === "refresh") return queryRetry(operation, "AVAILABILITY", "Dropbox credentials could not be refreshed");
221
+ if (exchange.error === "request") return queryRetry(operation, "TRANSPORT", "Dropbox request failed");
222
+ if (exchange.status === 429) return queryRetry(operation, "RATE_LIMIT", "Dropbox rate limited the request", exchange.retryAfterMs);
223
+ if (exchange.status === 408 || exchange.status >= 500) return queryRetry(operation, "AVAILABILITY", "Dropbox is temporarily unavailable", exchange.retryAfterMs);
224
+ if (exchange.status === 409) {
225
+ const summary = errorSummary(exchange.body);
226
+ if (notFound && summary.startsWith("path/not_found")) return queryFailure(operation, notFound, "NOT_FOUND", "Dropbox did not find the resource", empty);
227
+ if (cursorExpired && summary.startsWith("reset/")) return queryFailure(operation, cursorExpired, "PROVIDER_REJECTION", "Dropbox folder cursor expired", empty);
228
+ }
229
+ if (exchange.status !== 200) return queryFailure(operation, "providerRejected", "PROVIDER_REJECTION", `Dropbox rejected HTTP ${exchange.status}`, empty);
230
+ if (exchange.error === "tooLarge") return queryFailure(operation, "invalidResponse", "RESPONSE_TOO_LARGE", "Dropbox response exceeded the configured limit", empty);
231
+ if (exchange.error) return queryRetry(operation, "TRANSPORT", "Dropbox response was interrupted");
232
+ return void 0;
233
+ }
234
+ var ListFolderOperation = class {
235
+ /** Bind the provider client. */
236
+ constructor(client) {
237
+ this.client = client;
238
+ if (!client) throw new TypeError("Dropbox client is required");
239
+ }
240
+ client;
241
+ /** Return stable manifest metadata. */
242
+ definition() {
243
+ return ListFolderDefinition;
244
+ }
245
+ /** List one folder page. */
246
+ async invoke(call, input) {
247
+ input = ListFolderInputSchema.parse(input);
248
+ if (!validPath(input.path, true) || !Number.isInteger(input.limit) || input.limit < 1 || input.limit > 2e3)
249
+ return queryFailure("listFolder", "defect", "VALIDATION", "folder path or page limit is invalid", emptyFolderPage);
250
+ const exchange = await this.client.postJSON(call, "/2/files/list_folder", { path: input.path, limit: input.limit });
251
+ const decision = queryDecision("listFolder", exchange, emptyFolderPage, "notFound");
252
+ if (decision) return decision;
253
+ try {
254
+ return newQueryBranch("listed", decodeFolderPage(exchange.body));
255
+ } catch {
256
+ return queryFailure("listFolder", "invalidResponse", "PROTOCOL", "Dropbox returned invalid JSON", emptyFolderPage);
257
+ }
258
+ }
259
+ };
260
+ var GetMetadataOperation = class {
261
+ /** Bind the provider client. */
262
+ constructor(client) {
263
+ this.client = client;
264
+ if (!client) throw new TypeError("Dropbox client is required");
265
+ }
266
+ client;
267
+ /** Return stable manifest metadata. */
268
+ definition() {
269
+ return GetMetadataDefinition;
270
+ }
271
+ /** Read one file or folder identity. */
272
+ async invoke(call, input) {
273
+ input = GetMetadataInputSchema.parse(input);
274
+ if (!validPath(input.path, false)) return queryFailure("getMetadata", "defect", "VALIDATION", "file or folder path is invalid", emptyEntryMetadata);
275
+ const exchange = await this.client.postJSON(call, "/2/files/get_metadata", { path: input.path });
276
+ const decision = queryDecision("getMetadata", exchange, emptyEntryMetadata, "notFound");
277
+ if (decision) return decision;
278
+ try {
279
+ return newQueryBranch("found", decodeEntry(objectBody(exchange.body)));
280
+ } catch {
281
+ return queryFailure("getMetadata", "invalidResponse", "PROTOCOL", "Dropbox returned invalid JSON", emptyEntryMetadata);
282
+ }
283
+ }
284
+ };
285
+ var ContinueFolderOperation = class {
286
+ /** Bind the provider client. */
287
+ constructor(client) {
288
+ this.client = client;
289
+ if (!client) throw new TypeError("Dropbox client is required");
290
+ }
291
+ client;
292
+ /** Return stable manifest metadata. */
293
+ definition() {
294
+ return ContinueFolderDefinition;
295
+ }
296
+ /** Read the next folder page or change set. */
297
+ async invoke(call, input) {
298
+ input = ContinueFolderInputSchema.parse(input);
299
+ const cursor = input.cursor;
300
+ if (!cursor || Buffer.byteLength(cursor) > 4096 || Buffer.from(cursor).toString("utf8") !== cursor || /[\r\n]/.test(cursor) || cursor.includes("\0"))
301
+ return queryFailure("continueFolder", "defect", "VALIDATION", "folder cursor is invalid", emptyFolderPage);
302
+ const exchange = await this.client.postJSON(call, "/2/files/list_folder/continue", { cursor });
303
+ const decision = queryDecision("continueFolder", exchange, emptyFolderPage, "", "cursorExpired");
304
+ if (decision) return decision;
305
+ try {
306
+ return newQueryBranch("listed", decodeFolderPage(exchange.body));
307
+ } catch {
308
+ return queryFailure("continueFolder", "invalidResponse", "PROTOCOL", "Dropbox returned invalid JSON", emptyFolderPage);
309
+ }
310
+ }
311
+ };
312
+ var DownloadFileOperation = class {
313
+ /** Bind the provider client. */
314
+ constructor(client) {
315
+ this.client = client;
316
+ if (!client) throw new TypeError("Dropbox client is required");
317
+ }
318
+ client;
319
+ /** Return stable manifest metadata. */
320
+ definition() {
321
+ return DownloadFileDefinition;
322
+ }
323
+ /** Return one file identity and Base64 content. */
324
+ async invoke(call, input) {
325
+ input = DownloadFileInputSchema.parse(input);
326
+ if (!validPath(input.path, false)) return queryFailure("downloadFile", "defect", "VALIDATION", "file path is invalid", emptyDownloadedFile);
327
+ const exchange = await this.client.download(call, input.path);
328
+ if (exchange.error === "credential") return queryFailure("downloadFile", "defect", "AUTHENTICATION", "connection credentials are unavailable or invalid", emptyDownloadedFile);
329
+ if (exchange.error === "refresh") return queryRetry("downloadFile", "AVAILABILITY", "Dropbox credentials could not be refreshed");
330
+ if (exchange.error === "request") return queryRetry("downloadFile", "TRANSPORT", "Dropbox download request failed");
331
+ if (exchange.status === 429) return queryRetry("downloadFile", "RATE_LIMIT", "Dropbox rate limited the download", exchange.retryAfterMs);
332
+ if (exchange.status === 408 || exchange.status >= 500) return queryRetry("downloadFile", "AVAILABILITY", "Dropbox download is temporarily unavailable", exchange.retryAfterMs);
333
+ if (exchange.status === 409 && errorSummary(exchange.body).startsWith("path/not_found"))
334
+ return queryFailure("downloadFile", "notFound", "NOT_FOUND", "Dropbox did not find the file", emptyDownloadedFile);
335
+ if (exchange.status !== 200) return queryFailure("downloadFile", "providerRejected", "PROVIDER_REJECTION", `Dropbox rejected HTTP ${exchange.status}`, emptyDownloadedFile);
336
+ if (exchange.error === "tooLarge") return queryFailure("downloadFile", "tooLarge", "RESPONSE_TOO_LARGE", "Dropbox file exceeds the configured download limit", emptyDownloadedFile);
337
+ if (exchange.error) return queryRetry("downloadFile", "TRANSPORT", "Dropbox download response was interrupted");
338
+ try {
339
+ const file = decodeEntry(JSON.parse(exchange.metadata));
340
+ if (file.kind !== "file") throw new TypeError("Dropbox metadata is not a file");
341
+ return newQueryBranch("downloaded", { file, contentBase64: Buffer.from(exchange.body).toString("base64"), contentBytes: exchange.body.length });
342
+ } catch {
343
+ return queryFailure("downloadFile", "invalidResponse", "PROTOCOL", "Dropbox returned invalid file metadata", emptyDownloadedFile);
344
+ }
345
+ }
346
+ };
347
+ var UploadFileOperation = class {
348
+ /** Bind the provider client. */
349
+ constructor(client) {
350
+ this.client = client;
351
+ if (!client) throw new TypeError("Dropbox client is required");
352
+ }
353
+ client;
354
+ /** Return stable manifest metadata. */
355
+ definition() {
356
+ return UploadFileDefinition;
357
+ }
358
+ /** Record stable call identity; Dropbox uses absolute overwrite rather than a request key. */
359
+ idempotencyKey(callID, input) {
360
+ void input;
361
+ return callID;
362
+ }
363
+ /** Overwrite the same path with the same bytes on every retry. */
364
+ async invoke(call, input) {
365
+ input = UploadFileInputSchema.parse(input);
366
+ if (!input.path.startsWith("/") || !validPath(input.path, false)) return uploadFailure("defect", "VALIDATION", "upload path must be absolute");
367
+ if (Math.floor(input.contentBase64.length / 4) * 3 > this.client.maxUploadBytes) return uploadFailure("defect", "VALIDATION", "upload exceeds the configured byte limit");
368
+ const content = Buffer.from(input.contentBase64, "base64");
369
+ if (content.toString("base64") !== input.contentBase64) return uploadFailure("defect", "VALIDATION", "upload content must be bounded Base64");
370
+ if (content.length > this.client.maxUploadBytes) return uploadFailure("defect", "VALIDATION", "upload content must be bounded Base64");
371
+ const exchange = await this.client.upload(call, input.path, content);
372
+ if (exchange.error === "credential") return uploadFailure("defect", "AUTHENTICATION", "connection credentials are unavailable or invalid");
373
+ if (exchange.error === "refresh") return uploadRetry("AVAILABILITY", "Dropbox credentials could not be refreshed");
374
+ if (exchange.error === "request") return uploadRetry("TRANSPORT", "Dropbox upload request failed");
375
+ if (exchange.status === 429) return uploadRetry("RATE_LIMIT", "Dropbox rate limited the upload", exchange.retryAfterMs);
376
+ if (exchange.status === 408 || exchange.status >= 500) return uploadRetry("AVAILABILITY", "Dropbox upload is temporarily unavailable", exchange.retryAfterMs);
377
+ if (exchange.status !== 200) return uploadFailure("providerRejected", "PROVIDER_REJECTION", `Dropbox rejected HTTP ${exchange.status}`);
378
+ if (exchange.error === "tooLarge") return uploadFailure("invalidResponse", "RESPONSE_TOO_LARGE", "Dropbox upload metadata exceeded the configured limit");
379
+ if (exchange.error) return uploadRetry("TRANSPORT", "Dropbox upload response was interrupted");
380
+ try {
381
+ return newMutationBranch("uploaded", { file: decodeEntry(objectBody(exchange.body), true) });
382
+ } catch {
383
+ return uploadFailure("invalidResponse", "PROTOCOL", "Dropbox returned invalid upload metadata");
384
+ }
385
+ }
386
+ };
387
+
388
+ // src/client.ts
389
+ var DropboxClient = class {
390
+ /** Validated RPC endpoint root. */
391
+ baseURL;
392
+ /** Validated content endpoint root. */
393
+ contentBaseURL;
394
+ /** Per-request timeout in milliseconds. */
395
+ timeoutMs;
396
+ /** Maximum JSON response bytes. */
397
+ maxResponseBytes;
398
+ /** Maximum downloaded file bytes. */
399
+ maxDownloadBytes;
400
+ /** Maximum decoded upload file bytes. */
401
+ maxUploadBytes;
402
+ credentials;
403
+ refreshDriver;
404
+ send;
405
+ now;
406
+ /** Validate settings and inject provider dependencies before any network call. */
407
+ constructor(config, credentials, options = {}) {
408
+ if (!config || !credentials) throw new TypeError("Dropbox configuration and credentials are required");
409
+ this.baseURL = validateBaseURL(config.baseUrl || "https://api.dropboxapi.com");
410
+ this.contentBaseURL = validateBaseURL(config.contentBaseUrl || "https://content.dropboxapi.com");
411
+ this.timeoutMs = config.timeoutMs || 15e3;
412
+ this.maxResponseBytes = config.maxResponseBytes || 2097152;
413
+ this.maxDownloadBytes = config.maxDownloadBytes || 1048576;
414
+ this.maxUploadBytes = config.maxUploadBytes || 1048576;
415
+ if (![this.timeoutMs, this.maxResponseBytes, this.maxDownloadBytes, this.maxUploadBytes].every((value) => Number.isSafeInteger(value) && value > 0)) throw new TypeError("Dropbox request limits must be positive integers");
416
+ if (this.maxUploadBytes > 150 * 1024 * 1024) throw new TypeError("Dropbox upload limit exceeds 150 MiB");
417
+ this.credentials = credentials;
418
+ this.refreshDriver = options.refreshDriver ?? new ManifestCredentialRefreshDriver({
419
+ providerName: "Dropbox",
420
+ auth: Authorization,
421
+ credentialFields: CredentialFields
422
+ });
423
+ this.send = options.send ?? sendProviderRequest;
424
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
425
+ }
426
+ /** Bind the folder listing Query. */
427
+ listFolder() {
428
+ return new ListFolderOperation(this);
429
+ }
430
+ /** Bind the metadata Query. */
431
+ getMetadata() {
432
+ return new GetMetadataOperation(this);
433
+ }
434
+ /** Bind the cursor continuation Query. */
435
+ continueFolder() {
436
+ return new ContinueFolderOperation(this);
437
+ }
438
+ /** Bind the bounded download Query. */
439
+ downloadFile() {
440
+ return new DownloadFileOperation(this);
441
+ }
442
+ /** Bind the bounded replacement Mutation. */
443
+ uploadFile() {
444
+ return new UploadFileOperation(this);
445
+ }
446
+ /** Post one JSON request to the Dropbox RPC API. */
447
+ postJSON(call, path, payload) {
448
+ return this.post(call, this.baseURL + path, Buffer.from(JSON.stringify(payload)), {
449
+ Accept: "application/json",
450
+ "Content-Type": "application/json"
451
+ }, this.maxResponseBytes);
452
+ }
453
+ /** Download one file using Dropbox's content endpoint. */
454
+ download(call, path) {
455
+ return this.post(call, this.contentBaseURL + "/2/files/download", void 0, {
456
+ "Dropbox-API-Arg": asciiJSON({ path })
457
+ }, this.maxDownloadBytes, true);
458
+ }
459
+ /** Overwrite one file using Dropbox's content endpoint. */
460
+ upload(call, path, content) {
461
+ return this.post(call, this.contentBaseURL + "/2/files/upload", content, {
462
+ "Dropbox-API-Arg": asciiJSON({ path, mode: "overwrite", autorename: false }),
463
+ "Content-Type": "application/octet-stream"
464
+ }, this.maxResponseBytes);
465
+ }
466
+ async post(call, url, body, headers, successLimit, isDownload = false) {
467
+ let token;
468
+ try {
469
+ const credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
470
+ if (!(credentials.accessToken instanceof SecretString)) return { status: 0, body: new Uint8Array(), metadata: "", retryAfterMs: 0, error: "credential" };
471
+ token = credentials.accessToken.reveal();
472
+ } catch (error) {
473
+ return {
474
+ status: 0,
475
+ body: new Uint8Array(),
476
+ metadata: "",
477
+ retryAfterMs: 0,
478
+ error: error instanceof ReauthorizationRequiredError ? "credential" : "refresh"
479
+ };
480
+ }
481
+ if (!token || !isHeaderSafeCredential(token)) return { status: 0, body: new Uint8Array(), metadata: "", retryAfterMs: 0, error: "credential" };
482
+ const endpoint = new URL(url);
483
+ const request = {
484
+ url,
485
+ method: "POST",
486
+ headers: {
487
+ ...headers,
488
+ Authorization: "Bearer " + token,
489
+ "User-Agent": "Dex Connector (https://superdurable.io)"
490
+ },
491
+ maxResponseBytes: Math.max(successLimit, this.maxResponseBytes),
492
+ addressPolicy: endpoint.protocol === "http:" ? "privateNetworkHTTP" : "publicHTTPS",
493
+ timeoutMs: this.timeoutMs,
494
+ signal: call.context.cancellationSignal,
495
+ ...body === void 0 ? {} : { body }
496
+ };
497
+ let response;
498
+ try {
499
+ response = await this.send(request);
500
+ } catch (error) {
501
+ if (error instanceof BodyTooLargeError) {
502
+ const status = error.status ?? 0;
503
+ const responseHeaders = error.headers ?? {};
504
+ return {
505
+ status,
506
+ body: new Uint8Array(),
507
+ metadata: "",
508
+ retryAfterMs: parseRetryAfter(header(responseHeaders, "retry-after"), this.now()),
509
+ error: "tooLarge"
510
+ };
511
+ }
512
+ return { status: 0, body: new Uint8Array(), metadata: "", retryAfterMs: 0, error: "request" };
513
+ }
514
+ const metadata = isDownload ? header(response.headers, "dropbox-api-result") : "";
515
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"), this.now());
516
+ if (metadata.length > 65536 || metadata.includes(token) || Buffer.from(response.body).includes(token)) {
517
+ return { status: response.status, body: new Uint8Array(), metadata: "", retryAfterMs, error: "credential" };
518
+ }
519
+ const limit = response.status === 200 ? successLimit : this.maxResponseBytes;
520
+ if (response.body.length > limit) return { status: response.status, body: new Uint8Array(), metadata: "", retryAfterMs, error: "tooLarge" };
521
+ return { status: response.status, body: response.body, metadata, retryAfterMs };
522
+ }
523
+ };
524
+ function header(headers, name) {
525
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
526
+ return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
527
+ }
528
+ function asciiJSON(value) {
529
+ return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (character) => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0"));
530
+ }
531
+
532
+ // src/project.ts
533
+ function encodeCredentials(credentials) {
534
+ return {
535
+ oauth_client_id: credentials.oauthClientId,
536
+ oauth_client_secret: credentials.oauthClientSecret.reveal(),
537
+ access_token: credentials.accessToken.reveal(),
538
+ refresh_token: credentials.refreshToken.reveal()
539
+ };
540
+ }
541
+ function newProjectConnection(project, connectionName, options = {}) {
542
+ if (!project) throw new TypeError("Dropbox project is required");
543
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === "dropbox" && entry.connectionName === connectionName);
544
+ if (!selected || selected.provider !== "dropbox") throw new TypeError("Dropbox project connection is not configured");
545
+ const config = ConfigSchema.parse(selected.configuration);
546
+ const provider = newProjectCredentialProvider(project, connectionName, decodeCredentials, encodeCredentials, decodeSharedCredentials);
547
+ return newConnection(new DropboxClient(config, provider, options), { provider: "dropbox", name: connectionName });
548
+ }
549
+
550
+ // src/generated/steps.ts
551
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
552
+ function newListFolderStep(configuration) {
553
+ const { connection, connectionName, listed, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
554
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
555
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listFolder(), connection: connection.reference, branches: [
556
+ goToBranch("listed", listed),
557
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
558
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
559
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
560
+ ...defect ? [goToBranch("defect", defect)] : []
561
+ ] });
562
+ }
563
+ function newGetMetadataStep(configuration) {
564
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
565
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
566
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getMetadata(), connection: connection.reference, branches: [
567
+ goToBranch("found", found),
568
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
569
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
570
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
571
+ ...defect ? [goToBranch("defect", defect)] : []
572
+ ] });
573
+ }
574
+ function newContinueFolderStep(configuration) {
575
+ const { connection, connectionName, listed, cursorExpired, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
576
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
577
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.continueFolder(), connection: connection.reference, branches: [
578
+ goToBranch("listed", listed),
579
+ ...cursorExpired ? [goToBranch("cursorExpired", cursorExpired)] : [],
580
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
581
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
582
+ ...defect ? [goToBranch("defect", defect)] : []
583
+ ] });
584
+ }
585
+ function newDownloadFileStep(configuration) {
586
+ const { connection, connectionName, downloaded, notFound, tooLarge, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
587
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
588
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.downloadFile(), connection: connection.reference, branches: [
589
+ goToBranch("downloaded", downloaded),
590
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
591
+ ...tooLarge ? [goToBranch("tooLarge", tooLarge)] : [],
592
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
593
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
594
+ ...defect ? [goToBranch("defect", defect)] : []
595
+ ] });
596
+ }
597
+ function newUploadFileStep(configuration) {
598
+ const { connection, connectionName, uploaded, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
599
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
600
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.uploadFile(), connection: connection.reference, branches: [
601
+ goToBranch("uploaded", uploaded),
602
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
603
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
604
+ ...defect ? [goToBranch("defect", defect)] : []
605
+ ] });
606
+ }
607
+ export {
608
+ ConfigSchema,
609
+ Connection,
610
+ ConnectorID,
611
+ ContinueFolderBranch,
612
+ ContinueFolderBranchCursorExpired,
613
+ ContinueFolderBranchDefect,
614
+ ContinueFolderBranchInvalidResponse,
615
+ ContinueFolderBranchListed,
616
+ ContinueFolderBranchProviderRejected,
617
+ ContinueFolderDefinition,
618
+ ContinueFolderInputSchema,
619
+ ContinueFolderMetadata,
620
+ ContinueFolderOperation,
621
+ DownloadFileBranch,
622
+ DownloadFileBranchDefect,
623
+ DownloadFileBranchDownloaded,
624
+ DownloadFileBranchInvalidResponse,
625
+ DownloadFileBranchNotFound,
626
+ DownloadFileBranchProviderRejected,
627
+ DownloadFileBranchTooLarge,
628
+ DownloadFileDefinition,
629
+ DownloadFileInputSchema,
630
+ DownloadFileMetadata,
631
+ DownloadFileOperation,
632
+ DownloadedFileSchema,
633
+ DropboxClient,
634
+ EntryMetadataSchema,
635
+ FolderPageSchema,
636
+ GetMetadataBranch,
637
+ GetMetadataBranchDefect,
638
+ GetMetadataBranchFound,
639
+ GetMetadataBranchInvalidResponse,
640
+ GetMetadataBranchNotFound,
641
+ GetMetadataBranchProviderRejected,
642
+ GetMetadataDefinition,
643
+ GetMetadataInputSchema,
644
+ GetMetadataMetadata,
645
+ GetMetadataOperation,
646
+ ListFolderBranch,
647
+ ListFolderBranchDefect,
648
+ ListFolderBranchInvalidResponse,
649
+ ListFolderBranchListed,
650
+ ListFolderBranchNotFound,
651
+ ListFolderBranchProviderRejected,
652
+ ListFolderDefinition,
653
+ ListFolderInputSchema,
654
+ ListFolderMetadata,
655
+ ListFolderOperation,
656
+ ProviderID,
657
+ UploadFileBranch,
658
+ UploadFileBranchDefect,
659
+ UploadFileBranchInvalidResponse,
660
+ UploadFileBranchProviderRejected,
661
+ UploadFileBranchUploaded,
662
+ UploadFileDefinition,
663
+ UploadFileInputSchema,
664
+ UploadFileMetadata,
665
+ UploadFileOperation,
666
+ UploadedFileSchema,
667
+ decodeCredentials,
668
+ decodeSharedCredentials,
669
+ header,
670
+ newConnection,
671
+ newConnectionWithOperations,
672
+ newContinueFolderStep,
673
+ newDownloadFileStep,
674
+ newGetMetadataStep,
675
+ newListFolderStep,
676
+ newProjectConnection,
677
+ newUploadFileStep
678
+ };