@finueva/drive 0.8.0 → 0.10.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 CHANGED
@@ -1,3515 +1 @@
1
- //#region src/core.ts
2
- const DRIVE_API_ERROR_CODES = Object.freeze([
3
- "authentication_required",
4
- "identity_authority_unavailable",
5
- "permission_denied",
6
- "resource_not_found",
7
- "invalid_request",
8
- "invalid_pagination_cursor",
9
- "invalid_idempotency_key",
10
- "precondition_failed",
11
- "range_not_satisfiable",
12
- "idempotency_conflict",
13
- "quota_exceeded",
14
- "upload_recovery_required",
15
- "service_unavailable",
16
- "internal_error"
17
- ]);
18
- const DRIVE_API_ERROR_MESSAGES = Object.freeze({
19
- authentication_required: "Authentication is required.",
20
- identity_authority_unavailable: "Authentication is temporarily unavailable.",
21
- permission_denied: "The requested action is not permitted.",
22
- resource_not_found: "The requested resource was not found.",
23
- invalid_request: "The request is invalid.",
24
- invalid_pagination_cursor: "The pagination cursor is invalid.",
25
- invalid_idempotency_key: "The idempotency key is invalid.",
26
- precondition_failed: "The request precondition failed.",
27
- range_not_satisfiable: "The requested byte range is not satisfiable.",
28
- idempotency_conflict: "The idempotency key conflicts with an earlier request.",
29
- quota_exceeded: "The workspace storage quota would be exceeded.",
30
- upload_recovery_required: "The upload requires recovery before it can continue.",
31
- service_unavailable: "The service is temporarily unavailable.",
32
- internal_error: "The request could not be completed."
33
- });
34
- const SDK_MESSAGES = Object.freeze({
35
- invalid_input: "The Drive SDK input is invalid.",
36
- credential_unavailable: "A Drive credential could not be obtained.",
37
- network_error: "The Drive request could not reach the service.",
38
- timeout: "The Drive request timed out.",
39
- aborted: "The Drive request was aborted.",
40
- invalid_response: "Drive returned an invalid response."
41
- });
42
- var DriveError = class extends Error {
43
- code;
44
- status;
45
- requestId;
46
- details;
47
- constructor(code, options = {}) {
48
- super(code in DRIVE_API_ERROR_MESSAGES ? DRIVE_API_ERROR_MESSAGES[code] : SDK_MESSAGES[code]);
49
- this.name = "DriveError";
50
- this.code = code;
51
- this.status = options.status ?? null;
52
- this.requestId = options.requestId ?? null;
53
- this.details = Object.freeze({});
54
- }
55
- };
56
- //#endregion
57
- //#region src/internal/client/response.ts
58
- const ERROR_BODY_LIMIT = 16 * 1024;
59
- const SUCCESS_BODY_LIMIT = 256 * 1024;
60
- const RESPONSE_CHUNK_LIMIT = 256;
61
- const RESPONSE_DEADLINE_MILLISECONDS = 5e3;
62
- const REQUEST_ID = /^[A-Za-z0-9_-]{16,128}$/;
63
- const COLLECTION_ETAG = /^"drive\.permission-collection\.v1\.(0|[1-9][0-9]*)"$/;
64
- const GRANT_ETAG$1 = /^"drive\.permission-grant\.v1\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"$/;
65
- const LIST_ETAG$1 = /^"drive\.permission-list\.v1\.[0-9a-f]{64}"$/;
66
- const ITEM_ETAG = /^"drive\.item\.v1\.(0|[1-9][0-9]*)"$/;
67
- async function parseResponse(response, operationSignal, preconditionStatus, successStatuses, guard, allowsQuotaExceeded, allowedErrorCodes) {
68
- const requestId = safeRequestId(response.headers.get("x-request-id"));
69
- if (requestId === null) {
70
- cancelResponse(response);
71
- throw new DriveError("invalid_response", { status: response.status });
72
- }
73
- if (!successStatuses.includes(response.status)) throw await normalizeError(response, requestId, operationSignal, preconditionStatus, allowsQuotaExceeded, allowedErrorCodes);
74
- if (response.status === 304) {
75
- const contentLength = response.headers.get("content-length");
76
- const etag = response.headers.get("etag");
77
- const status = response.status;
78
- if (response.body !== null || contentLength !== null && contentLength !== "0" || response.headers.has("content-type") || etag === null || !/^"[\x21\x23-\x7e]{1,1022}"$/.test(etag) || !guard(void 0, status, response.headers)) {
79
- cancelResponse(response);
80
- throw new DriveError("invalid_response", {
81
- status,
82
- requestId
83
- });
84
- }
85
- return Object.freeze({
86
- data: void 0,
87
- status,
88
- requestId,
89
- validators: Object.freeze({ etag })
90
- });
91
- }
92
- const { value } = await parseBoundedJson(response, SUCCESS_BODY_LIMIT, response.status, requestId, operationSignal);
93
- const status = response.status;
94
- if (!guard(value, status, response.headers)) throw new DriveError("invalid_response", {
95
- status,
96
- requestId
97
- });
98
- return Object.freeze({
99
- data: value,
100
- status,
101
- requestId,
102
- validators: readValidators(response.headers)
103
- });
104
- }
105
- async function parseNoContentResponse(response, operationSignal, preconditionStatus, successStatuses, allowedErrorCodes) {
106
- const requestId = safeRequestId(response.headers.get("x-request-id"));
107
- if (requestId === null) {
108
- cancelResponse(response);
109
- throw new DriveError("invalid_response", { status: response.status });
110
- }
111
- if (!successStatuses.includes(response.status)) throw await normalizeError(response, requestId, operationSignal, preconditionStatus, false, allowedErrorCodes);
112
- const contentLength = response.headers.get("content-length");
113
- if (response.body !== null || contentLength !== null && contentLength !== "0" || response.headers.has("content-type")) {
114
- cancelResponse(response);
115
- throw new DriveError("invalid_response", {
116
- status: response.status,
117
- requestId
118
- });
119
- }
120
- return Object.freeze({
121
- data: void 0,
122
- status: response.status,
123
- requestId,
124
- validators: Object.freeze({})
125
- });
126
- }
127
- function parseCollectionEtag(value) {
128
- const match = COLLECTION_ETAG.exec(value);
129
- if (!match) return void 0;
130
- const revision = Number(match[1]);
131
- return Number.isSafeInteger(revision) ? revision : void 0;
132
- }
133
- function parseGrantEtag(value) {
134
- const match = GRANT_ETAG$1.exec(value);
135
- if (!match) return void 0;
136
- const collectionRevision = Number(match[1]);
137
- const grantRevision = Number(match[2]);
138
- return Number.isSafeInteger(collectionRevision) && Number.isSafeInteger(grantRevision) ? [collectionRevision, grantRevision] : void 0;
139
- }
140
- function parseItemEtag(value) {
141
- const match = ITEM_ETAG.exec(value);
142
- if (!match) return void 0;
143
- const revision = Number(match[1]);
144
- return Number.isSafeInteger(revision) ? revision : void 0;
145
- }
146
- async function normalizeError(response, headerRequestId, signal, preconditionStatus, allowsQuotaExceeded, allowedErrorCodes) {
147
- let parsed;
148
- try {
149
- parsed = await parseBoundedJson(response, ERROR_BODY_LIMIT, response.status, headerRequestId, signal);
150
- } catch (error) {
151
- if (error instanceof DriveError && error.code === "aborted") return error;
152
- return new DriveError("invalid_response", {
153
- status: response.status,
154
- requestId: headerRequestId
155
- });
156
- }
157
- const value = parsed.value;
158
- if (!isExactRecord$1(value, ["error"]) || !isExactRecord$1(value.error, [
159
- "code",
160
- "message",
161
- "requestId",
162
- "details"
163
- ])) return new DriveError("invalid_response", {
164
- status: response.status,
165
- requestId: headerRequestId
166
- });
167
- const envelope = value.error;
168
- if (typeof envelope.code !== "string" || !DRIVE_API_ERROR_CODES.includes(envelope.code) || envelope.message !== DRIVE_API_ERROR_MESSAGES[envelope.code] || !REQUEST_ID.test(String(envelope.requestId)) || envelope.requestId !== headerRequestId || !isExactRecord$1(envelope.details, []) || !errorStatusMatches(envelope.code, response.status, preconditionStatus, allowsQuotaExceeded, allowedErrorCodes) || parsed.text !== JSON.stringify(value)) return new DriveError("invalid_response", {
169
- status: response.status,
170
- requestId: headerRequestId
171
- });
172
- return new DriveError(envelope.code, {
173
- status: response.status,
174
- requestId: envelope.requestId
175
- });
176
- }
177
- function errorStatusMatches(code, status, preconditionStatus, allowsQuotaExceeded, allowedErrorCodes) {
178
- if (allowedErrorCodes && !allowedErrorCodes.includes(code)) return false;
179
- if (code === "quota_exceeded" && !allowsQuotaExceeded) return false;
180
- return {
181
- authentication_required: [401],
182
- identity_authority_unavailable: [503],
183
- permission_denied: [403],
184
- resource_not_found: [404],
185
- invalid_request: [422],
186
- invalid_pagination_cursor: [422],
187
- invalid_idempotency_key: [422],
188
- precondition_failed: preconditionStatus === null ? [] : [preconditionStatus],
189
- range_not_satisfiable: [416],
190
- idempotency_conflict: [409],
191
- quota_exceeded: [409],
192
- upload_recovery_required: [409],
193
- service_unavailable: [503],
194
- internal_error: [500]
195
- }[code].includes(status);
196
- }
197
- async function parseBoundedJson(response, maximumBytes, status, requestId, signal) {
198
- if (!response.body) throw new DriveError("invalid_response", {
199
- status,
200
- requestId
201
- });
202
- const reader = response.body.getReader();
203
- const decoder = new TextDecoder("utf-8", { fatal: true });
204
- let size = 0;
205
- let chunks = 0;
206
- let text = "";
207
- const contentLength = response.headers.get("content-length");
208
- if (contentLength !== null && (!/^(?:0|[1-9][0-9]*)$/.test(contentLength) || Number(contentLength) > maximumBytes)) {
209
- reader.cancel().catch(() => {});
210
- throw new DriveError("invalid_response", {
211
- status,
212
- requestId
213
- });
214
- }
215
- const deadline = new AbortController();
216
- const timeout = setTimeout(() => deadline.abort(), RESPONSE_DEADLINE_MILLISECONDS);
217
- try {
218
- while (true) {
219
- if (signal?.aborted) throw new DriveError("aborted");
220
- const { done, value } = await readResponseChunk(reader, signal, deadline.signal);
221
- if (done) break;
222
- chunks += 1;
223
- size += value.byteLength;
224
- if (chunks > RESPONSE_CHUNK_LIMIT || size > maximumBytes) throw new DriveError("invalid_response", {
225
- status,
226
- requestId
227
- });
228
- text += decoder.decode(value, { stream: true });
229
- }
230
- text += decoder.decode();
231
- return {
232
- value: JSON.parse(text),
233
- text
234
- };
235
- } catch (error) {
236
- if (error instanceof DriveError) {
237
- if (error.code === "aborted" || signal?.aborted) throw new DriveError("aborted");
238
- throw error;
239
- }
240
- throw new DriveError("invalid_response", {
241
- status,
242
- requestId
243
- });
244
- } finally {
245
- clearTimeout(timeout);
246
- reader.cancel().catch(() => {});
247
- }
248
- }
249
- async function readResponseChunk(reader, operationSignal, deadlineSignal) {
250
- if (operationSignal?.aborted) throw new DriveError("aborted");
251
- if (deadlineSignal.aborted) throw new DriveError("invalid_response");
252
- let removeOperationAbort = () => {};
253
- let removeDeadlineAbort = () => {};
254
- const operationAbort = new Promise((_, reject) => {
255
- if (!operationSignal) return;
256
- const onAbort = () => reject(new DriveError("aborted"));
257
- operationSignal.addEventListener("abort", onAbort, { once: true });
258
- removeOperationAbort = () => operationSignal.removeEventListener("abort", onAbort);
259
- });
260
- const deadlineAbort = new Promise((_, reject) => {
261
- const onAbort = () => reject(new DriveError("invalid_response"));
262
- deadlineSignal.addEventListener("abort", onAbort, { once: true });
263
- removeDeadlineAbort = () => deadlineSignal.removeEventListener("abort", onAbort);
264
- });
265
- try {
266
- return await Promise.race([
267
- reader.read(),
268
- operationAbort,
269
- deadlineAbort
270
- ]);
271
- } finally {
272
- removeOperationAbort();
273
- removeDeadlineAbort();
274
- }
275
- }
276
- function cancelResponse(response) {
277
- response.body?.cancel().catch(() => {});
278
- }
279
- function safeRequestId(value) {
280
- return value !== null && REQUEST_ID.test(value) ? value : null;
281
- }
282
- function readValidators(headers) {
283
- const etag = headers.get("etag");
284
- const permissionCollectionEtag = headers.get("drive-permission-collection-etag");
285
- const permissionGrantEtag = headers.get("drive-permission-grant-etag");
286
- return Object.freeze({
287
- ...etag !== null && (LIST_ETAG$1.test(etag) || parseItemEtag(etag) !== void 0) ? { etag } : {},
288
- ...permissionCollectionEtag !== null && parseCollectionEtag(permissionCollectionEtag) !== void 0 ? { permissionCollectionEtag } : {},
289
- ...permissionGrantEtag !== null && parseGrantEtag(permissionGrantEtag) !== void 0 ? { permissionGrantEtag } : {}
290
- });
291
- }
292
- function isExactRecord$1(value, keys) {
293
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
294
- return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
295
- }
296
- //#endregion
297
- //#region src/internal/client/guards.ts
298
- const ITEM_ID$1 = /^drive\.item\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
299
- const WORKSPACE_ID$1 = /^drive\.workspace\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
300
- const VOLUME_ID = /^drive\.volume\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
301
- const GRANT_ID$1 = /^drive\.grant\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
302
- const UPLOAD_ID$1 = /^drive\.upload\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
303
- const VERSION_ID$1 = /^drive\.version\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
304
- const RETRIEVAL_ID = /^drive\.retrieval\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
305
- const CURSOR$1 = /^drive\.cursor\.v1\.[A-Za-z0-9_-]+$/;
306
- const AUTH_ID$1 = /^[A-Za-z0-9_-]{1,128}$/;
307
- const GRANT_ETAG = /^"drive\.permission-grant\.v1\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"$/;
308
- const LIST_ETAG = /^"drive\.permission-list\.v1\.[0-9a-f]{64}"$/;
309
- const PERMISSION_ACTIONS$1 = Object.freeze([
310
- "items:content:read",
311
- "items:create",
312
- "items:delete",
313
- "items:metadata:read",
314
- "items:permissions:read",
315
- "items:update"
316
- ]);
317
- const EFFECTIVE_ACTIONS = Object.freeze([
318
- "items:content:read",
319
- "items:create",
320
- "items:delete",
321
- "items:metadata:read",
322
- "items:permissions:manage",
323
- "items:permissions:read",
324
- "items:update"
325
- ]);
326
- const MAX_UPLOAD_BYTE_LENGTH$1 = 33554432e4;
327
- const UPLOAD_PART_BYTE_LENGTH$2 = 32 * 1024 * 1024;
328
- const CONTENT_DIGEST$1 = /^sha256:[0-9a-f]{64}$/;
329
- const UTF8 = new TextEncoder();
330
- function isWorkspaceUsage(value) {
331
- if (!isExactRecord(value, [
332
- "workspaceId",
333
- "provider",
334
- "usedBytes",
335
- "reservedBytes",
336
- "limitBytes",
337
- "availableBytes",
338
- "accounting",
339
- "reservedBytesIncludeUnresolvedUploads",
340
- "unresolvedReservedBytes",
341
- "warnings"
342
- ]) || typeof value.workspaceId !== "string" || !WORKSPACE_ID$1.test(value.workspaceId) || value.provider !== "managed" || value.accounting !== "current-versions-and-reservations" || value.reservedBytesIncludeUnresolvedUploads !== true || !Array.isArray(value.warnings) || value.warnings.length > 1 || value.warnings.some((warning) => warning !== "unresolved-archive-ownership") || ![
343
- value.usedBytes,
344
- value.reservedBytes,
345
- value.limitBytes,
346
- value.availableBytes,
347
- value.unresolvedReservedBytes
348
- ].every((bytes) => typeof bytes === "string" && /^(0|[1-9][0-9]{0,18})$/.test(bytes))) return false;
349
- const available = BigInt(value.limitBytes) - BigInt(value.usedBytes) - BigInt(value.reservedBytes);
350
- const valid = BigInt(value.availableBytes) === (available > 0n ? available : 0n) && BigInt(value.unresolvedReservedBytes) <= BigInt(value.reservedBytes) && (value.unresolvedReservedBytes === "0" || value.warnings.length === 1);
351
- if (valid) Object.freeze(value.warnings);
352
- return valid;
353
- }
354
- function isWorkspaceDiscoveryPage(value) {
355
- if (!isExactRecord(value, ["items", "nextCursor"]) || !Array.isArray(value.items) || value.items.length > 50 || !(value.nextCursor === null || typeof value.nextCursor === "string" && value.nextCursor.length > 0 && value.nextCursor.length <= 2048 && /^[A-Za-z0-9_.-]+$/.test(value.nextCursor)) || value.items.length === 0 && value.nextCursor !== null) return false;
356
- const ids = new Set();
357
- const valid = value.items.every((item) => {
358
- if (!isExactRecord(item, [
359
- "workspaceId",
360
- "itemId",
361
- "parentId",
362
- "type",
363
- "name",
364
- "lifecycleState",
365
- "revision",
366
- "currentVersion",
367
- "volumeId",
368
- "provider",
369
- "createdAtEpochMilliseconds",
370
- "modifiedAtEpochMilliseconds",
371
- "creatorUserId",
372
- "etag",
373
- "trashedAtEpochMilliseconds",
374
- "purgeAfterEpochMilliseconds"
375
- ]) || item.lifecycleState !== "active" && item.lifecycleState !== "trashed" || typeof item.volumeId !== "string" || !VOLUME_ID.test(item.volumeId) || item.provider !== "managed" || item.creatorUserId !== null && (typeof item.creatorUserId !== "string" || !AUTH_ID$1.test(item.creatorUserId)) || ![
376
- item.createdAtEpochMilliseconds,
377
- item.modifiedAtEpochMilliseconds,
378
- item.trashedAtEpochMilliseconds,
379
- item.purgeAfterEpochMilliseconds
380
- ].every((date) => date === null || isSafeInteger$1(date))) return false;
381
- const metadata = {
382
- workspaceId: item.workspaceId,
383
- itemId: item.itemId,
384
- parentId: item.parentId,
385
- type: item.type,
386
- name: item.name,
387
- lifecycleState: "active",
388
- revision: item.revision,
389
- currentVersion: item.currentVersion
390
- };
391
- if (typeof metadata.workspaceId !== "string" || !WORKSPACE_ID$1.test(metadata.workspaceId) || typeof metadata.itemId !== "string" || !ITEM_ID$1.test(metadata.itemId) || metadata.parentId === null || metadata.parentId === metadata.itemId || !isManagedItemMetadata(metadata, metadata.workspaceId, metadata.itemId) || item.etag !== `"drive.item.v1.${metadata.revision}"` || ids.has(metadata.itemId)) return false;
392
- if (item.lifecycleState === "active" ? item.trashedAtEpochMilliseconds !== null || item.purgeAfterEpochMilliseconds !== null : !isSafeInteger$1(item.trashedAtEpochMilliseconds) || !isSafeInteger$1(item.purgeAfterEpochMilliseconds) || item.purgeAfterEpochMilliseconds <= item.trashedAtEpochMilliseconds) return false;
393
- ids.add(metadata.itemId);
394
- return true;
395
- });
396
- if (valid) {
397
- for (const item of value.items) Object.freeze(item);
398
- Object.freeze(value.items);
399
- Object.freeze(value);
400
- }
401
- return valid;
402
- }
403
- function isCurrentWorkspaceSources(value) {
404
- if (!isExactRecord(value, [
405
- "workspace",
406
- "volumes",
407
- "knownProviders",
408
- "externalConnectionsSupported"
409
- ]) || !isCurrentWorkspace(value.workspace) || !Array.isArray(value.volumes) || value.volumes.length !== 1 || !Array.isArray(value.knownProviders) || value.externalConnectionsSupported !== false) return false;
410
- const volume = value.volumes[0];
411
- const providers = [
412
- "managed",
413
- "google-drive",
414
- "onedrive",
415
- "dropbox",
416
- "s3-compatible"
417
- ];
418
- return isExactRecord(volume, [
419
- "volumeId",
420
- "rootItemId",
421
- "provider",
422
- "name"
423
- ]) && volume.volumeId === value.workspace.rootVolumeId && volume.rootItemId === value.workspace.rootItemId && volume.provider === "managed" && volume.name === "Files" && value.knownProviders.length === providers.length && value.knownProviders.every((provider, index) => provider === providers[index]);
424
- }
425
- function isCurrentWorkspace(value) {
426
- if (!isExactRecord(value, [
427
- "workspaceId",
428
- "rootVolumeId",
429
- "rootItemId",
430
- "workspaceReference"
431
- ]) || typeof value.workspaceId !== "string" || !WORKSPACE_ID$1.test(value.workspaceId) || typeof value.rootVolumeId !== "string" || !VOLUME_ID.test(value.rootVolumeId) || typeof value.rootItemId !== "string" || !ITEM_ID$1.test(value.rootItemId)) return false;
432
- const reference = value.workspaceReference;
433
- return isExactRecord(reference, ["type", "userId"]) && reference.type === "personal" && typeof reference.userId === "string" && AUTH_ID$1.test(reference.userId) || isExactRecord(reference, ["type", "organizationId"]) && reference.type === "organization" && typeof reference.organizationId === "string" && AUTH_ID$1.test(reference.organizationId);
434
- }
435
- function isManagedDownloadDescriptor(value) {
436
- if (!isExactRecord(value, [
437
- "mode",
438
- "method",
439
- "url",
440
- "headers",
441
- "expiresAtEpochMilliseconds",
442
- "response"
443
- ]) || value.mode !== "presigned-single" || value.method !== "GET" && value.method !== "HEAD" || typeof value.url !== "string" || !isSafeCapabilityUrl(value.url) || !isSafeInteger$1(value.expiresAtEpochMilliseconds) || !isExactRecord(value.headers, ["if-match"]) && !isExactRecord(value.headers, ["if-match", "range"]) || typeof value.headers["if-match"] !== "string" || !isStrongEtag(value.headers["if-match"]) || value.headers.range !== void 0 && (typeof value.headers.range !== "string" || !/^bytes=(?:0|[1-9][0-9]*)-(?:0|[1-9][0-9]*)$/.test(value.headers.range)) || !isExactRecord(value.response, [
444
- "status",
445
- "versionId",
446
- "byteLength",
447
- "contentLength",
448
- "contentType",
449
- "contentDisposition",
450
- "etag",
451
- "acceptRanges",
452
- "contentRange"
453
- ]) || value.response.status !== 200 && value.response.status !== 206 || typeof value.response.versionId !== "string" || !VERSION_ID$1.test(value.response.versionId) || !isSafeInteger$1(value.response.byteLength) || !isSafeInteger$1(value.response.contentLength) || typeof value.response.contentType !== "string" || !/^[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?\/[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?$/.test(value.response.contentType) || typeof value.response.contentDisposition !== "string" || value.response.contentDisposition.length > 2048 || !/^[\x20-\x7e]+$/.test(value.response.contentDisposition) || value.response.etag !== value.headers["if-match"] || value.response.acceptRanges !== "bytes" || value.response.contentRange !== null && typeof value.response.contentRange !== "string") return false;
454
- if (!downloadDescriptorIsCoherent(value)) return false;
455
- Object.freeze(value.headers);
456
- Object.freeze(value.response);
457
- Object.freeze(value);
458
- return true;
459
- }
460
- function downloadDescriptorIsCoherent(value) {
461
- const response = value.response;
462
- if (response.contentLength > response.byteLength || value.method === "HEAD" && response.status !== 200 || !response.contentDisposition.startsWith("attachment; filename=\"")) return false;
463
- if (response.status === 200) return value.headers.range === void 0 && response.contentRange === null && response.contentLength === response.byteLength;
464
- if (value.method !== "GET" || value.headers.range === void 0 || response.contentRange === null) return false;
465
- const range = /^bytes=(0|[1-9][0-9]*)-(0|[1-9][0-9]*)$/.exec(value.headers.range);
466
- const contentRange = /^bytes (0|[1-9][0-9]*)-(0|[1-9][0-9]*)\/(0|[1-9][0-9]*)$/.exec(response.contentRange);
467
- if (!range || !contentRange) return false;
468
- const start = Number(range[1]);
469
- const end = Number(range[2]);
470
- const contentStart = Number(contentRange[1]);
471
- const contentEnd = Number(contentRange[2]);
472
- const byteLength = Number(contentRange[3]);
473
- return [
474
- start,
475
- end,
476
- contentStart,
477
- contentEnd,
478
- byteLength
479
- ].every(isSafeInteger$1) && start === contentStart && end === contentEnd && byteLength === response.byteLength && start <= end && end < byteLength && response.contentLength === end - start + 1;
480
- }
481
- function isManagedDownloadRestorePending(value) {
482
- return isExactRecord(value, [
483
- "mode",
484
- "operationId",
485
- "versionId",
486
- "state",
487
- "pollAfterSeconds"
488
- ]) && value.mode === "restore-pending" && typeof value.operationId === "string" && RETRIEVAL_ID.test(value.operationId) && typeof value.versionId === "string" && VERSION_ID$1.test(value.versionId) && (value.state === "pending" || value.state === "restoring") && isSafeInteger$1(value.pollAfterSeconds) && value.pollAfterSeconds >= 1 && value.pollAfterSeconds <= 60;
489
- }
490
- function isFolderPage(value, workspaceId, parentItemId) {
491
- if (!(isExactRecord(value, ["items", "nextCursor"]) && Array.isArray(value.items) && value.items.length <= 50 && value.items.every(isFolderItem) && (value.nextCursor === null || typeof value.nextCursor === "string" && value.nextCursor.length <= 699 && CURSOR$1.test(value.nextCursor)))) return false;
492
- return value.items.every((item) => item.workspaceId === workspaceId && item.parentItemId === parentItemId) && isStrictlyOrdered(value.items, (item) => item.itemId);
493
- }
494
- function isFolderItem(value) {
495
- return isExactRecord(value, [
496
- "workspaceId",
497
- "volumeId",
498
- "itemId",
499
- "parentItemId",
500
- "kind",
501
- "name",
502
- "visibility",
503
- "revision"
504
- ]) && typeof value.workspaceId === "string" && WORKSPACE_ID$1.test(value.workspaceId) && typeof value.volumeId === "string" && VOLUME_ID.test(value.volumeId) && typeof value.itemId === "string" && ITEM_ID$1.test(value.itemId) && typeof value.parentItemId === "string" && ITEM_ID$1.test(value.parentItemId) && (value.kind === "file" || value.kind === "folder") && isSafeFilename$1(value.name) && (value.visibility === "workspace" || value.visibility === "restricted") && isSafeInteger$1(value.revision);
505
- }
506
- function isManagedLifecycleItem(value, workspaceId, itemId, expectedState) {
507
- if (!isExactRecord(value, [
508
- "workspaceId",
509
- "volumeId",
510
- "itemId",
511
- "parentItemId",
512
- "kind",
513
- "name",
514
- "state",
515
- "revision",
516
- "purgeAfterEpochMilliseconds"
517
- ]) || value.workspaceId !== workspaceId || value.itemId !== itemId || typeof value.volumeId !== "string" || !VOLUME_ID.test(value.volumeId) || typeof value.parentItemId !== "string" || !ITEM_ID$1.test(value.parentItemId) || value.kind !== "file" && value.kind !== "folder" || !isSafeFilename$1(value.name) || value.state !== expectedState || !isSafeInteger$1(value.revision) || (value.state === "active" ? value.purgeAfterEpochMilliseconds !== null : !isSafeInteger$1(value.purgeAfterEpochMilliseconds))) return false;
518
- Object.freeze(value);
519
- return true;
520
- }
521
- function isManagedItemMetadata(value, workspaceId, itemId) {
522
- if (!isExactRecord(value, [
523
- "workspaceId",
524
- "itemId",
525
- "parentId",
526
- "type",
527
- "name",
528
- "lifecycleState",
529
- "revision",
530
- "currentVersion"
531
- ]) || value.workspaceId !== workspaceId || value.itemId !== itemId || !(value.parentId === null || typeof value.parentId === "string" && ITEM_ID$1.test(value.parentId)) || value.type !== "file" && value.type !== "folder" || !isSafeFilename$1(value.name) || value.lifecycleState !== "active" || !isSafeInteger$1(value.revision) || (value.type === "folder" ? value.currentVersion !== null : !isCurrentVersionMetadata(value.currentVersion))) return false;
532
- if (value.currentVersion !== null) Object.freeze(value.currentVersion);
533
- Object.freeze(value);
534
- return true;
535
- }
536
- function isWorkspaceItemSearchPage(value, workspaceId, query, limit) {
537
- if (!isExactRecord(value, ["items", "nextCursor"]) || !Array.isArray(value.items) || value.items.length > limit || !value.items.every((item) => isWorkspaceItemSearchItem(item, workspaceId, query)) || !(value.nextCursor === null || typeof value.nextCursor === "string" && value.nextCursor.length <= 699 && CURSOR$1.test(value.nextCursor)) || value.items.length === 0 && value.nextCursor !== null || new Set(value.items.map((item) => item.itemId)).size !== value.items.length || !isWorkspaceItemSearchOrder(value.items)) return false;
538
- for (const item of value.items) {
539
- if (item.currentVersion !== null) Object.freeze(item.currentVersion);
540
- Object.freeze(item);
541
- }
542
- Object.freeze(value.items);
543
- Object.freeze(value);
544
- return true;
545
- }
546
- function itemEtagMatchesRevision(headers, revision) {
547
- const etag = headers.get("etag");
548
- return etag !== null && parseItemEtag(etag) === revision;
549
- }
550
- function isCurrentVersionMetadata(value) {
551
- return isExactRecord(value, [
552
- "versionId",
553
- "state",
554
- "byteLength",
555
- "mediaType",
556
- "protectionClassification"
557
- ]) && typeof value.versionId === "string" && VERSION_ID$1.test(value.versionId) && value.state === "current" && isSafeInteger$1(value.byteLength) && isMediaType$1(value.mediaType) && (value.protectionClassification === "ordinary" || value.protectionClassification === "opaque-encrypted");
558
- }
559
- function isWorkspaceItemSearchItem(value, workspaceId, query) {
560
- return isExactRecord(value, [
561
- "workspaceId",
562
- "volumeId",
563
- "provider",
564
- "itemId",
565
- "parentId",
566
- "type",
567
- "name",
568
- "lifecycleState",
569
- "revision",
570
- "currentVersion"
571
- ]) && value.workspaceId === workspaceId && typeof value.volumeId === "string" && VOLUME_ID.test(value.volumeId) && value.provider === "managed" && typeof value.itemId === "string" && ITEM_ID$1.test(value.itemId) && (value.parentId === null || typeof value.parentId === "string" && ITEM_ID$1.test(value.parentId)) && (value.type === "file" || value.type === "folder") && isSafeFilename$1(value.name) && value.name.startsWith(query) && value.lifecycleState === "active" && isSafeInteger$1(value.revision) && (value.type === "folder" ? value.currentVersion === null : isCurrentVersionMetadata(value.currentVersion));
572
- }
573
- function isWorkspaceItemSearchOrder(items) {
574
- for (let index = 1; index < items.length; index += 1) {
575
- const previous = items[index - 1];
576
- const current = items[index];
577
- const nameOrder = compareBinary(previous.name, current.name);
578
- if (nameOrder > 0 || nameOrder === 0 && previous.itemId >= current.itemId) return false;
579
- }
580
- return true;
581
- }
582
- function compareBinary(left, right) {
583
- const leftBytes = UTF8.encode(left);
584
- const rightBytes = UTF8.encode(right);
585
- const length = Math.min(leftBytes.length, rightBytes.length);
586
- for (let index = 0; index < length; index += 1) if (leftBytes[index] !== rightBytes[index]) return leftBytes[index] - rightBytes[index];
587
- return leftBytes.length - rightBytes.length;
588
- }
589
- function isManagedItemVersionPage(value, limit) {
590
- if (!isExactRecord(value, ["items", "nextCursor"]) || !Array.isArray(value.items) || value.items.length > limit || !value.items.every(isManagedItemVersion) || !(value.nextCursor === null || typeof value.nextCursor === "string" && value.nextCursor.length <= 699 && CURSOR$1.test(value.nextCursor)) || value.nextCursor !== null && value.items.length === 0 || !isStrictlyOrdered(value.items, (version) => version.versionId)) return false;
591
- for (const version of value.items) Object.freeze(version);
592
- Object.freeze(value.items);
593
- Object.freeze(value);
594
- return true;
595
- }
596
- function isManagedItemVersionRestoreResult(value, versionId) {
597
- if (!isExactRecord(value, ["itemRevision", "currentVersionId"]) || !isSafeInteger$1(value.itemRevision) || value.currentVersionId !== versionId) return false;
598
- Object.freeze(value);
599
- return true;
600
- }
601
- function isPermissionPage(value, headers, targetItemId) {
602
- if (!(isExactRecord(value, [
603
- "items",
604
- "nextCursor",
605
- "collectionRevision",
606
- "collectionEtag"
607
- ]) && Array.isArray(value.items) && value.items.length <= 50 && value.items.every(isPermissionGrant) && (value.nextCursor === null || typeof value.nextCursor === "string" && value.nextCursor.length <= 699 && CURSOR$1.test(value.nextCursor)) && isSafeInteger$1(value.collectionRevision) && typeof value.collectionEtag === "string" && parseCollectionEtag(value.collectionEtag) === value.collectionRevision)) return false;
608
- const collectionHeader = headers.get("drive-permission-collection-etag");
609
- const representationEtag = headers.get("etag");
610
- const collectionRevision = value.collectionRevision;
611
- if (!isSafeInteger$1(collectionRevision)) return false;
612
- return collectionHeader === value.collectionEtag && representationEtag !== null && LIST_ETAG.test(representationEtag) && value.items.every((grant) => (grant.source === "direct" ? grant.sourceItemId === targetItemId : grant.sourceItemId !== targetItemId) && grant.etag === permissionGrantEtag(collectionRevision, grant.revision)) && isStrictlyOrdered(value.items, (grant) => `${grant.sourceItemId}\0${grant.grantId}`);
613
- }
614
- function isPermissionMutation(value, targetItemId, expectedGrantId) {
615
- if (!isExactRecord(value, [
616
- "outcome",
617
- "grant",
618
- "collectionRevision"
619
- ]) || value.outcome !== "committed" && value.outcome !== "replayed" || !isSafeInteger$1(value.collectionRevision)) return false;
620
- const grant = value.grant;
621
- return isExactRecord(grant, [
622
- "source",
623
- "sourceItemId",
624
- "grantId",
625
- "grantee",
626
- "actions",
627
- "availability",
628
- "expiresAtEpochMilliseconds",
629
- "revision"
630
- ]) && grant.source === "direct" && typeof grant.sourceItemId === "string" && grant.sourceItemId === targetItemId && typeof grant.grantId === "string" && GRANT_ID$1.test(grant.grantId) && (expectedGrantId === void 0 || grant.grantId === expectedGrantId) && isGrantee(grant.grantee) && isPermissionActions(grant.actions) && [
631
- "active",
632
- "expired",
633
- "revoked"
634
- ].includes(String(grant.availability)) && (grant.expiresAtEpochMilliseconds === null || isSafeInteger$1(grant.expiresAtEpochMilliseconds)) && isSafeInteger$1(grant.revision);
635
- }
636
- function isEffectivePermissionResponse(value, targetItemId) {
637
- if (!isExactRecord(value, ["actions"]) || !Array.isArray(value.actions) || value.actions.length !== 7) return false;
638
- for (let index = 0; index < value.actions.length; index += 1) {
639
- const action = value.actions[index];
640
- if (action === void 0 || !isExactRecord(action, [
641
- "action",
642
- "allowed",
643
- "basis",
644
- "sourceItemId",
645
- "grantId"
646
- ]) || action.action !== EFFECTIVE_ACTIONS[index] || typeof action.allowed !== "boolean" || !(action.basis === null || [
647
- "workspace_visibility",
648
- "restricted_administrator_bypass",
649
- "direct_grant",
650
- "inherited_grant"
651
- ].includes(String(action.basis))) || !(action.sourceItemId === null || typeof action.sourceItemId === "string" && ITEM_ID$1.test(action.sourceItemId)) || !(action.grantId === null || typeof action.grantId === "string" && GRANT_ID$1.test(action.grantId)) || !effectiveSourceIsCoherent(action, targetItemId)) return false;
652
- }
653
- return true;
654
- }
655
- function isUploadSession(value, expectedByteLength) {
656
- if (!isExactRecord(value, [
657
- "itemId",
658
- "versionId",
659
- "uploadId",
660
- "mode",
661
- "partByteLength",
662
- "partCount",
663
- "revision",
664
- "expiresAtEpochMilliseconds"
665
- ]) || typeof value.itemId !== "string" || !ITEM_ID$1.test(value.itemId) || typeof value.versionId !== "string" || !VERSION_ID$1.test(value.versionId) || typeof value.uploadId !== "string" || !UPLOAD_ID$1.test(value.uploadId) || value.mode !== "presigned-multipart" && value.mode !== "server-mediated-zero-byte" || value.partByteLength !== UPLOAD_PART_BYTE_LENGTH$2 || !isSafeInteger$1(value.partCount) || value.partCount > 1e4 || value.partCount !== Math.ceil(expectedByteLength / UPLOAD_PART_BYTE_LENGTH$2) || (expectedByteLength === 0 ? value.mode !== "server-mediated-zero-byte" : value.mode !== "presigned-multipart") || !isSafeInteger$1(value.revision) || !isSafeInteger$1(value.expiresAtEpochMilliseconds) || value.expiresAtEpochMilliseconds <= Date.now()) return false;
666
- Object.freeze(value);
667
- return true;
668
- }
669
- function isUploadStatus(value, afterPartNumber, limit) {
670
- if (!isExactRecord(value, [
671
- "itemId",
672
- "versionId",
673
- "uploadId",
674
- "mode",
675
- "lifecycle",
676
- "revision",
677
- "partPolicy",
678
- "confirmedParts",
679
- "nextAfterPartNumber",
680
- "expiresAtEpochMilliseconds",
681
- "ready"
682
- ], ["verification"]) || typeof value.itemId !== "string" || !ITEM_ID$1.test(value.itemId) || typeof value.versionId !== "string" || !VERSION_ID$1.test(value.versionId) || typeof value.uploadId !== "string" || !UPLOAD_ID$1.test(value.uploadId) || value.mode !== "presigned-multipart" && value.mode !== "server-mediated-zero-byte" || ![
683
- "initiating",
684
- "recovery-required",
685
- "uploading",
686
- "completing",
687
- "provider-completed",
688
- "verifying",
689
- "failed",
690
- "ready",
691
- "aborting",
692
- "aborted"
693
- ].includes(String(value.lifecycle)) || !isSafeInteger$1(value.revision) || !isExactRecord(value.partPolicy, [
694
- "partByteLength",
695
- "partCount",
696
- "maxParts"
697
- ]) || value.partPolicy.partByteLength !== UPLOAD_PART_BYTE_LENGTH$2 || !isSafeInteger$1(value.partPolicy.partCount) || value.partPolicy.partCount > 1e4 || value.partPolicy.maxParts !== 1e4 || (value.mode === "server-mediated-zero-byte" ? value.partPolicy.partCount !== 0 : value.partPolicy.partCount < 1) || !Array.isArray(value.confirmedParts) || value.confirmedParts.length > limit || !isSafeInteger$1(value.expiresAtEpochMilliseconds)) return false;
698
- let previousPartNumber = afterPartNumber;
699
- if (value.verification !== void 0) {
700
- const progress = value.verification;
701
- if (!isExactRecord(progress, [
702
- "state",
703
- "verifiedByteLength",
704
- "totalByteLength",
705
- "revision"
706
- ]) || ![
707
- "pending",
708
- "verified",
709
- "failed"
710
- ].includes(String(progress.state)) || !isSafeInteger$1(progress.verifiedByteLength) || !isSafeInteger$1(progress.totalByteLength) || progress.totalByteLength > MAX_UPLOAD_BYTE_LENGTH$1 || progress.verifiedByteLength > progress.totalByteLength || !isSafeInteger$1(progress.revision) || progress.state === "verified" && progress.verifiedByteLength !== progress.totalByteLength) return false;
711
- Object.freeze(progress);
712
- }
713
- if (["verifying", "failed"].includes(String(value.lifecycle)) && value.verification === void 0) return false;
714
- for (const part of value.confirmedParts) {
715
- if (!isExactRecord(part, ["partNumber", "checksumSha256"]) || !isSafeInteger$1(part.partNumber) || part.partNumber <= previousPartNumber || part.partNumber > value.partPolicy.partCount || !isPartChecksum$1(part.checksumSha256)) return false;
716
- previousPartNumber = part.partNumber;
717
- }
718
- if (!(value.nextAfterPartNumber === null || isSafeInteger$1(value.nextAfterPartNumber) && value.confirmedParts.length === limit && value.nextAfterPartNumber === previousPartNumber) || value.mode === "server-mediated-zero-byte" && (value.confirmedParts.length !== 0 || value.nextAfterPartNumber !== null) || value.lifecycle === "ready" !== (value.ready !== null) || value.ready !== null && (!isReadyUpload(value.ready, { uploadId: value.uploadId }) || value.ready.itemId !== value.itemId || value.ready.versionId !== value.versionId || !isExactRecord(value.verification, [
719
- "state",
720
- "verifiedByteLength",
721
- "totalByteLength",
722
- "revision"
723
- ]) || value.verification.state !== "verified" || value.verification.totalByteLength !== value.ready.byteLength)) return false;
724
- Object.freeze(value.partPolicy);
725
- for (const part of value.confirmedParts) Object.freeze(part);
726
- Object.freeze(value.confirmedParts);
727
- Object.freeze(value);
728
- return true;
729
- }
730
- function isUploadPartDescriptor(value, expectedPartNumber, allowInsecureHttp, contentMd5) {
731
- if (!isExactRecord(value, [
732
- "url",
733
- "method",
734
- "headers",
735
- "partNumber",
736
- "expectedByteLength",
737
- "expiresAtEpochMilliseconds"
738
- ]) || !isSignedTransferUrl(value.url, allowInsecureHttp) || value.method !== "PUT" || !contentMd5 || !isExactRecord(value.headers, ["content-md5"]) || value.headers["content-md5"] !== contentMd5 || value.partNumber !== expectedPartNumber || !isSafeInteger$1(value.expectedByteLength) || value.expectedByteLength < 1 || value.expectedByteLength > UPLOAD_PART_BYTE_LENGTH$2 || !isSafeInteger$1(value.expiresAtEpochMilliseconds) || value.expiresAtEpochMilliseconds <= Date.now()) return false;
739
- Object.freeze(value.headers);
740
- Object.freeze(value);
741
- return true;
742
- }
743
- function isUploadPartResult(value, expectedPartNumber, expectedUploadRevision) {
744
- if (!isExactRecord(value, ["partNumber", "revision"]) || value.partNumber !== expectedPartNumber || value.revision !== expectedUploadRevision + 1 || !isSafeInteger$1(value.revision)) return false;
745
- Object.freeze(value);
746
- return true;
747
- }
748
- function isReadyUpload(value, expected) {
749
- if (!isExactRecord(value, [
750
- "itemId",
751
- "versionId",
752
- "uploadId",
753
- "byteLength",
754
- "callerDeclaredContentDigest",
755
- "displayFilename",
756
- "mediaType",
757
- "state"
758
- ]) || typeof value.itemId !== "string" || !ITEM_ID$1.test(value.itemId) || typeof value.versionId !== "string" || !VERSION_ID$1.test(value.versionId) || value.uploadId !== expected.uploadId || !isSafeInteger$1(value.byteLength) || value.byteLength < 0 || value.byteLength > MAX_UPLOAD_BYTE_LENGTH$1 || typeof value.callerDeclaredContentDigest !== "string" || !CONTENT_DIGEST$1.test(value.callerDeclaredContentDigest) || !isSafeFilename$1(value.displayFilename) || !isMediaType$1(value.mediaType) || value.state !== "ready" || expected.byteLength !== void 0 && value.byteLength !== expected.byteLength || expected.callerDeclaredContentDigest !== void 0 && value.callerDeclaredContentDigest !== expected.callerDeclaredContentDigest || expected.displayFilename !== void 0 && value.displayFilename !== expected.displayFilename || expected.mediaType !== void 0 && value.mediaType !== expected.mediaType) return false;
759
- Object.freeze(value);
760
- return true;
761
- }
762
- function isPendingUpload(value, uploadId) {
763
- if (!isExactRecord(value, [
764
- "itemId",
765
- "versionId",
766
- "uploadId",
767
- "state",
768
- "verifiedByteLength",
769
- "totalByteLength",
770
- "verificationRevision"
771
- ]) || typeof value.itemId !== "string" || !ITEM_ID$1.test(value.itemId) || typeof value.versionId !== "string" || !VERSION_ID$1.test(value.versionId) || value.uploadId !== uploadId || value.state !== "verifying" || !isSafeInteger$1(value.verifiedByteLength) || !isSafeInteger$1(value.totalByteLength) || value.totalByteLength > MAX_UPLOAD_BYTE_LENGTH$1 || value.verifiedByteLength > value.totalByteLength || !isSafeInteger$1(value.verificationRevision)) return false;
772
- Object.freeze(value);
773
- return true;
774
- }
775
- function isPartChecksum$1(value) {
776
- return typeof value === "string" && /^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/.test(value);
777
- }
778
- function isManagedItemVersion(value) {
779
- const valid = isExactRecord(value, managedItemVersionKeys) && managedItemVersionFieldsAreValid(value);
780
- if (valid) Object.freeze(value);
781
- return valid;
782
- }
783
- function isManagedItemVersionResource(value, workspaceId, itemId, versionId) {
784
- const valid = isExactRecord(value, [
785
- ...managedItemVersionKeys,
786
- "workspaceId",
787
- "itemId"
788
- ]) && value.workspaceId === workspaceId && value.itemId === itemId && value.versionId === versionId && managedItemVersionFieldsAreValid(value);
789
- if (valid) Object.freeze(value);
790
- return valid;
791
- }
792
- const managedItemVersionKeys = Object.freeze([
793
- "versionId",
794
- "state",
795
- "revision",
796
- "byteLength",
797
- "contentDigest",
798
- "mediaType",
799
- "displayFilename",
800
- "protectionClassification",
801
- "archiveState"
802
- ]);
803
- function managedItemVersionFieldsAreValid(value) {
804
- return typeof value.versionId === "string" && VERSION_ID$1.test(value.versionId) && (value.state === "current" || value.state === "superseded") && isSafeInteger$1(value.revision) && isSafeInteger$1(value.byteLength) && typeof value.contentDigest === "string" && CONTENT_DIGEST$1.test(value.contentDigest) && isMediaType$1(value.mediaType) && isSafeFilename$1(value.displayFilename) && (value.protectionClassification === "ordinary" || value.protectionClassification === "opaque-encrypted") && [
805
- "available",
806
- "cold",
807
- "restoring",
808
- "unavailable",
809
- "corrupt"
810
- ].includes(String(value.archiveState));
811
- }
812
- function mutationValidatorsAreCoherent(headers) {
813
- const collection = headers.get("drive-permission-collection-etag");
814
- const grant = headers.get("drive-permission-grant-etag");
815
- const collectionRevision = collection === null ? void 0 : parseCollectionEtag(collection);
816
- if (collectionRevision === void 0) return false;
817
- if (grant === null) return true;
818
- const currentGrant = parseGrantEtag(grant);
819
- return currentGrant !== void 0 && currentGrant[0] === collectionRevision;
820
- }
821
- function isPermissionGrant(value) {
822
- return isExactRecord(value, [
823
- "source",
824
- "sourceItemId",
825
- "grantId",
826
- "grantee",
827
- "actions",
828
- "availability",
829
- "expiresAtEpochMilliseconds",
830
- "revision",
831
- "etag"
832
- ]) && (value.source === "direct" || value.source === "inherited") && typeof value.sourceItemId === "string" && ITEM_ID$1.test(value.sourceItemId) && typeof value.grantId === "string" && GRANT_ID$1.test(value.grantId) && isGrantee(value.grantee) && isPermissionActions(value.actions) && [
833
- "active",
834
- "expired",
835
- "revoked"
836
- ].includes(String(value.availability)) && (value.expiresAtEpochMilliseconds === null || isSafeInteger$1(value.expiresAtEpochMilliseconds)) && isSafeInteger$1(value.revision) && typeof value.etag === "string" && GRANT_ETAG.test(value.etag);
837
- }
838
- function isGrantee(value) {
839
- return isExactRecord(value, ["type", "userId"]) && value.type === "user" && typeof value.userId === "string" && AUTH_ID$1.test(value.userId) || isExactRecord(value, ["type", "teamId"]) && value.type === "team" && typeof value.teamId === "string" && AUTH_ID$1.test(value.teamId);
840
- }
841
- function isPermissionActions(value) {
842
- return Array.isArray(value) && value.length >= 1 && value.length <= 6 && new Set(value).size === value.length && value.every((action) => PERMISSION_ACTIONS$1.includes(action)) && value.every((action, index) => index === 0 || PERMISSION_ACTIONS$1.indexOf(action) > PERMISSION_ACTIONS$1.indexOf(value[index - 1]));
843
- }
844
- function effectiveSourceIsCoherent(action, targetItemId) {
845
- if (!action.allowed) return action.basis === null && action.sourceItemId === null && action.grantId === null;
846
- if (action.basis === "workspace_visibility" || action.basis === "restricted_administrator_bypass") return action.sourceItemId === null && action.grantId === null;
847
- if (action.basis === "direct_grant") return action.sourceItemId === targetItemId && typeof action.grantId === "string";
848
- if (action.basis === "inherited_grant") return typeof action.sourceItemId === "string" && action.sourceItemId !== targetItemId && typeof action.grantId === "string";
849
- return false;
850
- }
851
- function permissionGrantEtag(collectionRevision, grantRevision) {
852
- return `"drive.permission-grant.v1.${collectionRevision}.${grantRevision}"`;
853
- }
854
- function isSafeFilename$1(value) {
855
- if (typeof value !== "string" || value.length === 0 || value.length > 510 || value.normalize("NFC") !== value || value.endsWith(".") || value.endsWith(" ") || filenameIsReserved$1(value)) return false;
856
- let codePoints = 0;
857
- let bytes = 0;
858
- for (const character of value) {
859
- const point = character.codePointAt(0);
860
- if (point === void 0 || point === 47 || point === 92 || point <= 31 || point >= 127 && point <= 159 || point === 8232 || point === 8233 || point >= 55296 && point <= 57343) return false;
861
- codePoints += 1;
862
- bytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
863
- if (codePoints > 255 || bytes > 255) return false;
864
- }
865
- return true;
866
- }
867
- function isMediaType$1(value) {
868
- return typeof value === "string" && value.length <= 255 && /^[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?\/[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?$/.test(value);
869
- }
870
- function isSignedTransferUrl(value, allowInsecureHttp) {
871
- if (typeof value !== "string" || value.length < 1 || value.length > 8192 || value !== value.trim()) return false;
872
- try {
873
- const url = new URL(value);
874
- const loopbackHost = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
875
- return (url.protocol === "https:" || url.protocol === "http:" && allowInsecureHttp && loopbackHost) && url.username === "" && url.password === "" && url.hash === "" && url.host !== "";
876
- } catch {
877
- return false;
878
- }
879
- }
880
- function filenameIsReserved$1(value) {
881
- const base = value.split(".", 1)[0].toUpperCase();
882
- return value === "." || value === ".." || [
883
- "CON",
884
- "PRN",
885
- "AUX",
886
- "NUL",
887
- "CLOCK$",
888
- "CONIN$",
889
- "CONOUT$"
890
- ].includes(base) || /^COM[1-9]$/.test(base) || /^LPT[1-9]$/.test(base);
891
- }
892
- function isStrictlyOrdered(values, key) {
893
- return values.every((value, index) => index === 0 || key(values[index - 1]) < key(value));
894
- }
895
- function isSafeInteger$1(value) {
896
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
897
- }
898
- function isStrongEtag(value) {
899
- return /^"[\x21\x23-\x7e]{1,1022}"$/.test(value);
900
- }
901
- function isSafeCapabilityUrl(value) {
902
- try {
903
- const url = new URL(value);
904
- const localHttp = url.protocol === "http:" && [
905
- "localhost",
906
- "127.0.0.1",
907
- "[::1]"
908
- ].includes(url.hostname);
909
- return (url.protocol === "https:" || localHttp) && !url.username && !url.password && !url.hash;
910
- } catch {
911
- return false;
912
- }
913
- }
914
- function isExactRecord(value, keys, optional = []) {
915
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
916
- return Object.keys(value).every((key) => keys.includes(key) || optional.includes(key)) && keys.every((key) => Object.hasOwn(value, key));
917
- }
918
- //#endregion
919
- //#region src/internal/client/request.ts
920
- const ITEM_ID = /^drive\.item\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
921
- const WORKSPACE_ID = /^drive\.workspace\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
922
- const GRANT_ID = /^drive\.grant\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
923
- const UPLOAD_ID = /^drive\.upload\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
924
- const VERSION_ID = /^drive\.version\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
925
- const CURSOR = /^drive\.cursor\.v1\.[A-Za-z0-9_-]+$/;
926
- const AUTH_ID = /^[A-Za-z0-9_-]{1,128}$/;
927
- const PERMISSION_ACTIONS = Object.freeze([
928
- "items:content:read",
929
- "items:create",
930
- "items:delete",
931
- "items:metadata:read",
932
- "items:permissions:read",
933
- "items:update"
934
- ]);
935
- const IDEMPOTENCY_KEY = /^[A-Za-z0-9_-]{16,128}$/;
936
- const CONTENT_DIGEST = /^sha256:[0-9a-f]{64}$/;
937
- const PART_CHECKSUM = /^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/;
938
- const MAX_UPLOAD_BYTE_LENGTH = 33554432e4;
939
- const UPLOAD_PART_BYTE_LENGTH$1 = 32 * 1024 * 1024;
940
- function validateCurrentWorkspaceInput(value) {
941
- const signal = validateSignal(captureRecord(value === void 0 ? {} : value, [], ["signal"]).signal);
942
- return signal === void 0 ? {} : { signal };
943
- }
944
- function validateWorkspaceDiscoveryInput(value, list) {
945
- const input = captureRecord(value, ["workspaceId"], list ? [
946
- "signal",
947
- "view",
948
- "kind",
949
- "creatorUserId",
950
- "limit",
951
- "cursor"
952
- ] : ["signal"]);
953
- const signal = validateSignal(input.signal);
954
- if (typeof input.workspaceId !== "string" || !WORKSPACE_ID.test(input.workspaceId) || input.view !== void 0 && input.view !== "recent" && input.view !== "shared" && input.view !== "trash" || input.kind !== void 0 && input.kind !== "file" && input.kind !== "folder" || input.creatorUserId !== void 0 && (typeof input.creatorUserId !== "string" || !AUTH_ID.test(input.creatorUserId)) || input.limit !== void 0 && (typeof input.limit !== "number" || !Number.isInteger(input.limit) || input.limit < 1 || input.limit > 50) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length < 1 || input.cursor.length > 2048 || !/^[A-Za-z0-9_.-]+$/.test(input.cursor))) throw new DriveError("invalid_input");
955
- return {
956
- workspaceId: input.workspaceId,
957
- signal,
958
- query: {
959
- ...input.view === void 0 ? {} : { view: input.view },
960
- ...input.kind === void 0 ? {} : { kind: input.kind },
961
- ...input.creatorUserId === void 0 ? {} : { creatorUserId: input.creatorUserId },
962
- ...input.limit === void 0 ? {} : { limit: input.limit },
963
- ...input.cursor === void 0 ? {} : { cursor: input.cursor }
964
- }
965
- };
966
- }
967
- function validateResourceInput(value) {
968
- const input = captureRecord(value, ["workspaceId", "itemId"], ["signal"]);
969
- const workspaceId = input.workspaceId;
970
- const itemId = input.itemId;
971
- const signal = validateSignal(input.signal);
972
- if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId) || typeof itemId !== "string" || !ITEM_ID.test(itemId)) throw new DriveError("invalid_input");
973
- return {
974
- workspaceId,
975
- itemId,
976
- ...signal === void 0 ? {} : { signal }
977
- };
978
- }
979
- function validateItemVersionInput(value) {
980
- const input = captureRecord(value, [
981
- "workspaceId",
982
- "itemId",
983
- "versionId"
984
- ], ["signal"]);
985
- const resource = validateResourceInput({
986
- workspaceId: input.workspaceId,
987
- itemId: input.itemId,
988
- ...input.signal === void 0 ? {} : { signal: input.signal }
989
- });
990
- if (typeof input.versionId !== "string" || !VERSION_ID.test(input.versionId)) throw new DriveError("invalid_input");
991
- return {
992
- ...resource,
993
- versionId: input.versionId
994
- };
995
- }
996
- function validateCreateDownloadInput(value) {
997
- const input = captureRecord(value, [
998
- "workspaceId",
999
- "itemId",
1000
- "idempotencyKey"
1001
- ], [
1002
- "versionId",
1003
- "method",
1004
- "range",
1005
- "ifMatch",
1006
- "ifNoneMatch",
1007
- "ifRange",
1008
- "signal"
1009
- ]);
1010
- const resource = validateResourceInput({
1011
- workspaceId: input.workspaceId,
1012
- itemId: input.itemId,
1013
- ...input.signal === void 0 ? {} : { signal: input.signal }
1014
- });
1015
- const method = input.method ?? "GET";
1016
- if (!isIdempotencyKey(input.idempotencyKey) || input.versionId !== void 0 && (typeof input.versionId !== "string" || !VERSION_ID.test(input.versionId)) || method !== "GET" && method !== "HEAD" || input.range !== void 0 && (typeof input.range !== "string" || input.range.length > 128 || !/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/.test(input.range)) || !isOptionalHeaderValue(input.ifMatch) || !isOptionalHeaderValue(input.ifNoneMatch) || !isOptionalHeaderValue(input.ifRange)) throw new DriveError("invalid_input");
1017
- return {
1018
- ...resource,
1019
- idempotencyKey: input.idempotencyKey,
1020
- method,
1021
- ...input.versionId === void 0 ? {} : { versionId: input.versionId },
1022
- ...input.range === void 0 ? {} : { range: input.range },
1023
- ...input.ifMatch === void 0 ? {} : { ifMatch: input.ifMatch },
1024
- ...input.ifNoneMatch === void 0 ? {} : { ifNoneMatch: input.ifNoneMatch },
1025
- ...input.ifRange === void 0 ? {} : { ifRange: input.ifRange }
1026
- };
1027
- }
1028
- function validateSearchWorkspaceItemsInput(value) {
1029
- const input = captureRecord(value, ["workspaceId", "query"], [
1030
- "limit",
1031
- "cursor",
1032
- "signal"
1033
- ]);
1034
- const signal = validateSignal(input.signal);
1035
- if (typeof input.workspaceId !== "string" || !WORKSPACE_ID.test(input.workspaceId) || !isSearchQuery(input.query) || input.limit !== void 0 && (!isSafeInteger(input.limit) || input.limit < 1 || input.limit > 50) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length > 699 || !CURSOR.test(input.cursor))) throw new DriveError("invalid_input");
1036
- return {
1037
- workspaceId: input.workspaceId,
1038
- query: input.query,
1039
- ...input.limit === void 0 ? {} : { limit: input.limit },
1040
- ...input.cursor === void 0 ? {} : { cursor: input.cursor },
1041
- ...signal === void 0 ? {} : { signal }
1042
- };
1043
- }
1044
- function validatePageInput(value) {
1045
- const input = captureRecord(value, ["workspaceId", "itemId"], [
1046
- "signal",
1047
- "limit",
1048
- "cursor"
1049
- ]);
1050
- const resource = validateResourceInput({
1051
- workspaceId: input.workspaceId,
1052
- itemId: input.itemId,
1053
- ...input.signal === void 0 ? {} : { signal: input.signal }
1054
- });
1055
- const limit = input.limit;
1056
- const cursor = input.cursor;
1057
- if (limit !== void 0 && (!Number.isSafeInteger(limit) || typeof limit !== "number" || limit < 1 || limit > 50) || cursor !== void 0 && (typeof cursor !== "string" || cursor.length > 699 || !CURSOR.test(cursor))) throw new DriveError("invalid_input");
1058
- return {
1059
- ...resource,
1060
- ...limit === void 0 ? {} : { limit },
1061
- ...cursor === void 0 ? {} : { cursor }
1062
- };
1063
- }
1064
- function validateCreateFolderInput(value) {
1065
- const input = captureRecord(value, [
1066
- "workspaceId",
1067
- "itemId",
1068
- "name",
1069
- "idempotencyKey"
1070
- ], ["signal"]);
1071
- const resource = validateResourceInput({
1072
- workspaceId: input.workspaceId,
1073
- itemId: input.itemId,
1074
- ...input.signal === void 0 ? {} : { signal: input.signal }
1075
- });
1076
- if (!isSafeFilename(input.name) || !isIdempotencyKey(input.idempotencyKey)) throw new DriveError("invalid_input");
1077
- return {
1078
- ...resource,
1079
- name: input.name,
1080
- idempotencyKey: input.idempotencyKey
1081
- };
1082
- }
1083
- function validateUpdateItemInput(value) {
1084
- const input = captureRecord(value, [
1085
- "workspaceId",
1086
- "itemId",
1087
- "name",
1088
- "parentItemId",
1089
- "idempotencyKey",
1090
- "ifMatch"
1091
- ], ["signal"]);
1092
- const mutation = validateLifecycleMutationInput({
1093
- workspaceId: input.workspaceId,
1094
- itemId: input.itemId,
1095
- idempotencyKey: input.idempotencyKey,
1096
- ifMatch: input.ifMatch,
1097
- ...input.signal === void 0 ? {} : { signal: input.signal }
1098
- });
1099
- if (!isSafeFilename(input.name) || typeof input.parentItemId !== "string" || !ITEM_ID.test(input.parentItemId)) throw new DriveError("invalid_input");
1100
- return {
1101
- ...mutation,
1102
- name: input.name,
1103
- parentItemId: input.parentItemId
1104
- };
1105
- }
1106
- function validateLifecycleMutationInput(value) {
1107
- const input = captureRecord(value, [
1108
- "workspaceId",
1109
- "itemId",
1110
- "idempotencyKey",
1111
- "ifMatch"
1112
- ], ["signal"]);
1113
- const resource = validateResourceInput({
1114
- workspaceId: input.workspaceId,
1115
- itemId: input.itemId,
1116
- ...input.signal === void 0 ? {} : { signal: input.signal }
1117
- });
1118
- if (!isIdempotencyKey(input.idempotencyKey) || typeof input.ifMatch !== "string" || parseItemEtag(input.ifMatch) === void 0) throw new DriveError("invalid_input");
1119
- return {
1120
- ...resource,
1121
- idempotencyKey: input.idempotencyKey,
1122
- ifMatch: input.ifMatch
1123
- };
1124
- }
1125
- function validateRestoreItemVersionInput(value) {
1126
- const input = captureRecord(value, [
1127
- "workspaceId",
1128
- "itemId",
1129
- "versionId",
1130
- "idempotencyKey",
1131
- "ifMatch"
1132
- ], ["signal"]);
1133
- const mutation = validateLifecycleMutationInput({
1134
- workspaceId: input.workspaceId,
1135
- itemId: input.itemId,
1136
- idempotencyKey: input.idempotencyKey,
1137
- ifMatch: input.ifMatch,
1138
- ...input.signal === void 0 ? {} : { signal: input.signal }
1139
- });
1140
- if (typeof input.versionId !== "string" || !VERSION_ID.test(input.versionId)) throw new DriveError("invalid_input");
1141
- return {
1142
- ...mutation,
1143
- versionId: input.versionId
1144
- };
1145
- }
1146
- function validateCreatePermissionInput(value) {
1147
- const input = captureRecord(value, [
1148
- "workspaceId",
1149
- "itemId",
1150
- "grantee",
1151
- "actions",
1152
- "expiresAtEpochMilliseconds",
1153
- "ifMatch",
1154
- "idempotencyKey"
1155
- ], ["signal"]);
1156
- const resource = validateResourceInput({
1157
- workspaceId: input.workspaceId,
1158
- itemId: input.itemId,
1159
- ...input.signal === void 0 ? {} : { signal: input.signal }
1160
- });
1161
- const grantee = validateGrantee(input.grantee);
1162
- const actions = validateInputActions(input.actions);
1163
- const expiry = input.expiresAtEpochMilliseconds;
1164
- if (!isExpiry(expiry) || typeof input.ifMatch !== "string" || parseCollectionEtag(input.ifMatch) === void 0 || !isIdempotencyKey(input.idempotencyKey)) throw new DriveError("invalid_input");
1165
- return {
1166
- ...resource,
1167
- grantee,
1168
- actions,
1169
- expiresAtEpochMilliseconds: expiry,
1170
- ifMatch: input.ifMatch,
1171
- idempotencyKey: input.idempotencyKey
1172
- };
1173
- }
1174
- function validateGrantMutationInput(value) {
1175
- const input = captureRecord(value, [
1176
- "workspaceId",
1177
- "itemId",
1178
- "grantId",
1179
- "ifMatch",
1180
- "idempotencyKey"
1181
- ], ["signal"]);
1182
- const resource = validateResourceInput({
1183
- workspaceId: input.workspaceId,
1184
- itemId: input.itemId,
1185
- ...input.signal === void 0 ? {} : { signal: input.signal }
1186
- });
1187
- if (typeof input.grantId !== "string" || !GRANT_ID.test(input.grantId) || typeof input.ifMatch !== "string" || parseGrantEtag(input.ifMatch) === void 0 || !isIdempotencyKey(input.idempotencyKey)) throw new DriveError("invalid_input");
1188
- return {
1189
- ...resource,
1190
- grantId: input.grantId,
1191
- ifMatch: input.ifMatch,
1192
- idempotencyKey: input.idempotencyKey
1193
- };
1194
- }
1195
- function validateUpdatePermissionInput(value) {
1196
- const input = captureRecord(value, [
1197
- "workspaceId",
1198
- "itemId",
1199
- "grantId",
1200
- "ifMatch",
1201
- "idempotencyKey"
1202
- ], [
1203
- "signal",
1204
- "actions",
1205
- "expiresAtEpochMilliseconds"
1206
- ]);
1207
- const mutation = validateGrantMutationInput({
1208
- workspaceId: input.workspaceId,
1209
- itemId: input.itemId,
1210
- grantId: input.grantId,
1211
- ifMatch: input.ifMatch,
1212
- idempotencyKey: input.idempotencyKey,
1213
- ...input.signal === void 0 ? {} : { signal: input.signal }
1214
- });
1215
- const actions = input.actions === void 0 ? void 0 : validateInputActions(input.actions);
1216
- const expiry = input.expiresAtEpochMilliseconds;
1217
- if (actions === void 0 && expiry === void 0 || expiry !== void 0 && !isExpiry(expiry)) throw new DriveError("invalid_input");
1218
- return {
1219
- ...mutation,
1220
- ...actions === void 0 ? {} : { actions },
1221
- ...expiry === void 0 ? {} : { expiresAtEpochMilliseconds: expiry }
1222
- };
1223
- }
1224
- function validateCreateUploadInput(value) {
1225
- const input = captureRecord(value, [
1226
- "workspaceId",
1227
- "parentItemId",
1228
- "expectedByteLength",
1229
- "displayFilename",
1230
- "mediaType",
1231
- "callerDeclaredContentDigest",
1232
- "protectionClassification",
1233
- "idempotencyKey"
1234
- ], ["signal"]);
1235
- const signal = validateSignal(input.signal);
1236
- if (typeof input.workspaceId !== "string" || !WORKSPACE_ID.test(input.workspaceId) || typeof input.parentItemId !== "string" || !ITEM_ID.test(input.parentItemId) || typeof input.expectedByteLength !== "number" || !Number.isSafeInteger(input.expectedByteLength) || input.expectedByteLength < 0 || input.expectedByteLength > MAX_UPLOAD_BYTE_LENGTH || !isSafeFilename(input.displayFilename) || !isMediaType(input.mediaType) || typeof input.callerDeclaredContentDigest !== "string" || !CONTENT_DIGEST.test(input.callerDeclaredContentDigest) || input.protectionClassification !== "ordinary" && input.protectionClassification !== "opaque-encrypted" || !isIdempotencyKey(input.idempotencyKey)) throw new DriveError("invalid_input");
1237
- return {
1238
- workspaceId: input.workspaceId,
1239
- parentItemId: input.parentItemId,
1240
- expectedByteLength: input.expectedByteLength,
1241
- displayFilename: input.displayFilename,
1242
- mediaType: input.mediaType,
1243
- callerDeclaredContentDigest: input.callerDeclaredContentDigest,
1244
- protectionClassification: input.protectionClassification,
1245
- idempotencyKey: input.idempotencyKey,
1246
- ...signal === void 0 ? {} : { signal }
1247
- };
1248
- }
1249
- function validateGetUploadStatusInput(value) {
1250
- const input = captureRecord(value, ["workspaceId", "uploadId"], [
1251
- "afterPartNumber",
1252
- "limit",
1253
- "signal"
1254
- ]);
1255
- const upload = validateUploadPath(input.workspaceId, input.uploadId, input.signal);
1256
- if (input.afterPartNumber !== void 0 && (!isSafeInteger(input.afterPartNumber) || input.afterPartNumber > 1e4) || input.limit !== void 0 && (!isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100)) throw new DriveError("invalid_input");
1257
- return {
1258
- ...upload,
1259
- ...input.afterPartNumber === void 0 ? {} : { afterPartNumber: input.afterPartNumber },
1260
- ...input.limit === void 0 ? {} : { limit: input.limit }
1261
- };
1262
- }
1263
- function validateCreateUploadPartDescriptorInput(value) {
1264
- const input = captureRecord(value, [
1265
- "workspaceId",
1266
- "uploadId",
1267
- "partNumber",
1268
- "checksumSha256",
1269
- "contentMd5"
1270
- ], ["signal"]);
1271
- const upload = validateUploadPath(input.workspaceId, input.uploadId, input.signal);
1272
- if (!isPartNumber(input.partNumber) || !isPartChecksum(input.checksumSha256)) throw new DriveError("invalid_input");
1273
- if (typeof input.contentMd5 !== "string" || !/^[A-Za-z0-9+/]{21}[AQgw]==$/.test(input.contentMd5)) throw new DriveError("invalid_input");
1274
- return {
1275
- ...upload,
1276
- partNumber: input.partNumber,
1277
- checksumSha256: input.checksumSha256,
1278
- contentMd5: input.contentMd5
1279
- };
1280
- }
1281
- function validateRecordUploadPartInput(value) {
1282
- const input = captureRecord(value, [
1283
- "workspaceId",
1284
- "uploadId",
1285
- "partNumber",
1286
- "expectedUploadRevision",
1287
- "byteLength",
1288
- "etag",
1289
- "checksumSha256"
1290
- ], ["signal"]);
1291
- const upload = validateUploadPath(input.workspaceId, input.uploadId, input.signal);
1292
- if (!isPartNumber(input.partNumber) || !isSafeInteger(input.expectedUploadRevision) || input.expectedUploadRevision >= Number.MAX_SAFE_INTEGER || !isSafeInteger(input.byteLength) || input.byteLength < 1 || input.byteLength > UPLOAD_PART_BYTE_LENGTH$1 || !isEtag$1(input.etag) || !isPartChecksum(input.checksumSha256)) throw new DriveError("invalid_input");
1293
- return {
1294
- ...upload,
1295
- partNumber: input.partNumber,
1296
- expectedUploadRevision: input.expectedUploadRevision,
1297
- byteLength: input.byteLength,
1298
- etag: input.etag,
1299
- checksumSha256: input.checksumSha256
1300
- };
1301
- }
1302
- function validateCompleteUploadInput(value) {
1303
- const input = captureRecord(value, [
1304
- "workspaceId",
1305
- "uploadId",
1306
- "idempotencyKey"
1307
- ], ["signal"]);
1308
- const upload = validateUploadPath(input.workspaceId, input.uploadId, input.signal);
1309
- if (!isIdempotencyKey(input.idempotencyKey)) throw new DriveError("invalid_input");
1310
- return {
1311
- ...upload,
1312
- idempotencyKey: input.idempotencyKey
1313
- };
1314
- }
1315
- function validateAbortUploadInput(value) {
1316
- const input = captureRecord(value, ["workspaceId", "uploadId"], ["signal"]);
1317
- return validateUploadPath(input.workspaceId, input.uploadId, input.signal);
1318
- }
1319
- function validateUploadFileInput(value) {
1320
- const input = captureRecord(value, [
1321
- "workspaceId",
1322
- "parentItemId",
1323
- "source",
1324
- "displayFilename",
1325
- "idempotencyKey",
1326
- "completionIdempotencyKey"
1327
- ], [
1328
- "mediaType",
1329
- "protectionClassification",
1330
- "signal",
1331
- "onProgress"
1332
- ]);
1333
- const signal = validateSignal(input.signal);
1334
- const mediaType = input.mediaType ?? "application/octet-stream";
1335
- const protectionClassification = input.protectionClassification ?? "ordinary";
1336
- let source;
1337
- let byteLength;
1338
- try {
1339
- if (!(input.source instanceof Blob)) throw new DriveError("invalid_input");
1340
- source = input.source;
1341
- byteLength = source.size;
1342
- } catch (error) {
1343
- if (error instanceof DriveError) throw error;
1344
- throw new DriveError("invalid_input");
1345
- }
1346
- if (typeof input.workspaceId !== "string" || !WORKSPACE_ID.test(input.workspaceId) || typeof input.parentItemId !== "string" || !ITEM_ID.test(input.parentItemId) || !Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > MAX_UPLOAD_BYTE_LENGTH || !isSafeFilename(input.displayFilename) || !isMediaType(mediaType) || protectionClassification !== "ordinary" && protectionClassification !== "opaque-encrypted" || !isIdempotencyKey(input.idempotencyKey) || !isIdempotencyKey(input.completionIdempotencyKey) || input.onProgress !== void 0 && typeof input.onProgress !== "function") throw new DriveError("invalid_input");
1347
- return {
1348
- workspaceId: input.workspaceId,
1349
- parentItemId: input.parentItemId,
1350
- source,
1351
- byteLength,
1352
- displayFilename: input.displayFilename,
1353
- mediaType,
1354
- protectionClassification,
1355
- idempotencyKey: input.idempotencyKey,
1356
- completionIdempotencyKey: input.completionIdempotencyKey,
1357
- ...signal === void 0 ? {} : { signal },
1358
- ...input.onProgress === void 0 ? {} : { onProgress: input.onProgress }
1359
- };
1360
- }
1361
- function resourcePath(input) {
1362
- return {
1363
- workspaceId: input.workspaceId,
1364
- itemId: input.itemId
1365
- };
1366
- }
1367
- function pageQuery(input) {
1368
- return {
1369
- ...input.limit === void 0 ? {} : { limit: input.limit },
1370
- ...input.cursor === void 0 ? {} : { cursor: input.cursor }
1371
- };
1372
- }
1373
- function operationOptions(_operationId, options) {
1374
- return options;
1375
- }
1376
- function captureRecord(value, required, optional) {
1377
- try {
1378
- if (typeof value !== "object" && typeof value !== "function" || value === null || Array.isArray(value)) throw new DriveError("invalid_input");
1379
- const descriptors = Object.getOwnPropertyDescriptors(value);
1380
- const keys = Reflect.ownKeys(descriptors);
1381
- const allowed = new Set([...required, ...optional]);
1382
- if (keys.some((key) => typeof key !== "string" || !allowed.has(key)) || required.some((key) => !Object.hasOwn(descriptors, key))) throw new DriveError("invalid_input");
1383
- const result = {};
1384
- for (const key of keys) {
1385
- if (typeof key !== "string") throw new DriveError("invalid_input");
1386
- const descriptor = descriptors[key];
1387
- if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) throw new DriveError("invalid_input");
1388
- result[key] = descriptor.value;
1389
- }
1390
- return result;
1391
- } catch (error) {
1392
- if (error instanceof DriveError) throw error;
1393
- throw new DriveError("invalid_input");
1394
- }
1395
- }
1396
- function validateSignal(value) {
1397
- if (value === void 0) return void 0;
1398
- if (!(value instanceof AbortSignal)) throw new DriveError("invalid_input");
1399
- return value;
1400
- }
1401
- function validateGrantee(value) {
1402
- const type = captureRecord(value, ["type"], ["userId", "teamId"]);
1403
- if (type.type === "user") {
1404
- const user = captureRecord(value, ["type", "userId"], []);
1405
- if (typeof user.userId === "string" && AUTH_ID.test(user.userId)) return {
1406
- type: "user",
1407
- userId: user.userId
1408
- };
1409
- }
1410
- if (type.type === "team") {
1411
- const team = captureRecord(value, ["type", "teamId"], []);
1412
- if (typeof team.teamId === "string" && AUTH_ID.test(team.teamId)) return {
1413
- type: "team",
1414
- teamId: team.teamId
1415
- };
1416
- }
1417
- throw new DriveError("invalid_input");
1418
- }
1419
- function validateInputActions(value) {
1420
- const actions = captureArray(value);
1421
- if (actions.length < 1 || actions.length > PERMISSION_ACTIONS.length || new Set(actions).size !== actions.length || !actions.every((action) => PERMISSION_ACTIONS.includes(action))) throw new DriveError("invalid_input");
1422
- return actions;
1423
- }
1424
- function captureArray(value) {
1425
- try {
1426
- if (!Array.isArray(value)) throw new DriveError("invalid_input");
1427
- const descriptors = Object.getOwnPropertyDescriptors(value);
1428
- if (Reflect.ownKeys(descriptors).some((key) => typeof key !== "string")) throw new DriveError("invalid_input");
1429
- const result = [];
1430
- for (let index = 0; index < value.length; index += 1) {
1431
- const descriptor = descriptors[String(index)];
1432
- if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) throw new DriveError("invalid_input");
1433
- result.push(descriptor.value);
1434
- }
1435
- if (Reflect.ownKeys(descriptors).length !== value.length + 1) throw new DriveError("invalid_input");
1436
- return result;
1437
- } catch (error) {
1438
- if (error instanceof DriveError) throw error;
1439
- throw new DriveError("invalid_input");
1440
- }
1441
- }
1442
- function isIdempotencyKey(value) {
1443
- return typeof value === "string" && IDEMPOTENCY_KEY.test(value);
1444
- }
1445
- function validateUploadPath(workspaceId, uploadId, signalValue) {
1446
- const signal = validateSignal(signalValue);
1447
- if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId) || typeof uploadId !== "string" || !UPLOAD_ID.test(uploadId)) throw new DriveError("invalid_input");
1448
- return {
1449
- workspaceId,
1450
- uploadId,
1451
- ...signal === void 0 ? {} : { signal }
1452
- };
1453
- }
1454
- function isPartNumber(value) {
1455
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= 1e4;
1456
- }
1457
- function isPartChecksum(value) {
1458
- return typeof value === "string" && PART_CHECKSUM.test(value);
1459
- }
1460
- function isEtag$1(value) {
1461
- return typeof value === "string" && value.length >= 1 && value.length <= 1024 && /^[\x20-\x7e]+$/.test(value);
1462
- }
1463
- function isMediaType(value) {
1464
- return typeof value === "string" && value.length <= 255 && /^[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?\/[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?$/.test(value);
1465
- }
1466
- function isSearchQuery(value) {
1467
- if (typeof value !== "string" || value.length === 0) return false;
1468
- try {
1469
- if (value.normalize("NFC") !== value) return false;
1470
- let codePoints = 0;
1471
- let bytes = 0;
1472
- for (const character of value) {
1473
- const point = character.codePointAt(0);
1474
- if (point === void 0 || point <= 31 || point >= 127 && point <= 159 || point === 8232 || point === 8233 || point >= 55296 && point <= 57343) return false;
1475
- codePoints += 1;
1476
- bytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
1477
- if (codePoints > 64 || bytes > 255) return false;
1478
- }
1479
- return true;
1480
- } catch {
1481
- return false;
1482
- }
1483
- }
1484
- function isExpiry(value) {
1485
- return value === null || isSafeInteger(value);
1486
- }
1487
- function isSafeFilename(value) {
1488
- if (typeof value !== "string" || value.length === 0 || value.length > 510 || value.normalize("NFC") !== value || value.endsWith(".") || value.endsWith(" ") || filenameIsReserved(value)) return false;
1489
- let codePoints = 0;
1490
- let bytes = 0;
1491
- for (const character of value) {
1492
- const point = character.codePointAt(0);
1493
- if (point === void 0 || point === 47 || point === 92 || point <= 31 || point >= 127 && point <= 159 || point === 8232 || point === 8233 || point >= 55296 && point <= 57343) return false;
1494
- codePoints += 1;
1495
- bytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
1496
- if (codePoints > 255 || bytes > 255) return false;
1497
- }
1498
- return true;
1499
- }
1500
- function filenameIsReserved(value) {
1501
- const base = value.split(".", 1)[0].toUpperCase();
1502
- return value === "." || value === ".." || [
1503
- "CON",
1504
- "PRN",
1505
- "AUX",
1506
- "NUL",
1507
- "CLOCK$",
1508
- "CONIN$",
1509
- "CONOUT$"
1510
- ].includes(base) || /^COM[1-9]$/.test(base) || /^LPT[1-9]$/.test(base);
1511
- }
1512
- function isSafeInteger(value) {
1513
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1514
- }
1515
- function isOptionalHeaderValue(value) {
1516
- return value === void 0 || typeof value === "string" && value.length <= 8192 && !value.split("").some((character) => {
1517
- const code = character.charCodeAt(0);
1518
- return code <= 31 || code === 127;
1519
- });
1520
- }
1521
- //#endregion
1522
- //#region ../../node_modules/.pnpm/openapi-fetch@0.17.0/node_modules/openapi-fetch/dist/index.mjs
1523
- const PATH_PARAM_RE = /\{[^{}]+\}/g;
1524
- const supportsRequestInitExt = () => {
1525
- return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
1526
- };
1527
- function randomID() {
1528
- return Math.random().toString(36).slice(2, 11);
1529
- }
1530
- function createClient(clientOptions) {
1531
- let { baseUrl = "", Request: CustomRequest = globalThis.Request, fetch: baseFetch = globalThis.fetch, querySerializer: globalQuerySerializer, bodySerializer: globalBodySerializer, pathSerializer: globalPathSerializer, headers: baseHeaders, requestInitExt = void 0, ...baseOptions } = { ...clientOptions };
1532
- requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
1533
- baseUrl = removeTrailingSlash(baseUrl);
1534
- const globalMiddlewares = [];
1535
- async function coreFetch(schemaPath, fetchOptions) {
1536
- const { baseUrl: localBaseUrl, fetch = baseFetch, Request = CustomRequest, headers, params = {}, parseAs = "json", querySerializer: requestQuerySerializer, bodySerializer = globalBodySerializer ?? defaultBodySerializer, pathSerializer: requestPathSerializer, body, middleware: requestMiddlewares = [], ...init } = fetchOptions || {};
1537
- let finalBaseUrl = baseUrl;
1538
- if (localBaseUrl) finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
1539
- let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
1540
- if (requestQuerySerializer) querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
1541
- ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
1542
- ...requestQuerySerializer
1543
- });
1544
- const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;
1545
- const serializedBody = body === void 0 ? void 0 : bodySerializer(body, mergeHeaders(baseHeaders, headers, params.header));
1546
- const finalHeaders = mergeHeaders(serializedBody === void 0 || serializedBody instanceof FormData ? {} : { "Content-Type": "application/json" }, baseHeaders, headers, params.header);
1547
- const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];
1548
- const requestInit = {
1549
- redirect: "follow",
1550
- ...baseOptions,
1551
- ...init,
1552
- body: serializedBody,
1553
- headers: finalHeaders
1554
- };
1555
- let id;
1556
- let options;
1557
- let request = new Request(createFinalURL(schemaPath, {
1558
- baseUrl: finalBaseUrl,
1559
- params,
1560
- querySerializer,
1561
- pathSerializer
1562
- }), requestInit);
1563
- let response;
1564
- for (const key in init) if (!(key in request)) request[key] = init[key];
1565
- if (finalMiddlewares.length) {
1566
- id = randomID();
1567
- options = Object.freeze({
1568
- baseUrl: finalBaseUrl,
1569
- fetch,
1570
- parseAs,
1571
- querySerializer,
1572
- bodySerializer,
1573
- pathSerializer
1574
- });
1575
- for (const m of finalMiddlewares) if (m && typeof m === "object" && typeof m.onRequest === "function") {
1576
- const result = await m.onRequest({
1577
- request,
1578
- schemaPath,
1579
- params,
1580
- options,
1581
- id
1582
- });
1583
- if (result) if (result instanceof Request) request = result;
1584
- else if (result instanceof Response) {
1585
- response = result;
1586
- break;
1587
- } else throw new Error("onRequest: must return new Request() or Response() when modifying the request");
1588
- }
1589
- }
1590
- if (!response) {
1591
- try {
1592
- response = await fetch(request, requestInitExt);
1593
- } catch (error2) {
1594
- let errorAfterMiddleware = error2;
1595
- if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
1596
- const m = finalMiddlewares[i];
1597
- if (m && typeof m === "object" && typeof m.onError === "function") {
1598
- const result = await m.onError({
1599
- request,
1600
- error: errorAfterMiddleware,
1601
- schemaPath,
1602
- params,
1603
- options,
1604
- id
1605
- });
1606
- if (result) {
1607
- if (result instanceof Response) {
1608
- errorAfterMiddleware = void 0;
1609
- response = result;
1610
- break;
1611
- }
1612
- if (result instanceof Error) {
1613
- errorAfterMiddleware = result;
1614
- continue;
1615
- }
1616
- throw new Error("onError: must return new Response() or instance of Error");
1617
- }
1618
- }
1619
- }
1620
- if (errorAfterMiddleware) throw errorAfterMiddleware;
1621
- }
1622
- if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
1623
- const m = finalMiddlewares[i];
1624
- if (m && typeof m === "object" && typeof m.onResponse === "function") {
1625
- const result = await m.onResponse({
1626
- request,
1627
- response,
1628
- schemaPath,
1629
- params,
1630
- options,
1631
- id
1632
- });
1633
- if (result) {
1634
- if (!(result instanceof Response)) throw new Error("onResponse: must return new Response() when modifying the response");
1635
- response = result;
1636
- }
1637
- }
1638
- }
1639
- }
1640
- const contentLength = response.headers.get("Content-Length");
1641
- if (response.status === 204 || request.method === "HEAD" || contentLength === "0" && !response.headers.get("Transfer-Encoding")?.includes("chunked")) return response.ok ? {
1642
- data: void 0,
1643
- response
1644
- } : {
1645
- error: void 0,
1646
- response
1647
- };
1648
- if (response.ok) {
1649
- const getResponseData = async () => {
1650
- if (parseAs === "stream") return response.body;
1651
- if (parseAs === "json" && !contentLength) {
1652
- const raw = await response.text();
1653
- return raw ? JSON.parse(raw) : void 0;
1654
- }
1655
- return await response[parseAs]();
1656
- };
1657
- return {
1658
- data: await getResponseData(),
1659
- response
1660
- };
1661
- }
1662
- let error = await response.text();
1663
- try {
1664
- error = JSON.parse(error);
1665
- } catch {}
1666
- return {
1667
- error,
1668
- response
1669
- };
1670
- }
1671
- return {
1672
- request(method, url, init) {
1673
- return coreFetch(url, {
1674
- ...init,
1675
- method: method.toUpperCase()
1676
- });
1677
- },
1678
- GET(url, init) {
1679
- return coreFetch(url, {
1680
- ...init,
1681
- method: "GET"
1682
- });
1683
- },
1684
- PUT(url, init) {
1685
- return coreFetch(url, {
1686
- ...init,
1687
- method: "PUT"
1688
- });
1689
- },
1690
- POST(url, init) {
1691
- return coreFetch(url, {
1692
- ...init,
1693
- method: "POST"
1694
- });
1695
- },
1696
- DELETE(url, init) {
1697
- return coreFetch(url, {
1698
- ...init,
1699
- method: "DELETE"
1700
- });
1701
- },
1702
- OPTIONS(url, init) {
1703
- return coreFetch(url, {
1704
- ...init,
1705
- method: "OPTIONS"
1706
- });
1707
- },
1708
- HEAD(url, init) {
1709
- return coreFetch(url, {
1710
- ...init,
1711
- method: "HEAD"
1712
- });
1713
- },
1714
- PATCH(url, init) {
1715
- return coreFetch(url, {
1716
- ...init,
1717
- method: "PATCH"
1718
- });
1719
- },
1720
- TRACE(url, init) {
1721
- return coreFetch(url, {
1722
- ...init,
1723
- method: "TRACE"
1724
- });
1725
- },
1726
- use(...middleware) {
1727
- for (const m of middleware) {
1728
- if (!m) continue;
1729
- if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
1730
- globalMiddlewares.push(m);
1731
- }
1732
- },
1733
- eject(...middleware) {
1734
- for (const m of middleware) {
1735
- const i = globalMiddlewares.indexOf(m);
1736
- if (i !== -1) globalMiddlewares.splice(i, 1);
1737
- }
1738
- }
1739
- };
1740
- }
1741
- function serializePrimitiveParam(name, value, options) {
1742
- if (value === void 0 || value === null) return "";
1743
- if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
1744
- return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
1745
- }
1746
- function serializeObjectParam(name, value, options) {
1747
- if (!value || typeof value !== "object") return "";
1748
- const values = [];
1749
- const joiner = {
1750
- simple: ",",
1751
- label: ".",
1752
- matrix: ";"
1753
- }[options.style] || "&";
1754
- if (options.style !== "deepObject" && options.explode === false) {
1755
- for (const k in value) values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
1756
- const final2 = values.join(",");
1757
- switch (options.style) {
1758
- case "form": return `${name}=${final2}`;
1759
- case "label": return `.${final2}`;
1760
- case "matrix": return `;${name}=${final2}`;
1761
- default: return final2;
1762
- }
1763
- }
1764
- for (const k in value) {
1765
- const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
1766
- values.push(serializePrimitiveParam(finalName, value[k], options));
1767
- }
1768
- const final = values.join(joiner);
1769
- return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
1770
- }
1771
- function serializeArrayParam(name, value, options) {
1772
- if (!Array.isArray(value)) return "";
1773
- if (options.explode === false) {
1774
- const joiner2 = {
1775
- form: ",",
1776
- spaceDelimited: "%20",
1777
- pipeDelimited: "|"
1778
- }[options.style] || ",";
1779
- const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);
1780
- switch (options.style) {
1781
- case "simple": return final;
1782
- case "label": return `.${final}`;
1783
- case "matrix": return `;${name}=${final}`;
1784
- default: return `${name}=${final}`;
1785
- }
1786
- }
1787
- const joiner = {
1788
- simple: ",",
1789
- label: ".",
1790
- matrix: ";"
1791
- }[options.style] || "&";
1792
- const values = [];
1793
- for (const v of value) if (options.style === "simple" || options.style === "label") values.push(options.allowReserved === true ? v : encodeURIComponent(v));
1794
- else values.push(serializePrimitiveParam(name, v, options));
1795
- return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
1796
- }
1797
- function createQuerySerializer(options) {
1798
- return function querySerializer(queryParams) {
1799
- const search = [];
1800
- if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
1801
- const value = queryParams[name];
1802
- if (value === void 0 || value === null) continue;
1803
- if (Array.isArray(value)) {
1804
- if (value.length === 0) continue;
1805
- search.push(serializeArrayParam(name, value, {
1806
- style: "form",
1807
- explode: true,
1808
- ...options?.array,
1809
- allowReserved: options?.allowReserved || false
1810
- }));
1811
- continue;
1812
- }
1813
- if (typeof value === "object") {
1814
- search.push(serializeObjectParam(name, value, {
1815
- style: "deepObject",
1816
- explode: true,
1817
- ...options?.object,
1818
- allowReserved: options?.allowReserved || false
1819
- }));
1820
- continue;
1821
- }
1822
- search.push(serializePrimitiveParam(name, value, options));
1823
- }
1824
- return search.join("&");
1825
- };
1826
- }
1827
- function defaultPathSerializer(pathname, pathParams) {
1828
- let nextURL = pathname;
1829
- for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
1830
- let name = match.substring(1, match.length - 1);
1831
- let explode = false;
1832
- let style = "simple";
1833
- if (name.endsWith("*")) {
1834
- explode = true;
1835
- name = name.substring(0, name.length - 1);
1836
- }
1837
- if (name.startsWith(".")) {
1838
- style = "label";
1839
- name = name.substring(1);
1840
- } else if (name.startsWith(";")) {
1841
- style = "matrix";
1842
- name = name.substring(1);
1843
- }
1844
- if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) continue;
1845
- const value = pathParams[name];
1846
- if (Array.isArray(value)) {
1847
- nextURL = nextURL.replace(match, serializeArrayParam(name, value, {
1848
- style,
1849
- explode
1850
- }));
1851
- continue;
1852
- }
1853
- if (typeof value === "object") {
1854
- nextURL = nextURL.replace(match, serializeObjectParam(name, value, {
1855
- style,
1856
- explode
1857
- }));
1858
- continue;
1859
- }
1860
- if (style === "matrix") {
1861
- nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
1862
- continue;
1863
- }
1864
- nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
1865
- }
1866
- return nextURL;
1867
- }
1868
- function defaultBodySerializer(body, headers) {
1869
- if (body instanceof FormData) return body;
1870
- if (headers) {
1871
- if ((headers.get instanceof Function ? headers.get("Content-Type") ?? headers.get("content-type") : headers["Content-Type"] ?? headers["content-type"]) === "application/x-www-form-urlencoded") return new URLSearchParams(body).toString();
1872
- }
1873
- return JSON.stringify(body);
1874
- }
1875
- function createFinalURL(pathname, options) {
1876
- let finalURL = `${options.baseUrl}${pathname}`;
1877
- if (options.params?.path) finalURL = options.pathSerializer(finalURL, options.params.path);
1878
- let search = options.querySerializer(options.params.query ?? {});
1879
- if (search.startsWith("?")) search = search.substring(1);
1880
- if (search) finalURL += `?${search}`;
1881
- return finalURL;
1882
- }
1883
- function mergeHeaders(...allHeaders) {
1884
- const finalHeaders = new Headers();
1885
- for (const h of allHeaders) {
1886
- if (!h || typeof h !== "object") continue;
1887
- const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
1888
- for (const [k, v] of iterator) if (v === null) finalHeaders.delete(k);
1889
- else if (Array.isArray(v)) for (const v2 of v) finalHeaders.append(k, v2);
1890
- else if (v !== void 0) finalHeaders.set(k, v);
1891
- }
1892
- return finalHeaders;
1893
- }
1894
- function removeTrailingSlash(url) {
1895
- if (url.endsWith("/")) return url.substring(0, url.length - 1);
1896
- return url;
1897
- }
1898
- String.fromCharCode;
1899
- const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
1900
- const JOIN_LEADING_SLASH_RE = /^\.?\//;
1901
- function hasTrailingSlash(input = "", respectQueryAndFragment) {
1902
- if (!respectQueryAndFragment) return input.endsWith("/");
1903
- return TRAILING_SLASH_RE.test(input);
1904
- }
1905
- function withTrailingSlash(input = "", respectQueryAndFragment) {
1906
- if (!respectQueryAndFragment) return input.endsWith("/") ? input : input + "/";
1907
- if (hasTrailingSlash(input, true)) return input || "/";
1908
- let path = input;
1909
- let fragment = "";
1910
- const fragmentIndex = input.indexOf("#");
1911
- if (fragmentIndex !== -1) {
1912
- path = input.slice(0, fragmentIndex);
1913
- fragment = input.slice(fragmentIndex);
1914
- if (!path) return fragment;
1915
- }
1916
- const [s0, ...s] = path.split("?");
1917
- return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
1918
- }
1919
- function isNonEmptyURL(url) {
1920
- return url && url !== "/";
1921
- }
1922
- function joinURL(base, ...input) {
1923
- let url = base || "";
1924
- for (const segment of input.filter((url2) => isNonEmptyURL(url2))) if (url) {
1925
- const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
1926
- url = withTrailingSlash(url) + _segment;
1927
- } else url = segment;
1928
- return url;
1929
- }
1930
- //#endregion
1931
- //#region src/internal/client/transport.ts
1932
- const DEFAULT_REQUEST_TIMEOUT_MILLISECONDS = 3e4;
1933
- const MAX_REQUEST_TIMEOUT_MILLISECONDS = 12e4;
1934
- function createClientRuntime(config) {
1935
- let runtime;
1936
- try {
1937
- runtime = Object.freeze({
1938
- baseUrl: parseBaseUrl(config.baseUrl),
1939
- fetchImplementation: config.fetch ?? globalThis.fetch.bind(globalThis),
1940
- getCredential: config.getCredential,
1941
- timeoutMilliseconds: parseTimeoutMilliseconds(config.timeoutMilliseconds)
1942
- });
1943
- } catch {
1944
- throw new DriveError("invalid_input");
1945
- }
1946
- if (typeof runtime.fetchImplementation !== "function" || typeof runtime.getCredential !== "function") throw new DriveError("invalid_input");
1947
- return runtime;
1948
- }
1949
- async function execute(runtime, signal, preconditionStatus, send, successStatuses, guard, allowsQuotaExceeded = false, allowedErrorCodes) {
1950
- const operation = createOperationSignal(signal, runtime.timeoutMilliseconds);
1951
- try {
1952
- const operationSignal = operation.signal;
1953
- throwIfAborted(operationSignal);
1954
- const credential = await obtainCredential(runtime.getCredential, operationSignal);
1955
- let capturedResponse;
1956
- await send(createClient({
1957
- baseUrl: runtime.baseUrl,
1958
- fetch: async (request) => {
1959
- try {
1960
- const response = await raceWithAbort(runtime.fetchImplementation(request), operationSignal);
1961
- if (!(response instanceof Response)) throw new DriveError("invalid_response");
1962
- capturedResponse = response;
1963
- } catch (error) {
1964
- if (error instanceof DriveError) throw error;
1965
- throw operationSignal.aborted ? new DriveError("aborted") : new DriveError("network_error");
1966
- }
1967
- return new Response(null, { status: 204 });
1968
- }
1969
- }), {
1970
- cache: "no-store",
1971
- credentials: "omit",
1972
- headers: new Headers({ authorization: `Bearer ${credential}` }),
1973
- signal: operationSignal
1974
- });
1975
- if (!capturedResponse) throw new DriveError("network_error");
1976
- return guard === null ? await parseNoContentResponse(capturedResponse, operationSignal, preconditionStatus, successStatuses, allowedErrorCodes) : await parseResponse(capturedResponse, operationSignal, preconditionStatus, successStatuses, guard, allowsQuotaExceeded, allowedErrorCodes);
1977
- } catch (error) {
1978
- if (operation.didTimeout()) throw new DriveError("timeout");
1979
- if (error instanceof DriveError) throw error;
1980
- throw operation.signal.aborted ? new DriveError("aborted") : new DriveError("network_error");
1981
- } finally {
1982
- operation.dispose();
1983
- }
1984
- }
1985
- function parseTimeoutMilliseconds(value) {
1986
- if (value === void 0) return DEFAULT_REQUEST_TIMEOUT_MILLISECONDS;
1987
- if (!Number.isSafeInteger(value) || value < 1 || value > MAX_REQUEST_TIMEOUT_MILLISECONDS) throw new DriveError("invalid_input");
1988
- return value;
1989
- }
1990
- function createOperationSignal(callerSignal, timeoutMilliseconds) {
1991
- const controller = new AbortController();
1992
- let timedOut = false;
1993
- const onAbort = () => controller.abort();
1994
- if (callerSignal?.aborted) controller.abort();
1995
- else callerSignal?.addEventListener("abort", onAbort, { once: true });
1996
- const timeout = setTimeout(() => {
1997
- timedOut = true;
1998
- controller.abort();
1999
- }, timeoutMilliseconds);
2000
- return {
2001
- signal: controller.signal,
2002
- didTimeout: () => timedOut,
2003
- dispose: () => {
2004
- clearTimeout(timeout);
2005
- callerSignal?.removeEventListener("abort", onAbort);
2006
- }
2007
- };
2008
- }
2009
- function parseBaseUrl(value) {
2010
- if (typeof value !== "string") throw new TypeError("Drive base URL is invalid");
2011
- let url;
2012
- try {
2013
- url = new URL(value);
2014
- } catch {
2015
- throw new TypeError("Drive base URL is invalid");
2016
- }
2017
- const localHttp = url.protocol === "http:" && [
2018
- "localhost",
2019
- "127.0.0.1",
2020
- "[::1]"
2021
- ].includes(url.hostname);
2022
- if (url.protocol !== "https:" && !localHttp || url.username || url.password || url.search || url.hash || !url.host) throw new TypeError("Drive base URL is invalid");
2023
- return joinURL(url.origin, url.pathname);
2024
- }
2025
- async function obtainCredential(provider, signal) {
2026
- throwIfAborted(signal);
2027
- let credential;
2028
- try {
2029
- credential = await raceWithAbort(provider({ signal }), signal);
2030
- } catch (error) {
2031
- if (error instanceof DriveError && error.code === "aborted") throw error;
2032
- throw signal.aborted ? new DriveError("aborted") : new DriveError("credential_unavailable");
2033
- }
2034
- if (typeof credential !== "string" || credential.length < 1 || credential.length > 16384 || !/^[\x21-\x7e]+$/.test(credential)) throw new DriveError("credential_unavailable");
2035
- return credential;
2036
- }
2037
- function throwIfAborted(signal) {
2038
- if (signal.aborted) throw new DriveError("aborted");
2039
- }
2040
- async function raceWithAbort(promise, signal) {
2041
- throwIfAborted(signal);
2042
- let removeAbort = () => {};
2043
- const aborted = new Promise((_, reject) => {
2044
- const onAbort = () => reject(new DriveError("aborted"));
2045
- signal.addEventListener("abort", onAbort, { once: true });
2046
- removeAbort = () => signal.removeEventListener("abort", onAbort);
2047
- });
2048
- try {
2049
- return await Promise.race([promise, aborted]);
2050
- } finally {
2051
- removeAbort();
2052
- }
2053
- }
2054
- //#endregion
2055
- //#region src/internal/client/operations.ts
2056
- const CURRENT_WORKSPACE_ERROR_CODES = Object.freeze([
2057
- "authentication_required",
2058
- "identity_authority_unavailable",
2059
- "permission_denied",
2060
- "resource_not_found",
2061
- "invalid_request",
2062
- "service_unavailable"
2063
- ]);
2064
- const GET_ITEM_ERROR_CODES = Object.freeze([
2065
- "authentication_required",
2066
- "identity_authority_unavailable",
2067
- "permission_denied",
2068
- "resource_not_found",
2069
- "invalid_request",
2070
- "precondition_failed",
2071
- "service_unavailable"
2072
- ]);
2073
- const SEARCH_WORKSPACE_ITEMS_ERROR_CODES = Object.freeze([
2074
- "authentication_required",
2075
- "identity_authority_unavailable",
2076
- "permission_denied",
2077
- "resource_not_found",
2078
- "invalid_request",
2079
- "invalid_pagination_cursor",
2080
- "precondition_failed",
2081
- "service_unavailable"
2082
- ]);
2083
- const TRANSFER_ERROR_CODES = Object.freeze([
2084
- "authentication_required",
2085
- "identity_authority_unavailable",
2086
- "permission_denied",
2087
- "resource_not_found",
2088
- "invalid_request",
2089
- "precondition_failed",
2090
- "upload_recovery_required",
2091
- "service_unavailable"
2092
- ]);
2093
- const STATUS_ERROR_CODES = Object.freeze([
2094
- "authentication_required",
2095
- "identity_authority_unavailable",
2096
- "permission_denied",
2097
- "resource_not_found",
2098
- "invalid_request",
2099
- "service_unavailable"
2100
- ]);
2101
- const CREATE_UPLOAD_ERROR_CODES = Object.freeze([
2102
- ...TRANSFER_ERROR_CODES,
2103
- "invalid_idempotency_key",
2104
- "idempotency_conflict",
2105
- "quota_exceeded"
2106
- ]);
2107
- const COMPLETE_UPLOAD_ERROR_CODES = Object.freeze([...TRANSFER_ERROR_CODES, "invalid_idempotency_key"]);
2108
- const LIFECYCLE_MUTATION_ERROR_CODES = Object.freeze([
2109
- "authentication_required",
2110
- "identity_authority_unavailable",
2111
- "permission_denied",
2112
- "resource_not_found",
2113
- "invalid_request",
2114
- "invalid_idempotency_key",
2115
- "idempotency_conflict",
2116
- "precondition_failed",
2117
- "service_unavailable"
2118
- ]);
2119
- const LIST_ITEM_VERSIONS_ERROR_CODES = Object.freeze([
2120
- "authentication_required",
2121
- "identity_authority_unavailable",
2122
- "permission_denied",
2123
- "resource_not_found",
2124
- "invalid_request",
2125
- "precondition_failed",
2126
- "service_unavailable"
2127
- ]);
2128
- const DOWNLOAD_ERROR_CODES = Object.freeze([
2129
- "authentication_required",
2130
- "identity_authority_unavailable",
2131
- "permission_denied",
2132
- "resource_not_found",
2133
- "invalid_request",
2134
- "invalid_idempotency_key",
2135
- "idempotency_conflict",
2136
- "precondition_failed",
2137
- "range_not_satisfiable",
2138
- "service_unavailable"
2139
- ]);
2140
- function createDriveOperations(runtime) {
2141
- return Object.freeze({
2142
- getCurrentWorkspace: (input) => getCurrentWorkspace(runtime, input),
2143
- listWorkspaceItems: (input) => listWorkspaceItems(runtime, input),
2144
- getWorkspaceUsage: (input) => getWorkspaceUsage(runtime, input),
2145
- getCurrentWorkspaceSources: (input) => getCurrentWorkspaceSources(runtime, input),
2146
- getItem: (input) => getItem(runtime, input),
2147
- searchWorkspaceItems: (input) => searchWorkspaceItems(runtime, input),
2148
- listFolderChildren: (input) => listFolderChildren(runtime, input),
2149
- createFolder: (input) => createFolder(runtime, input),
2150
- updateItem: (input) => updateItem(runtime, input),
2151
- trashItem: (input) => trashItem(runtime, input),
2152
- restoreItem: (input) => restoreItem(runtime, input),
2153
- deleteItem: (input) => deleteItem(runtime, input),
2154
- listItemVersions: (input) => listItemVersions(runtime, input),
2155
- getItemVersion: (input) => getItemVersion(runtime, input),
2156
- restoreItemVersion: (input) => restoreItemVersion(runtime, input),
2157
- createDownload: (input) => createDownload(runtime, input),
2158
- downloadItem: (input) => downloadItem(runtime, input),
2159
- listItemPermissions: (input) => listItemPermissions(runtime, input),
2160
- readEffectiveItemPermissions: (input) => readEffectiveItemPermissions(runtime, input),
2161
- createItemPermission: (input) => createItemPermission(runtime, input),
2162
- updateItemPermission: (input) => updateItemPermission(runtime, input),
2163
- revokeItemPermission: (input) => revokeItemPermission(runtime, input),
2164
- createUpload: (input) => createUpload(runtime, input),
2165
- getUploadStatus: (input) => getUploadStatus(runtime, input),
2166
- createUploadPartDescriptor: (input) => createUploadPartDescriptor(runtime, input),
2167
- recordUploadPart: (input) => recordUploadPart(runtime, input),
2168
- completeUpload: (input) => completeUpload(runtime, input),
2169
- abortUpload: (input) => abortUpload(runtime, input)
2170
- });
2171
- }
2172
- async function createDownload(runtime, input) {
2173
- const validated = validateCreateDownloadInput(input);
2174
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/downloads", {
2175
- ...operationOptions("createDownload", { params: {
2176
- path: {
2177
- workspaceId: validated.workspaceId,
2178
- itemId: validated.itemId
2179
- },
2180
- query: validated.versionId === void 0 ? {} : { versionId: validated.versionId },
2181
- header: {
2182
- "Idempotency-Key": validated.idempotencyKey,
2183
- "Download-Method": validated.method,
2184
- ...validated.range === void 0 ? {} : { Range: validated.range },
2185
- ...validated.ifMatch === void 0 ? {} : { "If-Match": validated.ifMatch },
2186
- ...validated.ifNoneMatch === void 0 ? {} : { "If-None-Match": validated.ifNoneMatch },
2187
- ...validated.ifRange === void 0 ? {} : { "If-Range": validated.ifRange }
2188
- }
2189
- } }),
2190
- ...requestOptions
2191
- }), [
2192
- 200,
2193
- 202,
2194
- 304
2195
- ], (value, status) => status === 200 ? isManagedDownloadDescriptor(value) : status === 202 ? isManagedDownloadRestorePending(value) : value === void 0, false, DOWNLOAD_ERROR_CODES);
2196
- }
2197
- async function downloadItem(runtime, input) {
2198
- const validated = validateCreateDownloadInput(input);
2199
- const created = await createDownload(runtime, input);
2200
- if (created.status === 202 || created.status === 304) return created;
2201
- const descriptor = created.data;
2202
- if (descriptor.expiresAtEpochMilliseconds <= Date.now()) throw new DriveError("invalid_response");
2203
- const operation = createOperationSignal(validated.signal, runtime.timeoutMilliseconds);
2204
- try {
2205
- const response = await raceWithAbort(runtime.fetchImplementation(directDownloadRequest(descriptor, operation.signal)), operation.signal);
2206
- if (!responseMatchesDownloadDescriptor(response, descriptor)) {
2207
- await response.body?.cancel().catch(() => void 0);
2208
- throw new DriveError("invalid_response");
2209
- }
2210
- const responseHeaders = downloadResponseHeaders(descriptor);
2211
- if (descriptor.method === "HEAD") {
2212
- await response.body?.cancel().catch(() => void 0);
2213
- operation.dispose();
2214
- return new Response(null, {
2215
- status: response.status,
2216
- headers: responseHeaders
2217
- });
2218
- }
2219
- if (!response.body) {
2220
- operation.dispose();
2221
- if (descriptor.response.contentLength !== 0) throw new DriveError("invalid_response");
2222
- return new Response(null, {
2223
- status: response.status,
2224
- headers: responseHeaders
2225
- });
2226
- }
2227
- operation.dispose();
2228
- return new Response(streamWithOperationLifetime(response.body, descriptor.response.contentLength, validated.signal), {
2229
- status: response.status,
2230
- headers: responseHeaders
2231
- });
2232
- } catch (error) {
2233
- operation.dispose();
2234
- if (operation.didTimeout()) throw new DriveError("timeout");
2235
- if (error instanceof DriveError) throw error;
2236
- throw operation.signal.aborted ? new DriveError(operation.didTimeout() ? "timeout" : "aborted") : new DriveError("network_error");
2237
- }
2238
- }
2239
- function downloadResponseHeaders(descriptor) {
2240
- const expected = descriptor.response;
2241
- const headers = new Headers();
2242
- headers.set("accept-ranges", expected.acceptRanges);
2243
- headers.set("content-disposition", expected.contentDisposition);
2244
- headers.set("content-length", String(expected.contentLength));
2245
- headers.set("content-type", expected.contentType);
2246
- headers.set("etag", expected.etag);
2247
- if (expected.contentRange === null) headers.delete("content-range");
2248
- else headers.set("content-range", expected.contentRange);
2249
- return headers;
2250
- }
2251
- function directDownloadRequest(descriptor, signal) {
2252
- const base = {
2253
- method: descriptor.method,
2254
- headers: descriptor.headers,
2255
- redirect: "manual",
2256
- signal
2257
- };
2258
- try {
2259
- return new Request(descriptor.url, {
2260
- ...base,
2261
- cache: "no-store",
2262
- credentials: "omit",
2263
- referrerPolicy: "no-referrer"
2264
- });
2265
- } catch {
2266
- try {
2267
- return new Request(descriptor.url, {
2268
- ...base,
2269
- credentials: "omit",
2270
- referrerPolicy: "no-referrer"
2271
- });
2272
- } catch {
2273
- return new Request(descriptor.url, {
2274
- ...base,
2275
- credentials: "omit"
2276
- });
2277
- }
2278
- }
2279
- }
2280
- function responseMatchesDownloadDescriptor(response, descriptor) {
2281
- const expected = descriptor.response;
2282
- const encoding = response.headers.get("content-encoding");
2283
- return response.status === expected.status && response.headers.get("etag") === expected.etag && response.headers.get("content-length") === String(expected.contentLength) && (encoding === null || encoding === "identity") && (expected.contentRange === null ? response.headers.get("content-range") === null : response.headers.get("content-range") === expected.contentRange);
2284
- }
2285
- function streamWithOperationLifetime(source, expectedLength, signal) {
2286
- const reader = source.getReader();
2287
- let receivedLength = 0;
2288
- let finished = false;
2289
- let removeAbort = () => {};
2290
- return new ReadableStream({
2291
- start(controller) {
2292
- if (!signal) return;
2293
- const onAbort = () => {
2294
- if (finished) return;
2295
- finished = true;
2296
- removeAbort();
2297
- reader.cancel().catch(() => void 0);
2298
- controller.error(new DriveError("aborted"));
2299
- };
2300
- if (signal.aborted) onAbort();
2301
- else {
2302
- signal.addEventListener("abort", onAbort, { once: true });
2303
- removeAbort = () => signal.removeEventListener("abort", onAbort);
2304
- }
2305
- },
2306
- async pull(controller) {
2307
- if (finished) return;
2308
- try {
2309
- const chunk = await reader.read();
2310
- if (finished) return;
2311
- if (chunk.done) {
2312
- finished = true;
2313
- removeAbort();
2314
- reader.releaseLock();
2315
- if (receivedLength === expectedLength) controller.close();
2316
- else controller.error(new DriveError("invalid_response"));
2317
- } else {
2318
- receivedLength += chunk.value.byteLength;
2319
- if (!Number.isSafeInteger(receivedLength) || receivedLength > expectedLength) {
2320
- finished = true;
2321
- removeAbort();
2322
- await reader.cancel().catch(() => void 0);
2323
- controller.error(new DriveError("invalid_response"));
2324
- return;
2325
- }
2326
- controller.enqueue(chunk.value);
2327
- }
2328
- } catch (error) {
2329
- if (finished) return;
2330
- finished = true;
2331
- removeAbort();
2332
- await reader.cancel().catch(() => void 0);
2333
- controller.error(error instanceof DriveError ? error : signal?.aborted ? new DriveError("aborted") : new DriveError("network_error"));
2334
- }
2335
- },
2336
- async cancel(reason) {
2337
- if (finished) return;
2338
- finished = true;
2339
- removeAbort();
2340
- await reader.cancel(reason).catch(() => void 0);
2341
- }
2342
- });
2343
- }
2344
- async function getCurrentWorkspaceSources(runtime, input) {
2345
- return execute(runtime, validateCurrentWorkspaceInput(input).signal, null, (api, requestOptions) => api.GET("/api/v1/workspaces/current/sources", {
2346
- ...operationOptions("getCurrentWorkspaceSources", { params: {} }),
2347
- ...requestOptions
2348
- }), [200], isCurrentWorkspaceSources, false, CURRENT_WORKSPACE_ERROR_CODES);
2349
- }
2350
- async function listWorkspaceItems(runtime, input) {
2351
- const validated = validateWorkspaceDiscoveryInput(input, true);
2352
- return execute(runtime, validated.signal, null, (api, options) => api.GET("/api/v1/workspaces/{workspaceId}/items", {
2353
- ...operationOptions("listWorkspaceItems", { params: {
2354
- path: { workspaceId: validated.workspaceId },
2355
- query: validated.query
2356
- } }),
2357
- ...options
2358
- }), [200], (value) => isWorkspaceDiscoveryPage(value) && value.items.length <= (validated.query.limit ?? 25) && value.items.every((item, index, items) => item.workspaceId === validated.workspaceId && item.lifecycleState === (validated.query.view === "trash" ? "trashed" : "active") && ((validated.query.view ?? "recent") !== "recent" || item.modifiedAtEpochMilliseconds !== null) && (validated.query.kind === void 0 || item.type === validated.query.kind) && (validated.query.creatorUserId === void 0 || item.creatorUserId === validated.query.creatorUserId) && (index === 0 || ((validated.query.view ?? "recent") === "recent" ? items[index - 1].modifiedAtEpochMilliseconds > item.modifiedAtEpochMilliseconds || items[index - 1].modifiedAtEpochMilliseconds === item.modifiedAtEpochMilliseconds && items[index - 1].itemId < item.itemId : items[index - 1].itemId < item.itemId))), false, SEARCH_WORKSPACE_ITEMS_ERROR_CODES);
2359
- }
2360
- async function getWorkspaceUsage(runtime, input) {
2361
- const validated = validateWorkspaceDiscoveryInput(input, false);
2362
- return execute(runtime, validated.signal, null, (api, options) => api.GET("/api/v1/workspaces/{workspaceId}/usage", {
2363
- ...operationOptions("getWorkspaceUsage", { params: { path: { workspaceId: validated.workspaceId } } }),
2364
- ...options
2365
- }), [200], (value) => isWorkspaceUsage(value) && value.workspaceId === validated.workspaceId, false, SEARCH_WORKSPACE_ITEMS_ERROR_CODES);
2366
- }
2367
- async function getCurrentWorkspace(runtime, input) {
2368
- return execute(runtime, validateCurrentWorkspaceInput(input).signal, null, (api, requestOptions) => api.GET("/api/v1/workspaces/current", {
2369
- ...operationOptions("getCurrentWorkspace", { params: {} }),
2370
- ...requestOptions
2371
- }), [200], isCurrentWorkspace, false, CURRENT_WORKSPACE_ERROR_CODES);
2372
- }
2373
- async function getItem(runtime, input) {
2374
- const validated = validateResourceInput(input);
2375
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}", {
2376
- ...operationOptions("getItem", { params: { path: resourcePath(validated) } }),
2377
- ...requestOptions
2378
- }), [200], (value, _status, headers) => isManagedItemMetadata(value, validated.workspaceId, validated.itemId) && itemEtagMatchesRevision(headers, value.revision), false, GET_ITEM_ERROR_CODES);
2379
- }
2380
- async function searchWorkspaceItems(runtime, input) {
2381
- const validated = validateSearchWorkspaceItemsInput(input);
2382
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/search", {
2383
- ...operationOptions("searchWorkspaceItems", { params: {
2384
- path: { workspaceId: validated.workspaceId },
2385
- query: {
2386
- query: validated.query,
2387
- ...validated.limit === void 0 ? {} : { limit: validated.limit },
2388
- ...validated.cursor === void 0 ? {} : { cursor: validated.cursor }
2389
- }
2390
- } }),
2391
- ...requestOptions
2392
- }), [200], (value) => isWorkspaceItemSearchPage(value, validated.workspaceId, validated.query, validated.limit ?? 50), false, SEARCH_WORKSPACE_ITEMS_ERROR_CODES);
2393
- }
2394
- async function listFolderChildren(runtime, input) {
2395
- const validated = validatePageInput(input);
2396
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/children", {
2397
- ...operationOptions("listFolderChildren", { params: {
2398
- path: resourcePath(validated),
2399
- query: pageQuery(validated)
2400
- } }),
2401
- ...requestOptions
2402
- }), [200], (value) => isFolderPage(value, validated.workspaceId, validated.itemId));
2403
- }
2404
- async function createFolder(runtime, input) {
2405
- const validated = validateCreateFolderInput(input);
2406
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/children", {
2407
- ...operationOptions("createFolder", {
2408
- params: {
2409
- path: resourcePath(validated),
2410
- header: { "Idempotency-Key": validated.idempotencyKey }
2411
- },
2412
- body: { name: validated.name }
2413
- }),
2414
- ...requestOptions
2415
- }), [200, 201], (value) => isFolderItem(value) && value.workspaceId === validated.workspaceId && value.parentItemId === validated.itemId && value.kind === "folder" && value.name === validated.name);
2416
- }
2417
- async function updateItem(runtime, input) {
2418
- const validated = validateUpdateItemInput(input);
2419
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.PATCH("/api/v1/workspaces/{workspaceId}/items/{itemId}", {
2420
- ...operationOptions("updateItem", {
2421
- params: {
2422
- path: resourcePath(validated),
2423
- header: {
2424
- "Idempotency-Key": validated.idempotencyKey,
2425
- "If-Match": validated.ifMatch
2426
- }
2427
- },
2428
- body: {
2429
- name: validated.name,
2430
- parentItemId: validated.parentItemId
2431
- }
2432
- }),
2433
- ...requestOptions
2434
- }), [200], (value, _status, headers) => isManagedLifecycleItem(value, validated.workspaceId, validated.itemId, "active") && value.name === validated.name && value.parentItemId === validated.parentItemId && itemEtagMatchesRevision(headers, value.revision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2435
- }
2436
- async function trashItem(runtime, input) {
2437
- const validated = validateLifecycleMutationInput(input);
2438
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/trash", {
2439
- ...operationOptions("trashItem", { params: {
2440
- path: resourcePath(validated),
2441
- header: {
2442
- "Idempotency-Key": validated.idempotencyKey,
2443
- "If-Match": validated.ifMatch
2444
- }
2445
- } }),
2446
- ...requestOptions
2447
- }), [200], (value, _status, headers) => isManagedLifecycleItem(value, validated.workspaceId, validated.itemId, "trashed") && itemEtagMatchesRevision(headers, value.revision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2448
- }
2449
- async function restoreItem(runtime, input) {
2450
- const validated = validateLifecycleMutationInput(input);
2451
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/restore", {
2452
- ...operationOptions("restoreItem", { params: {
2453
- path: resourcePath(validated),
2454
- header: {
2455
- "Idempotency-Key": validated.idempotencyKey,
2456
- "If-Match": validated.ifMatch
2457
- }
2458
- } }),
2459
- ...requestOptions
2460
- }), [200], (value, _status, headers) => isManagedLifecycleItem(value, validated.workspaceId, validated.itemId, "active") && itemEtagMatchesRevision(headers, value.revision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2461
- }
2462
- async function deleteItem(runtime, input) {
2463
- const validated = validateLifecycleMutationInput(input);
2464
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.DELETE("/api/v1/workspaces/{workspaceId}/items/{itemId}", {
2465
- ...operationOptions("deleteItem", { params: {
2466
- path: resourcePath(validated),
2467
- header: {
2468
- "Idempotency-Key": validated.idempotencyKey,
2469
- "If-Match": validated.ifMatch
2470
- }
2471
- } }),
2472
- ...requestOptions
2473
- }), [200, 202], (value, _status, headers) => isManagedLifecycleItem(value, validated.workspaceId, validated.itemId, "deleting") && itemEtagMatchesRevision(headers, value.revision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2474
- }
2475
- async function listItemVersions(runtime, input) {
2476
- const validated = validatePageInput(input);
2477
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/versions", {
2478
- ...operationOptions("listItemVersions", { params: {
2479
- path: resourcePath(validated),
2480
- query: pageQuery(validated)
2481
- } }),
2482
- ...requestOptions
2483
- }), [200], (value) => isManagedItemVersionPage(value, validated.limit ?? 50), false, LIST_ITEM_VERSIONS_ERROR_CODES);
2484
- }
2485
- async function getItemVersion(runtime, input) {
2486
- const validated = validateItemVersionInput(input);
2487
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}", {
2488
- ...operationOptions("getItemVersion", { params: { path: {
2489
- ...resourcePath(validated),
2490
- versionId: validated.versionId
2491
- } } }),
2492
- ...requestOptions
2493
- }), [200], (value) => isManagedItemVersionResource(value, validated.workspaceId, validated.itemId, validated.versionId), false, LIST_ITEM_VERSIONS_ERROR_CODES);
2494
- }
2495
- async function restoreItemVersion(runtime, input) {
2496
- const validated = validateRestoreItemVersionInput(input);
2497
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}/restore", {
2498
- ...operationOptions("restoreItemVersion", { params: {
2499
- path: {
2500
- ...resourcePath(validated),
2501
- versionId: validated.versionId
2502
- },
2503
- header: {
2504
- "Idempotency-Key": validated.idempotencyKey,
2505
- "If-Match": validated.ifMatch
2506
- }
2507
- } }),
2508
- ...requestOptions
2509
- }), [200], (value, _status, headers) => isManagedItemVersionRestoreResult(value, validated.versionId) && itemEtagMatchesRevision(headers, value.itemRevision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2510
- }
2511
- async function listItemPermissions(runtime, input) {
2512
- const validated = validatePageInput(input);
2513
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions", {
2514
- ...operationOptions("listItemPermissions", { params: {
2515
- path: resourcePath(validated),
2516
- query: pageQuery(validated)
2517
- } }),
2518
- ...requestOptions
2519
- }), [200], (value, _status, headers) => isPermissionPage(value, headers, validated.itemId));
2520
- }
2521
- async function readEffectiveItemPermissions(runtime, input) {
2522
- const validated = validateResourceInput(input);
2523
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/effective", {
2524
- ...operationOptions("readEffectiveItemPermissions", { params: { path: resourcePath(validated) } }),
2525
- ...requestOptions
2526
- }), [200], (value) => isEffectivePermissionResponse(value, validated.itemId));
2527
- }
2528
- async function createItemPermission(runtime, input) {
2529
- const validated = validateCreatePermissionInput(input);
2530
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions", {
2531
- ...operationOptions("createItemPermission", {
2532
- params: {
2533
- path: resourcePath(validated),
2534
- header: {
2535
- "Idempotency-Key": validated.idempotencyKey,
2536
- "If-Match": validated.ifMatch
2537
- }
2538
- },
2539
- body: {
2540
- grantee: validated.grantee,
2541
- actions: validated.actions,
2542
- expiresAtEpochMilliseconds: validated.expiresAtEpochMilliseconds
2543
- }
2544
- }),
2545
- ...requestOptions
2546
- }), [200, 201], (value, status, headers) => isPermissionMutation(value, validated.itemId) && (status === 201 && value.outcome === "committed" || status === 200 && value.outcome === "replayed") && (status === 200 || value.grant.availability !== "revoked") && mutationValidatorsAreCoherent(headers));
2547
- }
2548
- async function updateItemPermission(runtime, input) {
2549
- const validated = validateUpdatePermissionInput(input);
2550
- const body = {};
2551
- if (validated.actions !== void 0) body.actions = validated.actions;
2552
- if (validated.expiresAtEpochMilliseconds !== void 0) body.expiresAtEpochMilliseconds = validated.expiresAtEpochMilliseconds;
2553
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.PATCH("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}", {
2554
- ...operationOptions("updateItemPermission", {
2555
- params: {
2556
- path: {
2557
- ...resourcePath(validated),
2558
- grantId: validated.grantId
2559
- },
2560
- header: {
2561
- "Idempotency-Key": validated.idempotencyKey,
2562
- "If-Match": validated.ifMatch
2563
- }
2564
- },
2565
- body
2566
- }),
2567
- ...requestOptions
2568
- }), [200], (value, _status, headers) => isPermissionMutation(value, validated.itemId, validated.grantId) && value.grant.availability !== "revoked" && mutationValidatorsAreCoherent(headers));
2569
- }
2570
- async function revokeItemPermission(runtime, input) {
2571
- const validated = validateGrantMutationInput(input);
2572
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.DELETE("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}", {
2573
- ...operationOptions("revokeItemPermission", { params: {
2574
- path: {
2575
- ...resourcePath(validated),
2576
- grantId: validated.grantId
2577
- },
2578
- header: {
2579
- "Idempotency-Key": validated.idempotencyKey,
2580
- "If-Match": validated.ifMatch
2581
- }
2582
- } }),
2583
- ...requestOptions
2584
- }), [200], (value, _status, headers) => isPermissionMutation(value, validated.itemId, validated.grantId) && value.grant.availability === "revoked" && parseCollectionEtag(headers.get("drive-permission-collection-etag") ?? "") !== void 0 && headers.get("drive-permission-grant-etag") === null);
2585
- }
2586
- async function createUpload(runtime, input) {
2587
- const validated = validateCreateUploadInput(input);
2588
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads", {
2589
- ...operationOptions("createUpload", {
2590
- params: {
2591
- path: { workspaceId: validated.workspaceId },
2592
- header: { "Idempotency-Key": validated.idempotencyKey }
2593
- },
2594
- body: {
2595
- parentItemId: validated.parentItemId,
2596
- expectedByteLength: validated.expectedByteLength,
2597
- displayFilename: validated.displayFilename,
2598
- mediaType: validated.mediaType,
2599
- callerDeclaredContentDigest: validated.callerDeclaredContentDigest,
2600
- protectionClassification: validated.protectionClassification
2601
- }
2602
- }),
2603
- ...requestOptions
2604
- }), [200, 201], (value) => isUploadSession(value, validated.expectedByteLength), true, CREATE_UPLOAD_ERROR_CODES);
2605
- }
2606
- async function getUploadStatus(runtime, input) {
2607
- const validated = validateGetUploadStatusInput(input);
2608
- const afterPartNumber = validated.afterPartNumber ?? 0;
2609
- const limit = validated.limit ?? 100;
2610
- return execute(runtime, validated.signal, null, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}", {
2611
- ...operationOptions("getUploadStatus", { params: {
2612
- path: {
2613
- workspaceId: validated.workspaceId,
2614
- uploadId: validated.uploadId
2615
- },
2616
- query: {
2617
- ...validated.afterPartNumber === void 0 ? {} : { afterPartNumber: String(validated.afterPartNumber) },
2618
- ...validated.limit === void 0 ? {} : { limit: String(validated.limit) }
2619
- }
2620
- } }),
2621
- ...requestOptions
2622
- }), [200], (value) => isUploadStatus(value, afterPartNumber, limit) && value.uploadId === validated.uploadId, false, STATUS_ERROR_CODES);
2623
- }
2624
- async function createUploadPartDescriptor(runtime, input) {
2625
- const validated = validateCreateUploadPartDescriptorInput(input);
2626
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts", {
2627
- ...operationOptions("createUploadPartDescriptor", {
2628
- params: { path: {
2629
- workspaceId: validated.workspaceId,
2630
- uploadId: validated.uploadId
2631
- } },
2632
- body: {
2633
- partNumber: validated.partNumber,
2634
- checksumSha256: validated.checksumSha256,
2635
- contentMd5: validated.contentMd5
2636
- }
2637
- }),
2638
- ...requestOptions
2639
- }), [200], (value) => isUploadPartDescriptor(value, validated.partNumber, new URL(runtime.baseUrl).protocol === "http:", validated.contentMd5), false, TRANSFER_ERROR_CODES);
2640
- }
2641
- async function recordUploadPart(runtime, input) {
2642
- const validated = validateRecordUploadPartInput(input);
2643
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts/{partNumber}", {
2644
- ...operationOptions("recordUploadPart", {
2645
- params: { path: {
2646
- workspaceId: validated.workspaceId,
2647
- uploadId: validated.uploadId,
2648
- partNumber: String(validated.partNumber)
2649
- } },
2650
- body: {
2651
- expectedUploadRevision: validated.expectedUploadRevision,
2652
- byteLength: validated.byteLength,
2653
- etag: validated.etag,
2654
- checksumSha256: validated.checksumSha256
2655
- }
2656
- }),
2657
- ...requestOptions
2658
- }), [200], (value) => isUploadPartResult(value, validated.partNumber, validated.expectedUploadRevision), false, TRANSFER_ERROR_CODES);
2659
- }
2660
- async function completeUpload(runtime, input) {
2661
- const validated = validateCompleteUploadInput(input);
2662
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/complete", {
2663
- ...operationOptions("completeUpload", { params: {
2664
- path: {
2665
- workspaceId: validated.workspaceId,
2666
- uploadId: validated.uploadId
2667
- },
2668
- header: { "Idempotency-Key": validated.idempotencyKey }
2669
- } }),
2670
- ...requestOptions
2671
- }), [200, 202], (value, status) => status === 202 ? isPendingUpload(value, validated.uploadId) : isReadyUpload(value, { uploadId: validated.uploadId }), false, COMPLETE_UPLOAD_ERROR_CODES);
2672
- }
2673
- async function abortUpload(runtime, input) {
2674
- const validated = validateAbortUploadInput(input);
2675
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.DELETE("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}", {
2676
- ...operationOptions("abortUpload", { params: { path: {
2677
- workspaceId: validated.workspaceId,
2678
- uploadId: validated.uploadId
2679
- } } }),
2680
- ...requestOptions
2681
- }), [204], null, false, TRANSFER_ERROR_CODES);
2682
- }
2683
- //#endregion
2684
- //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_u64.js
2685
- const fromNumH = (n) => n / 2 ** 32 | 0;
2686
- const fromNumL = (n) => n >>> 0;
2687
- function setU64FromNum(view, byteOffset, n, isLE) {
2688
- const h = fromNumH(n);
2689
- const l = fromNumL(n);
2690
- view.setUint32(byteOffset, isLE ? l : h, isLE);
2691
- view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
2692
- }
2693
- //#endregion
2694
- //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/utils.js
2695
- function isBytes(a) {
2696
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
2697
- }
2698
- const atitle = (title) => title ? `"${title}" ` : "";
2699
- function anumber(n, title = "") {
2700
- if (typeof n !== "number") throw new TypeError(atitle(title) + "expected number, got " + typeof n);
2701
- if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
2702
- return n;
2703
- }
2704
- function abytes(value, length, title = "") {
2705
- if (isBytes(value) && (length === void 0 || value.length === length)) return value;
2706
- if (length !== void 0) anumber(length, "length");
2707
- const bytes = isBytes(value);
2708
- const ofLen = length !== void 0 ? ` of length ${length}` : "";
2709
- const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
2710
- const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
2711
- if (!bytes) throw new TypeError(message);
2712
- throw new RangeError(message);
2713
- }
2714
- const aobject = (value, label) => {
2715
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
2716
- };
2717
- function aexists(instance, checkFinished = true) {
2718
- if (instance.destroyed) throw new Error("hash was destroyed");
2719
- if (checkFinished && instance.finished) throw new Error("digest() was already called");
2720
- }
2721
- function aoutput(out, instance) {
2722
- abytes(out, void 0, "output");
2723
- const min = instance.outputLen;
2724
- if (!(out.length >= min)) throw new RangeError("\"output\" expected length >= " + min);
2725
- }
2726
- function clean(...arrays) {
2727
- for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
2728
- }
2729
- function createView(arr) {
2730
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2731
- }
2732
- function rotr(word, shift) {
2733
- return word << 32 - shift | word >>> shift;
2734
- }
2735
- function rotl(word, shift) {
2736
- return word << shift | word >>> 32 - shift >>> 0;
2737
- }
2738
- const hasHexBuiltin = (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
2739
- const hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
2740
- function bytesToHex(bytes) {
2741
- abytes(bytes);
2742
- if (hasHexBuiltin) return bytes.toHex();
2743
- let hex = "";
2744
- for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
2745
- return hex;
2746
- }
2747
- function checkOpts(defaults, opts, title = "opts") {
2748
- aobject(defaults, "defaults");
2749
- if (opts !== void 0) aobject(opts, title);
2750
- return Object.assign(defaults, opts);
2751
- }
2752
- function createHasher(hashCons, info = {}) {
2753
- if (typeof hashCons !== "function") throw new TypeError("\"hashCons\" expected function, got type=" + typeof hashCons);
2754
- info = checkOpts({}, info, "info");
2755
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
2756
- const tmp = hashCons(void 0);
2757
- hashC.outputLen = tmp.outputLen;
2758
- hashC.blockLen = tmp.blockLen;
2759
- hashC.canXOF = tmp.canXOF;
2760
- hashC.create = (opts) => hashCons(opts);
2761
- Object.assign(hashC, info);
2762
- return Object.freeze(hashC);
2763
- }
2764
- const oidNist = (suffix) => ({ oid: Uint8Array.from([
2765
- 6,
2766
- 9,
2767
- 96,
2768
- 134,
2769
- 72,
2770
- 1,
2771
- 101,
2772
- 3,
2773
- 4,
2774
- 2,
2775
- suffix
2776
- ]) });
2777
- //#endregion
2778
- //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_md.js
2779
- function Chi(a, b, c) {
2780
- return a & b ^ ~a & c;
2781
- }
2782
- function Maj(a, b, c) {
2783
- return a & b ^ a & c ^ b & c;
2784
- }
2785
- var HashMD = class {
2786
- blockLen;
2787
- outputLen;
2788
- canXOF = false;
2789
- padOffset;
2790
- isLE;
2791
- buffer;
2792
- view;
2793
- finished = false;
2794
- length = 0;
2795
- pos = 0;
2796
- destroyed = false;
2797
- constructor(blockLen, outputLen, padOffset, isLE) {
2798
- this.blockLen = blockLen;
2799
- this.outputLen = outputLen;
2800
- this.padOffset = padOffset;
2801
- this.isLE = isLE;
2802
- this.buffer = new Uint8Array(blockLen);
2803
- this.view = createView(this.buffer);
2804
- }
2805
- update(data) {
2806
- aexists(this);
2807
- abytes(data);
2808
- const { view, buffer, blockLen } = this;
2809
- const len = data.length;
2810
- let processed = false;
2811
- for (let pos = 0; pos < len;) {
2812
- const take = Math.min(blockLen - this.pos, len - pos);
2813
- if (take === blockLen) {
2814
- const dataView = createView(data);
2815
- for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
2816
- processed = true;
2817
- continue;
2818
- }
2819
- buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
2820
- this.pos += take;
2821
- pos += take;
2822
- if (this.pos === blockLen) {
2823
- this.process(view, 0);
2824
- this.pos = 0;
2825
- processed = true;
2826
- }
2827
- }
2828
- this.length += data.length;
2829
- if (processed) this.roundClean();
2830
- return this;
2831
- }
2832
- digestInto(out) {
2833
- aexists(this);
2834
- aoutput(out, this);
2835
- this.finished = true;
2836
- const { buffer, view, blockLen, isLE } = this;
2837
- let { pos } = this;
2838
- buffer[pos++] = 128;
2839
- buffer.fill(0, pos);
2840
- if (this.padOffset > blockLen - pos) {
2841
- this.process(view, 0);
2842
- buffer.fill(0);
2843
- }
2844
- setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
2845
- this.process(view, 0);
2846
- this.roundClean();
2847
- const oview = out === buffer ? view : createView(out);
2848
- const len = this.outputLen;
2849
- const outLen = len / 4;
2850
- const state = this.get();
2851
- if (len % 4 || outLen > state.length) throw new Error("invalid outputLen");
2852
- for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
2853
- }
2854
- digest() {
2855
- const { buffer, outputLen } = this;
2856
- this.digestInto(buffer);
2857
- const res = buffer.slice(0, outputLen);
2858
- this.destroy();
2859
- return res;
2860
- }
2861
- _cloneIntoMeta(to) {
2862
- const { buffer, length, finished, destroyed, pos } = this;
2863
- to.destroyed = destroyed;
2864
- to.finished = finished;
2865
- to.length = length;
2866
- to.pos = pos;
2867
- if (pos) to.buffer.set(buffer);
2868
- return to;
2869
- }
2870
- clone() {
2871
- return this._cloneInto();
2872
- }
2873
- };
2874
- const SHA256_IV = Uint32Array.from([
2875
- 1779033703,
2876
- 3144134277,
2877
- 1013904242,
2878
- 2773480762,
2879
- 1359893119,
2880
- 2600822924,
2881
- 528734635,
2882
- 1541459225
2883
- ]);
2884
- //#endregion
2885
- //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/sha2.js
2886
- const SHA256_K = Uint32Array.from([
2887
- 1116352408,
2888
- 1899447441,
2889
- 3049323471,
2890
- 3921009573,
2891
- 961987163,
2892
- 1508970993,
2893
- 2453635748,
2894
- 2870763221,
2895
- 3624381080,
2896
- 310598401,
2897
- 607225278,
2898
- 1426881987,
2899
- 1925078388,
2900
- 2162078206,
2901
- 2614888103,
2902
- 3248222580,
2903
- 3835390401,
2904
- 4022224774,
2905
- 264347078,
2906
- 604807628,
2907
- 770255983,
2908
- 1249150122,
2909
- 1555081692,
2910
- 1996064986,
2911
- 2554220882,
2912
- 2821834349,
2913
- 2952996808,
2914
- 3210313671,
2915
- 3336571891,
2916
- 3584528711,
2917
- 113926993,
2918
- 338241895,
2919
- 666307205,
2920
- 773529912,
2921
- 1294757372,
2922
- 1396182291,
2923
- 1695183700,
2924
- 1986661051,
2925
- 2177026350,
2926
- 2456956037,
2927
- 2730485921,
2928
- 2820302411,
2929
- 3259730800,
2930
- 3345764771,
2931
- 3516065817,
2932
- 3600352804,
2933
- 4094571909,
2934
- 275423344,
2935
- 430227734,
2936
- 506948616,
2937
- 659060556,
2938
- 883997877,
2939
- 958139571,
2940
- 1322822218,
2941
- 1537002063,
2942
- 1747873779,
2943
- 1955562222,
2944
- 2024104815,
2945
- 2227730452,
2946
- 2361852424,
2947
- 2428436474,
2948
- 2756734187,
2949
- 3204031479,
2950
- 3329325298
2951
- ]);
2952
- const SHA256_W = new Uint32Array(64);
2953
- var SHA2_32B = class extends HashMD {
2954
- A = 0;
2955
- B = 0;
2956
- C = 0;
2957
- D = 0;
2958
- E = 0;
2959
- F = 0;
2960
- G = 0;
2961
- H = 0;
2962
- constructor(outputLen, IV) {
2963
- super(64, outputLen, 8, false);
2964
- this.A = IV[0] | 0;
2965
- this.B = IV[1] | 0;
2966
- this.C = IV[2] | 0;
2967
- this.D = IV[3] | 0;
2968
- this.E = IV[4] | 0;
2969
- this.F = IV[5] | 0;
2970
- this.G = IV[6] | 0;
2971
- this.H = IV[7] | 0;
2972
- }
2973
- get() {
2974
- const { A, B, C, D, E, F, G, H } = this;
2975
- return [
2976
- A,
2977
- B,
2978
- C,
2979
- D,
2980
- E,
2981
- F,
2982
- G,
2983
- H
2984
- ];
2985
- }
2986
- set(A, B, C, D, E, F, G, H) {
2987
- this.A = A | 0;
2988
- this.B = B | 0;
2989
- this.C = C | 0;
2990
- this.D = D | 0;
2991
- this.E = E | 0;
2992
- this.F = F | 0;
2993
- this.G = G | 0;
2994
- this.H = H | 0;
2995
- }
2996
- _cloneInto(to) {
2997
- (to ||= new this.constructor()).set(...this.get());
2998
- return this._cloneIntoMeta(to);
2999
- }
3000
- process(view, offset) {
3001
- for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
3002
- for (let i = 16; i < 64; i++) {
3003
- const W15 = SHA256_W[i - 15];
3004
- const W2 = SHA256_W[i - 2];
3005
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
3006
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
3007
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
3008
- }
3009
- let { A, B, C, D, E, F, G, H } = this;
3010
- for (let i = 0; i < 64; i++) {
3011
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
3012
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
3013
- const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
3014
- H = G;
3015
- G = F;
3016
- F = E;
3017
- E = D + T1 | 0;
3018
- D = C;
3019
- C = B;
3020
- B = A;
3021
- A = T1 + T2 | 0;
3022
- }
3023
- A = A + this.A | 0;
3024
- B = B + this.B | 0;
3025
- C = C + this.C | 0;
3026
- D = D + this.D | 0;
3027
- E = E + this.E | 0;
3028
- F = F + this.F | 0;
3029
- G = G + this.G | 0;
3030
- H = H + this.H | 0;
3031
- this.set(A, B, C, D, E, F, G, H);
3032
- }
3033
- roundClean() {
3034
- clean(SHA256_W);
3035
- }
3036
- destroy() {
3037
- this.destroyed = true;
3038
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
3039
- clean(this.buffer);
3040
- }
3041
- };
3042
- var _SHA256 = class extends SHA2_32B {
3043
- constructor() {
3044
- super(32, SHA256_IV);
3045
- }
3046
- };
3047
- const sha256 = createHasher(() => new _SHA256(), oidNist(1));
3048
- //#endregion
3049
- //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/legacy.js
3050
- const SHA1_IV = Uint32Array.from([
3051
- 1732584193,
3052
- 4023233417,
3053
- 2562383102,
3054
- 271733878,
3055
- 3285377520
3056
- ]);
3057
- const p32 = Math.pow(2, 32);
3058
- const K = Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
3059
- const MD5_IV = SHA1_IV.slice(0, 4);
3060
- const MD5_W = new Uint32Array(16);
3061
- const MD5_SHIFTS = (() => {
3062
- const S = [
3063
- [
3064
- 7,
3065
- 12,
3066
- 17,
3067
- 22
3068
- ],
3069
- [
3070
- 5,
3071
- 9,
3072
- 14,
3073
- 20
3074
- ],
3075
- [
3076
- 4,
3077
- 11,
3078
- 16,
3079
- 23
3080
- ],
3081
- [
3082
- 6,
3083
- 10,
3084
- 15,
3085
- 21
3086
- ]
3087
- ];
3088
- return Uint8Array.from({ length: 64 }, (_, i) => S[Math.floor(i / 16)][i % 4]);
3089
- })();
3090
- var _MD5 = class extends HashMD {
3091
- A = MD5_IV[0] | 0;
3092
- B = MD5_IV[1] | 0;
3093
- C = MD5_IV[2] | 0;
3094
- D = MD5_IV[3] | 0;
3095
- constructor() {
3096
- super(64, 16, 8, true);
3097
- }
3098
- get() {
3099
- const { A, B, C, D } = this;
3100
- return [
3101
- A,
3102
- B,
3103
- C,
3104
- D
3105
- ];
3106
- }
3107
- set(A, B, C, D) {
3108
- this.A = A | 0;
3109
- this.B = B | 0;
3110
- this.C = C | 0;
3111
- this.D = D | 0;
3112
- }
3113
- _cloneInto(to) {
3114
- (to ||= new this.constructor()).set(...this.get());
3115
- return this._cloneIntoMeta(to);
3116
- }
3117
- process(view, offset) {
3118
- for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);
3119
- let { A, B, C, D } = this;
3120
- for (let i = 0; i < 64; i++) {
3121
- let F, g;
3122
- if (i < 16) {
3123
- F = Chi(B, C, D);
3124
- g = i;
3125
- } else if (i < 32) {
3126
- F = Chi(D, B, C);
3127
- g = (5 * i + 1) % 16;
3128
- } else if (i < 48) {
3129
- F = B ^ C ^ D;
3130
- g = (3 * i + 5) % 16;
3131
- } else {
3132
- F = C ^ (B | ~D);
3133
- g = 7 * i % 16;
3134
- }
3135
- F = F + A + K[i] + MD5_W[g];
3136
- A = D;
3137
- D = C;
3138
- C = B;
3139
- B = B + rotl(F, MD5_SHIFTS[i]);
3140
- }
3141
- A = A + this.A | 0;
3142
- B = B + this.B | 0;
3143
- C = C + this.C | 0;
3144
- D = D + this.D | 0;
3145
- this.set(A, B, C, D);
3146
- }
3147
- roundClean() {
3148
- clean(MD5_W);
3149
- }
3150
- destroy() {
3151
- this.destroyed = true;
3152
- this.set(0, 0, 0, 0);
3153
- clean(this.buffer);
3154
- }
3155
- };
3156
- const md5 = createHasher(() => new _MD5());
3157
- //#endregion
3158
- //#region src/internal/client/upload.ts
3159
- const UPLOAD_PART_BYTE_LENGTH = 32 * 1024 * 1024;
3160
- const STATUS_PAGE_LIMIT = 100;
3161
- const STATUS_PAGE_MAXIMUM = 100;
3162
- const ABORT_DEADLINE_MILLISECONDS = 5e3;
3163
- async function uploadFileInternal(runtime, input, controls) {
3164
- const validated = validateUploadFileInput(input);
3165
- const totalPartCount = Math.ceil(validated.byteLength / UPLOAD_PART_BYTE_LENGTH);
3166
- emitProgress(validated.onProgress, "preparing", 0, validated.byteLength, 0, totalPartCount);
3167
- let session;
3168
- try {
3169
- const digests = await hashSource(validated.source, validated.byteLength, totalPartCount, validated.signal);
3170
- const created = await controls.createUpload({
3171
- workspaceId: validated.workspaceId,
3172
- parentItemId: validated.parentItemId,
3173
- expectedByteLength: validated.byteLength,
3174
- displayFilename: validated.displayFilename,
3175
- mediaType: validated.mediaType,
3176
- callerDeclaredContentDigest: digests.callerDeclaredContentDigest,
3177
- protectionClassification: validated.protectionClassification,
3178
- idempotencyKey: validated.idempotencyKey,
3179
- ...validated.signal === void 0 ? {} : { signal: validated.signal }
3180
- });
3181
- session = created.data;
3182
- assertSessionPolicy(session, validated.byteLength, totalPartCount, created.status, created.requestId);
3183
- const resumed = await readResumeState(controls, validated, session, digests);
3184
- emitProgress(validated.onProgress, "uploading", resumed.confirmedByteLength, validated.byteLength, resumed.confirmedParts.size, totalPartCount);
3185
- if (resumed.readyResult) {
3186
- emitProgress(validated.onProgress, "completing", resumed.confirmedByteLength, validated.byteLength, resumed.confirmedParts.size, totalPartCount);
3187
- return resumed.readyResult;
3188
- }
3189
- let revision = resumed.revision;
3190
- let confirmedByteLength = resumed.confirmedByteLength;
3191
- let confirmedPartCount = resumed.confirmedParts.size;
3192
- if (resumed.lifecycle === "uploading") for (const partNumber of pendingUploadPartNumbers(session.partCount, resumed.confirmedParts)) {
3193
- const index = partNumber - 1;
3194
- throwIfCallerAborted(validated.signal);
3195
- const start = index * session.partByteLength;
3196
- const end = Math.min(start + session.partByteLength, validated.byteLength);
3197
- const expectedByteLength = end - start;
3198
- const checksumSha256 = digests.partChecksums[index];
3199
- if (!checksumSha256) throw new DriveError("invalid_response");
3200
- const descriptorResult = await controls.createUploadPartDescriptor({
3201
- workspaceId: validated.workspaceId,
3202
- uploadId: session.uploadId,
3203
- partNumber,
3204
- checksumSha256,
3205
- contentMd5: digests.partMd5s[index],
3206
- ...validated.signal === void 0 ? {} : { signal: validated.signal }
3207
- });
3208
- const descriptor = descriptorResult.data;
3209
- if (descriptor.expectedByteLength !== expectedByteLength || descriptor.expiresAtEpochMilliseconds > session.expiresAtEpochMilliseconds) throw new DriveError("invalid_response", {
3210
- status: descriptorResult.status,
3211
- requestId: descriptorResult.requestId
3212
- });
3213
- const etag = await putPart(runtime, descriptor, slicePart(validated.source, start, end, expectedByteLength), validated.signal);
3214
- revision = await recordPartWithReconciliation(controls, validated, session, partNumber, revision, expectedByteLength, etag, checksumSha256);
3215
- confirmedByteLength += expectedByteLength;
3216
- confirmedPartCount += 1;
3217
- emitProgress(validated.onProgress, "uploading", confirmedByteLength, validated.byteLength, confirmedPartCount, totalPartCount);
3218
- }
3219
- emitProgress(validated.onProgress, "completing", confirmedByteLength, validated.byteLength, confirmedPartCount, totalPartCount);
3220
- const completed = await completeWithReconciliation(controls, validated, session, digests);
3221
- if (completed.data.state === "verifying") emitProgress(validated.onProgress, "verifying", confirmedByteLength, validated.byteLength, confirmedPartCount, totalPartCount);
3222
- return completed;
3223
- } catch (error) {
3224
- if (validated.signal?.aborted && session) await bestEffortAbort(controls, validated.workspaceId, session.uploadId);
3225
- if (error instanceof DriveError) throw error;
3226
- throw validated.signal?.aborted ? new DriveError("aborted") : new DriveError("invalid_input");
3227
- }
3228
- }
3229
- function* pendingUploadPartNumbers(partCount, confirmedParts) {
3230
- for (let partNumber = 1; partNumber <= partCount; partNumber += 1) if (!confirmedParts.has(partNumber)) yield partNumber;
3231
- }
3232
- async function readResumeState(controls, input, session, digests) {
3233
- const confirmedParts = new Set();
3234
- let confirmedByteLength = 0;
3235
- let afterPartNumber = 0;
3236
- let baseline;
3237
- let baselineRequestId;
3238
- let readyResult;
3239
- for (let pageNumber = 0; pageNumber < STATUS_PAGE_MAXIMUM; pageNumber += 1) {
3240
- const result = await controls.getUploadStatus({
3241
- workspaceId: input.workspaceId,
3242
- uploadId: session.uploadId,
3243
- afterPartNumber,
3244
- limit: STATUS_PAGE_LIMIT,
3245
- ...input.signal === void 0 ? {} : { signal: input.signal }
3246
- });
3247
- const status = result.data;
3248
- assertStatusMatchesSession(status, session);
3249
- if (baseline) assertSameStatusSnapshot(status, baseline);
3250
- else {
3251
- baseline = status;
3252
- baselineRequestId = result.requestId;
3253
- }
3254
- for (const part of status.confirmedParts) {
3255
- const expectedChecksum = digests.partChecksums[part.partNumber - 1];
3256
- if (!expectedChecksum || part.checksumSha256 !== expectedChecksum || confirmedParts.has(part.partNumber)) throw new DriveError("invalid_response", {
3257
- status: result.status,
3258
- requestId: result.requestId
3259
- });
3260
- confirmedParts.add(part.partNumber);
3261
- confirmedByteLength += expectedPartByteLength(input.byteLength, part.partNumber);
3262
- }
3263
- if (status.lifecycle === "ready" && status.ready) {
3264
- assertReadyMatchesInput(status.ready, session, input, digests, result.requestId);
3265
- readyResult = resultFromStatus(result, status.ready);
3266
- }
3267
- if (status.nextAfterPartNumber === null) break;
3268
- if (pageNumber === STATUS_PAGE_MAXIMUM - 1) throw new DriveError("invalid_response", {
3269
- status: result.status,
3270
- requestId: result.requestId
3271
- });
3272
- afterPartNumber = status.nextAfterPartNumber;
3273
- }
3274
- if (!baseline) throw new DriveError("invalid_response");
3275
- if (session.mode === "presigned-multipart" && [
3276
- "completing",
3277
- "provider-completed",
3278
- "verifying",
3279
- "ready"
3280
- ].includes(baseline.lifecycle) && confirmedParts.size !== session.partCount) throw new DriveError("invalid_response");
3281
- failForTerminalStatus(baseline.lifecycle, baselineRequestId);
3282
- return Object.freeze({
3283
- revision: baseline.revision,
3284
- confirmedParts,
3285
- confirmedByteLength,
3286
- lifecycle: baseline.lifecycle,
3287
- ...readyResult === void 0 ? {} : { readyResult }
3288
- });
3289
- }
3290
- async function recordPartWithReconciliation(controls, input, session, partNumber, expectedUploadRevision, byteLength, etag, checksumSha256) {
3291
- const record = (revision) => controls.recordUploadPart({
3292
- workspaceId: input.workspaceId,
3293
- uploadId: session.uploadId,
3294
- partNumber,
3295
- expectedUploadRevision: revision,
3296
- byteLength,
3297
- etag,
3298
- checksumSha256,
3299
- ...input.signal === void 0 ? {} : { signal: input.signal }
3300
- });
3301
- try {
3302
- return (await record(expectedUploadRevision)).data.revision;
3303
- } catch (error) {
3304
- if (!isAmbiguousControlFailure(error) || input.signal?.aborted) throw error;
3305
- const statusResult = await controls.getUploadStatus({
3306
- workspaceId: input.workspaceId,
3307
- uploadId: session.uploadId,
3308
- afterPartNumber: partNumber - 1,
3309
- limit: 1,
3310
- ...input.signal === void 0 ? {} : { signal: input.signal }
3311
- });
3312
- const status = statusResult.data;
3313
- assertStatusMatchesSession(status, session);
3314
- failForTerminalStatus(status.lifecycle, statusResult.requestId);
3315
- const confirmed = status.confirmedParts.find((part) => part.partNumber === partNumber);
3316
- if (confirmed) {
3317
- if (confirmed.checksumSha256 !== checksumSha256) throw new DriveError("invalid_response", {
3318
- status: statusResult.status,
3319
- requestId: statusResult.requestId
3320
- });
3321
- return status.revision;
3322
- }
3323
- if (status.lifecycle !== "uploading") throw new DriveError("precondition_failed");
3324
- return (await record(status.revision)).data.revision;
3325
- }
3326
- }
3327
- async function completeWithReconciliation(controls, input, session, digests) {
3328
- try {
3329
- const completed = await controls.completeUpload({
3330
- workspaceId: input.workspaceId,
3331
- uploadId: session.uploadId,
3332
- idempotencyKey: input.completionIdempotencyKey,
3333
- ...input.signal === void 0 ? {} : { signal: input.signal }
3334
- });
3335
- if (completed.data.state === "ready") assertReadyMatchesInput(completed.data, session, input, digests, completed.requestId);
3336
- else if (completed.data.itemId !== session.itemId || completed.data.versionId !== session.versionId || completed.data.uploadId !== session.uploadId || completed.data.totalByteLength !== input.byteLength) throw new DriveError("invalid_response");
3337
- return completed;
3338
- } catch (error) {
3339
- if (!isAmbiguousControlFailure(error) || input.signal?.aborted) throw error;
3340
- const statusResult = await controls.getUploadStatus({
3341
- workspaceId: input.workspaceId,
3342
- uploadId: session.uploadId,
3343
- afterPartNumber: 0,
3344
- limit: 1,
3345
- ...input.signal === void 0 ? {} : { signal: input.signal }
3346
- });
3347
- const status = statusResult.data;
3348
- assertStatusMatchesSession(status, session);
3349
- if (status.lifecycle !== "ready" || !status.ready) throw error;
3350
- assertReadyMatchesInput(status.ready, session, input, digests, statusResult.requestId);
3351
- return resultFromStatus(statusResult, status.ready);
3352
- }
3353
- }
3354
- async function hashSource(source, byteLength, partCount, signal) {
3355
- const fullHash = sha256.create();
3356
- const partChecksums = [];
3357
- const partMd5s = [];
3358
- for (let index = 0; index < partCount; index += 1) {
3359
- throwIfCallerAborted(signal);
3360
- const start = index * UPLOAD_PART_BYTE_LENGTH;
3361
- const end = Math.min(start + UPLOAD_PART_BYTE_LENGTH, byteLength);
3362
- const part = slicePart(source, start, end, end - start);
3363
- let buffer;
3364
- try {
3365
- buffer = signal ? await raceWithAbort(part.arrayBuffer(), signal) : await part.arrayBuffer();
3366
- } catch (error) {
3367
- if (error instanceof DriveError) throw error;
3368
- throw signal?.aborted ? new DriveError("aborted") : new DriveError("invalid_input");
3369
- }
3370
- if (buffer.byteLength !== end - start) throw new DriveError("invalid_input");
3371
- const bytes = new Uint8Array(buffer);
3372
- fullHash.update(bytes);
3373
- partChecksums.push(toBase64(sha256(bytes)));
3374
- partMd5s.push(toBase64(md5(bytes)));
3375
- }
3376
- return Object.freeze({
3377
- callerDeclaredContentDigest: `sha256:${bytesToHex(fullHash.digest())}`,
3378
- partChecksums: Object.freeze(partChecksums),
3379
- partMd5s: Object.freeze(partMd5s)
3380
- });
3381
- }
3382
- async function putPart(runtime, descriptor, part, callerSignal) {
3383
- const remainingMilliseconds = descriptor.expiresAtEpochMilliseconds - Date.now();
3384
- if (remainingMilliseconds < 1) throw new DriveError("invalid_response");
3385
- const operation = createOperationSignal(callerSignal, Math.min(runtime.timeoutMilliseconds, remainingMilliseconds));
3386
- let response;
3387
- try {
3388
- response = await raceWithAbort(runtime.fetchImplementation(descriptor.url, {
3389
- method: descriptor.method,
3390
- body: part,
3391
- headers: descriptor.headers,
3392
- credentials: "omit",
3393
- cache: "no-store",
3394
- redirect: "error",
3395
- referrerPolicy: "no-referrer",
3396
- signal: operation.signal
3397
- }), operation.signal);
3398
- if (!(response instanceof Response)) throw new DriveError("invalid_response");
3399
- const etag = response.headers.get("etag");
3400
- const md5Response = response.headers.get("content-md5");
3401
- const checksumMatches = md5Response === null || md5Response === descriptor.headers["content-md5"];
3402
- if (response.status < 200 || response.status > 299 || !isEtag(etag) || !checksumMatches) throw new DriveError("invalid_response", { status: response.status });
3403
- return etag;
3404
- } catch (error) {
3405
- if (operation.didTimeout()) throw new DriveError("timeout");
3406
- if (callerSignal?.aborted) throw new DriveError("aborted");
3407
- if (error instanceof DriveError) throw error;
3408
- throw new DriveError("network_error");
3409
- } finally {
3410
- operation.dispose();
3411
- response?.body?.cancel().catch(() => {});
3412
- }
3413
- }
3414
- function assertSessionPolicy(session, byteLength, partCount, status, requestId) {
3415
- const expectedMode = byteLength === 0 ? "server-mediated-zero-byte" : "presigned-multipart";
3416
- if (session.mode !== expectedMode || session.partByteLength !== UPLOAD_PART_BYTE_LENGTH || session.partCount !== partCount || session.expiresAtEpochMilliseconds <= Date.now()) throw new DriveError("invalid_response", {
3417
- status,
3418
- requestId
3419
- });
3420
- }
3421
- function assertStatusMatchesSession(status, session) {
3422
- if (status.itemId !== session.itemId || status.versionId !== session.versionId || status.uploadId !== session.uploadId || status.mode !== session.mode || status.revision < session.revision || status.partPolicy.partByteLength !== session.partByteLength || status.partPolicy.partCount !== session.partCount || status.partPolicy.maxParts !== 1e4 || status.expiresAtEpochMilliseconds !== session.expiresAtEpochMilliseconds) throw new DriveError("invalid_response");
3423
- }
3424
- function assertSameStatusSnapshot(status, baseline) {
3425
- if (status.itemId !== baseline.itemId || status.versionId !== baseline.versionId || status.uploadId !== baseline.uploadId || status.mode !== baseline.mode || status.lifecycle !== baseline.lifecycle || status.revision !== baseline.revision || status.partPolicy.partByteLength !== baseline.partPolicy.partByteLength || status.partPolicy.partCount !== baseline.partPolicy.partCount || status.partPolicy.maxParts !== baseline.partPolicy.maxParts || status.expiresAtEpochMilliseconds !== baseline.expiresAtEpochMilliseconds || JSON.stringify(status.ready) !== JSON.stringify(baseline.ready)) throw new DriveError("invalid_response");
3426
- }
3427
- function assertReadyMatchesInput(ready, session, input, digests, requestId) {
3428
- if (ready.itemId !== session.itemId || ready.versionId !== session.versionId || ready.uploadId !== session.uploadId || ready.byteLength !== input.byteLength || ready.callerDeclaredContentDigest !== digests.callerDeclaredContentDigest || ready.displayFilename !== input.displayFilename || ready.mediaType !== input.mediaType) throw new DriveError("invalid_response", {
3429
- status: 200,
3430
- requestId
3431
- });
3432
- }
3433
- function failForTerminalStatus(lifecycle, requestId) {
3434
- if (lifecycle === "initiating" || lifecycle === "recovery-required") throw new DriveError("upload_recovery_required", {
3435
- status: 409,
3436
- ...requestId === void 0 ? {} : { requestId }
3437
- });
3438
- if (lifecycle === "aborting" || lifecycle === "aborted" || lifecycle === "failed") throw new DriveError("precondition_failed", {
3439
- status: 409,
3440
- ...requestId === void 0 ? {} : { requestId }
3441
- });
3442
- }
3443
- function resultFromStatus(status, ready) {
3444
- return Object.freeze({
3445
- data: ready,
3446
- status: status.status,
3447
- requestId: status.requestId,
3448
- validators: status.validators
3449
- });
3450
- }
3451
- function expectedPartByteLength(byteLength, partNumber) {
3452
- return Math.min(UPLOAD_PART_BYTE_LENGTH, byteLength - (partNumber - 1) * UPLOAD_PART_BYTE_LENGTH);
3453
- }
3454
- function slicePart(source, start, end, expectedByteLength) {
3455
- try {
3456
- const part = source.slice(start, end);
3457
- if (!(part instanceof Blob) || part.size !== expectedByteLength) throw new DriveError("invalid_input");
3458
- return part;
3459
- } catch (error) {
3460
- if (error instanceof DriveError) throw error;
3461
- throw new DriveError("invalid_input");
3462
- }
3463
- }
3464
- function emitProgress(callback, phase, confirmedByteLength, totalByteLength, confirmedPartCount, totalPartCount) {
3465
- if (!callback) return;
3466
- const progress = Object.freeze({
3467
- phase,
3468
- confirmedByteLength,
3469
- totalByteLength,
3470
- confirmedPartCount,
3471
- totalPartCount
3472
- });
3473
- try {
3474
- callback(progress);
3475
- } catch {}
3476
- }
3477
- async function bestEffortAbort(controls, workspaceId, uploadId) {
3478
- const controller = new AbortController();
3479
- const timeout = setTimeout(() => controller.abort(), ABORT_DEADLINE_MILLISECONDS);
3480
- try {
3481
- await controls.abortUpload({
3482
- workspaceId,
3483
- uploadId,
3484
- signal: controller.signal
3485
- });
3486
- } catch {} finally {
3487
- clearTimeout(timeout);
3488
- }
3489
- }
3490
- function isAmbiguousControlFailure(value) {
3491
- return value instanceof DriveError && (value.code === "network_error" || value.code === "timeout" || value.code === "invalid_response");
3492
- }
3493
- function throwIfCallerAborted(signal) {
3494
- if (signal?.aborted) throw new DriveError("aborted");
3495
- }
3496
- function toBase64(bytes) {
3497
- let binary = "";
3498
- for (const byte of bytes) binary += String.fromCharCode(byte);
3499
- return btoa(binary);
3500
- }
3501
- function isEtag(value) {
3502
- return value !== null && value.length >= 1 && value.length <= 1024 && /^[\x20-\x7e]+$/.test(value);
3503
- }
3504
- //#endregion
3505
- //#region src/client.ts
3506
- function createDriveClient(config) {
3507
- const runtime = createClientRuntime(config);
3508
- const operations = createDriveOperations(runtime);
3509
- return Object.freeze({
3510
- ...operations,
3511
- uploadFile: (input) => uploadFileInternal(runtime, input, operations)
3512
- });
3513
- }
3514
- //#endregion
3515
- export { DRIVE_API_ERROR_CODES, DRIVE_API_ERROR_MESSAGES, DriveError, createDriveClient };
1
+ const e=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`recipient_unavailable`,`rate_limited`,`permission_denied`,`resource_not_found`,`invalid_request`,`invalid_pagination_cursor`,`invalid_idempotency_key`,`precondition_failed`,`range_not_satisfiable`,`idempotency_conflict`,`quota_exceeded`,`upload_recovery_required`,`service_unavailable`,`internal_error`]),t=Object.freeze({authentication_required:`Authentication is required.`,identity_authority_unavailable:`Authentication is temporarily unavailable.`,recipient_unavailable:`The recipient is unavailable.`,rate_limited:`Too many requests.`,permission_denied:`The requested action is not permitted.`,resource_not_found:`The requested resource was not found.`,invalid_request:`The request is invalid.`,invalid_pagination_cursor:`The pagination cursor is invalid.`,invalid_idempotency_key:`The idempotency key is invalid.`,precondition_failed:`The request precondition failed.`,range_not_satisfiable:`The requested byte range is not satisfiable.`,idempotency_conflict:`The idempotency key conflicts with an earlier request.`,quota_exceeded:`The workspace storage quota would be exceeded.`,upload_recovery_required:`The upload requires recovery before it can continue.`,service_unavailable:`The service is temporarily unavailable.`,internal_error:`The request could not be completed.`}),n=Object.freeze({invalid_input:`The Drive SDK input is invalid.`,credential_unavailable:`A Drive credential could not be obtained.`,network_error:`The Drive request could not reach the service.`,timeout:`The Drive request timed out.`,aborted:`The Drive request was aborted.`,invalid_response:`Drive returned an invalid response.`});var r=class extends Error{code;status;requestId;details;constructor(e,r={}){super(e in t?t[e]:n[e]),this.name=`DriveError`,this.code=e,this.status=r.status??null,this.requestId=r.requestId??null,this.details=Object.freeze({})}};const i=/^[A-Za-z0-9_-]{16,128}$/,a=/^"drive\.permission-collection\.v1\.(0|[1-9][0-9]*)"$/,o=/^"drive\.permission-grant\.v1\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"$/,s=/^"drive\.permission-list\.v1\.[0-9a-f]{64}"$/,c=/^"drive\.item\.v1\.(0|[1-9][0-9]*)"$/;async function l(e,t,n,i,a,o,s){let c=ee(e.headers.get(`x-request-id`));if(c===null)throw v(e),new r(`invalid_response`,{status:e.status});if(!i.includes(e.status))throw await m(e,c,t,n,o,s);if(e.status===304){let t=e.headers.get(`content-length`),n=e.headers.get(`etag`),i=e.status;if(e.body!==null||t!==null&&t!==`0`||e.headers.has(`content-type`)||n===null||!/^"[\x21\x23-\x7e]{1,1022}"$/.test(n)||!a(void 0,i,e.headers))throw v(e),new r(`invalid_response`,{status:i,requestId:c});return Object.freeze({data:void 0,status:i,requestId:c,validators:Object.freeze({etag:n})})}let{value:l}=await g(e,262144,e.status,c,t),u=e.status;if(!a(l,u,e.headers))throw new r(`invalid_response`,{status:u,requestId:c});return Object.freeze({data:l,status:u,requestId:c,validators:te(e.headers)})}async function u(e,t,n,i,a){let o=ee(e.headers.get(`x-request-id`));if(o===null)throw v(e),new r(`invalid_response`,{status:e.status});if(!i.includes(e.status))throw await m(e,o,t,n,!1,a);let s=e.headers.get(`content-length`);if(e.body!==null||s!==null&&s!==`0`||e.headers.has(`content-type`))throw v(e),new r(`invalid_response`,{status:e.status,requestId:o});return Object.freeze({data:void 0,status:e.status,requestId:o,validators:Object.freeze({})})}function d(e){let t=a.exec(e);if(!t)return;let n=Number(t[1]);return Number.isSafeInteger(n)?n:void 0}function f(e){let t=o.exec(e);if(!t)return;let n=Number(t[1]),r=Number(t[2]);return Number.isSafeInteger(n)&&Number.isSafeInteger(r)?[n,r]:void 0}function p(e){let t=c.exec(e);if(!t)return;let n=Number(t[1]);return Number.isSafeInteger(n)?n:void 0}async function m(n,a,o,s,c,l){let u;try{u=await g(n,16384,n.status,a,o)}catch(e){return e instanceof r&&e.code===`aborted`?e:new r(`invalid_response`,{status:n.status,requestId:a})}let d=u.value;if(!y(d,[`error`])||!y(d.error,[`code`,`message`,`requestId`,`details`]))return new r(`invalid_response`,{status:n.status,requestId:a});let f=d.error;return typeof f.code!=`string`||!e.includes(f.code)||f.message!==t[f.code]||!i.test(String(f.requestId))||f.requestId!==a||!y(f.details,[])||!h(f.code,n.status,s,c,l)||u.text!==JSON.stringify(d)?new r(`invalid_response`,{status:n.status,requestId:a}):new r(f.code,{status:n.status,requestId:f.requestId})}function h(e,t,n,r,i){return i&&!i.includes(e)||e===`quota_exceeded`&&!r?!1:{authentication_required:[401],identity_authority_unavailable:[503],recipient_unavailable:[404],rate_limited:[429],permission_denied:[403],resource_not_found:[404],invalid_request:[422],invalid_pagination_cursor:[422],invalid_idempotency_key:[422],precondition_failed:n===null?[]:[n],range_not_satisfiable:[416],idempotency_conflict:[409],quota_exceeded:[409],upload_recovery_required:[409],service_unavailable:[503],internal_error:[500]}[e].includes(t)}async function g(e,t,n,i,a){if(!e.body)throw new r(`invalid_response`,{status:n,requestId:i});let o=e.body.getReader(),s=new TextDecoder(`utf-8`,{fatal:!0}),c=0,l=0,u=``,d=e.headers.get(`content-length`);if(d!==null&&(!/^(?:0|[1-9][0-9]*)$/.test(d)||Number(d)>t))throw o.cancel().catch(()=>{}),new r(`invalid_response`,{status:n,requestId:i});let f=new AbortController,p=setTimeout(()=>f.abort(),5e3);try{for(;;){if(a?.aborted)throw new r(`aborted`);let{done:e,value:d}=await _(o,a,f.signal);if(e)break;if(l+=1,c+=d.byteLength,l>256||c>t)throw new r(`invalid_response`,{status:n,requestId:i});u+=s.decode(d,{stream:!0})}return u+=s.decode(),{value:JSON.parse(u),text:u}}catch(e){throw e instanceof r?e.code===`aborted`||a?.aborted?new r(`aborted`):e:new r(`invalid_response`,{status:n,requestId:i})}finally{clearTimeout(p),o.cancel().catch(()=>{})}}async function _(e,t,n){if(t?.aborted)throw new r(`aborted`);if(n.aborted)throw new r(`invalid_response`);let i=()=>{},a=()=>{},o=new Promise((e,n)=>{if(!t)return;let a=()=>n(new r(`aborted`));t.addEventListener(`abort`,a,{once:!0}),i=()=>t.removeEventListener(`abort`,a)}),s=new Promise((e,t)=>{let i=()=>t(new r(`invalid_response`));n.addEventListener(`abort`,i,{once:!0}),a=()=>n.removeEventListener(`abort`,i)});try{return await Promise.race([e.read(),o,s])}finally{i(),a()}}function v(e){e.body?.cancel().catch(()=>{})}function ee(e){return e!==null&&i.test(e)?e:null}function te(e){let t=e.get(`etag`),n=e.get(`drive-permission-collection-etag`),r=e.get(`drive-permission-grant-etag`);return Object.freeze({...t!==null&&(s.test(t)||p(t)!==void 0)?{etag:t}:{},...n!==null&&d(n)!==void 0?{permissionCollectionEtag:n}:{},...r!==null&&f(r)!==void 0?{permissionGrantEtag:r}:{}})}function y(e,t){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}const b=/^drive\.item\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,x=/^drive\.workspace\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,S=/^drive\.volume\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,C=/^drive\.grant\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ne=/^drive\.upload\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,w=/^drive\.version\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,re=/^drive\.retrieval\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,T=/^drive\.cursor\.v1\.[A-Za-z0-9_-]+$/,E=/^[A-Za-z0-9_-]{1,128}$/,D=/^"drive\.permission-grant\.v1\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"$/,O=/^"drive\.permission-list\.v1\.[0-9a-f]{64}"$/,k=Object.freeze([`items:content:read`,`items:create`,`items:delete`,`items:metadata:read`,`items:permissions:read`,`items:update`]),A=Object.freeze([`items:content:read`,`items:create`,`items:delete`,`items:metadata:read`,`items:permissions:manage`,`items:permissions:read`,`items:update`]),j=33554432e4,M=32*1024*1024,ie=/^sha256:[0-9a-f]{64}$/,ae=new TextEncoder;function oe(e){if(!I(e,[`items`,`nextCursor`])||!Array.isArray(e.items)||e.items.length>50||e.nextCursor!==null&&(typeof e.nextCursor!=`string`||e.nextCursor.length<1||e.nextCursor.length>2048||!/^[A-Za-z0-9_.-]+$/.test(e.nextCursor))||e.items.length===0&&e.nextCursor!==null)return!1;let t=``;for(let n of e.items){if(!I(n,[`workspaceId`,`itemId`])||typeof n.workspaceId!=`string`||!x.test(n.workspaceId)||typeof n.itemId!=`string`||!b.test(n.itemId))return!1;let e=`${n.workspaceId}/${n.itemId}`;if(t&&t>=e)return!1;t=e}return!0}function se(e){if(!I(e,[`workspaceId`,`provider`,`usedBytes`,`reservedBytes`,`limitBytes`,`availableBytes`,`accounting`,`reservedBytesIncludeUnresolvedUploads`,`unresolvedReservedBytes`,`warnings`])||typeof e.workspaceId!=`string`||!x.test(e.workspaceId)||e.provider!==`managed`||e.accounting!==`current-versions-and-reservations`||e.reservedBytesIncludeUnresolvedUploads!==!0||!Array.isArray(e.warnings)||e.warnings.length>1||e.warnings.some(e=>e!==`unresolved-archive-ownership`)||![e.usedBytes,e.reservedBytes,e.limitBytes,e.availableBytes,e.unresolvedReservedBytes].every(e=>typeof e==`string`&&/^(0|[1-9][0-9]{0,18})$/.test(e)))return!1;let t=BigInt(e.limitBytes)-BigInt(e.usedBytes)-BigInt(e.reservedBytes),n=BigInt(e.availableBytes)===(t>0n?t:0n)&&BigInt(e.unresolvedReservedBytes)<=BigInt(e.reservedBytes)&&(e.unresolvedReservedBytes===`0`||e.warnings.length===1);return n&&Object.freeze(e.warnings),n}function ce(e){if(!I(e,[`items`,`nextCursor`])||!Array.isArray(e.items)||e.items.length>50||!(e.nextCursor===null||typeof e.nextCursor==`string`&&e.nextCursor.length>0&&e.nextCursor.length<=2048&&/^[A-Za-z0-9_.-]+$/.test(e.nextCursor))||e.items.length===0&&e.nextCursor!==null)return!1;let t=new Set,n=e.items.every(e=>{if(!I(e,[`workspaceId`,`itemId`,`parentId`,`type`,`name`,`lifecycleState`,`revision`,`currentVersion`,`volumeId`,`provider`,`createdAtEpochMilliseconds`,`modifiedAtEpochMilliseconds`,`creatorUserId`,`etag`,`trashedAtEpochMilliseconds`,`purgeAfterEpochMilliseconds`])||e.lifecycleState!==`active`&&e.lifecycleState!==`trashed`||typeof e.volumeId!=`string`||!S.test(e.volumeId)||e.provider!==`managed`||e.creatorUserId!==null&&(typeof e.creatorUserId!=`string`||!E.test(e.creatorUserId))||![e.createdAtEpochMilliseconds,e.modifiedAtEpochMilliseconds,e.trashedAtEpochMilliseconds,e.purgeAfterEpochMilliseconds].every(e=>e===null||F(e)))return!1;let n={workspaceId:e.workspaceId,itemId:e.itemId,parentId:e.parentId,type:e.type,name:e.name,lifecycleState:`active`,revision:e.revision,currentVersion:e.currentVersion};return typeof n.workspaceId!=`string`||!x.test(n.workspaceId)||typeof n.itemId!=`string`||!b.test(n.itemId)||n.parentId===null||n.parentId===n.itemId||!_e(n,n.workspaceId,n.itemId)||e.etag!==`"drive.item.v1.${n.revision}"`||t.has(n.itemId)||(e.lifecycleState===`active`?e.trashedAtEpochMilliseconds!==null||e.purgeAfterEpochMilliseconds!==null:!F(e.trashedAtEpochMilliseconds)||!F(e.purgeAfterEpochMilliseconds)||e.purgeAfterEpochMilliseconds<=e.trashedAtEpochMilliseconds)?!1:(t.add(n.itemId),!0)});if(n){for(let t of e.items)Object.freeze(t);Object.freeze(e.items),Object.freeze(e)}return n}function le(e){if(!I(e,[`workspace`,`volumes`,`knownProviders`,`externalConnectionsSupported`])||!ue(e.workspace)||!Array.isArray(e.volumes)||e.volumes.length!==1||!Array.isArray(e.knownProviders)||e.externalConnectionsSupported!==!1)return!1;let t=e.volumes[0],n=[`managed`,`google-drive`,`onedrive`,`dropbox`,`s3-compatible`];return I(t,[`volumeId`,`rootItemId`,`provider`,`name`])&&t.volumeId===e.workspace.rootVolumeId&&t.rootItemId===e.workspace.rootItemId&&t.provider===`managed`&&t.name===`Files`&&e.knownProviders.length===n.length&&e.knownProviders.every((e,t)=>e===n[t])}function ue(e){if(!I(e,[`workspaceId`,`rootVolumeId`,`rootItemId`,`workspaceReference`])||typeof e.workspaceId!=`string`||!x.test(e.workspaceId)||typeof e.rootVolumeId!=`string`||!S.test(e.rootVolumeId)||typeof e.rootItemId!=`string`||!b.test(e.rootItemId))return!1;let t=e.workspaceReference;return I(t,[`type`,`userId`])&&t.type===`personal`&&typeof t.userId==`string`&&E.test(t.userId)||I(t,[`type`,`organizationId`])&&t.type===`organization`&&typeof t.organizationId==`string`&&E.test(t.organizationId)}function de(e){return!I(e,[`mode`,`method`,`url`,`headers`,`expiresAtEpochMilliseconds`,`response`])||e.mode!==`presigned-single`||e.method!==`GET`&&e.method!==`HEAD`||typeof e.url!=`string`||!Ze(e.url)||!F(e.expiresAtEpochMilliseconds)||!I(e.headers,[`if-match`])&&!I(e.headers,[`if-match`,`range`])||typeof e.headers[`if-match`]!=`string`||!Xe(e.headers[`if-match`])||e.headers.range!==void 0&&(typeof e.headers.range!=`string`||!/^bytes=(?:0|[1-9][0-9]*)-(?:0|[1-9][0-9]*)$/.test(e.headers.range))||!I(e.response,[`status`,`versionId`,`byteLength`,`contentLength`,`contentType`,`contentDisposition`,`etag`,`acceptRanges`,`contentRange`])||e.response.status!==200&&e.response.status!==206||typeof e.response.versionId!=`string`||!w.test(e.response.versionId)||!F(e.response.byteLength)||!F(e.response.contentLength)||typeof e.response.contentType!=`string`||!/^[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?\/[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?$/.test(e.response.contentType)||typeof e.response.contentDisposition!=`string`||e.response.contentDisposition.length>2048||!/^[\x20-\x7e]+$/.test(e.response.contentDisposition)||e.response.etag!==e.headers[`if-match`]||e.response.acceptRanges!==`bytes`||e.response.contentRange!==null&&typeof e.response.contentRange!=`string`||!fe(e)?!1:(Object.freeze(e.headers),Object.freeze(e.response),Object.freeze(e),!0)}function fe(e){let t=e.response;if(t.contentLength>t.byteLength||e.method===`HEAD`&&t.status!==200||!t.contentDisposition.startsWith(`attachment; filename="`))return!1;if(t.status===200)return e.headers.range===void 0&&t.contentRange===null&&t.contentLength===t.byteLength;if(e.method!==`GET`||e.headers.range===void 0||t.contentRange===null)return!1;let n=/^bytes=(0|[1-9][0-9]*)-(0|[1-9][0-9]*)$/.exec(e.headers.range),r=/^bytes (0|[1-9][0-9]*)-(0|[1-9][0-9]*)\/(0|[1-9][0-9]*)$/.exec(t.contentRange);if(!n||!r)return!1;let i=Number(n[1]),a=Number(n[2]),o=Number(r[1]),s=Number(r[2]),c=Number(r[3]);return[i,a,o,s,c].every(F)&&i===o&&a===s&&c===t.byteLength&&i<=a&&a<c&&t.contentLength===a-i+1}function pe(e){return I(e,[`mode`,`operationId`,`versionId`,`state`,`pollAfterSeconds`])&&e.mode===`restore-pending`&&typeof e.operationId==`string`&&re.test(e.operationId)&&typeof e.versionId==`string`&&w.test(e.versionId)&&(e.state===`pending`||e.state===`restoring`)&&F(e.pollAfterSeconds)&&e.pollAfterSeconds>=1&&e.pollAfterSeconds<=60}function me(e,t,n){return I(e,[`items`,`nextCursor`])&&Array.isArray(e.items)&&e.items.length<=50&&e.items.every(he)&&(e.nextCursor===null||typeof e.nextCursor==`string`&&e.nextCursor.length<=699&&T.test(e.nextCursor))?e.items.every(e=>e.workspaceId===t&&e.parentItemId===n)&&Ye(e.items,e=>e.itemId):!1}function he(e){return I(e,[`workspaceId`,`volumeId`,`itemId`,`parentItemId`,`kind`,`name`,`visibility`,`revision`])&&typeof e.workspaceId==`string`&&x.test(e.workspaceId)&&typeof e.volumeId==`string`&&S.test(e.volumeId)&&typeof e.itemId==`string`&&b.test(e.itemId)&&typeof e.parentItemId==`string`&&b.test(e.parentItemId)&&(e.kind===`file`||e.kind===`folder`)&&P(e.name)&&(e.visibility===`workspace`||e.visibility===`restricted`)&&F(e.revision)}function ge(e,t,n,r){return!I(e,[`workspaceId`,`volumeId`,`itemId`,`parentItemId`,`kind`,`name`,`state`,`revision`,`purgeAfterEpochMilliseconds`])||e.workspaceId!==t||e.itemId!==n||typeof e.volumeId!=`string`||!S.test(e.volumeId)||typeof e.parentItemId!=`string`||!b.test(e.parentItemId)||e.kind!==`file`&&e.kind!==`folder`||!P(e.name)||e.state!==r||!F(e.revision)||(e.state===`active`?e.purgeAfterEpochMilliseconds!==null:!F(e.purgeAfterEpochMilliseconds))?!1:(Object.freeze(e),!0)}function _e(e,t,n){return!I(e,[`workspaceId`,`itemId`,`parentId`,`type`,`name`,`lifecycleState`,`revision`,`currentVersion`])||e.workspaceId!==t||e.itemId!==n||!(e.parentId===null||typeof e.parentId==`string`&&b.test(e.parentId))||e.type!==`file`&&e.type!==`folder`||!P(e.name)||e.lifecycleState!==`active`||!F(e.revision)||(e.type===`folder`?e.currentVersion!==null:!ye(e.currentVersion))?!1:(e.currentVersion!==null&&Object.freeze(e.currentVersion),Object.freeze(e),!0)}function ve(e,t,n,r){if(!I(e,[`items`,`nextCursor`])||!Array.isArray(e.items)||e.items.length>r||!e.items.every(e=>be(e,t,n))||!(e.nextCursor===null||typeof e.nextCursor==`string`&&e.nextCursor.length<=699&&T.test(e.nextCursor))||e.items.length===0&&e.nextCursor!==null||new Set(e.items.map(e=>e.itemId)).size!==e.items.length||!xe(e.items))return!1;for(let t of e.items)t.currentVersion!==null&&Object.freeze(t.currentVersion),Object.freeze(t);return Object.freeze(e.items),Object.freeze(e),!0}function N(e,t){let n=e.get(`etag`);return n!==null&&p(n)===t}function ye(e){return I(e,[`versionId`,`state`,`byteLength`,`mediaType`,`protectionClassification`])&&typeof e.versionId==`string`&&w.test(e.versionId)&&e.state===`current`&&F(e.byteLength)&&Ke(e.mediaType)&&(e.protectionClassification===`ordinary`||e.protectionClassification===`opaque-encrypted`)}function be(e,t,n){return I(e,[`workspaceId`,`volumeId`,`provider`,`itemId`,`parentId`,`type`,`name`,`lifecycleState`,`revision`,`currentVersion`])&&e.workspaceId===t&&typeof e.volumeId==`string`&&S.test(e.volumeId)&&e.provider===`managed`&&typeof e.itemId==`string`&&b.test(e.itemId)&&(e.parentId===null||typeof e.parentId==`string`&&b.test(e.parentId))&&(e.type===`file`||e.type===`folder`)&&P(e.name)&&e.name.startsWith(n)&&e.lifecycleState===`active`&&F(e.revision)&&(e.type===`folder`?e.currentVersion===null:ye(e.currentVersion))}function xe(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t],i=Se(n.name,r.name);if(i>0||i===0&&n.itemId>=r.itemId)return!1}return!0}function Se(e,t){let n=ae.encode(e),r=ae.encode(t),i=Math.min(n.length,r.length);for(let e=0;e<i;e+=1)if(n[e]!==r[e])return n[e]-r[e];return n.length-r.length}function Ce(e,t){if(!I(e,[`items`,`nextCursor`])||!Array.isArray(e.items)||e.items.length>t||!e.items.every(Ie)||!(e.nextCursor===null||typeof e.nextCursor==`string`&&e.nextCursor.length<=699&&T.test(e.nextCursor))||e.nextCursor!==null&&e.items.length===0||!Ye(e.items,e=>e.versionId))return!1;for(let t of e.items)Object.freeze(t);return Object.freeze(e.items),Object.freeze(e),!0}function we(e,t){return!I(e,[`itemRevision`,`currentVersionId`])||!F(e.itemRevision)||e.currentVersionId!==t?!1:(Object.freeze(e),!0)}function Te(e,t,n,r=O){if(!(I(e,[`items`,`nextCursor`,`collectionRevision`,`collectionEtag`])&&Array.isArray(e.items)&&e.items.length<=50&&e.items.every(Ve)&&(e.nextCursor===null||typeof e.nextCursor==`string`&&e.nextCursor.length<=699&&T.test(e.nextCursor))&&F(e.collectionRevision)&&typeof e.collectionEtag==`string`&&d(e.collectionEtag)===e.collectionRevision))return!1;let i=t.get(`drive-permission-collection-etag`),a=t.get(`etag`),o=e.collectionRevision;return F(o)?i===e.collectionEtag&&a!==null&&r.test(a)&&e.items.every(e=>(e.source===`direct`?e.sourceItemId===n:e.sourceItemId!==n)&&e.etag===Ge(o,e.revision))&&Ye(e.items,e=>`${e.sourceItemId}\0${e.grantId}`):!1}function Ee(e,t,n){if(!I(e,[`items`,`nextCursor`,`collectionRevision`,`collectionEtag`])||!Array.isArray(e.items)||e.items.length>50)return!1;let r=[];for(let t of e.items){if(!I(t,[`source`,`sourceItemId`,`grantId`,`grantee`,`actions`,`availability`,`expiresAtEpochMilliseconds`,`revision`,`etag`,`recipient`]))return!1;let{recipient:e,...n}=t;if(!Ve(n)||e!==null&&(!I(e,[`userId`,`name`,`email`,`resolvedAt`,`expiresAt`])||n.grantee.type!==`user`||e.userId!==n.grantee.userId||typeof e.name!=`string`||e.name.length<1||ae.encode(e.name).byteLength>1024||typeof e.email!=`string`||e.email.length<3||ae.encode(e.email).byteLength>320||!e.email.includes(`@`)||!F(e.resolvedAt)||!F(e.expiresAt)||e.expiresAt!==e.resolvedAt+864e5))return!1;r.push(n)}return Te({...e,items:r},t,n,/^"drive\.sharing-people\.v1\.[0-9a-f]{64}"$/)}function De(e,t,n){if(!I(e,[`outcome`,`grant`,`collectionRevision`])||e.outcome!==`committed`&&e.outcome!==`replayed`||!F(e.collectionRevision))return!1;let r=e.grant;return I(r,[`source`,`sourceItemId`,`grantId`,`grantee`,`actions`,`availability`,`expiresAtEpochMilliseconds`,`revision`])&&r.source===`direct`&&typeof r.sourceItemId==`string`&&r.sourceItemId===t&&typeof r.grantId==`string`&&C.test(r.grantId)&&(n===void 0||r.grantId===n)&&He(r.grantee)&&Ue(r.actions)&&[`active`,`expired`,`revoked`].includes(String(r.availability))&&(r.expiresAtEpochMilliseconds===null||F(r.expiresAtEpochMilliseconds))&&F(r.revision)}function Oe(e,t){if(!I(e,[`actions`])||!Array.isArray(e.actions)||e.actions.length!==7)return!1;for(let n=0;n<e.actions.length;n+=1){let r=e.actions[n];if(r===void 0||!I(r,[`action`,`allowed`,`basis`,`sourceItemId`,`grantId`])||r.action!==A[n]||typeof r.allowed!=`boolean`||!(r.basis===null||[`workspace_visibility`,`restricted_administrator_bypass`,`direct_grant`,`inherited_grant`].includes(String(r.basis)))||!(r.sourceItemId===null||typeof r.sourceItemId==`string`&&b.test(r.sourceItemId))||!(r.grantId===null||typeof r.grantId==`string`&&C.test(r.grantId))||!We(r,t))return!1}return!0}function ke(e,t){return!I(e,[`itemId`,`versionId`,`uploadId`,`mode`,`partByteLength`,`partCount`,`revision`,`expiresAtEpochMilliseconds`])||typeof e.itemId!=`string`||!b.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||typeof e.uploadId!=`string`||!ne.test(e.uploadId)||e.mode!==`presigned-multipart`&&e.mode!==`server-mediated-zero-byte`||e.partByteLength!==M||!F(e.partCount)||e.partCount>1e4||e.partCount!==Math.ceil(t/M)||(t===0?e.mode!==`server-mediated-zero-byte`:e.mode!==`presigned-multipart`)||!F(e.revision)||!F(e.expiresAtEpochMilliseconds)||e.expiresAtEpochMilliseconds<=Date.now()?!1:(Object.freeze(e),!0)}function Ae(e,t,n){if(!I(e,[`itemId`,`versionId`,`uploadId`,`mode`,`lifecycle`,`revision`,`partPolicy`,`confirmedParts`,`nextAfterPartNumber`,`expiresAtEpochMilliseconds`,`ready`],[`verification`])||typeof e.itemId!=`string`||!b.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||typeof e.uploadId!=`string`||!ne.test(e.uploadId)||e.mode!==`presigned-multipart`&&e.mode!==`server-mediated-zero-byte`||![`initiating`,`recovery-required`,`uploading`,`completing`,`provider-completed`,`verifying`,`failed`,`ready`,`aborting`,`aborted`].includes(String(e.lifecycle))||!F(e.revision)||!I(e.partPolicy,[`partByteLength`,`partCount`,`maxParts`])||e.partPolicy.partByteLength!==M||!F(e.partPolicy.partCount)||e.partPolicy.partCount>1e4||e.partPolicy.maxParts!==1e4||(e.mode===`server-mediated-zero-byte`?e.partPolicy.partCount!==0:e.partPolicy.partCount<1)||!Array.isArray(e.confirmedParts)||e.confirmedParts.length>n||!F(e.expiresAtEpochMilliseconds))return!1;let r=t;if(e.verification!==void 0){let t=e.verification;if(!I(t,[`state`,`verifiedByteLength`,`totalByteLength`,`revision`])||![`pending`,`verified`,`failed`].includes(String(t.state))||!F(t.verifiedByteLength)||!F(t.totalByteLength)||t.totalByteLength>j||t.verifiedByteLength>t.totalByteLength||!F(t.revision)||t.state===`verified`&&t.verifiedByteLength!==t.totalByteLength)return!1;Object.freeze(t)}if([`verifying`,`failed`].includes(String(e.lifecycle))&&e.verification===void 0)return!1;for(let t of e.confirmedParts){if(!I(t,[`partNumber`,`checksumSha256`])||!F(t.partNumber)||t.partNumber<=r||t.partNumber>e.partPolicy.partCount||!Fe(t.checksumSha256))return!1;r=t.partNumber}if(!(e.nextAfterPartNumber===null||F(e.nextAfterPartNumber)&&e.confirmedParts.length===n&&e.nextAfterPartNumber===r)||e.mode===`server-mediated-zero-byte`&&(e.confirmedParts.length!==0||e.nextAfterPartNumber!==null)||e.lifecycle===`ready`!=(e.ready!==null)||e.ready!==null&&(!Ne(e.ready,{uploadId:e.uploadId})||e.ready.itemId!==e.itemId||e.ready.versionId!==e.versionId||!I(e.verification,[`state`,`verifiedByteLength`,`totalByteLength`,`revision`])||e.verification.state!==`verified`||e.verification.totalByteLength!==e.ready.byteLength))return!1;Object.freeze(e.partPolicy);for(let t of e.confirmedParts)Object.freeze(t);return Object.freeze(e.confirmedParts),Object.freeze(e),!0}function je(e,t,n,r){return!I(e,[`url`,`method`,`headers`,`partNumber`,`expectedByteLength`,`expiresAtEpochMilliseconds`])||!qe(e.url,n)||e.method!==`PUT`||!r||!I(e.headers,[`content-md5`])||e.headers[`content-md5`]!==r||e.partNumber!==t||!F(e.expectedByteLength)||e.expectedByteLength<1||e.expectedByteLength>M||!F(e.expiresAtEpochMilliseconds)||e.expiresAtEpochMilliseconds<=Date.now()?!1:(Object.freeze(e.headers),Object.freeze(e),!0)}function Me(e,t,n){return!I(e,[`partNumber`,`revision`])||e.partNumber!==t||e.revision!==n+1||!F(e.revision)?!1:(Object.freeze(e),!0)}function Ne(e,t){return!I(e,[`itemId`,`versionId`,`uploadId`,`byteLength`,`callerDeclaredContentDigest`,`displayFilename`,`mediaType`,`state`])||typeof e.itemId!=`string`||!b.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||e.uploadId!==t.uploadId||!F(e.byteLength)||e.byteLength<0||e.byteLength>j||typeof e.callerDeclaredContentDigest!=`string`||!ie.test(e.callerDeclaredContentDigest)||!P(e.displayFilename)||!Ke(e.mediaType)||e.state!==`ready`||t.byteLength!==void 0&&e.byteLength!==t.byteLength||t.callerDeclaredContentDigest!==void 0&&e.callerDeclaredContentDigest!==t.callerDeclaredContentDigest||t.displayFilename!==void 0&&e.displayFilename!==t.displayFilename||t.mediaType!==void 0&&e.mediaType!==t.mediaType?!1:(Object.freeze(e),!0)}function Pe(e,t){return!I(e,[`itemId`,`versionId`,`uploadId`,`state`,`verifiedByteLength`,`totalByteLength`,`verificationRevision`])||typeof e.itemId!=`string`||!b.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||e.uploadId!==t||e.state!==`verifying`||!F(e.verifiedByteLength)||!F(e.totalByteLength)||e.totalByteLength>j||e.verifiedByteLength>e.totalByteLength||!F(e.verificationRevision)?!1:(Object.freeze(e),!0)}function Fe(e){return typeof e==`string`&&/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/.test(e)}function Ie(e){let t=I(e,Re)&&ze(e);return t&&Object.freeze(e),t}function Le(e,t,n,r){let i=I(e,[...Re,`workspaceId`,`itemId`])&&e.workspaceId===t&&e.itemId===n&&e.versionId===r&&ze(e);return i&&Object.freeze(e),i}const Re=Object.freeze([`versionId`,`state`,`revision`,`byteLength`,`contentDigest`,`mediaType`,`displayFilename`,`protectionClassification`,`archiveState`]);function ze(e){return typeof e.versionId==`string`&&w.test(e.versionId)&&(e.state===`current`||e.state===`superseded`)&&F(e.revision)&&F(e.byteLength)&&typeof e.contentDigest==`string`&&ie.test(e.contentDigest)&&Ke(e.mediaType)&&P(e.displayFilename)&&(e.protectionClassification===`ordinary`||e.protectionClassification===`opaque-encrypted`)&&[`available`,`cold`,`restoring`,`unavailable`,`corrupt`].includes(String(e.archiveState))}function Be(e){let t=e.get(`drive-permission-collection-etag`),n=e.get(`drive-permission-grant-etag`),r=t===null?void 0:d(t);if(r===void 0)return!1;if(n===null)return!0;let i=f(n);return i!==void 0&&i[0]===r}function Ve(e){return I(e,[`source`,`sourceItemId`,`grantId`,`grantee`,`actions`,`availability`,`expiresAtEpochMilliseconds`,`revision`,`etag`])&&(e.source===`direct`||e.source===`inherited`)&&typeof e.sourceItemId==`string`&&b.test(e.sourceItemId)&&typeof e.grantId==`string`&&C.test(e.grantId)&&He(e.grantee)&&Ue(e.actions)&&[`active`,`expired`,`revoked`].includes(String(e.availability))&&(e.expiresAtEpochMilliseconds===null||F(e.expiresAtEpochMilliseconds))&&F(e.revision)&&typeof e.etag==`string`&&D.test(e.etag)}function He(e){return I(e,[`type`,`userId`])&&e.type===`user`&&typeof e.userId==`string`&&E.test(e.userId)||I(e,[`type`,`teamId`])&&e.type===`team`&&typeof e.teamId==`string`&&E.test(e.teamId)}function Ue(e){return Array.isArray(e)&&e.length>=1&&e.length<=6&&new Set(e).size===e.length&&e.every(e=>k.includes(e))&&e.every((t,n)=>n===0||k.indexOf(t)>k.indexOf(e[n-1]))}function We(e,t){return e.allowed?e.basis===`workspace_visibility`||e.basis===`restricted_administrator_bypass`?e.sourceItemId===null&&e.grantId===null:e.basis===`direct_grant`?e.sourceItemId===t&&typeof e.grantId==`string`:e.basis===`inherited_grant`&&typeof e.sourceItemId==`string`&&e.sourceItemId!==t&&typeof e.grantId==`string`:e.basis===null&&e.sourceItemId===null&&e.grantId===null}function Ge(e,t){return`"drive.permission-grant.v1.${e}.${t}"`}function P(e){if(typeof e!=`string`||e.length===0||e.length>510||e.normalize(`NFC`)!==e||e.endsWith(`.`)||e.endsWith(` `)||Je(e))return!1;let t=0,n=0;for(let r of e){let e=r.codePointAt(0);if(e===void 0||e===47||e===92||e<=31||e>=127&&e<=159||e===8232||e===8233||e>=55296&&e<=57343||(t+=1,n+=e<=127?1:e<=2047?2:e<=65535?3:4,t>255||n>255))return!1}return!0}function Ke(e){return typeof e==`string`&&e.length<=255&&/^[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?\/[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?$/.test(e)}function qe(e,t){if(typeof e!=`string`||e.length<1||e.length>8192||e!==e.trim())return!1;try{let n=new URL(e),r=n.hostname===`localhost`||n.hostname===`127.0.0.1`||n.hostname===`[::1]`;return(n.protocol===`https:`||n.protocol===`http:`&&t&&r)&&n.username===``&&n.password===``&&n.hash===``&&n.host!==``}catch{return!1}}function Je(e){let t=e.split(`.`,1)[0].toUpperCase();return e===`.`||e===`..`||[`CON`,`PRN`,`AUX`,`NUL`,`CLOCK$`,`CONIN$`,`CONOUT$`].includes(t)||/^COM[1-9]$/.test(t)||/^LPT[1-9]$/.test(t)}function Ye(e,t){return e.every((n,r)=>r===0||t(e[r-1])<t(n))}function F(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Xe(e){return/^"[\x21\x23-\x7e]{1,1022}"$/.test(e)}function Ze(e){try{let t=new URL(e),n=t.protocol===`http:`&&[`localhost`,`127.0.0.1`,`[::1]`].includes(t.hostname);return(t.protocol===`https:`||n)&&!t.username&&!t.password&&!t.hash}catch{return!1}}function I(e,t,n=[]){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.keys(e).every(e=>t.includes(e)||n.includes(e))&&t.every(t=>Object.hasOwn(e,t))}const Qe=/^drive\.item\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,L=/^drive\.workspace\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,$e=/^drive\.grant\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,et=/^drive\.upload\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,tt=/^drive\.version\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,nt=/^drive\.cursor\.v1\.[A-Za-z0-9_-]+$/,rt=/^[A-Za-z0-9_-]{1,128}$/,it=Object.freeze([`items:content:read`,`items:create`,`items:delete`,`items:metadata:read`,`items:permissions:read`,`items:update`]),at=/^[A-Za-z0-9_-]{16,128}$/,ot=/^sha256:[0-9a-f]{64}$/,st=/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/,ct=33554432e4;function lt(e){let t=U(H(e===void 0?{}:e,[],[`signal`]).signal);return t===void 0?{}:{signal:t}}function ut(e){let t=H(e===void 0?{}:e,[],[`signal`,`limit`,`cursor`]),n=U(t.signal);if(t.limit!==void 0&&(typeof t.limit!=`number`||!Number.isInteger(t.limit)||t.limit<1||t.limit>50)||t.cursor!==void 0&&(typeof t.cursor!=`string`||t.cursor.length<1||t.cursor.length>2048||!/^[A-Za-z0-9_.-]+$/.test(t.cursor)))throw new r(`invalid_input`);return{signal:n,query:{...t.limit===void 0?{}:{limit:t.limit},...t.cursor===void 0?{}:{cursor:t.cursor}}}}function dt(e,t){let n=H(e,[`workspaceId`],t?[`signal`,`view`,`kind`,`creatorUserId`,`limit`,`cursor`]:[`signal`]),i=U(n.signal);if(typeof n.workspaceId!=`string`||!L.test(n.workspaceId)||n.view!==void 0&&n.view!==`recent`&&n.view!==`shared`&&n.view!==`trash`||n.kind!==void 0&&n.kind!==`file`&&n.kind!==`folder`||n.creatorUserId!==void 0&&(typeof n.creatorUserId!=`string`||!rt.test(n.creatorUserId))||n.limit!==void 0&&(typeof n.limit!=`number`||!Number.isInteger(n.limit)||n.limit<1||n.limit>50)||n.cursor!==void 0&&(typeof n.cursor!=`string`||n.cursor.length<1||n.cursor.length>2048||!/^[A-Za-z0-9_.-]+$/.test(n.cursor)))throw new r(`invalid_input`);return{workspaceId:n.workspaceId,signal:i,query:{...n.view===void 0?{}:{view:n.view},...n.kind===void 0?{}:{kind:n.kind},...n.creatorUserId===void 0?{}:{creatorUserId:n.creatorUserId},...n.limit===void 0?{}:{limit:n.limit},...n.cursor===void 0?{}:{cursor:n.cursor}}}}function R(e){let t=H(e,[`workspaceId`,`itemId`],[`signal`]),n=t.workspaceId,i=t.itemId,a=U(t.signal);if(typeof n!=`string`||!L.test(n)||typeof i!=`string`||!Qe.test(i))throw new r(`invalid_input`);return{workspaceId:n,itemId:i,...a===void 0?{}:{signal:a}}}function ft(e){let t=H(e,[`workspaceId`,`itemId`,`versionId`],[`signal`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(typeof t.versionId!=`string`||!tt.test(t.versionId))throw new r(`invalid_input`);return{...n,versionId:t.versionId}}function pt(e){let t=H(e,[`workspaceId`,`itemId`,`idempotencyKey`],[`versionId`,`method`,`range`,`ifMatch`,`ifNoneMatch`,`ifRange`,`signal`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}}),i=t.method??`GET`;if(!W(t.idempotencyKey)||t.versionId!==void 0&&(typeof t.versionId!=`string`||!tt.test(t.versionId))||i!==`GET`&&i!==`HEAD`||t.range!==void 0&&(typeof t.range!=`string`||t.range.length>128||!/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/.test(t.range))||!Ht(t.ifMatch)||!Ht(t.ifNoneMatch)||!Ht(t.ifRange))throw new r(`invalid_input`);return{...n,idempotencyKey:t.idempotencyKey,method:i,...t.versionId===void 0?{}:{versionId:t.versionId},...t.range===void 0?{}:{range:t.range},...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch},...t.ifRange===void 0?{}:{ifRange:t.ifRange}}}function mt(e){let t=H(e,[`workspaceId`,`query`],[`limit`,`cursor`,`signal`]),n=U(t.signal);if(typeof t.workspaceId!=`string`||!L.test(t.workspaceId)||!Rt(t.query)||t.limit!==void 0&&(!K(t.limit)||t.limit<1||t.limit>50)||t.cursor!==void 0&&(typeof t.cursor!=`string`||t.cursor.length>699||!nt.test(t.cursor)))throw new r(`invalid_input`);return{workspaceId:t.workspaceId,query:t.query,...t.limit===void 0?{}:{limit:t.limit},...t.cursor===void 0?{}:{cursor:t.cursor},...n===void 0?{}:{signal:n}}}function ht(e){let t=H(e,[`workspaceId`,`itemId`],[`signal`,`limit`,`cursor`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}}),i=t.limit,a=t.cursor;if(i!==void 0&&(!Number.isSafeInteger(i)||typeof i!=`number`||i<1||i>50)||a!==void 0&&(typeof a!=`string`||a.length>699||!nt.test(a)))throw new r(`invalid_input`);return{...n,...i===void 0?{}:{limit:i},...a===void 0?{}:{cursor:a}}}function gt(e){let t=H(e,[`workspaceId`,`itemId`,`name`,`idempotencyKey`],[`signal`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(!Bt(t.name)||!W(t.idempotencyKey))throw new r(`invalid_input`);return{...n,name:t.name,idempotencyKey:t.idempotencyKey}}function _t(e){let t=H(e,[`workspaceId`,`itemId`,`name`,`parentItemId`,`idempotencyKey`,`ifMatch`],[`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,idempotencyKey:t.idempotencyKey,ifMatch:t.ifMatch,...t.signal===void 0?{}:{signal:t.signal}});if(!Bt(t.name)||typeof t.parentItemId!=`string`||!Qe.test(t.parentItemId))throw new r(`invalid_input`);return{...n,name:t.name,parentItemId:t.parentItemId}}function z(e){let t=H(e,[`workspaceId`,`itemId`,`idempotencyKey`,`ifMatch`],[`signal`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(!W(t.idempotencyKey)||typeof t.ifMatch!=`string`||p(t.ifMatch)===void 0)throw new r(`invalid_input`);return{...n,idempotencyKey:t.idempotencyKey,ifMatch:t.ifMatch}}function vt(e){let t=H(e,[`workspaceId`,`itemId`,`versionId`,`idempotencyKey`,`ifMatch`],[`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,idempotencyKey:t.idempotencyKey,ifMatch:t.ifMatch,...t.signal===void 0?{}:{signal:t.signal}});if(typeof t.versionId!=`string`||!tt.test(t.versionId))throw new r(`invalid_input`);return{...n,versionId:t.versionId}}function yt(e){let t=H(e,[`workspaceId`,`itemId`,`grantee`,`actions`,`expiresAtEpochMilliseconds`,`ifMatch`,`idempotencyKey`],[`signal`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}}),i=jt(t.grantee),a=Mt(t.actions),o=t.expiresAtEpochMilliseconds;if(!zt(o)||typeof t.ifMatch!=`string`||d(t.ifMatch)===void 0||!W(t.idempotencyKey))throw new r(`invalid_input`);return{...n,grantee:i,actions:a,expiresAtEpochMilliseconds:o,ifMatch:t.ifMatch,idempotencyKey:t.idempotencyKey}}function bt(e){let t=H(e,[`workspaceId`,`itemId`,`email`,`role`,`ifMatch`,`idempotencyKey`],[`signal`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(typeof t.email!=`string`||t.email.length<3||t.email.length>320||t.role!==`viewer`&&t.role!==`editor`||typeof t.ifMatch!=`string`||d(t.ifMatch)===void 0||!W(t.idempotencyKey))throw new r(`invalid_input`);let i=t.email.trim().toLowerCase();if(!i.includes(`@`)||/\s/.test(i)||new TextEncoder().encode(i).byteLength>320)throw new r(`invalid_input`);return{...n,email:i,role:t.role,ifMatch:t.ifMatch,idempotencyKey:t.idempotencyKey}}function xt(e){let t=H(e,[`workspaceId`,`itemId`,`grantId`,`ifMatch`,`idempotencyKey`],[`signal`]),n=R({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(typeof t.grantId!=`string`||!$e.test(t.grantId)||typeof t.ifMatch!=`string`||f(t.ifMatch)===void 0||!W(t.idempotencyKey))throw new r(`invalid_input`);return{...n,grantId:t.grantId,ifMatch:t.ifMatch,idempotencyKey:t.idempotencyKey}}function St(e){let t=H(e,[`workspaceId`,`itemId`,`grantId`,`ifMatch`,`idempotencyKey`],[`signal`,`actions`,`expiresAtEpochMilliseconds`]),n=xt({workspaceId:t.workspaceId,itemId:t.itemId,grantId:t.grantId,ifMatch:t.ifMatch,idempotencyKey:t.idempotencyKey,...t.signal===void 0?{}:{signal:t.signal}}),i=t.actions===void 0?void 0:Mt(t.actions),a=t.expiresAtEpochMilliseconds;if(i===void 0&&a===void 0||a!==void 0&&!zt(a))throw new r(`invalid_input`);return{...n,...i===void 0?{}:{actions:i},...a===void 0?{}:{expiresAtEpochMilliseconds:a}}}function Ct(e){let t=H(e,[`workspaceId`,`parentItemId`,`expectedByteLength`,`displayFilename`,`mediaType`,`callerDeclaredContentDigest`,`protectionClassification`,`idempotencyKey`],[`signal`]),n=U(t.signal);if(typeof t.workspaceId!=`string`||!L.test(t.workspaceId)||typeof t.parentItemId!=`string`||!Qe.test(t.parentItemId)||typeof t.expectedByteLength!=`number`||!Number.isSafeInteger(t.expectedByteLength)||t.expectedByteLength<0||t.expectedByteLength>ct||!Bt(t.displayFilename)||!Lt(t.mediaType)||typeof t.callerDeclaredContentDigest!=`string`||!ot.test(t.callerDeclaredContentDigest)||t.protectionClassification!==`ordinary`&&t.protectionClassification!==`opaque-encrypted`||!W(t.idempotencyKey))throw new r(`invalid_input`);return{workspaceId:t.workspaceId,parentItemId:t.parentItemId,expectedByteLength:t.expectedByteLength,displayFilename:t.displayFilename,mediaType:t.mediaType,callerDeclaredContentDigest:t.callerDeclaredContentDigest,protectionClassification:t.protectionClassification,idempotencyKey:t.idempotencyKey,...n===void 0?{}:{signal:n}}}function wt(e){let t=H(e,[`workspaceId`,`uploadId`],[`afterPartNumber`,`limit`,`signal`]),n=G(t.workspaceId,t.uploadId,t.signal);if(t.afterPartNumber!==void 0&&(!K(t.afterPartNumber)||t.afterPartNumber>1e4)||t.limit!==void 0&&(!K(t.limit)||t.limit<1||t.limit>100))throw new r(`invalid_input`);return{...n,...t.afterPartNumber===void 0?{}:{afterPartNumber:t.afterPartNumber},...t.limit===void 0?{}:{limit:t.limit}}}function Tt(e){let t=H(e,[`workspaceId`,`uploadId`,`partNumber`,`checksumSha256`,`contentMd5`],[`signal`]),n=G(t.workspaceId,t.uploadId,t.signal);if(!Pt(t.partNumber)||!Ft(t.checksumSha256)||typeof t.contentMd5!=`string`||!/^[A-Za-z0-9+/]{21}[AQgw]==$/.test(t.contentMd5))throw new r(`invalid_input`);return{...n,partNumber:t.partNumber,checksumSha256:t.checksumSha256,contentMd5:t.contentMd5}}function Et(e){let t=H(e,[`workspaceId`,`uploadId`,`partNumber`,`expectedUploadRevision`,`byteLength`,`etag`,`checksumSha256`],[`signal`]),n=G(t.workspaceId,t.uploadId,t.signal);if(!Pt(t.partNumber)||!K(t.expectedUploadRevision)||t.expectedUploadRevision>=2**53-1||!K(t.byteLength)||t.byteLength<1||t.byteLength>33554432||!It(t.etag)||!Ft(t.checksumSha256))throw new r(`invalid_input`);return{...n,partNumber:t.partNumber,expectedUploadRevision:t.expectedUploadRevision,byteLength:t.byteLength,etag:t.etag,checksumSha256:t.checksumSha256}}function Dt(e){let t=H(e,[`workspaceId`,`uploadId`,`idempotencyKey`],[`signal`]),n=G(t.workspaceId,t.uploadId,t.signal);if(!W(t.idempotencyKey))throw new r(`invalid_input`);return{...n,idempotencyKey:t.idempotencyKey}}function Ot(e){let t=H(e,[`workspaceId`,`uploadId`],[`signal`]);return G(t.workspaceId,t.uploadId,t.signal)}function kt(e){let t=H(e,[`workspaceId`,`parentItemId`,`source`,`displayFilename`,`idempotencyKey`,`completionIdempotencyKey`],[`mediaType`,`protectionClassification`,`signal`,`onProgress`]),n=U(t.signal),i=t.mediaType??`application/octet-stream`,a=t.protectionClassification??`ordinary`,o,s;try{if(!(t.source instanceof Blob))throw new r(`invalid_input`);o=t.source,s=o.size}catch(e){throw e instanceof r?e:new r(`invalid_input`)}if(typeof t.workspaceId!=`string`||!L.test(t.workspaceId)||typeof t.parentItemId!=`string`||!Qe.test(t.parentItemId)||!Number.isSafeInteger(s)||s<0||s>ct||!Bt(t.displayFilename)||!Lt(i)||a!==`ordinary`&&a!==`opaque-encrypted`||!W(t.idempotencyKey)||!W(t.completionIdempotencyKey)||t.onProgress!==void 0&&typeof t.onProgress!=`function`)throw new r(`invalid_input`);return{workspaceId:t.workspaceId,parentItemId:t.parentItemId,source:o,byteLength:s,displayFilename:t.displayFilename,mediaType:i,protectionClassification:a,idempotencyKey:t.idempotencyKey,completionIdempotencyKey:t.completionIdempotencyKey,...n===void 0?{}:{signal:n},...t.onProgress===void 0?{}:{onProgress:t.onProgress}}}function B(e){return{workspaceId:e.workspaceId,itemId:e.itemId}}function At(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor}}}function V(e,t){return t}function H(e,t,n){try{if(typeof e!=`object`&&typeof e!=`function`||e===null||Array.isArray(e))throw new r(`invalid_input`);let i=Object.getOwnPropertyDescriptors(e),a=Reflect.ownKeys(i),o=new Set([...t,...n]);if(a.some(e=>typeof e!=`string`||!o.has(e))||t.some(e=>!Object.hasOwn(i,e)))throw new r(`invalid_input`);let s={};for(let e of a){if(typeof e!=`string`)throw new r(`invalid_input`);let t=i[e];if(!t||!(`value`in t)||!t.enumerable)throw new r(`invalid_input`);s[e]=t.value}return s}catch(e){throw e instanceof r?e:new r(`invalid_input`)}}function U(e){if(e!==void 0){if(!(e instanceof AbortSignal))throw new r(`invalid_input`);return e}}function jt(e){let t=H(e,[`type`],[`userId`,`teamId`]);if(t.type===`user`){let t=H(e,[`type`,`userId`],[]);if(typeof t.userId==`string`&&rt.test(t.userId))return{type:`user`,userId:t.userId}}if(t.type===`team`){let t=H(e,[`type`,`teamId`],[]);if(typeof t.teamId==`string`&&rt.test(t.teamId))return{type:`team`,teamId:t.teamId}}throw new r(`invalid_input`)}function Mt(e){let t=Nt(e);if(t.length<1||t.length>it.length||new Set(t).size!==t.length||!t.every(e=>it.includes(e)))throw new r(`invalid_input`);return t}function Nt(e){try{if(!Array.isArray(e))throw new r(`invalid_input`);let t=Object.getOwnPropertyDescriptors(e);if(Reflect.ownKeys(t).some(e=>typeof e!=`string`))throw new r(`invalid_input`);let n=[];for(let i=0;i<e.length;i+=1){let e=t[String(i)];if(!e||!(`value`in e)||!e.enumerable)throw new r(`invalid_input`);n.push(e.value)}if(Reflect.ownKeys(t).length!==e.length+1)throw new r(`invalid_input`);return n}catch(e){throw e instanceof r?e:new r(`invalid_input`)}}function W(e){return typeof e==`string`&&at.test(e)}function G(e,t,n){let i=U(n);if(typeof e!=`string`||!L.test(e)||typeof t!=`string`||!et.test(t))throw new r(`invalid_input`);return{workspaceId:e,uploadId:t,...i===void 0?{}:{signal:i}}}function Pt(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=1&&e<=1e4}function Ft(e){return typeof e==`string`&&st.test(e)}function It(e){return typeof e==`string`&&e.length>=1&&e.length<=1024&&/^[\x20-\x7e]+$/.test(e)}function Lt(e){return typeof e==`string`&&e.length<=255&&/^[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?\/[a-z0-9](?:[a-z0-9!#$&^_.+-]{0,125}[a-z0-9])?$/.test(e)}function Rt(e){if(typeof e!=`string`||e.length===0)return!1;try{if(e.normalize(`NFC`)!==e)return!1;let t=0,n=0;for(let r of e){let e=r.codePointAt(0);if(e===void 0||e<=31||e>=127&&e<=159||e===8232||e===8233||e>=55296&&e<=57343||(t+=1,n+=e<=127?1:e<=2047?2:e<=65535?3:4,t>64||n>255))return!1}return!0}catch{return!1}}function zt(e){return e===null||K(e)}function Bt(e){if(typeof e!=`string`||e.length===0||e.length>510||e.normalize(`NFC`)!==e||e.endsWith(`.`)||e.endsWith(` `)||Vt(e))return!1;let t=0,n=0;for(let r of e){let e=r.codePointAt(0);if(e===void 0||e===47||e===92||e<=31||e>=127&&e<=159||e===8232||e===8233||e>=55296&&e<=57343||(t+=1,n+=e<=127?1:e<=2047?2:e<=65535?3:4,t>255||n>255))return!1}return!0}function Vt(e){let t=e.split(`.`,1)[0].toUpperCase();return e===`.`||e===`..`||[`CON`,`PRN`,`AUX`,`NUL`,`CLOCK$`,`CONIN$`,`CONOUT$`].includes(t)||/^COM[1-9]$/.test(t)||/^LPT[1-9]$/.test(t)}function K(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ht(e){return e===void 0||typeof e==`string`&&e.length<=8192&&!e.split(``).some(e=>{let t=e.charCodeAt(0);return t<=31||t===127})}const Ut=/\{[^{}]+\}/g,Wt=()=>typeof process==`object`&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Gt(){return Math.random().toString(36).slice(2,11)}function Kt(e){let{baseUrl:t=``,Request:n=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:i,bodySerializer:a,pathSerializer:o,headers:s,requestInitExt:c=void 0,...l}={...e};c=Wt()?c:void 0,t=tn(t);let u=[];async function d(e,d){let{baseUrl:f,fetch:p=r,Request:m=n,headers:h,params:g={},parseAs:_=`json`,querySerializer:v,bodySerializer:ee=a??Qt,pathSerializer:te,body:y,middleware:b=[],...x}=d||{},S=t;f&&(S=tn(f)??t);let C=typeof i==`function`?i:Xt(i);v&&(C=typeof v==`function`?v:Xt({...typeof i==`object`?i:{},...v}));let ne=te||o||Zt,w=y===void 0?void 0:ee(y,en(s,h,g.header)),re=en(w===void 0||w instanceof FormData?{}:{"Content-Type":`application/json`},s,h,g.header),T=[...u,...b],E={redirect:`follow`,...l,...x,body:w,headers:re},D,O,k=new m($t(e,{baseUrl:S,params:g,querySerializer:C,pathSerializer:ne}),E),A;for(let e in x)e in k||(k[e]=x[e]);if(T.length){D=Gt(),O=Object.freeze({baseUrl:S,fetch:p,parseAs:_,querySerializer:C,bodySerializer:ee,pathSerializer:ne});for(let t of T)if(t&&typeof t==`object`&&typeof t.onRequest==`function`){let n=await t.onRequest({request:k,schemaPath:e,params:g,options:O,id:D});if(n)if(n instanceof m)k=n;else if(n instanceof Response){A=n;break}else throw Error(`onRequest: must return new Request() or Response() when modifying the request`)}}if(!A){try{A=await p(k,c)}catch(t){let n=t;if(T.length)for(let t=T.length-1;t>=0;t--){let r=T[t];if(r&&typeof r==`object`&&typeof r.onError==`function`){let t=await r.onError({request:k,error:n,schemaPath:e,params:g,options:O,id:D});if(t){if(t instanceof Response){n=void 0,A=t;break}if(t instanceof Error){n=t;continue}throw Error(`onError: must return new Response() or instance of Error`)}}}if(n)throw n}if(T.length)for(let t=T.length-1;t>=0;t--){let n=T[t];if(n&&typeof n==`object`&&typeof n.onResponse==`function`){let t=await n.onResponse({request:k,response:A,schemaPath:e,params:g,options:O,id:D});if(t){if(!(t instanceof Response))throw Error(`onResponse: must return new Response() when modifying the response`);A=t}}}}let j=A.headers.get(`Content-Length`);if(A.status===204||k.method===`HEAD`||j===`0`&&!A.headers.get(`Transfer-Encoding`)?.includes(`chunked`))return A.ok?{data:void 0,response:A}:{error:void 0,response:A};if(A.ok)return{data:await(async()=>{if(_===`stream`)return A.body;if(_===`json`&&!j){let e=await A.text();return e?JSON.parse(e):void 0}return await A[_]()})(),response:A};let M=await A.text();try{M=JSON.parse(M)}catch{}return{error:M,response:A}}return{request(e,t,n){return d(t,{...n,method:e.toUpperCase()})},GET(e,t){return d(e,{...t,method:`GET`})},PUT(e,t){return d(e,{...t,method:`PUT`})},POST(e,t){return d(e,{...t,method:`POST`})},DELETE(e,t){return d(e,{...t,method:`DELETE`})},OPTIONS(e,t){return d(e,{...t,method:`OPTIONS`})},HEAD(e,t){return d(e,{...t,method:`HEAD`})},PATCH(e,t){return d(e,{...t,method:`PATCH`})},TRACE(e,t){return d(e,{...t,method:`TRACE`})},use(...e){for(let t of e)if(t){if(typeof t!=`object`||!(`onRequest`in t||`onResponse`in t||`onError`in t))throw Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");u.push(t)}},eject(...e){for(let t of e){let e=u.indexOf(t);e!==-1&&u.splice(e,1)}}}}function qt(e,t,n){if(t==null)return``;if(typeof t==`object`)throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${n?.allowReserved===!0?t:encodeURIComponent(t)}`}function Jt(e,t,n){if(!t||typeof t!=`object`)return``;let r=[],i={simple:`,`,label:`.`,matrix:`;`}[n.style]||`&`;if(n.style!==`deepObject`&&n.explode===!1){for(let e in t)r.push(e,n.allowReserved===!0?t[e]:encodeURIComponent(t[e]));let i=r.join(`,`);switch(n.style){case`form`:return`${e}=${i}`;case`label`:return`.${i}`;case`matrix`:return`;${e}=${i}`;default:return i}}for(let i in t){let a=n.style===`deepObject`?`${e}[${i}]`:i;r.push(qt(a,t[i],n))}let a=r.join(i);return n.style===`label`||n.style===`matrix`?`${i}${a}`:a}function Yt(e,t,n){if(!Array.isArray(t))return``;if(n.explode===!1){let r={form:`,`,spaceDelimited:`%20`,pipeDelimited:`|`}[n.style]||`,`,i=(n.allowReserved===!0?t:t.map(e=>encodeURIComponent(e))).join(r);switch(n.style){case`simple`:return i;case`label`:return`.${i}`;case`matrix`:return`;${e}=${i}`;default:return`${e}=${i}`}}let r={simple:`,`,label:`.`,matrix:`;`}[n.style]||`&`,i=[];for(let r of t)n.style===`simple`||n.style===`label`?i.push(n.allowReserved===!0?r:encodeURIComponent(r)):i.push(qt(e,r,n));return n.style===`label`||n.style===`matrix`?`${r}${i.join(r)}`:i.join(r)}function Xt(e){return function(t){let n=[];if(t&&typeof t==`object`)for(let r in t){let i=t[r];if(i!=null){if(Array.isArray(i)){if(i.length===0)continue;n.push(Yt(r,i,{style:`form`,explode:!0,...e?.array,allowReserved:e?.allowReserved||!1}));continue}if(typeof i==`object`){n.push(Jt(r,i,{style:`deepObject`,explode:!0,...e?.object,allowReserved:e?.allowReserved||!1}));continue}n.push(qt(r,i,e))}}return n.join(`&`)}}function Zt(e,t){let n=e;for(let r of e.match(Ut)??[]){let e=r.substring(1,r.length-1),i=!1,a=`simple`;if(e.endsWith(`*`)&&(i=!0,e=e.substring(0,e.length-1)),e.startsWith(`.`)?(a=`label`,e=e.substring(1)):e.startsWith(`;`)&&(a=`matrix`,e=e.substring(1)),!t||t[e]===void 0||t[e]===null)continue;let o=t[e];if(Array.isArray(o)){n=n.replace(r,Yt(e,o,{style:a,explode:i}));continue}if(typeof o==`object`){n=n.replace(r,Jt(e,o,{style:a,explode:i}));continue}if(a===`matrix`){n=n.replace(r,`;${qt(e,o)}`);continue}n=n.replace(r,a===`label`?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return n}function Qt(e,t){return e instanceof FormData?e:t&&(t.get instanceof Function?t.get(`Content-Type`)??t.get(`content-type`):t[`Content-Type`]??t[`content-type`])===`application/x-www-form-urlencoded`?new URLSearchParams(e).toString():JSON.stringify(e)}function $t(e,t){let n=`${t.baseUrl}${e}`;t.params?.path&&(n=t.pathSerializer(n,t.params.path));let r=t.querySerializer(t.params.query??{});return r.startsWith(`?`)&&(r=r.substring(1)),r&&(n+=`?${r}`),n}function en(...e){let t=new Headers;for(let n of e){if(!n||typeof n!=`object`)continue;let e=n instanceof Headers?n.entries():Object.entries(n);for(let[n,r]of e)if(r===null)t.delete(n);else if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.set(n,r)}return t}function tn(e){return e.endsWith(`/`)?e.substring(0,e.length-1):e}String.fromCharCode;const nn=/\/$|\/\?|\/#/,rn=/^\.?\//;function an(e=``,t){return t?nn.test(e):e.endsWith(`/`)}function on(e=``,t){if(!t)return e.endsWith(`/`)?e:e+`/`;if(an(e,!0))return e||`/`;let n=e,r=``,i=e.indexOf(`#`);if(i!==-1&&(n=e.slice(0,i),r=e.slice(i),!n))return r;let[a,...o]=n.split(`?`);return a+`/`+(o.length>0?`?${o.join(`?`)}`:``)+r}function sn(e){return e&&e!==`/`}function cn(e,...t){let n=e||``;for(let e of t.filter(e=>sn(e)))if(n){let t=e.replace(rn,``);n=on(n)+t}else n=e;return n}function ln(e){let t;try{t=Object.freeze({baseUrl:fn(e.baseUrl),fetchImplementation:e.fetch??globalThis.fetch.bind(globalThis),getCredential:e.getCredential,timeoutMilliseconds:un(e.timeoutMilliseconds)})}catch{throw new r(`invalid_input`)}if(typeof t.fetchImplementation!=`function`||typeof t.getCredential!=`function`)throw new r(`invalid_input`);return t}async function q(e,t,n,i,a,o,s=!1,c){let d=dn(t,e.timeoutMilliseconds);try{let t=d.signal;mn(t);let f=await pn(e.getCredential,t),p;if(await i(Kt({baseUrl:e.baseUrl,fetch:async n=>{try{let i=await J(e.fetchImplementation(n),t);if(!(i instanceof Response))throw new r(`invalid_response`);p=i}catch(e){throw e instanceof r?e:t.aborted?new r(`aborted`):new r(`network_error`)}return new Response(null,{status:204})}}),{cache:`no-store`,credentials:`omit`,headers:new Headers({authorization:`Bearer ${f}`}),signal:t}),!p)throw new r(`network_error`);return o===null?await u(p,t,n,a,c):await l(p,t,n,a,o,s,c)}catch(e){throw d.didTimeout()?new r(`timeout`):e instanceof r?e:d.signal.aborted?new r(`aborted`):new r(`network_error`)}finally{d.dispose()}}function un(e){if(e===void 0)return 3e4;if(!Number.isSafeInteger(e)||e<1||e>12e4)throw new r(`invalid_input`);return e}function dn(e,t){let n=new AbortController,r=!1,i=()=>n.abort();e?.aborted?n.abort():e?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,didTimeout:()=>r,dispose:()=>{clearTimeout(a),e?.removeEventListener(`abort`,i)}}}function fn(e){if(typeof e!=`string`)throw TypeError(`Drive base URL is invalid`);let t;try{t=new URL(e)}catch{throw TypeError(`Drive base URL is invalid`)}let n=t.protocol===`http:`&&[`localhost`,`127.0.0.1`,`[::1]`].includes(t.hostname);if(t.protocol!==`https:`&&!n||t.username||t.password||t.search||t.hash||!t.host)throw TypeError(`Drive base URL is invalid`);return cn(t.origin,t.pathname)}async function pn(e,t){mn(t);let n;try{n=await J(e({signal:t}),t)}catch(e){throw e instanceof r&&e.code===`aborted`?e:t.aborted?new r(`aborted`):new r(`credential_unavailable`)}if(typeof n!=`string`||n.length<1||n.length>16384||!/^[\x21-\x7e]+$/.test(n))throw new r(`credential_unavailable`);return n}function mn(e){if(e.aborted)throw new r(`aborted`)}async function J(e,t){mn(t);let n=()=>{},i=new Promise((e,i)=>{let a=()=>i(new r(`aborted`));t.addEventListener(`abort`,a,{once:!0}),n=()=>t.removeEventListener(`abort`,a)});try{return await Promise.race([e,i])}finally{n()}}const hn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`service_unavailable`]),gn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`precondition_failed`,`service_unavailable`]),Y=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`invalid_pagination_cursor`,`precondition_failed`,`service_unavailable`]),_n=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`precondition_failed`,`upload_recovery_required`,`service_unavailable`]),vn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`service_unavailable`]),yn=Object.freeze([..._n,`invalid_idempotency_key`,`idempotency_conflict`,`quota_exceeded`]),bn=Object.freeze([..._n,`invalid_idempotency_key`]),xn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`invalid_idempotency_key`,`idempotency_conflict`,`precondition_failed`,`service_unavailable`]),Sn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`precondition_failed`,`service_unavailable`]),Cn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`invalid_idempotency_key`,`idempotency_conflict`,`precondition_failed`,`range_not_satisfiable`,`service_unavailable`]);function wn(e){return Object.freeze({registerItemRecipient:t=>Xn(e,t),listItemSharingPeople:t=>Zn(e,t),listIncomingShares:t=>Tn(e,t),getCurrentWorkspace:t=>Fn(e,t),listWorkspaceItems:t=>Nn(e,t),getWorkspaceUsage:t=>Pn(e,t),getCurrentWorkspaceSources:t=>Mn(e,t),getItem:t=>In(e,t),searchWorkspaceItems:t=>Ln(e,t),listFolderChildren:t=>Rn(e,t),createFolder:t=>zn(e,t),updateItem:t=>Bn(e,t),trashItem:t=>Vn(e,t),restoreItem:t=>Hn(e,t),deleteItem:t=>Un(e,t),listItemVersions:t=>Wn(e,t),getItemVersion:t=>Gn(e,t),restoreItemVersion:t=>Kn(e,t),createDownload:t=>En(e,t),downloadItem:t=>Dn(e,t),listItemPermissions:t=>qn(e,t),readEffectiveItemPermissions:t=>Jn(e,t),createItemPermission:t=>Yn(e,t),updateItemPermission:t=>Qn(e,t),revokeItemPermission:t=>$n(e,t),createUpload:t=>er(e,t),getUploadStatus:t=>tr(e,t),createUploadPartDescriptor:t=>nr(e,t),recordUploadPart:t=>rr(e,t),completeUpload:t=>ir(e,t),abortUpload:t=>ar(e,t)})}async function Tn(e,t){let n=ut(t);return q(e,n.signal,409,(e,t)=>e.GET(`/api/v1/shares/incoming`,{...V(`listIncomingShares`,{params:{query:n.query}}),...t}),[200],oe,!1,Y)}async function En(e,t){let n=pt(t);return q(e,n.signal,412,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/downloads`,{...V(`createDownload`,{params:{path:{workspaceId:n.workspaceId,itemId:n.itemId},query:n.versionId===void 0?{}:{versionId:n.versionId},header:{"Idempotency-Key":n.idempotencyKey,"Download-Method":n.method,...n.range===void 0?{}:{Range:n.range},...n.ifMatch===void 0?{}:{"If-Match":n.ifMatch},...n.ifNoneMatch===void 0?{}:{"If-None-Match":n.ifNoneMatch},...n.ifRange===void 0?{}:{"If-Range":n.ifRange}}}}),...t}),[200,202,304],(e,t)=>t===200?de(e):t===202?pe(e):e===void 0,!1,Cn)}async function Dn(e,t){let n=pt(t),i=await En(e,t);if(i.status===202||i.status===304)return i;let a=i.data;if(a.expiresAtEpochMilliseconds<=Date.now())throw new r(`invalid_response`);let o=dn(n.signal,e.timeoutMilliseconds);try{let t=await J(e.fetchImplementation(kn(a,o.signal)),o.signal);if(!An(t,a))throw await t.body?.cancel().catch(()=>void 0),new r(`invalid_response`);let i=On(a);if(a.method===`HEAD`)return await t.body?.cancel().catch(()=>void 0),o.dispose(),new Response(null,{status:t.status,headers:i});if(!t.body){if(o.dispose(),a.response.contentLength!==0)throw new r(`invalid_response`);return new Response(null,{status:t.status,headers:i})}return o.dispose(),new Response(jn(t.body,a.response.contentLength,n.signal),{status:t.status,headers:i})}catch(e){throw o.dispose(),o.didTimeout()?new r(`timeout`):e instanceof r?e:o.signal.aborted?new r(o.didTimeout()?`timeout`:`aborted`):new r(`network_error`)}}function On(e){let t=e.response,n=new Headers;return n.set(`accept-ranges`,t.acceptRanges),n.set(`content-disposition`,t.contentDisposition),n.set(`content-length`,String(t.contentLength)),n.set(`content-type`,t.contentType),n.set(`etag`,t.etag),t.contentRange===null?n.delete(`content-range`):n.set(`content-range`,t.contentRange),n}function kn(e,t){let n={method:e.method,headers:e.headers,redirect:`manual`,signal:t};try{return new Request(e.url,{...n,cache:`no-store`,credentials:`omit`,referrerPolicy:`no-referrer`})}catch{try{return new Request(e.url,{...n,credentials:`omit`,referrerPolicy:`no-referrer`})}catch{return new Request(e.url,{...n,credentials:`omit`})}}}function An(e,t){let n=t.response,r=e.headers.get(`content-encoding`);return e.status===n.status&&e.headers.get(`etag`)===n.etag&&e.headers.get(`content-length`)===String(n.contentLength)&&(r===null||r===`identity`)&&(n.contentRange===null?e.headers.get(`content-range`)===null:e.headers.get(`content-range`)===n.contentRange)}function jn(e,t,n){let i=e.getReader(),a=0,o=!1,s=()=>{};return new ReadableStream({start(e){if(!n)return;let t=()=>{o||(o=!0,s(),i.cancel().catch(()=>void 0),e.error(new r(`aborted`)))};n.aborted?t():(n.addEventListener(`abort`,t,{once:!0}),s=()=>n.removeEventListener(`abort`,t))},async pull(e){if(!o)try{let n=await i.read();if(o)return;if(n.done)o=!0,s(),i.releaseLock(),a===t?e.close():e.error(new r(`invalid_response`));else{if(a+=n.value.byteLength,!Number.isSafeInteger(a)||a>t){o=!0,s(),await i.cancel().catch(()=>void 0),e.error(new r(`invalid_response`));return}e.enqueue(n.value)}}catch(t){if(o)return;o=!0,s(),await i.cancel().catch(()=>void 0),e.error(t instanceof r?t:n?.aborted?new r(`aborted`):new r(`network_error`))}},async cancel(e){o||(o=!0,s(),await i.cancel(e).catch(()=>void 0))}})}async function Mn(e,t){return q(e,lt(t).signal,null,(e,t)=>e.GET(`/api/v1/workspaces/current/sources`,{...V(`getCurrentWorkspaceSources`,{params:{}}),...t}),[200],le,!1,hn)}async function Nn(e,t){let n=dt(t,!0);return q(e,n.signal,null,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items`,{...V(`listWorkspaceItems`,{params:{path:{workspaceId:n.workspaceId},query:n.query}}),...t}),[200],e=>ce(e)&&e.items.length<=(n.query.limit??25)&&e.items.every((e,t,r)=>e.workspaceId===n.workspaceId&&e.lifecycleState===(n.query.view===`trash`?`trashed`:`active`)&&((n.query.view??`recent`)!==`recent`||e.modifiedAtEpochMilliseconds!==null)&&(n.query.kind===void 0||e.type===n.query.kind)&&(n.query.creatorUserId===void 0||e.creatorUserId===n.query.creatorUserId)&&(t===0||((n.query.view??`recent`)===`recent`?r[t-1].modifiedAtEpochMilliseconds>e.modifiedAtEpochMilliseconds||r[t-1].modifiedAtEpochMilliseconds===e.modifiedAtEpochMilliseconds&&r[t-1].itemId<e.itemId:r[t-1].itemId<e.itemId))),!1,Y)}async function Pn(e,t){let n=dt(t,!1);return q(e,n.signal,null,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/usage`,{...V(`getWorkspaceUsage`,{params:{path:{workspaceId:n.workspaceId}}}),...t}),[200],e=>se(e)&&e.workspaceId===n.workspaceId,!1,Y)}async function Fn(e,t){return q(e,lt(t).signal,null,(e,t)=>e.GET(`/api/v1/workspaces/current`,{...V(`getCurrentWorkspace`,{params:{}}),...t}),[200],ue,!1,hn)}async function In(e,t){let n=R(t);return q(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}`,{...V(`getItem`,{params:{path:B(n)}}),...t}),[200],(e,t,r)=>_e(e,n.workspaceId,n.itemId)&&N(r,e.revision),!1,gn)}async function Ln(e,t){let n=mt(t);return q(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/search`,{...V(`searchWorkspaceItems`,{params:{path:{workspaceId:n.workspaceId},query:{query:n.query,...n.limit===void 0?{}:{limit:n.limit},...n.cursor===void 0?{}:{cursor:n.cursor}}}}),...t}),[200],e=>ve(e,n.workspaceId,n.query,n.limit??50),!1,Y)}async function Rn(e,t){let n=ht(t);return q(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/children`,{...V(`listFolderChildren`,{params:{path:B(n),query:At(n)}}),...t}),[200],e=>me(e,n.workspaceId,n.itemId))}async function zn(e,t){let n=gt(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/children`,{...V(`createFolder`,{params:{path:B(n),header:{"Idempotency-Key":n.idempotencyKey}},body:{name:n.name}}),...t}),[200,201],e=>he(e)&&e.workspaceId===n.workspaceId&&e.parentItemId===n.itemId&&e.kind===`folder`&&e.name===n.name)}async function Bn(e,t){let n=_t(t);return q(e,n.signal,409,(e,t)=>e.PATCH(`/api/v1/workspaces/{workspaceId}/items/{itemId}`,{...V(`updateItem`,{params:{path:B(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}},body:{name:n.name,parentItemId:n.parentItemId}}),...t}),[200],(e,t,r)=>ge(e,n.workspaceId,n.itemId,`active`)&&e.name===n.name&&e.parentItemId===n.parentItemId&&N(r,e.revision),!1,xn)}async function Vn(e,t){let n=z(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/trash`,{...V(`trashItem`,{params:{path:B(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>ge(e,n.workspaceId,n.itemId,`trashed`)&&N(r,e.revision),!1,xn)}async function Hn(e,t){let n=z(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/restore`,{...V(`restoreItem`,{params:{path:B(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>ge(e,n.workspaceId,n.itemId,`active`)&&N(r,e.revision),!1,xn)}async function Un(e,t){let n=z(t);return q(e,n.signal,409,(e,t)=>e.DELETE(`/api/v1/workspaces/{workspaceId}/items/{itemId}`,{...V(`deleteItem`,{params:{path:B(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200,202],(e,t,r)=>ge(e,n.workspaceId,n.itemId,`deleting`)&&N(r,e.revision),!1,xn)}async function Wn(e,t){let n=ht(t);return q(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/versions`,{...V(`listItemVersions`,{params:{path:B(n),query:At(n)}}),...t}),[200],e=>Ce(e,n.limit??50),!1,Sn)}async function Gn(e,t){let n=ft(t);return q(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}`,{...V(`getItemVersion`,{params:{path:{...B(n),versionId:n.versionId}}}),...t}),[200],e=>Le(e,n.workspaceId,n.itemId,n.versionId),!1,Sn)}async function Kn(e,t){let n=vt(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}/restore`,{...V(`restoreItemVersion`,{params:{path:{...B(n),versionId:n.versionId},header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>we(e,n.versionId)&&N(r,e.itemRevision),!1,xn)}async function qn(e,t){let n=ht(t);return q(e,n.signal,412,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions`,{...V(`listItemPermissions`,{params:{path:B(n),query:At(n)}}),...t}),[200],(e,t,r)=>Te(e,r,n.itemId))}async function Jn(e,t){let n=R(t);return q(e,n.signal,412,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/effective`,{...V(`readEffectiveItemPermissions`,{params:{path:B(n)}}),...t}),[200],e=>Oe(e,n.itemId))}async function Yn(e,t){let n=yt(t);return q(e,n.signal,412,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions`,{...V(`createItemPermission`,{params:{path:B(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}},body:{grantee:n.grantee,actions:n.actions,expiresAtEpochMilliseconds:n.expiresAtEpochMilliseconds}}),...t}),[200,201],(e,t,r)=>De(e,n.itemId)&&(t===201&&e.outcome===`committed`||t===200&&e.outcome===`replayed`)&&(t===200||e.grant.availability!==`revoked`)&&Be(r))}async function Xn(e,t){let n=bt(t);return q(e,n.signal,412,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/sharing`,{...V(`registerItemRecipient`,{params:{path:B(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}},body:{email:n.email,role:n.role}}),...t}),[200,201],(e,t,r)=>De(e,n.itemId)&&(t===201&&e.outcome===`committed`||t===200&&e.outcome===`replayed`)&&(t===200||e.grant.availability!==`revoked`)&&Be(r),!1,[...Y,`recipient_unavailable`,`rate_limited`,`idempotency_conflict`,`invalid_idempotency_key`])}async function Zn(e,t){let n=ht(t);return q(e,n.signal,412,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/sharing/people`,{...V(`listItemSharingPeople`,{params:{path:B(n),query:At(n)}}),...t}),[200],(e,t,r)=>Ee(e,r,n.itemId))}async function Qn(e,t){let n=St(t),r={};return n.actions!==void 0&&(r.actions=n.actions),n.expiresAtEpochMilliseconds!==void 0&&(r.expiresAtEpochMilliseconds=n.expiresAtEpochMilliseconds),q(e,n.signal,412,(e,t)=>e.PATCH(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}`,{...V(`updateItemPermission`,{params:{path:{...B(n),grantId:n.grantId},header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}},body:r}),...t}),[200],(e,t,r)=>De(e,n.itemId,n.grantId)&&e.grant.availability!==`revoked`&&Be(r))}async function $n(e,t){let n=xt(t);return q(e,n.signal,412,(e,t)=>e.DELETE(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}`,{...V(`revokeItemPermission`,{params:{path:{...B(n),grantId:n.grantId},header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>De(e,n.itemId,n.grantId)&&e.grant.availability===`revoked`&&d(r.get(`drive-permission-collection-etag`)??``)!==void 0&&r.get(`drive-permission-grant-etag`)===null)}async function er(e,t){let n=Ct(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads`,{...V(`createUpload`,{params:{path:{workspaceId:n.workspaceId},header:{"Idempotency-Key":n.idempotencyKey}},body:{parentItemId:n.parentItemId,expectedByteLength:n.expectedByteLength,displayFilename:n.displayFilename,mediaType:n.mediaType,callerDeclaredContentDigest:n.callerDeclaredContentDigest,protectionClassification:n.protectionClassification}}),...t}),[200,201],e=>ke(e,n.expectedByteLength),!0,yn)}async function tr(e,t){let n=wt(t),r=n.afterPartNumber??0,i=n.limit??100;return q(e,n.signal,null,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}`,{...V(`getUploadStatus`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId},query:{...n.afterPartNumber===void 0?{}:{afterPartNumber:String(n.afterPartNumber)},...n.limit===void 0?{}:{limit:String(n.limit)}}}}),...t}),[200],e=>Ae(e,r,i)&&e.uploadId===n.uploadId,!1,vn)}async function nr(e,t){let n=Tt(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts`,{...V(`createUploadPartDescriptor`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId}},body:{partNumber:n.partNumber,checksumSha256:n.checksumSha256,contentMd5:n.contentMd5}}),...t}),[200],t=>je(t,n.partNumber,new URL(e.baseUrl).protocol===`http:`,n.contentMd5),!1,_n)}async function rr(e,t){let n=Et(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts/{partNumber}`,{...V(`recordUploadPart`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId,partNumber:String(n.partNumber)}},body:{expectedUploadRevision:n.expectedUploadRevision,byteLength:n.byteLength,etag:n.etag,checksumSha256:n.checksumSha256}}),...t}),[200],e=>Me(e,n.partNumber,n.expectedUploadRevision),!1,_n)}async function ir(e,t){let n=Dt(t);return q(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/complete`,{...V(`completeUpload`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId},header:{"Idempotency-Key":n.idempotencyKey}}}),...t}),[200,202],(e,t)=>t===202?Pe(e,n.uploadId):Ne(e,{uploadId:n.uploadId}),!1,bn)}async function ar(e,t){let n=Ot(t);return q(e,n.signal,409,(e,t)=>e.DELETE(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}`,{...V(`abortUpload`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId}}}),...t}),[204],null,!1,_n)}const or=e=>e/2**32|0,sr=e=>e>>>0;function cr(e,t,n,r){let i=or(n),a=sr(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function lr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ur=e=>e?`"${e}" `:``;function dr(e,t=``){if(typeof e!=`number`)throw TypeError(ur(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ur(t)+`expected integer >= 0, got `+e);return e}function fr(e,t,n=``){if(lr(e)&&(t===void 0||e.length===t))return e;t!==void 0&&dr(t,`length`);let r=lr(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ur(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const pr=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function mr(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function hr(e,t){fr(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function gr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _r(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function X(e,t){return e<<32-t|e>>>t}function vr(e,t){return e<<t|e>>>32-t>>>0}const yr=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,br=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function xr(e){if(fr(e),yr)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=br[e[n]];return t}function Sr(e,t,n=`opts`){return pr(e,`defaults`),t!==void 0&&pr(t,n),Object.assign(e,t)}function Cr(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=Sr({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}const wr=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Tr(e,t,n){return e&t^~e&n}function Er(e,t,n){return e&t^e&n^t&n}var Dr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=_r(this.buffer)}update(e){mr(this),fr(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=_r(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0;continue}n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){mr(this),hr(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),cr(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:_r(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const Or=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),kr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Z=new Uint32Array(64);var Ar=class extends Dr{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)Z[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Z[e-15],n=Z[e-2],r=X(t,7)^X(t,18)^t>>>3,i=X(n,17)^X(n,19)^n>>>10;Z[e]=i+Z[e-7]+r+Z[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=X(o,6)^X(o,11)^X(o,25),u=l+t+Tr(o,s,c)+kr[e]+Z[e]|0,d=(X(n,2)^X(n,13)^X(n,22))+Er(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){gr(Z)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),gr(this.buffer)}},jr=class extends Ar{constructor(){super(32,Or)}};const Mr=Cr(()=>new jr,wr(1)),Nr=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Pr=2**32,Fr=Array.from({length:64},(e,t)=>Math.floor(Pr*Math.abs(Math.sin(t+1)))),Ir=Nr.slice(0,4),Lr=new Uint32Array(16),Rr=(()=>{let e=[[7,12,17,22],[5,9,14,20],[4,11,16,23],[6,10,15,21]];return Uint8Array.from({length:64},(t,n)=>e[Math.floor(n/16)][n%4])})();var zr=class extends Dr{A=Ir[0]|0;B=Ir[1]|0;C=Ir[2]|0;D=Ir[3]|0;constructor(){super(64,16,8,!0)}get(){let{A:e,B:t,C:n,D:r}=this;return[e,t,n,r]}set(e,t,n,r){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)Lr[n]=e.getUint32(t,!0);let{A:n,B:r,C:i,D:a}=this;for(let e=0;e<64;e++){let t,o;e<16?(t=Tr(r,i,a),o=e):e<32?(t=Tr(a,r,i),o=(5*e+1)%16):e<48?(t=r^i^a,o=(3*e+5)%16):(t=i^(r|~a),o=7*e%16),t=t+n+Fr[e]+Lr[o],n=a,a=i,i=r,r+=vr(t,Rr[e])}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,this.set(n,r,i,a)}roundClean(){gr(Lr)}destroy(){this.destroyed=!0,this.set(0,0,0,0),gr(this.buffer)}};const Br=Cr(()=>new zr),Q=32*1024*1024;async function Vr(e,t,n){let i=kt(t),a=Math.ceil(i.byteLength/Q);$(i.onProgress,`preparing`,0,i.byteLength,0,a);let o;try{let t=await Kr(i.source,i.byteLength,a,i.signal),s=await n.createUpload({workspaceId:i.workspaceId,parentItemId:i.parentItemId,expectedByteLength:i.byteLength,displayFilename:i.displayFilename,mediaType:i.mediaType,callerDeclaredContentDigest:t.callerDeclaredContentDigest,protectionClassification:i.protectionClassification,idempotencyKey:i.idempotencyKey,...i.signal===void 0?{}:{signal:i.signal}});o=s.data,Jr(o,i.byteLength,a,s.status,s.requestId);let c=await Ur(n,i,o,t);if($(i.onProgress,`uploading`,c.confirmedByteLength,i.byteLength,c.confirmedParts.size,a),c.readyResult)return $(i.onProgress,`completing`,c.confirmedByteLength,i.byteLength,c.confirmedParts.size,a),c.readyResult;let l=c.revision,u=c.confirmedByteLength,d=c.confirmedParts.size;if(c.lifecycle===`uploading`)for(let s of Hr(o.partCount,c.confirmedParts)){let c=s-1;ii(i.signal);let f=c*o.partByteLength,p=Math.min(f+o.partByteLength,i.byteLength),m=p-f,h=t.partChecksums[c];if(!h)throw new r(`invalid_response`);let g=await n.createUploadPartDescriptor({workspaceId:i.workspaceId,uploadId:o.uploadId,partNumber:s,checksumSha256:h,contentMd5:t.partMd5s[c],...i.signal===void 0?{}:{signal:i.signal}}),_=g.data;if(_.expectedByteLength!==m||_.expiresAtEpochMilliseconds>o.expiresAtEpochMilliseconds)throw new r(`invalid_response`,{status:g.status,requestId:g.requestId});let v=await qr(e,_,ti(i.source,f,p,m),i.signal);l=await Wr(n,i,o,s,l,m,v,h),u+=m,d+=1,$(i.onProgress,`uploading`,u,i.byteLength,d,a)}$(i.onProgress,`completing`,u,i.byteLength,d,a);let f=await Gr(n,i,o,t);return f.data.state===`verifying`&&$(i.onProgress,`verifying`,u,i.byteLength,d,a),f}catch(e){throw i.signal?.aborted&&o&&await ni(n,i.workspaceId,o.uploadId),e instanceof r?e:i.signal?.aborted?new r(`aborted`):new r(`invalid_input`)}}function*Hr(e,t){for(let n=1;n<=e;n+=1)t.has(n)||(yield n)}async function Ur(e,t,n,i){let a=new Set,o=0,s=0,c,l,u;for(let d=0;d<100;d+=1){let f=await e.getUploadStatus({workspaceId:t.workspaceId,uploadId:n.uploadId,afterPartNumber:s,limit:100,...t.signal===void 0?{}:{signal:t.signal}}),p=f.data;Yr(p,n),c?Xr(p,c):(c=p,l=f.requestId);for(let e of p.confirmedParts){let n=i.partChecksums[e.partNumber-1];if(!n||e.checksumSha256!==n||a.has(e.partNumber))throw new r(`invalid_response`,{status:f.status,requestId:f.requestId});a.add(e.partNumber),o+=ei(t.byteLength,e.partNumber)}if(p.lifecycle===`ready`&&p.ready&&(Zr(p.ready,n,t,i,f.requestId),u=$r(f,p.ready)),p.nextAfterPartNumber===null)break;if(d===99)throw new r(`invalid_response`,{status:f.status,requestId:f.requestId});s=p.nextAfterPartNumber}if(!c||n.mode===`presigned-multipart`&&[`completing`,`provider-completed`,`verifying`,`ready`].includes(c.lifecycle)&&a.size!==n.partCount)throw new r(`invalid_response`);return Qr(c.lifecycle,l),Object.freeze({revision:c.revision,confirmedParts:a,confirmedByteLength:o,lifecycle:c.lifecycle,...u===void 0?{}:{readyResult:u}})}async function Wr(e,t,n,i,a,o,s,c){let l=r=>e.recordUploadPart({workspaceId:t.workspaceId,uploadId:n.uploadId,partNumber:i,expectedUploadRevision:r,byteLength:o,etag:s,checksumSha256:c,...t.signal===void 0?{}:{signal:t.signal}});try{return(await l(a)).data.revision}catch(a){if(!ri(a)||t.signal?.aborted)throw a;let o=await e.getUploadStatus({workspaceId:t.workspaceId,uploadId:n.uploadId,afterPartNumber:i-1,limit:1,...t.signal===void 0?{}:{signal:t.signal}}),s=o.data;Yr(s,n),Qr(s.lifecycle,o.requestId);let u=s.confirmedParts.find(e=>e.partNumber===i);if(u){if(u.checksumSha256!==c)throw new r(`invalid_response`,{status:o.status,requestId:o.requestId});return s.revision}if(s.lifecycle!==`uploading`)throw new r(`precondition_failed`);return(await l(s.revision)).data.revision}}async function Gr(e,t,n,i){try{let a=await e.completeUpload({workspaceId:t.workspaceId,uploadId:n.uploadId,idempotencyKey:t.completionIdempotencyKey,...t.signal===void 0?{}:{signal:t.signal}});if(a.data.state===`ready`)Zr(a.data,n,t,i,a.requestId);else if(a.data.itemId!==n.itemId||a.data.versionId!==n.versionId||a.data.uploadId!==n.uploadId||a.data.totalByteLength!==t.byteLength)throw new r(`invalid_response`);return a}catch(r){if(!ri(r)||t.signal?.aborted)throw r;let a=await e.getUploadStatus({workspaceId:t.workspaceId,uploadId:n.uploadId,afterPartNumber:0,limit:1,...t.signal===void 0?{}:{signal:t.signal}}),o=a.data;if(Yr(o,n),o.lifecycle!==`ready`||!o.ready)throw r;return Zr(o.ready,n,t,i,a.requestId),$r(a,o.ready)}}async function Kr(e,t,n,i){let a=Mr.create(),o=[],s=[];for(let c=0;c<n;c+=1){ii(i);let n=c*Q,l=Math.min(n+Q,t),u=ti(e,n,l,l-n),d;try{d=i?await J(u.arrayBuffer(),i):await u.arrayBuffer()}catch(e){throw e instanceof r?e:i?.aborted?new r(`aborted`):new r(`invalid_input`)}if(d.byteLength!==l-n)throw new r(`invalid_input`);let f=new Uint8Array(d);a.update(f),o.push(ai(Mr(f))),s.push(ai(Br(f)))}return Object.freeze({callerDeclaredContentDigest:`sha256:${xr(a.digest())}`,partChecksums:Object.freeze(o),partMd5s:Object.freeze(s)})}async function qr(e,t,n,i){let a=t.expiresAtEpochMilliseconds-Date.now();if(a<1)throw new r(`invalid_response`);let o=dn(i,Math.min(e.timeoutMilliseconds,a)),s;try{if(s=await J(e.fetchImplementation(t.url,{method:t.method,body:n,headers:t.headers,credentials:`omit`,cache:`no-store`,redirect:`error`,referrerPolicy:`no-referrer`,signal:o.signal}),o.signal),!(s instanceof Response))throw new r(`invalid_response`);let i=s.headers.get(`etag`),a=s.headers.get(`content-md5`),c=a===null||a===t.headers[`content-md5`];if(s.status<200||s.status>299||!oi(i)||!c)throw new r(`invalid_response`,{status:s.status});return i}catch(e){throw o.didTimeout()?new r(`timeout`):i?.aborted?new r(`aborted`):e instanceof r?e:new r(`network_error`)}finally{o.dispose(),s?.body?.cancel().catch(()=>{})}}function Jr(e,t,n,i,a){let o=t===0?`server-mediated-zero-byte`:`presigned-multipart`;if(e.mode!==o||e.partByteLength!==Q||e.partCount!==n||e.expiresAtEpochMilliseconds<=Date.now())throw new r(`invalid_response`,{status:i,requestId:a})}function Yr(e,t){if(e.itemId!==t.itemId||e.versionId!==t.versionId||e.uploadId!==t.uploadId||e.mode!==t.mode||e.revision<t.revision||e.partPolicy.partByteLength!==t.partByteLength||e.partPolicy.partCount!==t.partCount||e.partPolicy.maxParts!==1e4||e.expiresAtEpochMilliseconds!==t.expiresAtEpochMilliseconds)throw new r(`invalid_response`)}function Xr(e,t){if(e.itemId!==t.itemId||e.versionId!==t.versionId||e.uploadId!==t.uploadId||e.mode!==t.mode||e.lifecycle!==t.lifecycle||e.revision!==t.revision||e.partPolicy.partByteLength!==t.partPolicy.partByteLength||e.partPolicy.partCount!==t.partPolicy.partCount||e.partPolicy.maxParts!==t.partPolicy.maxParts||e.expiresAtEpochMilliseconds!==t.expiresAtEpochMilliseconds||JSON.stringify(e.ready)!==JSON.stringify(t.ready))throw new r(`invalid_response`)}function Zr(e,t,n,i,a){if(e.itemId!==t.itemId||e.versionId!==t.versionId||e.uploadId!==t.uploadId||e.byteLength!==n.byteLength||e.callerDeclaredContentDigest!==i.callerDeclaredContentDigest||e.displayFilename!==n.displayFilename||e.mediaType!==n.mediaType)throw new r(`invalid_response`,{status:200,requestId:a})}function Qr(e,t){if(e===`initiating`||e===`recovery-required`)throw new r(`upload_recovery_required`,{status:409,...t===void 0?{}:{requestId:t}});if(e===`aborting`||e===`aborted`||e===`failed`)throw new r(`precondition_failed`,{status:409,...t===void 0?{}:{requestId:t}})}function $r(e,t){return Object.freeze({data:t,status:e.status,requestId:e.requestId,validators:e.validators})}function ei(e,t){return Math.min(Q,e-(t-1)*Q)}function ti(e,t,n,i){try{let a=e.slice(t,n);if(!(a instanceof Blob)||a.size!==i)throw new r(`invalid_input`);return a}catch(e){throw e instanceof r?e:new r(`invalid_input`)}}function $(e,t,n,r,i,a){if(!e)return;let o=Object.freeze({phase:t,confirmedByteLength:n,totalByteLength:r,confirmedPartCount:i,totalPartCount:a});try{e(o)}catch{}}async function ni(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),5e3);try{await e.abortUpload({workspaceId:t,uploadId:n,signal:r.signal})}catch{}finally{clearTimeout(i)}}function ri(e){return e instanceof r&&(e.code===`network_error`||e.code===`timeout`||e.code===`invalid_response`)}function ii(e){if(e?.aborted)throw new r(`aborted`)}function ai(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function oi(e){return e!==null&&e.length>=1&&e.length<=1024&&/^[\x20-\x7e]+$/.test(e)}function si(e){let t=ln(e),n=wn(t);return Object.freeze({...n,uploadFile:e=>Vr(t,e,n)})}export{e as DRIVE_API_ERROR_CODES,t as DRIVE_API_ERROR_MESSAGES,r as DriveError,si as createDriveClient};