@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/server.js CHANGED
@@ -1,2732 +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$1 = 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$1 || !isSafeInteger$1(value.partCount) || value.partCount > 1e4 || value.partCount !== Math.ceil(expectedByteLength / UPLOAD_PART_BYTE_LENGTH$1) || (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$1 || !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$1 || !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 = 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 || !isEtag(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 resourcePath(input) {
1320
- return {
1321
- workspaceId: input.workspaceId,
1322
- itemId: input.itemId
1323
- };
1324
- }
1325
- function pageQuery(input) {
1326
- return {
1327
- ...input.limit === void 0 ? {} : { limit: input.limit },
1328
- ...input.cursor === void 0 ? {} : { cursor: input.cursor }
1329
- };
1330
- }
1331
- function operationOptions(_operationId, options) {
1332
- return options;
1333
- }
1334
- function captureRecord(value, required, optional) {
1335
- try {
1336
- if (typeof value !== "object" && typeof value !== "function" || value === null || Array.isArray(value)) throw new DriveError("invalid_input");
1337
- const descriptors = Object.getOwnPropertyDescriptors(value);
1338
- const keys = Reflect.ownKeys(descriptors);
1339
- const allowed = new Set([...required, ...optional]);
1340
- if (keys.some((key) => typeof key !== "string" || !allowed.has(key)) || required.some((key) => !Object.hasOwn(descriptors, key))) throw new DriveError("invalid_input");
1341
- const result = {};
1342
- for (const key of keys) {
1343
- if (typeof key !== "string") throw new DriveError("invalid_input");
1344
- const descriptor = descriptors[key];
1345
- if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) throw new DriveError("invalid_input");
1346
- result[key] = descriptor.value;
1347
- }
1348
- return result;
1349
- } catch (error) {
1350
- if (error instanceof DriveError) throw error;
1351
- throw new DriveError("invalid_input");
1352
- }
1353
- }
1354
- function validateSignal(value) {
1355
- if (value === void 0) return void 0;
1356
- if (!(value instanceof AbortSignal)) throw new DriveError("invalid_input");
1357
- return value;
1358
- }
1359
- function validateGrantee(value) {
1360
- const type = captureRecord(value, ["type"], ["userId", "teamId"]);
1361
- if (type.type === "user") {
1362
- const user = captureRecord(value, ["type", "userId"], []);
1363
- if (typeof user.userId === "string" && AUTH_ID.test(user.userId)) return {
1364
- type: "user",
1365
- userId: user.userId
1366
- };
1367
- }
1368
- if (type.type === "team") {
1369
- const team = captureRecord(value, ["type", "teamId"], []);
1370
- if (typeof team.teamId === "string" && AUTH_ID.test(team.teamId)) return {
1371
- type: "team",
1372
- teamId: team.teamId
1373
- };
1374
- }
1375
- throw new DriveError("invalid_input");
1376
- }
1377
- function validateInputActions(value) {
1378
- const actions = captureArray(value);
1379
- 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");
1380
- return actions;
1381
- }
1382
- function captureArray(value) {
1383
- try {
1384
- if (!Array.isArray(value)) throw new DriveError("invalid_input");
1385
- const descriptors = Object.getOwnPropertyDescriptors(value);
1386
- if (Reflect.ownKeys(descriptors).some((key) => typeof key !== "string")) throw new DriveError("invalid_input");
1387
- const result = [];
1388
- for (let index = 0; index < value.length; index += 1) {
1389
- const descriptor = descriptors[String(index)];
1390
- if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) throw new DriveError("invalid_input");
1391
- result.push(descriptor.value);
1392
- }
1393
- if (Reflect.ownKeys(descriptors).length !== value.length + 1) throw new DriveError("invalid_input");
1394
- return result;
1395
- } catch (error) {
1396
- if (error instanceof DriveError) throw error;
1397
- throw new DriveError("invalid_input");
1398
- }
1399
- }
1400
- function isIdempotencyKey(value) {
1401
- return typeof value === "string" && IDEMPOTENCY_KEY.test(value);
1402
- }
1403
- function validateUploadPath(workspaceId, uploadId, signalValue) {
1404
- const signal = validateSignal(signalValue);
1405
- if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId) || typeof uploadId !== "string" || !UPLOAD_ID.test(uploadId)) throw new DriveError("invalid_input");
1406
- return {
1407
- workspaceId,
1408
- uploadId,
1409
- ...signal === void 0 ? {} : { signal }
1410
- };
1411
- }
1412
- function isPartNumber(value) {
1413
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= 1e4;
1414
- }
1415
- function isPartChecksum(value) {
1416
- return typeof value === "string" && PART_CHECKSUM.test(value);
1417
- }
1418
- function isEtag(value) {
1419
- return typeof value === "string" && value.length >= 1 && value.length <= 1024 && /^[\x20-\x7e]+$/.test(value);
1420
- }
1421
- function isMediaType(value) {
1422
- 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);
1423
- }
1424
- function isSearchQuery(value) {
1425
- if (typeof value !== "string" || value.length === 0) return false;
1426
- try {
1427
- if (value.normalize("NFC") !== value) return false;
1428
- let codePoints = 0;
1429
- let bytes = 0;
1430
- for (const character of value) {
1431
- const point = character.codePointAt(0);
1432
- if (point === void 0 || point <= 31 || point >= 127 && point <= 159 || point === 8232 || point === 8233 || point >= 55296 && point <= 57343) return false;
1433
- codePoints += 1;
1434
- bytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
1435
- if (codePoints > 64 || bytes > 255) return false;
1436
- }
1437
- return true;
1438
- } catch {
1439
- return false;
1440
- }
1441
- }
1442
- function isExpiry(value) {
1443
- return value === null || isSafeInteger(value);
1444
- }
1445
- function isSafeFilename(value) {
1446
- if (typeof value !== "string" || value.length === 0 || value.length > 510 || value.normalize("NFC") !== value || value.endsWith(".") || value.endsWith(" ") || filenameIsReserved(value)) return false;
1447
- let codePoints = 0;
1448
- let bytes = 0;
1449
- for (const character of value) {
1450
- const point = character.codePointAt(0);
1451
- if (point === void 0 || point === 47 || point === 92 || point <= 31 || point >= 127 && point <= 159 || point === 8232 || point === 8233 || point >= 55296 && point <= 57343) return false;
1452
- codePoints += 1;
1453
- bytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
1454
- if (codePoints > 255 || bytes > 255) return false;
1455
- }
1456
- return true;
1457
- }
1458
- function filenameIsReserved(value) {
1459
- const base = value.split(".", 1)[0].toUpperCase();
1460
- return value === "." || value === ".." || [
1461
- "CON",
1462
- "PRN",
1463
- "AUX",
1464
- "NUL",
1465
- "CLOCK$",
1466
- "CONIN$",
1467
- "CONOUT$"
1468
- ].includes(base) || /^COM[1-9]$/.test(base) || /^LPT[1-9]$/.test(base);
1469
- }
1470
- function isSafeInteger(value) {
1471
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1472
- }
1473
- function isOptionalHeaderValue(value) {
1474
- return value === void 0 || typeof value === "string" && value.length <= 8192 && !value.split("").some((character) => {
1475
- const code = character.charCodeAt(0);
1476
- return code <= 31 || code === 127;
1477
- });
1478
- }
1479
- //#endregion
1480
- //#region ../../node_modules/.pnpm/openapi-fetch@0.17.0/node_modules/openapi-fetch/dist/index.mjs
1481
- const PATH_PARAM_RE = /\{[^{}]+\}/g;
1482
- const supportsRequestInitExt = () => {
1483
- return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
1484
- };
1485
- function randomID() {
1486
- return Math.random().toString(36).slice(2, 11);
1487
- }
1488
- function createClient(clientOptions) {
1489
- let { baseUrl = "", Request: CustomRequest = globalThis.Request, fetch: baseFetch = globalThis.fetch, querySerializer: globalQuerySerializer, bodySerializer: globalBodySerializer, pathSerializer: globalPathSerializer, headers: baseHeaders, requestInitExt = void 0, ...baseOptions } = { ...clientOptions };
1490
- requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
1491
- baseUrl = removeTrailingSlash(baseUrl);
1492
- const globalMiddlewares = [];
1493
- async function coreFetch(schemaPath, fetchOptions) {
1494
- const { baseUrl: localBaseUrl, fetch = baseFetch, Request = CustomRequest, headers, params = {}, parseAs = "json", querySerializer: requestQuerySerializer, bodySerializer = globalBodySerializer ?? defaultBodySerializer, pathSerializer: requestPathSerializer, body, middleware: requestMiddlewares = [], ...init } = fetchOptions || {};
1495
- let finalBaseUrl = baseUrl;
1496
- if (localBaseUrl) finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
1497
- let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
1498
- if (requestQuerySerializer) querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
1499
- ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
1500
- ...requestQuerySerializer
1501
- });
1502
- const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;
1503
- const serializedBody = body === void 0 ? void 0 : bodySerializer(body, mergeHeaders(baseHeaders, headers, params.header));
1504
- const finalHeaders = mergeHeaders(serializedBody === void 0 || serializedBody instanceof FormData ? {} : { "Content-Type": "application/json" }, baseHeaders, headers, params.header);
1505
- const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];
1506
- const requestInit = {
1507
- redirect: "follow",
1508
- ...baseOptions,
1509
- ...init,
1510
- body: serializedBody,
1511
- headers: finalHeaders
1512
- };
1513
- let id;
1514
- let options;
1515
- let request = new Request(createFinalURL(schemaPath, {
1516
- baseUrl: finalBaseUrl,
1517
- params,
1518
- querySerializer,
1519
- pathSerializer
1520
- }), requestInit);
1521
- let response;
1522
- for (const key in init) if (!(key in request)) request[key] = init[key];
1523
- if (finalMiddlewares.length) {
1524
- id = randomID();
1525
- options = Object.freeze({
1526
- baseUrl: finalBaseUrl,
1527
- fetch,
1528
- parseAs,
1529
- querySerializer,
1530
- bodySerializer,
1531
- pathSerializer
1532
- });
1533
- for (const m of finalMiddlewares) if (m && typeof m === "object" && typeof m.onRequest === "function") {
1534
- const result = await m.onRequest({
1535
- request,
1536
- schemaPath,
1537
- params,
1538
- options,
1539
- id
1540
- });
1541
- if (result) if (result instanceof Request) request = result;
1542
- else if (result instanceof Response) {
1543
- response = result;
1544
- break;
1545
- } else throw new Error("onRequest: must return new Request() or Response() when modifying the request");
1546
- }
1547
- }
1548
- if (!response) {
1549
- try {
1550
- response = await fetch(request, requestInitExt);
1551
- } catch (error2) {
1552
- let errorAfterMiddleware = error2;
1553
- if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
1554
- const m = finalMiddlewares[i];
1555
- if (m && typeof m === "object" && typeof m.onError === "function") {
1556
- const result = await m.onError({
1557
- request,
1558
- error: errorAfterMiddleware,
1559
- schemaPath,
1560
- params,
1561
- options,
1562
- id
1563
- });
1564
- if (result) {
1565
- if (result instanceof Response) {
1566
- errorAfterMiddleware = void 0;
1567
- response = result;
1568
- break;
1569
- }
1570
- if (result instanceof Error) {
1571
- errorAfterMiddleware = result;
1572
- continue;
1573
- }
1574
- throw new Error("onError: must return new Response() or instance of Error");
1575
- }
1576
- }
1577
- }
1578
- if (errorAfterMiddleware) throw errorAfterMiddleware;
1579
- }
1580
- if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
1581
- const m = finalMiddlewares[i];
1582
- if (m && typeof m === "object" && typeof m.onResponse === "function") {
1583
- const result = await m.onResponse({
1584
- request,
1585
- response,
1586
- schemaPath,
1587
- params,
1588
- options,
1589
- id
1590
- });
1591
- if (result) {
1592
- if (!(result instanceof Response)) throw new Error("onResponse: must return new Response() when modifying the response");
1593
- response = result;
1594
- }
1595
- }
1596
- }
1597
- }
1598
- const contentLength = response.headers.get("Content-Length");
1599
- if (response.status === 204 || request.method === "HEAD" || contentLength === "0" && !response.headers.get("Transfer-Encoding")?.includes("chunked")) return response.ok ? {
1600
- data: void 0,
1601
- response
1602
- } : {
1603
- error: void 0,
1604
- response
1605
- };
1606
- if (response.ok) {
1607
- const getResponseData = async () => {
1608
- if (parseAs === "stream") return response.body;
1609
- if (parseAs === "json" && !contentLength) {
1610
- const raw = await response.text();
1611
- return raw ? JSON.parse(raw) : void 0;
1612
- }
1613
- return await response[parseAs]();
1614
- };
1615
- return {
1616
- data: await getResponseData(),
1617
- response
1618
- };
1619
- }
1620
- let error = await response.text();
1621
- try {
1622
- error = JSON.parse(error);
1623
- } catch {}
1624
- return {
1625
- error,
1626
- response
1627
- };
1628
- }
1629
- return {
1630
- request(method, url, init) {
1631
- return coreFetch(url, {
1632
- ...init,
1633
- method: method.toUpperCase()
1634
- });
1635
- },
1636
- GET(url, init) {
1637
- return coreFetch(url, {
1638
- ...init,
1639
- method: "GET"
1640
- });
1641
- },
1642
- PUT(url, init) {
1643
- return coreFetch(url, {
1644
- ...init,
1645
- method: "PUT"
1646
- });
1647
- },
1648
- POST(url, init) {
1649
- return coreFetch(url, {
1650
- ...init,
1651
- method: "POST"
1652
- });
1653
- },
1654
- DELETE(url, init) {
1655
- return coreFetch(url, {
1656
- ...init,
1657
- method: "DELETE"
1658
- });
1659
- },
1660
- OPTIONS(url, init) {
1661
- return coreFetch(url, {
1662
- ...init,
1663
- method: "OPTIONS"
1664
- });
1665
- },
1666
- HEAD(url, init) {
1667
- return coreFetch(url, {
1668
- ...init,
1669
- method: "HEAD"
1670
- });
1671
- },
1672
- PATCH(url, init) {
1673
- return coreFetch(url, {
1674
- ...init,
1675
- method: "PATCH"
1676
- });
1677
- },
1678
- TRACE(url, init) {
1679
- return coreFetch(url, {
1680
- ...init,
1681
- method: "TRACE"
1682
- });
1683
- },
1684
- use(...middleware) {
1685
- for (const m of middleware) {
1686
- if (!m) continue;
1687
- 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()`");
1688
- globalMiddlewares.push(m);
1689
- }
1690
- },
1691
- eject(...middleware) {
1692
- for (const m of middleware) {
1693
- const i = globalMiddlewares.indexOf(m);
1694
- if (i !== -1) globalMiddlewares.splice(i, 1);
1695
- }
1696
- }
1697
- };
1698
- }
1699
- function serializePrimitiveParam(name, value, options) {
1700
- if (value === void 0 || value === null) return "";
1701
- if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
1702
- return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
1703
- }
1704
- function serializeObjectParam(name, value, options) {
1705
- if (!value || typeof value !== "object") return "";
1706
- const values = [];
1707
- const joiner = {
1708
- simple: ",",
1709
- label: ".",
1710
- matrix: ";"
1711
- }[options.style] || "&";
1712
- if (options.style !== "deepObject" && options.explode === false) {
1713
- for (const k in value) values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
1714
- const final2 = values.join(",");
1715
- switch (options.style) {
1716
- case "form": return `${name}=${final2}`;
1717
- case "label": return `.${final2}`;
1718
- case "matrix": return `;${name}=${final2}`;
1719
- default: return final2;
1720
- }
1721
- }
1722
- for (const k in value) {
1723
- const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
1724
- values.push(serializePrimitiveParam(finalName, value[k], options));
1725
- }
1726
- const final = values.join(joiner);
1727
- return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
1728
- }
1729
- function serializeArrayParam(name, value, options) {
1730
- if (!Array.isArray(value)) return "";
1731
- if (options.explode === false) {
1732
- const joiner2 = {
1733
- form: ",",
1734
- spaceDelimited: "%20",
1735
- pipeDelimited: "|"
1736
- }[options.style] || ",";
1737
- const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);
1738
- switch (options.style) {
1739
- case "simple": return final;
1740
- case "label": return `.${final}`;
1741
- case "matrix": return `;${name}=${final}`;
1742
- default: return `${name}=${final}`;
1743
- }
1744
- }
1745
- const joiner = {
1746
- simple: ",",
1747
- label: ".",
1748
- matrix: ";"
1749
- }[options.style] || "&";
1750
- const values = [];
1751
- for (const v of value) if (options.style === "simple" || options.style === "label") values.push(options.allowReserved === true ? v : encodeURIComponent(v));
1752
- else values.push(serializePrimitiveParam(name, v, options));
1753
- return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
1754
- }
1755
- function createQuerySerializer(options) {
1756
- return function querySerializer(queryParams) {
1757
- const search = [];
1758
- if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
1759
- const value = queryParams[name];
1760
- if (value === void 0 || value === null) continue;
1761
- if (Array.isArray(value)) {
1762
- if (value.length === 0) continue;
1763
- search.push(serializeArrayParam(name, value, {
1764
- style: "form",
1765
- explode: true,
1766
- ...options?.array,
1767
- allowReserved: options?.allowReserved || false
1768
- }));
1769
- continue;
1770
- }
1771
- if (typeof value === "object") {
1772
- search.push(serializeObjectParam(name, value, {
1773
- style: "deepObject",
1774
- explode: true,
1775
- ...options?.object,
1776
- allowReserved: options?.allowReserved || false
1777
- }));
1778
- continue;
1779
- }
1780
- search.push(serializePrimitiveParam(name, value, options));
1781
- }
1782
- return search.join("&");
1783
- };
1784
- }
1785
- function defaultPathSerializer(pathname, pathParams) {
1786
- let nextURL = pathname;
1787
- for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
1788
- let name = match.substring(1, match.length - 1);
1789
- let explode = false;
1790
- let style = "simple";
1791
- if (name.endsWith("*")) {
1792
- explode = true;
1793
- name = name.substring(0, name.length - 1);
1794
- }
1795
- if (name.startsWith(".")) {
1796
- style = "label";
1797
- name = name.substring(1);
1798
- } else if (name.startsWith(";")) {
1799
- style = "matrix";
1800
- name = name.substring(1);
1801
- }
1802
- if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) continue;
1803
- const value = pathParams[name];
1804
- if (Array.isArray(value)) {
1805
- nextURL = nextURL.replace(match, serializeArrayParam(name, value, {
1806
- style,
1807
- explode
1808
- }));
1809
- continue;
1810
- }
1811
- if (typeof value === "object") {
1812
- nextURL = nextURL.replace(match, serializeObjectParam(name, value, {
1813
- style,
1814
- explode
1815
- }));
1816
- continue;
1817
- }
1818
- if (style === "matrix") {
1819
- nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
1820
- continue;
1821
- }
1822
- nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
1823
- }
1824
- return nextURL;
1825
- }
1826
- function defaultBodySerializer(body, headers) {
1827
- if (body instanceof FormData) return body;
1828
- if (headers) {
1829
- 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();
1830
- }
1831
- return JSON.stringify(body);
1832
- }
1833
- function createFinalURL(pathname, options) {
1834
- let finalURL = `${options.baseUrl}${pathname}`;
1835
- if (options.params?.path) finalURL = options.pathSerializer(finalURL, options.params.path);
1836
- let search = options.querySerializer(options.params.query ?? {});
1837
- if (search.startsWith("?")) search = search.substring(1);
1838
- if (search) finalURL += `?${search}`;
1839
- return finalURL;
1840
- }
1841
- function mergeHeaders(...allHeaders) {
1842
- const finalHeaders = new Headers();
1843
- for (const h of allHeaders) {
1844
- if (!h || typeof h !== "object") continue;
1845
- const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
1846
- for (const [k, v] of iterator) if (v === null) finalHeaders.delete(k);
1847
- else if (Array.isArray(v)) for (const v2 of v) finalHeaders.append(k, v2);
1848
- else if (v !== void 0) finalHeaders.set(k, v);
1849
- }
1850
- return finalHeaders;
1851
- }
1852
- function removeTrailingSlash(url) {
1853
- if (url.endsWith("/")) return url.substring(0, url.length - 1);
1854
- return url;
1855
- }
1856
- String.fromCharCode;
1857
- const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
1858
- const JOIN_LEADING_SLASH_RE = /^\.?\//;
1859
- function hasTrailingSlash(input = "", respectQueryAndFragment) {
1860
- if (!respectQueryAndFragment) return input.endsWith("/");
1861
- return TRAILING_SLASH_RE.test(input);
1862
- }
1863
- function withTrailingSlash(input = "", respectQueryAndFragment) {
1864
- if (!respectQueryAndFragment) return input.endsWith("/") ? input : input + "/";
1865
- if (hasTrailingSlash(input, true)) return input || "/";
1866
- let path = input;
1867
- let fragment = "";
1868
- const fragmentIndex = input.indexOf("#");
1869
- if (fragmentIndex !== -1) {
1870
- path = input.slice(0, fragmentIndex);
1871
- fragment = input.slice(fragmentIndex);
1872
- if (!path) return fragment;
1873
- }
1874
- const [s0, ...s] = path.split("?");
1875
- return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
1876
- }
1877
- function isNonEmptyURL(url) {
1878
- return url && url !== "/";
1879
- }
1880
- function joinURL(base, ...input) {
1881
- let url = base || "";
1882
- for (const segment of input.filter((url2) => isNonEmptyURL(url2))) if (url) {
1883
- const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
1884
- url = withTrailingSlash(url) + _segment;
1885
- } else url = segment;
1886
- return url;
1887
- }
1888
- //#endregion
1889
- //#region src/internal/client/transport.ts
1890
- const DEFAULT_REQUEST_TIMEOUT_MILLISECONDS = 3e4;
1891
- const MAX_REQUEST_TIMEOUT_MILLISECONDS = 12e4;
1892
- function createClientRuntime(config) {
1893
- let runtime;
1894
- try {
1895
- runtime = Object.freeze({
1896
- baseUrl: parseBaseUrl(config.baseUrl),
1897
- fetchImplementation: config.fetch ?? globalThis.fetch.bind(globalThis),
1898
- getCredential: config.getCredential,
1899
- timeoutMilliseconds: parseTimeoutMilliseconds(config.timeoutMilliseconds)
1900
- });
1901
- } catch {
1902
- throw new DriveError("invalid_input");
1903
- }
1904
- if (typeof runtime.fetchImplementation !== "function" || typeof runtime.getCredential !== "function") throw new DriveError("invalid_input");
1905
- return runtime;
1906
- }
1907
- async function execute(runtime, signal, preconditionStatus, send, successStatuses, guard, allowsQuotaExceeded = false, allowedErrorCodes) {
1908
- const operation = createOperationSignal(signal, runtime.timeoutMilliseconds);
1909
- try {
1910
- const operationSignal = operation.signal;
1911
- throwIfAborted(operationSignal);
1912
- const credential = await obtainCredential(runtime.getCredential, operationSignal);
1913
- let capturedResponse;
1914
- await send(createClient({
1915
- baseUrl: runtime.baseUrl,
1916
- fetch: async (request) => {
1917
- try {
1918
- const response = await raceWithAbort(runtime.fetchImplementation(request), operationSignal);
1919
- if (!(response instanceof Response)) throw new DriveError("invalid_response");
1920
- capturedResponse = response;
1921
- } catch (error) {
1922
- if (error instanceof DriveError) throw error;
1923
- throw operationSignal.aborted ? new DriveError("aborted") : new DriveError("network_error");
1924
- }
1925
- return new Response(null, { status: 204 });
1926
- }
1927
- }), {
1928
- cache: "no-store",
1929
- credentials: "omit",
1930
- headers: new Headers({ authorization: `Bearer ${credential}` }),
1931
- signal: operationSignal
1932
- });
1933
- if (!capturedResponse) throw new DriveError("network_error");
1934
- return guard === null ? await parseNoContentResponse(capturedResponse, operationSignal, preconditionStatus, successStatuses, allowedErrorCodes) : await parseResponse(capturedResponse, operationSignal, preconditionStatus, successStatuses, guard, allowsQuotaExceeded, allowedErrorCodes);
1935
- } catch (error) {
1936
- if (operation.didTimeout()) throw new DriveError("timeout");
1937
- if (error instanceof DriveError) throw error;
1938
- throw operation.signal.aborted ? new DriveError("aborted") : new DriveError("network_error");
1939
- } finally {
1940
- operation.dispose();
1941
- }
1942
- }
1943
- function parseTimeoutMilliseconds(value) {
1944
- if (value === void 0) return DEFAULT_REQUEST_TIMEOUT_MILLISECONDS;
1945
- if (!Number.isSafeInteger(value) || value < 1 || value > MAX_REQUEST_TIMEOUT_MILLISECONDS) throw new DriveError("invalid_input");
1946
- return value;
1947
- }
1948
- function createOperationSignal(callerSignal, timeoutMilliseconds) {
1949
- const controller = new AbortController();
1950
- let timedOut = false;
1951
- const onAbort = () => controller.abort();
1952
- if (callerSignal?.aborted) controller.abort();
1953
- else callerSignal?.addEventListener("abort", onAbort, { once: true });
1954
- const timeout = setTimeout(() => {
1955
- timedOut = true;
1956
- controller.abort();
1957
- }, timeoutMilliseconds);
1958
- return {
1959
- signal: controller.signal,
1960
- didTimeout: () => timedOut,
1961
- dispose: () => {
1962
- clearTimeout(timeout);
1963
- callerSignal?.removeEventListener("abort", onAbort);
1964
- }
1965
- };
1966
- }
1967
- function parseBaseUrl(value) {
1968
- if (typeof value !== "string") throw new TypeError("Drive base URL is invalid");
1969
- let url;
1970
- try {
1971
- url = new URL(value);
1972
- } catch {
1973
- throw new TypeError("Drive base URL is invalid");
1974
- }
1975
- const localHttp = url.protocol === "http:" && [
1976
- "localhost",
1977
- "127.0.0.1",
1978
- "[::1]"
1979
- ].includes(url.hostname);
1980
- if (url.protocol !== "https:" && !localHttp || url.username || url.password || url.search || url.hash || !url.host) throw new TypeError("Drive base URL is invalid");
1981
- return joinURL(url.origin, url.pathname);
1982
- }
1983
- async function obtainCredential(provider, signal) {
1984
- throwIfAborted(signal);
1985
- let credential;
1986
- try {
1987
- credential = await raceWithAbort(provider({ signal }), signal);
1988
- } catch (error) {
1989
- if (error instanceof DriveError && error.code === "aborted") throw error;
1990
- throw signal.aborted ? new DriveError("aborted") : new DriveError("credential_unavailable");
1991
- }
1992
- if (typeof credential !== "string" || credential.length < 1 || credential.length > 16384 || !/^[\x21-\x7e]+$/.test(credential)) throw new DriveError("credential_unavailable");
1993
- return credential;
1994
- }
1995
- function throwIfAborted(signal) {
1996
- if (signal.aborted) throw new DriveError("aborted");
1997
- }
1998
- async function raceWithAbort(promise, signal) {
1999
- throwIfAborted(signal);
2000
- let removeAbort = () => {};
2001
- const aborted = new Promise((_, reject) => {
2002
- const onAbort = () => reject(new DriveError("aborted"));
2003
- signal.addEventListener("abort", onAbort, { once: true });
2004
- removeAbort = () => signal.removeEventListener("abort", onAbort);
2005
- });
2006
- try {
2007
- return await Promise.race([promise, aborted]);
2008
- } finally {
2009
- removeAbort();
2010
- }
2011
- }
2012
- //#endregion
2013
- //#region src/internal/client/operations.ts
2014
- const CURRENT_WORKSPACE_ERROR_CODES = Object.freeze([
2015
- "authentication_required",
2016
- "identity_authority_unavailable",
2017
- "permission_denied",
2018
- "resource_not_found",
2019
- "invalid_request",
2020
- "service_unavailable"
2021
- ]);
2022
- const GET_ITEM_ERROR_CODES = Object.freeze([
2023
- "authentication_required",
2024
- "identity_authority_unavailable",
2025
- "permission_denied",
2026
- "resource_not_found",
2027
- "invalid_request",
2028
- "precondition_failed",
2029
- "service_unavailable"
2030
- ]);
2031
- const SEARCH_WORKSPACE_ITEMS_ERROR_CODES = Object.freeze([
2032
- "authentication_required",
2033
- "identity_authority_unavailable",
2034
- "permission_denied",
2035
- "resource_not_found",
2036
- "invalid_request",
2037
- "invalid_pagination_cursor",
2038
- "precondition_failed",
2039
- "service_unavailable"
2040
- ]);
2041
- const TRANSFER_ERROR_CODES = Object.freeze([
2042
- "authentication_required",
2043
- "identity_authority_unavailable",
2044
- "permission_denied",
2045
- "resource_not_found",
2046
- "invalid_request",
2047
- "precondition_failed",
2048
- "upload_recovery_required",
2049
- "service_unavailable"
2050
- ]);
2051
- const STATUS_ERROR_CODES = Object.freeze([
2052
- "authentication_required",
2053
- "identity_authority_unavailable",
2054
- "permission_denied",
2055
- "resource_not_found",
2056
- "invalid_request",
2057
- "service_unavailable"
2058
- ]);
2059
- const CREATE_UPLOAD_ERROR_CODES = Object.freeze([
2060
- ...TRANSFER_ERROR_CODES,
2061
- "invalid_idempotency_key",
2062
- "idempotency_conflict",
2063
- "quota_exceeded"
2064
- ]);
2065
- const COMPLETE_UPLOAD_ERROR_CODES = Object.freeze([...TRANSFER_ERROR_CODES, "invalid_idempotency_key"]);
2066
- const LIFECYCLE_MUTATION_ERROR_CODES = Object.freeze([
2067
- "authentication_required",
2068
- "identity_authority_unavailable",
2069
- "permission_denied",
2070
- "resource_not_found",
2071
- "invalid_request",
2072
- "invalid_idempotency_key",
2073
- "idempotency_conflict",
2074
- "precondition_failed",
2075
- "service_unavailable"
2076
- ]);
2077
- const LIST_ITEM_VERSIONS_ERROR_CODES = Object.freeze([
2078
- "authentication_required",
2079
- "identity_authority_unavailable",
2080
- "permission_denied",
2081
- "resource_not_found",
2082
- "invalid_request",
2083
- "precondition_failed",
2084
- "service_unavailable"
2085
- ]);
2086
- const DOWNLOAD_ERROR_CODES = Object.freeze([
2087
- "authentication_required",
2088
- "identity_authority_unavailable",
2089
- "permission_denied",
2090
- "resource_not_found",
2091
- "invalid_request",
2092
- "invalid_idempotency_key",
2093
- "idempotency_conflict",
2094
- "precondition_failed",
2095
- "range_not_satisfiable",
2096
- "service_unavailable"
2097
- ]);
2098
- function createDriveClientInternal(config) {
2099
- return createDriveOperations(createClientRuntime(config));
2100
- }
2101
- function createDriveOperations(runtime) {
2102
- return Object.freeze({
2103
- getCurrentWorkspace: (input) => getCurrentWorkspace(runtime, input),
2104
- listWorkspaceItems: (input) => listWorkspaceItems(runtime, input),
2105
- getWorkspaceUsage: (input) => getWorkspaceUsage(runtime, input),
2106
- getCurrentWorkspaceSources: (input) => getCurrentWorkspaceSources(runtime, input),
2107
- getItem: (input) => getItem(runtime, input),
2108
- searchWorkspaceItems: (input) => searchWorkspaceItems(runtime, input),
2109
- listFolderChildren: (input) => listFolderChildren(runtime, input),
2110
- createFolder: (input) => createFolder(runtime, input),
2111
- updateItem: (input) => updateItem(runtime, input),
2112
- trashItem: (input) => trashItem(runtime, input),
2113
- restoreItem: (input) => restoreItem(runtime, input),
2114
- deleteItem: (input) => deleteItem(runtime, input),
2115
- listItemVersions: (input) => listItemVersions(runtime, input),
2116
- getItemVersion: (input) => getItemVersion(runtime, input),
2117
- restoreItemVersion: (input) => restoreItemVersion(runtime, input),
2118
- createDownload: (input) => createDownload(runtime, input),
2119
- downloadItem: (input) => downloadItem(runtime, input),
2120
- listItemPermissions: (input) => listItemPermissions(runtime, input),
2121
- readEffectiveItemPermissions: (input) => readEffectiveItemPermissions(runtime, input),
2122
- createItemPermission: (input) => createItemPermission(runtime, input),
2123
- updateItemPermission: (input) => updateItemPermission(runtime, input),
2124
- revokeItemPermission: (input) => revokeItemPermission(runtime, input),
2125
- createUpload: (input) => createUpload(runtime, input),
2126
- getUploadStatus: (input) => getUploadStatus(runtime, input),
2127
- createUploadPartDescriptor: (input) => createUploadPartDescriptor(runtime, input),
2128
- recordUploadPart: (input) => recordUploadPart(runtime, input),
2129
- completeUpload: (input) => completeUpload(runtime, input),
2130
- abortUpload: (input) => abortUpload(runtime, input)
2131
- });
2132
- }
2133
- async function createDownload(runtime, input) {
2134
- const validated = validateCreateDownloadInput(input);
2135
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/downloads", {
2136
- ...operationOptions("createDownload", { params: {
2137
- path: {
2138
- workspaceId: validated.workspaceId,
2139
- itemId: validated.itemId
2140
- },
2141
- query: validated.versionId === void 0 ? {} : { versionId: validated.versionId },
2142
- header: {
2143
- "Idempotency-Key": validated.idempotencyKey,
2144
- "Download-Method": validated.method,
2145
- ...validated.range === void 0 ? {} : { Range: validated.range },
2146
- ...validated.ifMatch === void 0 ? {} : { "If-Match": validated.ifMatch },
2147
- ...validated.ifNoneMatch === void 0 ? {} : { "If-None-Match": validated.ifNoneMatch },
2148
- ...validated.ifRange === void 0 ? {} : { "If-Range": validated.ifRange }
2149
- }
2150
- } }),
2151
- ...requestOptions
2152
- }), [
2153
- 200,
2154
- 202,
2155
- 304
2156
- ], (value, status) => status === 200 ? isManagedDownloadDescriptor(value) : status === 202 ? isManagedDownloadRestorePending(value) : value === void 0, false, DOWNLOAD_ERROR_CODES);
2157
- }
2158
- async function downloadItem(runtime, input) {
2159
- const validated = validateCreateDownloadInput(input);
2160
- const created = await createDownload(runtime, input);
2161
- if (created.status === 202 || created.status === 304) return created;
2162
- const descriptor = created.data;
2163
- if (descriptor.expiresAtEpochMilliseconds <= Date.now()) throw new DriveError("invalid_response");
2164
- const operation = createOperationSignal(validated.signal, runtime.timeoutMilliseconds);
2165
- try {
2166
- const response = await raceWithAbort(runtime.fetchImplementation(directDownloadRequest(descriptor, operation.signal)), operation.signal);
2167
- if (!responseMatchesDownloadDescriptor(response, descriptor)) {
2168
- await response.body?.cancel().catch(() => void 0);
2169
- throw new DriveError("invalid_response");
2170
- }
2171
- const responseHeaders = downloadResponseHeaders(descriptor);
2172
- if (descriptor.method === "HEAD") {
2173
- await response.body?.cancel().catch(() => void 0);
2174
- operation.dispose();
2175
- return new Response(null, {
2176
- status: response.status,
2177
- headers: responseHeaders
2178
- });
2179
- }
2180
- if (!response.body) {
2181
- operation.dispose();
2182
- if (descriptor.response.contentLength !== 0) throw new DriveError("invalid_response");
2183
- return new Response(null, {
2184
- status: response.status,
2185
- headers: responseHeaders
2186
- });
2187
- }
2188
- operation.dispose();
2189
- return new Response(streamWithOperationLifetime(response.body, descriptor.response.contentLength, validated.signal), {
2190
- status: response.status,
2191
- headers: responseHeaders
2192
- });
2193
- } catch (error) {
2194
- operation.dispose();
2195
- if (operation.didTimeout()) throw new DriveError("timeout");
2196
- if (error instanceof DriveError) throw error;
2197
- throw operation.signal.aborted ? new DriveError(operation.didTimeout() ? "timeout" : "aborted") : new DriveError("network_error");
2198
- }
2199
- }
2200
- function downloadResponseHeaders(descriptor) {
2201
- const expected = descriptor.response;
2202
- const headers = new Headers();
2203
- headers.set("accept-ranges", expected.acceptRanges);
2204
- headers.set("content-disposition", expected.contentDisposition);
2205
- headers.set("content-length", String(expected.contentLength));
2206
- headers.set("content-type", expected.contentType);
2207
- headers.set("etag", expected.etag);
2208
- if (expected.contentRange === null) headers.delete("content-range");
2209
- else headers.set("content-range", expected.contentRange);
2210
- return headers;
2211
- }
2212
- function directDownloadRequest(descriptor, signal) {
2213
- const base = {
2214
- method: descriptor.method,
2215
- headers: descriptor.headers,
2216
- redirect: "manual",
2217
- signal
2218
- };
2219
- try {
2220
- return new Request(descriptor.url, {
2221
- ...base,
2222
- cache: "no-store",
2223
- credentials: "omit",
2224
- referrerPolicy: "no-referrer"
2225
- });
2226
- } catch {
2227
- try {
2228
- return new Request(descriptor.url, {
2229
- ...base,
2230
- credentials: "omit",
2231
- referrerPolicy: "no-referrer"
2232
- });
2233
- } catch {
2234
- return new Request(descriptor.url, {
2235
- ...base,
2236
- credentials: "omit"
2237
- });
2238
- }
2239
- }
2240
- }
2241
- function responseMatchesDownloadDescriptor(response, descriptor) {
2242
- const expected = descriptor.response;
2243
- const encoding = response.headers.get("content-encoding");
2244
- 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);
2245
- }
2246
- function streamWithOperationLifetime(source, expectedLength, signal) {
2247
- const reader = source.getReader();
2248
- let receivedLength = 0;
2249
- let finished = false;
2250
- let removeAbort = () => {};
2251
- return new ReadableStream({
2252
- start(controller) {
2253
- if (!signal) return;
2254
- const onAbort = () => {
2255
- if (finished) return;
2256
- finished = true;
2257
- removeAbort();
2258
- reader.cancel().catch(() => void 0);
2259
- controller.error(new DriveError("aborted"));
2260
- };
2261
- if (signal.aborted) onAbort();
2262
- else {
2263
- signal.addEventListener("abort", onAbort, { once: true });
2264
- removeAbort = () => signal.removeEventListener("abort", onAbort);
2265
- }
2266
- },
2267
- async pull(controller) {
2268
- if (finished) return;
2269
- try {
2270
- const chunk = await reader.read();
2271
- if (finished) return;
2272
- if (chunk.done) {
2273
- finished = true;
2274
- removeAbort();
2275
- reader.releaseLock();
2276
- if (receivedLength === expectedLength) controller.close();
2277
- else controller.error(new DriveError("invalid_response"));
2278
- } else {
2279
- receivedLength += chunk.value.byteLength;
2280
- if (!Number.isSafeInteger(receivedLength) || receivedLength > expectedLength) {
2281
- finished = true;
2282
- removeAbort();
2283
- await reader.cancel().catch(() => void 0);
2284
- controller.error(new DriveError("invalid_response"));
2285
- return;
2286
- }
2287
- controller.enqueue(chunk.value);
2288
- }
2289
- } catch (error) {
2290
- if (finished) return;
2291
- finished = true;
2292
- removeAbort();
2293
- await reader.cancel().catch(() => void 0);
2294
- controller.error(error instanceof DriveError ? error : signal?.aborted ? new DriveError("aborted") : new DriveError("network_error"));
2295
- }
2296
- },
2297
- async cancel(reason) {
2298
- if (finished) return;
2299
- finished = true;
2300
- removeAbort();
2301
- await reader.cancel(reason).catch(() => void 0);
2302
- }
2303
- });
2304
- }
2305
- async function getCurrentWorkspaceSources(runtime, input) {
2306
- return execute(runtime, validateCurrentWorkspaceInput(input).signal, null, (api, requestOptions) => api.GET("/api/v1/workspaces/current/sources", {
2307
- ...operationOptions("getCurrentWorkspaceSources", { params: {} }),
2308
- ...requestOptions
2309
- }), [200], isCurrentWorkspaceSources, false, CURRENT_WORKSPACE_ERROR_CODES);
2310
- }
2311
- async function listWorkspaceItems(runtime, input) {
2312
- const validated = validateWorkspaceDiscoveryInput(input, true);
2313
- return execute(runtime, validated.signal, null, (api, options) => api.GET("/api/v1/workspaces/{workspaceId}/items", {
2314
- ...operationOptions("listWorkspaceItems", { params: {
2315
- path: { workspaceId: validated.workspaceId },
2316
- query: validated.query
2317
- } }),
2318
- ...options
2319
- }), [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);
2320
- }
2321
- async function getWorkspaceUsage(runtime, input) {
2322
- const validated = validateWorkspaceDiscoveryInput(input, false);
2323
- return execute(runtime, validated.signal, null, (api, options) => api.GET("/api/v1/workspaces/{workspaceId}/usage", {
2324
- ...operationOptions("getWorkspaceUsage", { params: { path: { workspaceId: validated.workspaceId } } }),
2325
- ...options
2326
- }), [200], (value) => isWorkspaceUsage(value) && value.workspaceId === validated.workspaceId, false, SEARCH_WORKSPACE_ITEMS_ERROR_CODES);
2327
- }
2328
- async function getCurrentWorkspace(runtime, input) {
2329
- return execute(runtime, validateCurrentWorkspaceInput(input).signal, null, (api, requestOptions) => api.GET("/api/v1/workspaces/current", {
2330
- ...operationOptions("getCurrentWorkspace", { params: {} }),
2331
- ...requestOptions
2332
- }), [200], isCurrentWorkspace, false, CURRENT_WORKSPACE_ERROR_CODES);
2333
- }
2334
- async function getItem(runtime, input) {
2335
- const validated = validateResourceInput(input);
2336
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}", {
2337
- ...operationOptions("getItem", { params: { path: resourcePath(validated) } }),
2338
- ...requestOptions
2339
- }), [200], (value, _status, headers) => isManagedItemMetadata(value, validated.workspaceId, validated.itemId) && itemEtagMatchesRevision(headers, value.revision), false, GET_ITEM_ERROR_CODES);
2340
- }
2341
- async function searchWorkspaceItems(runtime, input) {
2342
- const validated = validateSearchWorkspaceItemsInput(input);
2343
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/search", {
2344
- ...operationOptions("searchWorkspaceItems", { params: {
2345
- path: { workspaceId: validated.workspaceId },
2346
- query: {
2347
- query: validated.query,
2348
- ...validated.limit === void 0 ? {} : { limit: validated.limit },
2349
- ...validated.cursor === void 0 ? {} : { cursor: validated.cursor }
2350
- }
2351
- } }),
2352
- ...requestOptions
2353
- }), [200], (value) => isWorkspaceItemSearchPage(value, validated.workspaceId, validated.query, validated.limit ?? 50), false, SEARCH_WORKSPACE_ITEMS_ERROR_CODES);
2354
- }
2355
- async function listFolderChildren(runtime, input) {
2356
- const validated = validatePageInput(input);
2357
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/children", {
2358
- ...operationOptions("listFolderChildren", { params: {
2359
- path: resourcePath(validated),
2360
- query: pageQuery(validated)
2361
- } }),
2362
- ...requestOptions
2363
- }), [200], (value) => isFolderPage(value, validated.workspaceId, validated.itemId));
2364
- }
2365
- async function createFolder(runtime, input) {
2366
- const validated = validateCreateFolderInput(input);
2367
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/children", {
2368
- ...operationOptions("createFolder", {
2369
- params: {
2370
- path: resourcePath(validated),
2371
- header: { "Idempotency-Key": validated.idempotencyKey }
2372
- },
2373
- body: { name: validated.name }
2374
- }),
2375
- ...requestOptions
2376
- }), [200, 201], (value) => isFolderItem(value) && value.workspaceId === validated.workspaceId && value.parentItemId === validated.itemId && value.kind === "folder" && value.name === validated.name);
2377
- }
2378
- async function updateItem(runtime, input) {
2379
- const validated = validateUpdateItemInput(input);
2380
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.PATCH("/api/v1/workspaces/{workspaceId}/items/{itemId}", {
2381
- ...operationOptions("updateItem", {
2382
- params: {
2383
- path: resourcePath(validated),
2384
- header: {
2385
- "Idempotency-Key": validated.idempotencyKey,
2386
- "If-Match": validated.ifMatch
2387
- }
2388
- },
2389
- body: {
2390
- name: validated.name,
2391
- parentItemId: validated.parentItemId
2392
- }
2393
- }),
2394
- ...requestOptions
2395
- }), [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);
2396
- }
2397
- async function trashItem(runtime, input) {
2398
- const validated = validateLifecycleMutationInput(input);
2399
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/trash", {
2400
- ...operationOptions("trashItem", { params: {
2401
- path: resourcePath(validated),
2402
- header: {
2403
- "Idempotency-Key": validated.idempotencyKey,
2404
- "If-Match": validated.ifMatch
2405
- }
2406
- } }),
2407
- ...requestOptions
2408
- }), [200], (value, _status, headers) => isManagedLifecycleItem(value, validated.workspaceId, validated.itemId, "trashed") && itemEtagMatchesRevision(headers, value.revision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2409
- }
2410
- async function restoreItem(runtime, input) {
2411
- const validated = validateLifecycleMutationInput(input);
2412
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/restore", {
2413
- ...operationOptions("restoreItem", { params: {
2414
- path: resourcePath(validated),
2415
- header: {
2416
- "Idempotency-Key": validated.idempotencyKey,
2417
- "If-Match": validated.ifMatch
2418
- }
2419
- } }),
2420
- ...requestOptions
2421
- }), [200], (value, _status, headers) => isManagedLifecycleItem(value, validated.workspaceId, validated.itemId, "active") && itemEtagMatchesRevision(headers, value.revision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2422
- }
2423
- async function deleteItem(runtime, input) {
2424
- const validated = validateLifecycleMutationInput(input);
2425
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.DELETE("/api/v1/workspaces/{workspaceId}/items/{itemId}", {
2426
- ...operationOptions("deleteItem", { params: {
2427
- path: resourcePath(validated),
2428
- header: {
2429
- "Idempotency-Key": validated.idempotencyKey,
2430
- "If-Match": validated.ifMatch
2431
- }
2432
- } }),
2433
- ...requestOptions
2434
- }), [200, 202], (value, _status, headers) => isManagedLifecycleItem(value, validated.workspaceId, validated.itemId, "deleting") && itemEtagMatchesRevision(headers, value.revision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2435
- }
2436
- async function listItemVersions(runtime, input) {
2437
- const validated = validatePageInput(input);
2438
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/versions", {
2439
- ...operationOptions("listItemVersions", { params: {
2440
- path: resourcePath(validated),
2441
- query: pageQuery(validated)
2442
- } }),
2443
- ...requestOptions
2444
- }), [200], (value) => isManagedItemVersionPage(value, validated.limit ?? 50), false, LIST_ITEM_VERSIONS_ERROR_CODES);
2445
- }
2446
- async function getItemVersion(runtime, input) {
2447
- const validated = validateItemVersionInput(input);
2448
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}", {
2449
- ...operationOptions("getItemVersion", { params: { path: {
2450
- ...resourcePath(validated),
2451
- versionId: validated.versionId
2452
- } } }),
2453
- ...requestOptions
2454
- }), [200], (value) => isManagedItemVersionResource(value, validated.workspaceId, validated.itemId, validated.versionId), false, LIST_ITEM_VERSIONS_ERROR_CODES);
2455
- }
2456
- async function restoreItemVersion(runtime, input) {
2457
- const validated = validateRestoreItemVersionInput(input);
2458
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}/restore", {
2459
- ...operationOptions("restoreItemVersion", { params: {
2460
- path: {
2461
- ...resourcePath(validated),
2462
- versionId: validated.versionId
2463
- },
2464
- header: {
2465
- "Idempotency-Key": validated.idempotencyKey,
2466
- "If-Match": validated.ifMatch
2467
- }
2468
- } }),
2469
- ...requestOptions
2470
- }), [200], (value, _status, headers) => isManagedItemVersionRestoreResult(value, validated.versionId) && itemEtagMatchesRevision(headers, value.itemRevision), false, LIFECYCLE_MUTATION_ERROR_CODES);
2471
- }
2472
- async function listItemPermissions(runtime, input) {
2473
- const validated = validatePageInput(input);
2474
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions", {
2475
- ...operationOptions("listItemPermissions", { params: {
2476
- path: resourcePath(validated),
2477
- query: pageQuery(validated)
2478
- } }),
2479
- ...requestOptions
2480
- }), [200], (value, _status, headers) => isPermissionPage(value, headers, validated.itemId));
2481
- }
2482
- async function readEffectiveItemPermissions(runtime, input) {
2483
- const validated = validateResourceInput(input);
2484
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/effective", {
2485
- ...operationOptions("readEffectiveItemPermissions", { params: { path: resourcePath(validated) } }),
2486
- ...requestOptions
2487
- }), [200], (value) => isEffectivePermissionResponse(value, validated.itemId));
2488
- }
2489
- async function createItemPermission(runtime, input) {
2490
- const validated = validateCreatePermissionInput(input);
2491
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions", {
2492
- ...operationOptions("createItemPermission", {
2493
- params: {
2494
- path: resourcePath(validated),
2495
- header: {
2496
- "Idempotency-Key": validated.idempotencyKey,
2497
- "If-Match": validated.ifMatch
2498
- }
2499
- },
2500
- body: {
2501
- grantee: validated.grantee,
2502
- actions: validated.actions,
2503
- expiresAtEpochMilliseconds: validated.expiresAtEpochMilliseconds
2504
- }
2505
- }),
2506
- ...requestOptions
2507
- }), [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));
2508
- }
2509
- async function updateItemPermission(runtime, input) {
2510
- const validated = validateUpdatePermissionInput(input);
2511
- const body = {};
2512
- if (validated.actions !== void 0) body.actions = validated.actions;
2513
- if (validated.expiresAtEpochMilliseconds !== void 0) body.expiresAtEpochMilliseconds = validated.expiresAtEpochMilliseconds;
2514
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.PATCH("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}", {
2515
- ...operationOptions("updateItemPermission", {
2516
- params: {
2517
- path: {
2518
- ...resourcePath(validated),
2519
- grantId: validated.grantId
2520
- },
2521
- header: {
2522
- "Idempotency-Key": validated.idempotencyKey,
2523
- "If-Match": validated.ifMatch
2524
- }
2525
- },
2526
- body
2527
- }),
2528
- ...requestOptions
2529
- }), [200], (value, _status, headers) => isPermissionMutation(value, validated.itemId, validated.grantId) && value.grant.availability !== "revoked" && mutationValidatorsAreCoherent(headers));
2530
- }
2531
- async function revokeItemPermission(runtime, input) {
2532
- const validated = validateGrantMutationInput(input);
2533
- return execute(runtime, validated.signal, 412, (api, requestOptions) => api.DELETE("/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}", {
2534
- ...operationOptions("revokeItemPermission", { params: {
2535
- path: {
2536
- ...resourcePath(validated),
2537
- grantId: validated.grantId
2538
- },
2539
- header: {
2540
- "Idempotency-Key": validated.idempotencyKey,
2541
- "If-Match": validated.ifMatch
2542
- }
2543
- } }),
2544
- ...requestOptions
2545
- }), [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);
2546
- }
2547
- async function createUpload(runtime, input) {
2548
- const validated = validateCreateUploadInput(input);
2549
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads", {
2550
- ...operationOptions("createUpload", {
2551
- params: {
2552
- path: { workspaceId: validated.workspaceId },
2553
- header: { "Idempotency-Key": validated.idempotencyKey }
2554
- },
2555
- body: {
2556
- parentItemId: validated.parentItemId,
2557
- expectedByteLength: validated.expectedByteLength,
2558
- displayFilename: validated.displayFilename,
2559
- mediaType: validated.mediaType,
2560
- callerDeclaredContentDigest: validated.callerDeclaredContentDigest,
2561
- protectionClassification: validated.protectionClassification
2562
- }
2563
- }),
2564
- ...requestOptions
2565
- }), [200, 201], (value) => isUploadSession(value, validated.expectedByteLength), true, CREATE_UPLOAD_ERROR_CODES);
2566
- }
2567
- async function getUploadStatus(runtime, input) {
2568
- const validated = validateGetUploadStatusInput(input);
2569
- const afterPartNumber = validated.afterPartNumber ?? 0;
2570
- const limit = validated.limit ?? 100;
2571
- return execute(runtime, validated.signal, null, (api, requestOptions) => api.GET("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}", {
2572
- ...operationOptions("getUploadStatus", { params: {
2573
- path: {
2574
- workspaceId: validated.workspaceId,
2575
- uploadId: validated.uploadId
2576
- },
2577
- query: {
2578
- ...validated.afterPartNumber === void 0 ? {} : { afterPartNumber: String(validated.afterPartNumber) },
2579
- ...validated.limit === void 0 ? {} : { limit: String(validated.limit) }
2580
- }
2581
- } }),
2582
- ...requestOptions
2583
- }), [200], (value) => isUploadStatus(value, afterPartNumber, limit) && value.uploadId === validated.uploadId, false, STATUS_ERROR_CODES);
2584
- }
2585
- async function createUploadPartDescriptor(runtime, input) {
2586
- const validated = validateCreateUploadPartDescriptorInput(input);
2587
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts", {
2588
- ...operationOptions("createUploadPartDescriptor", {
2589
- params: { path: {
2590
- workspaceId: validated.workspaceId,
2591
- uploadId: validated.uploadId
2592
- } },
2593
- body: {
2594
- partNumber: validated.partNumber,
2595
- checksumSha256: validated.checksumSha256,
2596
- contentMd5: validated.contentMd5
2597
- }
2598
- }),
2599
- ...requestOptions
2600
- }), [200], (value) => isUploadPartDescriptor(value, validated.partNumber, new URL(runtime.baseUrl).protocol === "http:", validated.contentMd5), false, TRANSFER_ERROR_CODES);
2601
- }
2602
- async function recordUploadPart(runtime, input) {
2603
- const validated = validateRecordUploadPartInput(input);
2604
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts/{partNumber}", {
2605
- ...operationOptions("recordUploadPart", {
2606
- params: { path: {
2607
- workspaceId: validated.workspaceId,
2608
- uploadId: validated.uploadId,
2609
- partNumber: String(validated.partNumber)
2610
- } },
2611
- body: {
2612
- expectedUploadRevision: validated.expectedUploadRevision,
2613
- byteLength: validated.byteLength,
2614
- etag: validated.etag,
2615
- checksumSha256: validated.checksumSha256
2616
- }
2617
- }),
2618
- ...requestOptions
2619
- }), [200], (value) => isUploadPartResult(value, validated.partNumber, validated.expectedUploadRevision), false, TRANSFER_ERROR_CODES);
2620
- }
2621
- async function completeUpload(runtime, input) {
2622
- const validated = validateCompleteUploadInput(input);
2623
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.POST("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/complete", {
2624
- ...operationOptions("completeUpload", { params: {
2625
- path: {
2626
- workspaceId: validated.workspaceId,
2627
- uploadId: validated.uploadId
2628
- },
2629
- header: { "Idempotency-Key": validated.idempotencyKey }
2630
- } }),
2631
- ...requestOptions
2632
- }), [200, 202], (value, status) => status === 202 ? isPendingUpload(value, validated.uploadId) : isReadyUpload(value, { uploadId: validated.uploadId }), false, COMPLETE_UPLOAD_ERROR_CODES);
2633
- }
2634
- async function abortUpload(runtime, input) {
2635
- const validated = validateAbortUploadInput(input);
2636
- return execute(runtime, validated.signal, 409, (api, requestOptions) => api.DELETE("/api/v1/workspaces/{workspaceId}/uploads/{uploadId}", {
2637
- ...operationOptions("abortUpload", { params: { path: {
2638
- workspaceId: validated.workspaceId,
2639
- uploadId: validated.uploadId
2640
- } } }),
2641
- ...requestOptions
2642
- }), [204], null, false, TRANSFER_ERROR_CODES);
2643
- }
2644
- //#endregion
2645
- //#region src/internal/provisioning.ts
2646
- const environments = [
2647
- "local",
2648
- "development",
2649
- "staging",
2650
- "production"
2651
- ];
2652
- const identifier = /^[A-Za-z0-9_-]{1,128}$/;
2653
- function createDriveProvisioningClient(config) {
2654
- if (!config || !environments.includes(config.environment)) throw new DriveError("invalid_input");
2655
- const environment = config.environment;
2656
- const runtime = createClientRuntime({
2657
- baseUrl: config.baseUrl,
2658
- getCredential: config.getProvisioningCredential,
2659
- ...config.fetch === void 0 ? {} : { fetch: config.fetch },
2660
- ...config.timeoutMilliseconds === void 0 ? {} : { timeoutMilliseconds: config.timeoutMilliseconds }
2661
- });
2662
- return Object.freeze({ async provisionWorkspace(command, options) {
2663
- if (!exact(command, [
2664
- "version",
2665
- "environment",
2666
- "provisioningId",
2667
- "workspaceReference",
2668
- "entitlement"
2669
- ]) || command.version !== 1 || command.environment !== environment || typeof command.provisioningId !== "string" || !identifier.test(command.provisioningId) || !reference(command.workspaceReference) || !entitlement(command.entitlement)) throw new DriveError("invalid_input");
2670
- const body = {
2671
- version: command.version,
2672
- environment: command.environment,
2673
- provisioningId: command.provisioningId,
2674
- workspaceReference: { ...command.workspaceReference },
2675
- entitlement: { ...command.entitlement }
2676
- };
2677
- return execute(runtime, options?.signal, null, (api, boundary) => api.POST("/api/v1/platform/workspaces/provision", {
2678
- ...boundary,
2679
- redirect: "manual",
2680
- body
2681
- }), [200, 201], (value, status) => validResult(value, status, body), false, [
2682
- "authentication_required",
2683
- "permission_denied",
2684
- "idempotency_conflict",
2685
- "invalid_request",
2686
- "identity_authority_unavailable",
2687
- "service_unavailable"
2688
- ]);
2689
- } });
2690
- }
2691
- function exact(value, keys) {
2692
- return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
2693
- }
2694
- function reference(value) {
2695
- return exact(value, ["type", "userId"]) && value.type === "personal" && typeof value.userId === "string" && identifier.test(value.userId) || exact(value, ["type", "organizationId"]) && value.type === "organization" && typeof value.organizationId === "string" && identifier.test(value.organizationId);
2696
- }
2697
- function entitlement(value) {
2698
- return exact(value, [
2699
- "version",
2700
- "managedStorageEnabled",
2701
- "managedStorageByteLimit"
2702
- ]) && typeof value.version === "number" && Number.isSafeInteger(value.version) && value.version >= 0 && typeof value.managedStorageByteLimit === "number" && Number.isSafeInteger(value.managedStorageByteLimit) && (value.managedStorageEnabled === true && value.managedStorageByteLimit > 0 || value.managedStorageEnabled === false && value.managedStorageByteLimit === 0);
2703
- }
2704
- function validResult(value, status, command) {
2705
- if (!exact(value, ["outcome", "workspace"]) || (status === 201 ? value.outcome !== "committed" : value.outcome !== "replayed" && value.outcome !== "superseded") || !exact(value.workspace, [
2706
- "workspaceId",
2707
- "rootVolumeId",
2708
- "rootItemId",
2709
- "workspaceReference",
2710
- "entitlement"
2711
- ])) return false;
2712
- const { entitlement: current, ...workspace } = value.workspace;
2713
- if (!isCurrentWorkspace(workspace) || !entitlement(current)) return false;
2714
- const actual = workspace.workspaceReference;
2715
- const expected = command.workspaceReference;
2716
- if (!(actual.type === "personal" && expected.type === "personal" && actual.userId === expected.userId) && !(actual.type === "organization" && expected.type === "organization" && actual.organizationId === expected.organizationId)) return false;
2717
- return value.outcome === "superseded" ? current.version > command.entitlement.version : current.version === command.entitlement.version && current.managedStorageEnabled === command.entitlement.managedStorageEnabled && current.managedStorageByteLimit === command.entitlement.managedStorageByteLimit;
2718
- }
2719
- //#endregion
2720
- //#region src/server.ts
2721
- function createDriveServerClient(config) {
2722
- const credential = config.credential;
2723
- const getCredential = typeof credential === "string" ? async () => credential : credential;
2724
- return createDriveClientInternal({
2725
- baseUrl: config.baseUrl,
2726
- ...config.fetch === void 0 ? {} : { fetch: config.fetch },
2727
- getCredential,
2728
- ...config.timeoutMilliseconds === void 0 ? {} : { timeoutMilliseconds: config.timeoutMilliseconds }
2729
- });
2730
- }
2731
- //#endregion
2732
- export { createDriveProvisioningClient, createDriveServerClient };
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=te(e.headers.get(`x-request-id`));if(c===null)throw _(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 _(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 h(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:ne(e.headers)})}async function u(e,t,n,i,a){let o=te(e.headers.get(`x-request-id`));if(o===null)throw _(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 _(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 h(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(!v(d,[`error`])||!v(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||!v(f.details,[])||!ee(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 ee(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 h(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 g(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 g(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 _(e){e.body?.cancel().catch(()=>{})}function te(e){return e!==null&&i.test(e)?e:null}function ne(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 v(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 y=/^drive\.item\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,b=/^drive\.workspace\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,x=/^drive\.volume\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,S=/^drive\.grant\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,C=/^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}$/,N=new TextEncoder;function ae(e){if(!L(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(!L(n,[`workspaceId`,`itemId`])||typeof n.workspaceId!=`string`||!b.test(n.workspaceId)||typeof n.itemId!=`string`||!y.test(n.itemId))return!1;let e=`${n.workspaceId}/${n.itemId}`;if(t&&t>=e)return!1;t=e}return!0}function oe(e){if(!L(e,[`workspaceId`,`provider`,`usedBytes`,`reservedBytes`,`limitBytes`,`availableBytes`,`accounting`,`reservedBytesIncludeUnresolvedUploads`,`unresolvedReservedBytes`,`warnings`])||typeof e.workspaceId!=`string`||!b.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 se(e){if(!L(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(!L(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`||!x.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||I(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`||!b.test(n.workspaceId)||typeof n.itemId!=`string`||!y.test(n.itemId)||n.parentId===null||n.parentId===n.itemId||!ge(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:!I(e.trashedAtEpochMilliseconds)||!I(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 ce(e){if(!L(e,[`workspace`,`volumes`,`knownProviders`,`externalConnectionsSupported`])||!le(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 L(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 le(e){if(!L(e,[`workspaceId`,`rootVolumeId`,`rootItemId`,`workspaceReference`])||typeof e.workspaceId!=`string`||!b.test(e.workspaceId)||typeof e.rootVolumeId!=`string`||!x.test(e.rootVolumeId)||typeof e.rootItemId!=`string`||!y.test(e.rootItemId))return!1;let t=e.workspaceReference;return L(t,[`type`,`userId`])&&t.type===`personal`&&typeof t.userId==`string`&&E.test(t.userId)||L(t,[`type`,`organizationId`])&&t.type===`organization`&&typeof t.organizationId==`string`&&E.test(t.organizationId)}function ue(e){return!L(e,[`mode`,`method`,`url`,`headers`,`expiresAtEpochMilliseconds`,`response`])||e.mode!==`presigned-single`||e.method!==`GET`&&e.method!==`HEAD`||typeof e.url!=`string`||!Xe(e.url)||!I(e.expiresAtEpochMilliseconds)||!L(e.headers,[`if-match`])&&!L(e.headers,[`if-match`,`range`])||typeof e.headers[`if-match`]!=`string`||!Ye(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))||!L(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)||!I(e.response.byteLength)||!I(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`||!de(e)?!1:(Object.freeze(e.headers),Object.freeze(e.response),Object.freeze(e),!0)}function de(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(I)&&i===o&&a===s&&c===t.byteLength&&i<=a&&a<c&&t.contentLength===a-i+1}function fe(e){return L(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`)&&I(e.pollAfterSeconds)&&e.pollAfterSeconds>=1&&e.pollAfterSeconds<=60}function pe(e,t,n){return L(e,[`items`,`nextCursor`])&&Array.isArray(e.items)&&e.items.length<=50&&e.items.every(me)&&(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)&&Je(e.items,e=>e.itemId):!1}function me(e){return L(e,[`workspaceId`,`volumeId`,`itemId`,`parentItemId`,`kind`,`name`,`visibility`,`revision`])&&typeof e.workspaceId==`string`&&b.test(e.workspaceId)&&typeof e.volumeId==`string`&&x.test(e.volumeId)&&typeof e.itemId==`string`&&y.test(e.itemId)&&typeof e.parentItemId==`string`&&y.test(e.parentItemId)&&(e.kind===`file`||e.kind===`folder`)&&F(e.name)&&(e.visibility===`workspace`||e.visibility===`restricted`)&&I(e.revision)}function he(e,t,n,r){return!L(e,[`workspaceId`,`volumeId`,`itemId`,`parentItemId`,`kind`,`name`,`state`,`revision`,`purgeAfterEpochMilliseconds`])||e.workspaceId!==t||e.itemId!==n||typeof e.volumeId!=`string`||!x.test(e.volumeId)||typeof e.parentItemId!=`string`||!y.test(e.parentItemId)||e.kind!==`file`&&e.kind!==`folder`||!F(e.name)||e.state!==r||!I(e.revision)||(e.state===`active`?e.purgeAfterEpochMilliseconds!==null:!I(e.purgeAfterEpochMilliseconds))?!1:(Object.freeze(e),!0)}function ge(e,t,n){return!L(e,[`workspaceId`,`itemId`,`parentId`,`type`,`name`,`lifecycleState`,`revision`,`currentVersion`])||e.workspaceId!==t||e.itemId!==n||!(e.parentId===null||typeof e.parentId==`string`&&y.test(e.parentId))||e.type!==`file`&&e.type!==`folder`||!F(e.name)||e.lifecycleState!==`active`||!I(e.revision)||(e.type===`folder`?e.currentVersion!==null:!ve(e.currentVersion))?!1:(e.currentVersion!==null&&Object.freeze(e.currentVersion),Object.freeze(e),!0)}function _e(e,t,n,r){if(!L(e,[`items`,`nextCursor`])||!Array.isArray(e.items)||e.items.length>r||!e.items.every(e=>ye(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||!be(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 P(e,t){let n=e.get(`etag`);return n!==null&&p(n)===t}function ve(e){return L(e,[`versionId`,`state`,`byteLength`,`mediaType`,`protectionClassification`])&&typeof e.versionId==`string`&&w.test(e.versionId)&&e.state===`current`&&I(e.byteLength)&&Ge(e.mediaType)&&(e.protectionClassification===`ordinary`||e.protectionClassification===`opaque-encrypted`)}function ye(e,t,n){return L(e,[`workspaceId`,`volumeId`,`provider`,`itemId`,`parentId`,`type`,`name`,`lifecycleState`,`revision`,`currentVersion`])&&e.workspaceId===t&&typeof e.volumeId==`string`&&x.test(e.volumeId)&&e.provider===`managed`&&typeof e.itemId==`string`&&y.test(e.itemId)&&(e.parentId===null||typeof e.parentId==`string`&&y.test(e.parentId))&&(e.type===`file`||e.type===`folder`)&&F(e.name)&&e.name.startsWith(n)&&e.lifecycleState===`active`&&I(e.revision)&&(e.type===`folder`?e.currentVersion===null:ve(e.currentVersion))}function be(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t],i=xe(n.name,r.name);if(i>0||i===0&&n.itemId>=r.itemId)return!1}return!0}function xe(e,t){let n=N.encode(e),r=N.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 Se(e,t){if(!L(e,[`items`,`nextCursor`])||!Array.isArray(e.items)||e.items.length>t||!e.items.every(Fe)||!(e.nextCursor===null||typeof e.nextCursor==`string`&&e.nextCursor.length<=699&&T.test(e.nextCursor))||e.nextCursor!==null&&e.items.length===0||!Je(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 Ce(e,t){return!L(e,[`itemRevision`,`currentVersionId`])||!I(e.itemRevision)||e.currentVersionId!==t?!1:(Object.freeze(e),!0)}function we(e,t,n,r=O){if(!(L(e,[`items`,`nextCursor`,`collectionRevision`,`collectionEtag`])&&Array.isArray(e.items)&&e.items.length<=50&&e.items.every(Be)&&(e.nextCursor===null||typeof e.nextCursor==`string`&&e.nextCursor.length<=699&&T.test(e.nextCursor))&&I(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 I(o)?i===e.collectionEtag&&a!==null&&r.test(a)&&e.items.every(e=>(e.source===`direct`?e.sourceItemId===n:e.sourceItemId!==n)&&e.etag===We(o,e.revision))&&Je(e.items,e=>`${e.sourceItemId}\0${e.grantId}`):!1}function Te(e,t,n){if(!L(e,[`items`,`nextCursor`,`collectionRevision`,`collectionEtag`])||!Array.isArray(e.items)||e.items.length>50)return!1;let r=[];for(let t of e.items){if(!L(t,[`source`,`sourceItemId`,`grantId`,`grantee`,`actions`,`availability`,`expiresAtEpochMilliseconds`,`revision`,`etag`,`recipient`]))return!1;let{recipient:e,...n}=t;if(!Be(n)||e!==null&&(!L(e,[`userId`,`name`,`email`,`resolvedAt`,`expiresAt`])||n.grantee.type!==`user`||e.userId!==n.grantee.userId||typeof e.name!=`string`||e.name.length<1||N.encode(e.name).byteLength>1024||typeof e.email!=`string`||e.email.length<3||N.encode(e.email).byteLength>320||!e.email.includes(`@`)||!I(e.resolvedAt)||!I(e.expiresAt)||e.expiresAt!==e.resolvedAt+864e5))return!1;r.push(n)}return we({...e,items:r},t,n,/^"drive\.sharing-people\.v1\.[0-9a-f]{64}"$/)}function Ee(e,t,n){if(!L(e,[`outcome`,`grant`,`collectionRevision`])||e.outcome!==`committed`&&e.outcome!==`replayed`||!I(e.collectionRevision))return!1;let r=e.grant;return L(r,[`source`,`sourceItemId`,`grantId`,`grantee`,`actions`,`availability`,`expiresAtEpochMilliseconds`,`revision`])&&r.source===`direct`&&typeof r.sourceItemId==`string`&&r.sourceItemId===t&&typeof r.grantId==`string`&&S.test(r.grantId)&&(n===void 0||r.grantId===n)&&Ve(r.grantee)&&He(r.actions)&&[`active`,`expired`,`revoked`].includes(String(r.availability))&&(r.expiresAtEpochMilliseconds===null||I(r.expiresAtEpochMilliseconds))&&I(r.revision)}function De(e,t){if(!L(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||!L(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`&&y.test(r.sourceItemId))||!(r.grantId===null||typeof r.grantId==`string`&&S.test(r.grantId))||!Ue(r,t))return!1}return!0}function Oe(e,t){return!L(e,[`itemId`,`versionId`,`uploadId`,`mode`,`partByteLength`,`partCount`,`revision`,`expiresAtEpochMilliseconds`])||typeof e.itemId!=`string`||!y.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||typeof e.uploadId!=`string`||!C.test(e.uploadId)||e.mode!==`presigned-multipart`&&e.mode!==`server-mediated-zero-byte`||e.partByteLength!==M||!I(e.partCount)||e.partCount>1e4||e.partCount!==Math.ceil(t/M)||(t===0?e.mode!==`server-mediated-zero-byte`:e.mode!==`presigned-multipart`)||!I(e.revision)||!I(e.expiresAtEpochMilliseconds)||e.expiresAtEpochMilliseconds<=Date.now()?!1:(Object.freeze(e),!0)}function ke(e,t,n){if(!L(e,[`itemId`,`versionId`,`uploadId`,`mode`,`lifecycle`,`revision`,`partPolicy`,`confirmedParts`,`nextAfterPartNumber`,`expiresAtEpochMilliseconds`,`ready`],[`verification`])||typeof e.itemId!=`string`||!y.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||typeof e.uploadId!=`string`||!C.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))||!I(e.revision)||!L(e.partPolicy,[`partByteLength`,`partCount`,`maxParts`])||e.partPolicy.partByteLength!==M||!I(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||!I(e.expiresAtEpochMilliseconds))return!1;let r=t;if(e.verification!==void 0){let t=e.verification;if(!L(t,[`state`,`verifiedByteLength`,`totalByteLength`,`revision`])||![`pending`,`verified`,`failed`].includes(String(t.state))||!I(t.verifiedByteLength)||!I(t.totalByteLength)||t.totalByteLength>j||t.verifiedByteLength>t.totalByteLength||!I(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(!L(t,[`partNumber`,`checksumSha256`])||!I(t.partNumber)||t.partNumber<=r||t.partNumber>e.partPolicy.partCount||!Pe(t.checksumSha256))return!1;r=t.partNumber}if(!(e.nextAfterPartNumber===null||I(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&&(!Me(e.ready,{uploadId:e.uploadId})||e.ready.itemId!==e.itemId||e.ready.versionId!==e.versionId||!L(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 Ae(e,t,n,r){return!L(e,[`url`,`method`,`headers`,`partNumber`,`expectedByteLength`,`expiresAtEpochMilliseconds`])||!Ke(e.url,n)||e.method!==`PUT`||!r||!L(e.headers,[`content-md5`])||e.headers[`content-md5`]!==r||e.partNumber!==t||!I(e.expectedByteLength)||e.expectedByteLength<1||e.expectedByteLength>M||!I(e.expiresAtEpochMilliseconds)||e.expiresAtEpochMilliseconds<=Date.now()?!1:(Object.freeze(e.headers),Object.freeze(e),!0)}function je(e,t,n){return!L(e,[`partNumber`,`revision`])||e.partNumber!==t||e.revision!==n+1||!I(e.revision)?!1:(Object.freeze(e),!0)}function Me(e,t){return!L(e,[`itemId`,`versionId`,`uploadId`,`byteLength`,`callerDeclaredContentDigest`,`displayFilename`,`mediaType`,`state`])||typeof e.itemId!=`string`||!y.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||e.uploadId!==t.uploadId||!I(e.byteLength)||e.byteLength<0||e.byteLength>j||typeof e.callerDeclaredContentDigest!=`string`||!ie.test(e.callerDeclaredContentDigest)||!F(e.displayFilename)||!Ge(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 Ne(e,t){return!L(e,[`itemId`,`versionId`,`uploadId`,`state`,`verifiedByteLength`,`totalByteLength`,`verificationRevision`])||typeof e.itemId!=`string`||!y.test(e.itemId)||typeof e.versionId!=`string`||!w.test(e.versionId)||e.uploadId!==t||e.state!==`verifying`||!I(e.verifiedByteLength)||!I(e.totalByteLength)||e.totalByteLength>j||e.verifiedByteLength>e.totalByteLength||!I(e.verificationRevision)?!1:(Object.freeze(e),!0)}function Pe(e){return typeof e==`string`&&/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/.test(e)}function Fe(e){let t=L(e,Le)&&Re(e);return t&&Object.freeze(e),t}function Ie(e,t,n,r){let i=L(e,[...Le,`workspaceId`,`itemId`])&&e.workspaceId===t&&e.itemId===n&&e.versionId===r&&Re(e);return i&&Object.freeze(e),i}const Le=Object.freeze([`versionId`,`state`,`revision`,`byteLength`,`contentDigest`,`mediaType`,`displayFilename`,`protectionClassification`,`archiveState`]);function Re(e){return typeof e.versionId==`string`&&w.test(e.versionId)&&(e.state===`current`||e.state===`superseded`)&&I(e.revision)&&I(e.byteLength)&&typeof e.contentDigest==`string`&&ie.test(e.contentDigest)&&Ge(e.mediaType)&&F(e.displayFilename)&&(e.protectionClassification===`ordinary`||e.protectionClassification===`opaque-encrypted`)&&[`available`,`cold`,`restoring`,`unavailable`,`corrupt`].includes(String(e.archiveState))}function ze(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 Be(e){return L(e,[`source`,`sourceItemId`,`grantId`,`grantee`,`actions`,`availability`,`expiresAtEpochMilliseconds`,`revision`,`etag`])&&(e.source===`direct`||e.source===`inherited`)&&typeof e.sourceItemId==`string`&&y.test(e.sourceItemId)&&typeof e.grantId==`string`&&S.test(e.grantId)&&Ve(e.grantee)&&He(e.actions)&&[`active`,`expired`,`revoked`].includes(String(e.availability))&&(e.expiresAtEpochMilliseconds===null||I(e.expiresAtEpochMilliseconds))&&I(e.revision)&&typeof e.etag==`string`&&D.test(e.etag)}function Ve(e){return L(e,[`type`,`userId`])&&e.type===`user`&&typeof e.userId==`string`&&E.test(e.userId)||L(e,[`type`,`teamId`])&&e.type===`team`&&typeof e.teamId==`string`&&E.test(e.teamId)}function He(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 Ue(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 We(e,t){return`"drive.permission-grant.v1.${e}.${t}"`}function F(e){if(typeof e!=`string`||e.length===0||e.length>510||e.normalize(`NFC`)!==e||e.endsWith(`.`)||e.endsWith(` `)||qe(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 Ge(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 Ke(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 qe(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 Je(e,t){return e.every((n,r)=>r===0||t(e[r-1])<t(n))}function I(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ye(e){return/^"[\x21\x23-\x7e]{1,1022}"$/.test(e)}function Xe(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 L(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 Ze=/^drive\.item\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,R=/^drive\.workspace\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Qe=/^drive\.grant\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,$e=/^drive\.upload\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,et=/^drive\.version\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,tt=/^drive\.cursor\.v1\.[A-Za-z0-9_-]+$/,nt=/^[A-Za-z0-9_-]{1,128}$/,rt=Object.freeze([`items:content:read`,`items:create`,`items:delete`,`items:metadata:read`,`items:permissions:read`,`items:update`]),it=/^[A-Za-z0-9_-]{16,128}$/,at=/^sha256:[0-9a-f]{64}$/,ot=/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/;function st(e){let t=G(W(e===void 0?{}:e,[],[`signal`]).signal);return t===void 0?{}:{signal:t}}function ct(e){let t=W(e===void 0?{}:e,[],[`signal`,`limit`,`cursor`]),n=G(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 lt(e,t){let n=W(e,[`workspaceId`],t?[`signal`,`view`,`kind`,`creatorUserId`,`limit`,`cursor`]:[`signal`]),i=G(n.signal);if(typeof n.workspaceId!=`string`||!R.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`||!nt.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 z(e){let t=W(e,[`workspaceId`,`itemId`],[`signal`]),n=t.workspaceId,i=t.itemId,a=G(t.signal);if(typeof n!=`string`||!R.test(n)||typeof i!=`string`||!Ze.test(i))throw new r(`invalid_input`);return{workspaceId:n,itemId:i,...a===void 0?{}:{signal:a}}}function ut(e){let t=W(e,[`workspaceId`,`itemId`,`versionId`],[`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(typeof t.versionId!=`string`||!et.test(t.versionId))throw new r(`invalid_input`);return{...n,versionId:t.versionId}}function dt(e){let t=W(e,[`workspaceId`,`itemId`,`idempotencyKey`],[`versionId`,`method`,`range`,`ifMatch`,`ifNoneMatch`,`ifRange`,`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}}),i=t.method??`GET`;if(!K(t.idempotencyKey)||t.versionId!==void 0&&(typeof t.versionId!=`string`||!et.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))||!Rt(t.ifMatch)||!Rt(t.ifNoneMatch)||!Rt(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 ft(e){let t=W(e,[`workspaceId`,`query`],[`limit`,`cursor`,`signal`]),n=G(t.signal);if(typeof t.workspaceId!=`string`||!R.test(t.workspaceId)||!Pt(t.query)||t.limit!==void 0&&(!J(t.limit)||t.limit<1||t.limit>50)||t.cursor!==void 0&&(typeof t.cursor!=`string`||t.cursor.length>699||!tt.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 pt(e){let t=W(e,[`workspaceId`,`itemId`],[`signal`,`limit`,`cursor`]),n=z({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||!tt.test(a)))throw new r(`invalid_input`);return{...n,...i===void 0?{}:{limit:i},...a===void 0?{}:{cursor:a}}}function mt(e){let t=W(e,[`workspaceId`,`itemId`,`name`,`idempotencyKey`],[`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(!It(t.name)||!K(t.idempotencyKey))throw new r(`invalid_input`);return{...n,name:t.name,idempotencyKey:t.idempotencyKey}}function ht(e){let t=W(e,[`workspaceId`,`itemId`,`name`,`parentItemId`,`idempotencyKey`,`ifMatch`],[`signal`]),n=B({workspaceId:t.workspaceId,itemId:t.itemId,idempotencyKey:t.idempotencyKey,ifMatch:t.ifMatch,...t.signal===void 0?{}:{signal:t.signal}});if(!It(t.name)||typeof t.parentItemId!=`string`||!Ze.test(t.parentItemId))throw new r(`invalid_input`);return{...n,name:t.name,parentItemId:t.parentItemId}}function B(e){let t=W(e,[`workspaceId`,`itemId`,`idempotencyKey`,`ifMatch`],[`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(!K(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 gt(e){let t=W(e,[`workspaceId`,`itemId`,`versionId`,`idempotencyKey`,`ifMatch`],[`signal`]),n=B({workspaceId:t.workspaceId,itemId:t.itemId,idempotencyKey:t.idempotencyKey,ifMatch:t.ifMatch,...t.signal===void 0?{}:{signal:t.signal}});if(typeof t.versionId!=`string`||!et.test(t.versionId))throw new r(`invalid_input`);return{...n,versionId:t.versionId}}function _t(e){let t=W(e,[`workspaceId`,`itemId`,`grantee`,`actions`,`expiresAtEpochMilliseconds`,`ifMatch`,`idempotencyKey`],[`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}}),i=Dt(t.grantee),a=Ot(t.actions),o=t.expiresAtEpochMilliseconds;if(!Ft(o)||typeof t.ifMatch!=`string`||d(t.ifMatch)===void 0||!K(t.idempotencyKey))throw new r(`invalid_input`);return{...n,grantee:i,actions:a,expiresAtEpochMilliseconds:o,ifMatch:t.ifMatch,idempotencyKey:t.idempotencyKey}}function vt(e){let t=W(e,[`workspaceId`,`itemId`,`email`,`role`,`ifMatch`,`idempotencyKey`],[`signal`]),n=z({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||!K(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 yt(e){let t=W(e,[`workspaceId`,`itemId`,`grantId`,`ifMatch`,`idempotencyKey`],[`signal`]),n=z({workspaceId:t.workspaceId,itemId:t.itemId,...t.signal===void 0?{}:{signal:t.signal}});if(typeof t.grantId!=`string`||!Qe.test(t.grantId)||typeof t.ifMatch!=`string`||f(t.ifMatch)===void 0||!K(t.idempotencyKey))throw new r(`invalid_input`);return{...n,grantId:t.grantId,ifMatch:t.ifMatch,idempotencyKey:t.idempotencyKey}}function bt(e){let t=W(e,[`workspaceId`,`itemId`,`grantId`,`ifMatch`,`idempotencyKey`],[`signal`,`actions`,`expiresAtEpochMilliseconds`]),n=yt({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:Ot(t.actions),a=t.expiresAtEpochMilliseconds;if(i===void 0&&a===void 0||a!==void 0&&!Ft(a))throw new r(`invalid_input`);return{...n,...i===void 0?{}:{actions:i},...a===void 0?{}:{expiresAtEpochMilliseconds:a}}}function xt(e){let t=W(e,[`workspaceId`,`parentItemId`,`expectedByteLength`,`displayFilename`,`mediaType`,`callerDeclaredContentDigest`,`protectionClassification`,`idempotencyKey`],[`signal`]),n=G(t.signal);if(typeof t.workspaceId!=`string`||!R.test(t.workspaceId)||typeof t.parentItemId!=`string`||!Ze.test(t.parentItemId)||typeof t.expectedByteLength!=`number`||!Number.isSafeInteger(t.expectedByteLength)||t.expectedByteLength<0||t.expectedByteLength>33554432e4||!It(t.displayFilename)||!Nt(t.mediaType)||typeof t.callerDeclaredContentDigest!=`string`||!at.test(t.callerDeclaredContentDigest)||t.protectionClassification!==`ordinary`&&t.protectionClassification!==`opaque-encrypted`||!K(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 St(e){let t=W(e,[`workspaceId`,`uploadId`],[`afterPartNumber`,`limit`,`signal`]),n=q(t.workspaceId,t.uploadId,t.signal);if(t.afterPartNumber!==void 0&&(!J(t.afterPartNumber)||t.afterPartNumber>1e4)||t.limit!==void 0&&(!J(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 Ct(e){let t=W(e,[`workspaceId`,`uploadId`,`partNumber`,`checksumSha256`,`contentMd5`],[`signal`]),n=q(t.workspaceId,t.uploadId,t.signal);if(!At(t.partNumber)||!jt(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 wt(e){let t=W(e,[`workspaceId`,`uploadId`,`partNumber`,`expectedUploadRevision`,`byteLength`,`etag`,`checksumSha256`],[`signal`]),n=q(t.workspaceId,t.uploadId,t.signal);if(!At(t.partNumber)||!J(t.expectedUploadRevision)||t.expectedUploadRevision>=2**53-1||!J(t.byteLength)||t.byteLength<1||t.byteLength>33554432||!Mt(t.etag)||!jt(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 Tt(e){let t=W(e,[`workspaceId`,`uploadId`,`idempotencyKey`],[`signal`]),n=q(t.workspaceId,t.uploadId,t.signal);if(!K(t.idempotencyKey))throw new r(`invalid_input`);return{...n,idempotencyKey:t.idempotencyKey}}function Et(e){let t=W(e,[`workspaceId`,`uploadId`],[`signal`]);return q(t.workspaceId,t.uploadId,t.signal)}function V(e){return{workspaceId:e.workspaceId,itemId:e.itemId}}function H(e){return{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor}}}function U(e,t){return t}function W(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 G(e){if(e!==void 0){if(!(e instanceof AbortSignal))throw new r(`invalid_input`);return e}}function Dt(e){let t=W(e,[`type`],[`userId`,`teamId`]);if(t.type===`user`){let t=W(e,[`type`,`userId`],[]);if(typeof t.userId==`string`&&nt.test(t.userId))return{type:`user`,userId:t.userId}}if(t.type===`team`){let t=W(e,[`type`,`teamId`],[]);if(typeof t.teamId==`string`&&nt.test(t.teamId))return{type:`team`,teamId:t.teamId}}throw new r(`invalid_input`)}function Ot(e){let t=kt(e);if(t.length<1||t.length>rt.length||new Set(t).size!==t.length||!t.every(e=>rt.includes(e)))throw new r(`invalid_input`);return t}function kt(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 K(e){return typeof e==`string`&&it.test(e)}function q(e,t,n){let i=G(n);if(typeof e!=`string`||!R.test(e)||typeof t!=`string`||!$e.test(t))throw new r(`invalid_input`);return{workspaceId:e,uploadId:t,...i===void 0?{}:{signal:i}}}function At(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=1&&e<=1e4}function jt(e){return typeof e==`string`&&ot.test(e)}function Mt(e){return typeof e==`string`&&e.length>=1&&e.length<=1024&&/^[\x20-\x7e]+$/.test(e)}function Nt(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 Pt(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 Ft(e){return e===null||J(e)}function It(e){if(typeof e!=`string`||e.length===0||e.length>510||e.normalize(`NFC`)!==e||e.endsWith(`.`)||e.endsWith(` `)||Lt(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 Lt(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 J(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Rt(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 zt=/\{[^{}]+\}/g,Bt=()=>typeof process==`object`&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Vt(){return Math.random().toString(36).slice(2,11)}function Ht(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=Bt()?c:void 0,t=Zt(t);let u=[];async function d(e,d){let{baseUrl:f,fetch:p=r,Request:m=n,headers:ee,params:h={},parseAs:g=`json`,querySerializer:_,bodySerializer:te=a??Jt,pathSerializer:ne,body:v,middleware:y=[],...b}=d||{},x=t;f&&(x=Zt(f)??t);let S=typeof i==`function`?i:Kt(i);_&&(S=typeof _==`function`?_:Kt({...typeof i==`object`?i:{},..._}));let C=ne||o||qt,w=v===void 0?void 0:te(v,Xt(s,ee,h.header)),re=Xt(w===void 0||w instanceof FormData?{}:{"Content-Type":`application/json`},s,ee,h.header),T=[...u,...y],E={redirect:`follow`,...l,...b,body:w,headers:re},D,O,k=new m(Yt(e,{baseUrl:x,params:h,querySerializer:S,pathSerializer:C}),E),A;for(let e in b)e in k||(k[e]=b[e]);if(T.length){D=Vt(),O=Object.freeze({baseUrl:x,fetch:p,parseAs:g,querySerializer:S,bodySerializer:te,pathSerializer:C});for(let t of T)if(t&&typeof t==`object`&&typeof t.onRequest==`function`){let n=await t.onRequest({request:k,schemaPath:e,params:h,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:h,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:h,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(g===`stream`)return A.body;if(g===`json`&&!j){let e=await A.text();return e?JSON.parse(e):void 0}return await A[g]()})(),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 Ut(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 Wt(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(Ut(a,t[i],n))}let a=r.join(i);return n.style===`label`||n.style===`matrix`?`${i}${a}`:a}function Gt(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(Ut(e,r,n));return n.style===`label`||n.style===`matrix`?`${r}${i.join(r)}`:i.join(r)}function Kt(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(Gt(r,i,{style:`form`,explode:!0,...e?.array,allowReserved:e?.allowReserved||!1}));continue}if(typeof i==`object`){n.push(Wt(r,i,{style:`deepObject`,explode:!0,...e?.object,allowReserved:e?.allowReserved||!1}));continue}n.push(Ut(r,i,e))}}return n.join(`&`)}}function qt(e,t){let n=e;for(let r of e.match(zt)??[]){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,Gt(e,o,{style:a,explode:i}));continue}if(typeof o==`object`){n=n.replace(r,Wt(e,o,{style:a,explode:i}));continue}if(a===`matrix`){n=n.replace(r,`;${Ut(e,o)}`);continue}n=n.replace(r,a===`label`?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return n}function Jt(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 Yt(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 Xt(...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 Zt(e){return e.endsWith(`/`)?e.substring(0,e.length-1):e}String.fromCharCode;const Qt=/\/$|\/\?|\/#/,$t=/^\.?\//;function en(e=``,t){return t?Qt.test(e):e.endsWith(`/`)}function tn(e=``,t){if(!t)return e.endsWith(`/`)?e:e+`/`;if(en(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 nn(e){return e&&e!==`/`}function rn(e,...t){let n=e||``;for(let e of t.filter(e=>nn(e)))if(n){let t=e.replace($t,``);n=tn(n)+t}else n=e;return n}function an(e){let t;try{t=Object.freeze({baseUrl:cn(e.baseUrl),fetchImplementation:e.fetch??globalThis.fetch.bind(globalThis),getCredential:e.getCredential,timeoutMilliseconds:on(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 Y(e,t,n,i,a,o,s=!1,c){let d=sn(t,e.timeoutMilliseconds);try{let t=d.signal;un(t);let f=await ln(e.getCredential,t),p;if(await i(Ht({baseUrl:e.baseUrl,fetch:async n=>{try{let i=await dn(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 on(e){if(e===void 0)return 3e4;if(!Number.isSafeInteger(e)||e<1||e>12e4)throw new r(`invalid_input`);return e}function sn(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 cn(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 rn(t.origin,t.pathname)}async function ln(e,t){un(t);let n;try{n=await dn(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 un(e){if(e.aborted)throw new r(`aborted`)}async function dn(e,t){un(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 fn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`service_unavailable`]),pn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`precondition_failed`,`service_unavailable`]),X=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`invalid_pagination_cursor`,`precondition_failed`,`service_unavailable`]),Z=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`precondition_failed`,`upload_recovery_required`,`service_unavailable`]),mn=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`service_unavailable`]),hn=Object.freeze([...Z,`invalid_idempotency_key`,`idempotency_conflict`,`quota_exceeded`]),gn=Object.freeze([...Z,`invalid_idempotency_key`]),Q=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`invalid_idempotency_key`,`idempotency_conflict`,`precondition_failed`,`service_unavailable`]),_n=Object.freeze([`authentication_required`,`identity_authority_unavailable`,`permission_denied`,`resource_not_found`,`invalid_request`,`precondition_failed`,`service_unavailable`]),vn=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 yn(e){return bn(an(e))}function bn(e){return Object.freeze({registerItemRecipient:t=>Kn(e,t),listItemSharingPeople:t=>qn(e,t),listIncomingShares:t=>xn(e,t),getCurrentWorkspace:t=>jn(e,t),listWorkspaceItems:t=>kn(e,t),getWorkspaceUsage:t=>An(e,t),getCurrentWorkspaceSources:t=>On(e,t),getItem:t=>Mn(e,t),searchWorkspaceItems:t=>Nn(e,t),listFolderChildren:t=>Pn(e,t),createFolder:t=>Fn(e,t),updateItem:t=>In(e,t),trashItem:t=>Ln(e,t),restoreItem:t=>Rn(e,t),deleteItem:t=>zn(e,t),listItemVersions:t=>Bn(e,t),getItemVersion:t=>Vn(e,t),restoreItemVersion:t=>Hn(e,t),createDownload:t=>Sn(e,t),downloadItem:t=>Cn(e,t),listItemPermissions:t=>Un(e,t),readEffectiveItemPermissions:t=>Wn(e,t),createItemPermission:t=>Gn(e,t),updateItemPermission:t=>Jn(e,t),revokeItemPermission:t=>Yn(e,t),createUpload:t=>Xn(e,t),getUploadStatus:t=>Zn(e,t),createUploadPartDescriptor:t=>Qn(e,t),recordUploadPart:t=>$n(e,t),completeUpload:t=>er(e,t),abortUpload:t=>tr(e,t)})}async function xn(e,t){let n=ct(t);return Y(e,n.signal,409,(e,t)=>e.GET(`/api/v1/shares/incoming`,{...U(`listIncomingShares`,{params:{query:n.query}}),...t}),[200],ae,!1,X)}async function Sn(e,t){let n=dt(t);return Y(e,n.signal,412,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/downloads`,{...U(`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?ue(e):t===202?fe(e):e===void 0,!1,vn)}async function Cn(e,t){let n=dt(t),i=await Sn(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=sn(n.signal,e.timeoutMilliseconds);try{let t=await dn(e.fetchImplementation(Tn(a,o.signal)),o.signal);if(!En(t,a))throw await t.body?.cancel().catch(()=>void 0),new r(`invalid_response`);let i=wn(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(Dn(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 wn(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 Tn(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 En(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 Dn(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 On(e,t){return Y(e,st(t).signal,null,(e,t)=>e.GET(`/api/v1/workspaces/current/sources`,{...U(`getCurrentWorkspaceSources`,{params:{}}),...t}),[200],ce,!1,fn)}async function kn(e,t){let n=lt(t,!0);return Y(e,n.signal,null,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items`,{...U(`listWorkspaceItems`,{params:{path:{workspaceId:n.workspaceId},query:n.query}}),...t}),[200],e=>se(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,X)}async function An(e,t){let n=lt(t,!1);return Y(e,n.signal,null,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/usage`,{...U(`getWorkspaceUsage`,{params:{path:{workspaceId:n.workspaceId}}}),...t}),[200],e=>oe(e)&&e.workspaceId===n.workspaceId,!1,X)}async function jn(e,t){return Y(e,st(t).signal,null,(e,t)=>e.GET(`/api/v1/workspaces/current`,{...U(`getCurrentWorkspace`,{params:{}}),...t}),[200],le,!1,fn)}async function Mn(e,t){let n=z(t);return Y(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}`,{...U(`getItem`,{params:{path:V(n)}}),...t}),[200],(e,t,r)=>ge(e,n.workspaceId,n.itemId)&&P(r,e.revision),!1,pn)}async function Nn(e,t){let n=ft(t);return Y(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/search`,{...U(`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=>_e(e,n.workspaceId,n.query,n.limit??50),!1,X)}async function Pn(e,t){let n=pt(t);return Y(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/children`,{...U(`listFolderChildren`,{params:{path:V(n),query:H(n)}}),...t}),[200],e=>pe(e,n.workspaceId,n.itemId))}async function Fn(e,t){let n=mt(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/children`,{...U(`createFolder`,{params:{path:V(n),header:{"Idempotency-Key":n.idempotencyKey}},body:{name:n.name}}),...t}),[200,201],e=>me(e)&&e.workspaceId===n.workspaceId&&e.parentItemId===n.itemId&&e.kind===`folder`&&e.name===n.name)}async function In(e,t){let n=ht(t);return Y(e,n.signal,409,(e,t)=>e.PATCH(`/api/v1/workspaces/{workspaceId}/items/{itemId}`,{...U(`updateItem`,{params:{path:V(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}},body:{name:n.name,parentItemId:n.parentItemId}}),...t}),[200],(e,t,r)=>he(e,n.workspaceId,n.itemId,`active`)&&e.name===n.name&&e.parentItemId===n.parentItemId&&P(r,e.revision),!1,Q)}async function Ln(e,t){let n=B(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/trash`,{...U(`trashItem`,{params:{path:V(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>he(e,n.workspaceId,n.itemId,`trashed`)&&P(r,e.revision),!1,Q)}async function Rn(e,t){let n=B(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/restore`,{...U(`restoreItem`,{params:{path:V(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>he(e,n.workspaceId,n.itemId,`active`)&&P(r,e.revision),!1,Q)}async function zn(e,t){let n=B(t);return Y(e,n.signal,409,(e,t)=>e.DELETE(`/api/v1/workspaces/{workspaceId}/items/{itemId}`,{...U(`deleteItem`,{params:{path:V(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200,202],(e,t,r)=>he(e,n.workspaceId,n.itemId,`deleting`)&&P(r,e.revision),!1,Q)}async function Bn(e,t){let n=pt(t);return Y(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/versions`,{...U(`listItemVersions`,{params:{path:V(n),query:H(n)}}),...t}),[200],e=>Se(e,n.limit??50),!1,_n)}async function Vn(e,t){let n=ut(t);return Y(e,n.signal,409,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}`,{...U(`getItemVersion`,{params:{path:{...V(n),versionId:n.versionId}}}),...t}),[200],e=>Ie(e,n.workspaceId,n.itemId,n.versionId),!1,_n)}async function Hn(e,t){let n=gt(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/versions/{versionId}/restore`,{...U(`restoreItemVersion`,{params:{path:{...V(n),versionId:n.versionId},header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>Ce(e,n.versionId)&&P(r,e.itemRevision),!1,Q)}async function Un(e,t){let n=pt(t);return Y(e,n.signal,412,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions`,{...U(`listItemPermissions`,{params:{path:V(n),query:H(n)}}),...t}),[200],(e,t,r)=>we(e,r,n.itemId))}async function Wn(e,t){let n=z(t);return Y(e,n.signal,412,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/effective`,{...U(`readEffectiveItemPermissions`,{params:{path:V(n)}}),...t}),[200],e=>De(e,n.itemId))}async function Gn(e,t){let n=_t(t);return Y(e,n.signal,412,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions`,{...U(`createItemPermission`,{params:{path:V(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)=>Ee(e,n.itemId)&&(t===201&&e.outcome===`committed`||t===200&&e.outcome===`replayed`)&&(t===200||e.grant.availability!==`revoked`)&&ze(r))}async function Kn(e,t){let n=vt(t);return Y(e,n.signal,412,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/items/{itemId}/sharing`,{...U(`registerItemRecipient`,{params:{path:V(n),header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}},body:{email:n.email,role:n.role}}),...t}),[200,201],(e,t,r)=>Ee(e,n.itemId)&&(t===201&&e.outcome===`committed`||t===200&&e.outcome===`replayed`)&&(t===200||e.grant.availability!==`revoked`)&&ze(r),!1,[...X,`recipient_unavailable`,`rate_limited`,`idempotency_conflict`,`invalid_idempotency_key`])}async function qn(e,t){let n=pt(t);return Y(e,n.signal,412,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/items/{itemId}/sharing/people`,{...U(`listItemSharingPeople`,{params:{path:V(n),query:H(n)}}),...t}),[200],(e,t,r)=>Te(e,r,n.itemId))}async function Jn(e,t){let n=bt(t),r={};return n.actions!==void 0&&(r.actions=n.actions),n.expiresAtEpochMilliseconds!==void 0&&(r.expiresAtEpochMilliseconds=n.expiresAtEpochMilliseconds),Y(e,n.signal,412,(e,t)=>e.PATCH(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}`,{...U(`updateItemPermission`,{params:{path:{...V(n),grantId:n.grantId},header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}},body:r}),...t}),[200],(e,t,r)=>Ee(e,n.itemId,n.grantId)&&e.grant.availability!==`revoked`&&ze(r))}async function Yn(e,t){let n=yt(t);return Y(e,n.signal,412,(e,t)=>e.DELETE(`/api/v1/workspaces/{workspaceId}/items/{itemId}/permissions/{grantId}`,{...U(`revokeItemPermission`,{params:{path:{...V(n),grantId:n.grantId},header:{"Idempotency-Key":n.idempotencyKey,"If-Match":n.ifMatch}}}),...t}),[200],(e,t,r)=>Ee(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 Xn(e,t){let n=xt(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads`,{...U(`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=>Oe(e,n.expectedByteLength),!0,hn)}async function Zn(e,t){let n=St(t),r=n.afterPartNumber??0,i=n.limit??100;return Y(e,n.signal,null,(e,t)=>e.GET(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}`,{...U(`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=>ke(e,r,i)&&e.uploadId===n.uploadId,!1,mn)}async function Qn(e,t){let n=Ct(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts`,{...U(`createUploadPartDescriptor`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId}},body:{partNumber:n.partNumber,checksumSha256:n.checksumSha256,contentMd5:n.contentMd5}}),...t}),[200],t=>Ae(t,n.partNumber,new URL(e.baseUrl).protocol===`http:`,n.contentMd5),!1,Z)}async function $n(e,t){let n=wt(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/parts/{partNumber}`,{...U(`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=>je(e,n.partNumber,n.expectedUploadRevision),!1,Z)}async function er(e,t){let n=Tt(t);return Y(e,n.signal,409,(e,t)=>e.POST(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}/complete`,{...U(`completeUpload`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId},header:{"Idempotency-Key":n.idempotencyKey}}}),...t}),[200,202],(e,t)=>t===202?Ne(e,n.uploadId):Me(e,{uploadId:n.uploadId}),!1,gn)}async function tr(e,t){let n=Et(t);return Y(e,n.signal,409,(e,t)=>e.DELETE(`/api/v1/workspaces/{workspaceId}/uploads/{uploadId}`,{...U(`abortUpload`,{params:{path:{workspaceId:n.workspaceId,uploadId:n.uploadId}}}),...t}),[204],null,!1,Z)}const nr=[`local`,`development`,`staging`,`production`],rr=/^[A-Za-z0-9_-]{1,128}$/;function ir(e){if(!e||!nr.includes(e.environment))throw new r(`invalid_input`);let t=e.environment,n=an({baseUrl:e.baseUrl,getCredential:e.getProvisioningCredential,...e.fetch===void 0?{}:{fetch:e.fetch},...e.timeoutMilliseconds===void 0?{}:{timeoutMilliseconds:e.timeoutMilliseconds}});return Object.freeze({async provisionWorkspace(e,i){if(!$(e,[`version`,`environment`,`provisioningId`,`workspaceReference`,`entitlement`])||e.version!==1||e.environment!==t||typeof e.provisioningId!=`string`||!rr.test(e.provisioningId)||!ar(e.workspaceReference)||!or(e.entitlement))throw new r(`invalid_input`);let a={version:e.version,environment:e.environment,provisioningId:e.provisioningId,workspaceReference:{...e.workspaceReference},entitlement:{...e.entitlement}};return Y(n,i?.signal,null,(e,t)=>e.POST(`/api/v1/platform/workspaces/provision`,{...t,redirect:`manual`,body:a}),[200,201],(e,t)=>sr(e,t,a),!1,[`authentication_required`,`permission_denied`,`idempotency_conflict`,`invalid_request`,`identity_authority_unavailable`,`service_unavailable`])}})}function $(e,t){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function ar(e){return $(e,[`type`,`userId`])&&e.type===`personal`&&typeof e.userId==`string`&&rr.test(e.userId)||$(e,[`type`,`organizationId`])&&e.type===`organization`&&typeof e.organizationId==`string`&&rr.test(e.organizationId)}function or(e){return $(e,[`version`,`managedStorageEnabled`,`managedStorageByteLimit`])&&typeof e.version==`number`&&Number.isSafeInteger(e.version)&&e.version>=0&&typeof e.managedStorageByteLimit==`number`&&Number.isSafeInteger(e.managedStorageByteLimit)&&(e.managedStorageEnabled===!0&&e.managedStorageByteLimit>0||e.managedStorageEnabled===!1&&e.managedStorageByteLimit===0)}function sr(e,t,n){if(!$(e,[`outcome`,`workspace`])||(t===201?e.outcome!==`committed`:e.outcome!==`replayed`&&e.outcome!==`superseded`)||!$(e.workspace,[`workspaceId`,`rootVolumeId`,`rootItemId`,`workspaceReference`,`entitlement`]))return!1;let{entitlement:r,...i}=e.workspace;if(!le(i)||!or(r))return!1;let a=i.workspaceReference,o=n.workspaceReference;return(a.type!==`personal`||o.type!==`personal`||a.userId!==o.userId)&&(a.type!==`organization`||o.type!==`organization`||a.organizationId!==o.organizationId)?!1:e.outcome===`superseded`?r.version>n.entitlement.version:r.version===n.entitlement.version&&r.managedStorageEnabled===n.entitlement.managedStorageEnabled&&r.managedStorageByteLimit===n.entitlement.managedStorageByteLimit}function cr(e){let t=e.credential,n=typeof t==`string`?async()=>t:t;return yn({baseUrl:e.baseUrl,...e.fetch===void 0?{}:{fetch:e.fetch},getCredential:n,...e.timeoutMilliseconds===void 0?{}:{timeoutMilliseconds:e.timeoutMilliseconds}})}export{ir as createDriveProvisioningClient,cr as createDriveServerClient};