UNPKG

41 kBTypeScriptView Raw
1import { BodyResponseCallback, DecorateRequestOptions, GetConfig, MetadataCallback, ServiceObject, SetMetadataResponse } from './nodejs-common/index.js';
2import * as resumableUpload from './resumable-upload.js';
3import { Writable, Readable, PipelineSource } from 'stream';
4import * as http from 'http';
5import { PreconditionOptions, Storage } from './storage.js';
6import { AvailableServiceObjectMethods, Bucket } from './bucket.js';
7import { Acl, AclMetadata } from './acl.js';
8import { GetSignedUrlResponse, GetSignedUrlCallback, URLSigner, SignerGetSignedUrlConfig, Query } from './signer.js';
9import { Duplexify, GCCL_GCS_CMD_KEY } from './nodejs-common/util.js';
10import { CRC32C, CRC32CValidatorGenerator } from './crc32c.js';
11import { URL } from 'url';
12import { BaseMetadata, DeleteCallback, DeleteOptions, GetResponse, InstanceResponseCallback, RequestResponse, SetMetadataOptions } from './nodejs-common/service-object.js';
13import * as r from 'teeny-request';
14export type GetExpirationDateResponse = [Date];
15export interface GetExpirationDateCallback {
16 (err: Error | null, expirationDate?: Date | null, apiResponse?: unknown): void;
17}
18export interface PolicyDocument {
19 string: string;
20 base64: string;
21 signature: string;
22}
23export type SaveData = string | Buffer | Uint8Array | PipelineSource<string | Buffer | Uint8Array>;
24export type GenerateSignedPostPolicyV2Response = [PolicyDocument];
25export interface GenerateSignedPostPolicyV2Callback {
26 (err: Error | null, policy?: PolicyDocument): void;
27}
28export interface GenerateSignedPostPolicyV2Options {
29 equals?: string[] | string[][];
30 expires: string | number | Date;
31 startsWith?: string[] | string[][];
32 acl?: string;
33 successRedirect?: string;
34 successStatus?: string;
35 contentLengthRange?: {
36 min?: number;
37 max?: number;
38 };
39 /**
40 * @example
41 * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'
42 */
43 signingEndpoint?: string;
44}
45export interface PolicyFields {
46 [key: string]: string;
47}
48export interface GenerateSignedPostPolicyV4Options {
49 expires: string | number | Date;
50 bucketBoundHostname?: string;
51 virtualHostedStyle?: boolean;
52 conditions?: object[];
53 fields?: PolicyFields;
54 /**
55 * @example
56 * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'
57 */
58 signingEndpoint?: string;
59}
60export interface GenerateSignedPostPolicyV4Callback {
61 (err: Error | null, output?: SignedPostPolicyV4Output): void;
62}
63export type GenerateSignedPostPolicyV4Response = [SignedPostPolicyV4Output];
64export interface SignedPostPolicyV4Output {
65 url: string;
66 fields: PolicyFields;
67}
68export interface GetSignedUrlConfig extends Pick<SignerGetSignedUrlConfig, 'host' | 'signingEndpoint'> {
69 action: 'read' | 'write' | 'delete' | 'resumable';
70 version?: 'v2' | 'v4';
71 virtualHostedStyle?: boolean;
72 cname?: string;
73 contentMd5?: string;
74 contentType?: string;
75 expires: string | number | Date;
76 accessibleAt?: string | number | Date;
77 extensionHeaders?: http.OutgoingHttpHeaders;
78 promptSaveAs?: string;
79 responseDisposition?: string;
80 responseType?: string;
81 queryParams?: Query;
82}
83export interface GetFileMetadataOptions {
84 userProject?: string;
85}
86export type GetFileMetadataResponse = [FileMetadata, unknown];
87export interface GetFileMetadataCallback {
88 (err: Error | null, metadata?: FileMetadata, apiResponse?: unknown): void;
89}
90export interface GetFileOptions extends GetConfig {
91 userProject?: string;
92 generation?: number;
93 softDeleted?: boolean;
94}
95export type GetFileResponse = [File, unknown];
96export interface GetFileCallback {
97 (err: Error | null, file?: File, apiResponse?: unknown): void;
98}
99export interface FileExistsOptions {
100 userProject?: string;
101}
102export type FileExistsResponse = [boolean];
103export interface FileExistsCallback {
104 (err: Error | null, exists?: boolean): void;
105}
106export interface DeleteFileOptions {
107 ignoreNotFound?: boolean;
108 userProject?: string;
109}
110export type DeleteFileResponse = [unknown];
111export interface DeleteFileCallback {
112 (err: Error | null, apiResponse?: unknown): void;
113}
114export type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead';
115type PublicResumableUploadOptions = 'chunkSize' | 'highWaterMark' | 'isPartialUpload' | 'metadata' | 'origin' | 'offset' | 'predefinedAcl' | 'private' | 'public' | 'uri' | 'userProject';
116export interface CreateResumableUploadOptions extends Pick<resumableUpload.UploadConfig, PublicResumableUploadOptions> {
117 /**
118 * A CRC32C to resume from when continuing a previous upload. It is recommended
119 * to capture the `crc32c` event from previous upload sessions to provide in
120 * subsequent requests in order to accurately track the upload. This is **required**
121 * when validating a final portion of the uploaded object.
122 *
123 * @see {@link CRC32C.from} for possible values.
124 */
125 resumeCRC32C?: Parameters<(typeof CRC32C)['from']>[0];
126 preconditionOpts?: PreconditionOptions;
127 [GCCL_GCS_CMD_KEY]?: resumableUpload.UploadConfig[typeof GCCL_GCS_CMD_KEY];
128}
129export type CreateResumableUploadResponse = [string];
130export interface CreateResumableUploadCallback {
131 (err: Error | null, uri?: string): void;
132}
133export interface CreateWriteStreamOptions extends CreateResumableUploadOptions {
134 contentType?: string;
135 gzip?: string | boolean;
136 resumable?: boolean;
137 timeout?: number;
138 validation?: string | boolean;
139}
140export interface MakeFilePrivateOptions {
141 metadata?: FileMetadata;
142 strict?: boolean;
143 userProject?: string;
144 preconditionOpts?: PreconditionOptions;
145}
146export type MakeFilePrivateResponse = [unknown];
147export type MakeFilePrivateCallback = SetFileMetadataCallback;
148export interface IsPublicCallback {
149 (err: Error | null, resp?: boolean): void;
150}
151export type IsPublicResponse = [boolean];
152export type MakeFilePublicResponse = [unknown];
153export interface MakeFilePublicCallback {
154 (err?: Error | null, apiResponse?: unknown): void;
155}
156export type MoveResponse = [unknown];
157export interface MoveCallback {
158 (err: Error | null, destinationFile?: File | null, apiResponse?: unknown): void;
159}
160export interface MoveOptions {
161 userProject?: string;
162 preconditionOpts?: PreconditionOptions;
163}
164export type RenameOptions = MoveOptions;
165export type RenameResponse = MoveResponse;
166export type RenameCallback = MoveCallback;
167export type RotateEncryptionKeyOptions = string | Buffer | EncryptionKeyOptions;
168export interface EncryptionKeyOptions {
169 encryptionKey?: string | Buffer;
170 kmsKeyName?: string;
171 preconditionOpts?: PreconditionOptions;
172}
173export type RotateEncryptionKeyCallback = CopyCallback;
174export type RotateEncryptionKeyResponse = CopyResponse;
175export declare enum ActionToHTTPMethod {
176 read = "GET",
177 write = "PUT",
178 delete = "DELETE",
179 resumable = "POST"
180}
181/**
182 * @deprecated - no longer used
183 */
184export declare const STORAGE_POST_POLICY_BASE_URL = "https://storage.googleapis.com";
185export interface FileOptions {
186 crc32cGenerator?: CRC32CValidatorGenerator;
187 encryptionKey?: string | Buffer;
188 generation?: number | string;
189 kmsKeyName?: string;
190 preconditionOpts?: PreconditionOptions;
191 userProject?: string;
192}
193export interface CopyOptions {
194 cacheControl?: string;
195 contentEncoding?: string;
196 contentType?: string;
197 contentDisposition?: string;
198 destinationKmsKeyName?: string;
199 metadata?: {
200 [key: string]: string | boolean | number | null;
201 };
202 predefinedAcl?: string;
203 token?: string;
204 userProject?: string;
205 preconditionOpts?: PreconditionOptions;
206}
207export type CopyResponse = [File, unknown];
208export interface CopyCallback {
209 (err: Error | null, file?: File | null, apiResponse?: unknown): void;
210}
211export type DownloadResponse = [Buffer];
212export type DownloadCallback = (err: RequestError | null, contents: Buffer) => void;
213export interface DownloadOptions extends CreateReadStreamOptions {
214 destination?: string;
215}
216export interface CreateReadStreamOptions {
217 userProject?: string;
218 validation?: 'md5' | 'crc32c' | false | true;
219 start?: number;
220 end?: number;
221 decompress?: boolean;
222 [GCCL_GCS_CMD_KEY]?: string;
223}
224export interface SaveOptions extends CreateWriteStreamOptions {
225 onUploadProgress?: (progressEvent: any) => void;
226}
227export interface SaveCallback {
228 (err?: Error | null): void;
229}
230export interface SetFileMetadataOptions {
231 userProject?: string;
232}
233export interface SetFileMetadataCallback {
234 (err?: Error | null, apiResponse?: unknown): void;
235}
236export type SetFileMetadataResponse = [unknown];
237export type SetStorageClassResponse = [unknown];
238export interface SetStorageClassOptions {
239 userProject?: string;
240 preconditionOpts?: PreconditionOptions;
241}
242export interface SetStorageClassCallback {
243 (err?: Error | null, apiResponse?: unknown): void;
244}
245export interface RestoreOptions extends PreconditionOptions {
246 generation: number;
247 projection?: 'full' | 'noAcl';
248}
249export interface FileMetadata extends BaseMetadata {
250 acl?: AclMetadata[] | null;
251 bucket?: string;
252 cacheControl?: string;
253 componentCount?: number;
254 contentDisposition?: string;
255 contentEncoding?: string;
256 contentLanguage?: string;
257 contentType?: string;
258 crc32c?: string;
259 customerEncryption?: {
260 encryptionAlgorithm?: string;
261 keySha256?: string;
262 };
263 customTime?: string;
264 eventBasedHold?: boolean | null;
265 readonly eventBasedHoldReleaseTime?: string;
266 generation?: string | number;
267 hardDeleteTime?: string;
268 kmsKeyName?: string;
269 md5Hash?: string;
270 mediaLink?: string;
271 metadata?: {
272 [key: string]: string | boolean | number | null;
273 };
274 metageneration?: string | number;
275 name?: string;
276 owner?: {
277 entity?: string;
278 entityId?: string;
279 };
280 retention?: {
281 retainUntilTime?: string;
282 mode?: string;
283 } | null;
284 retentionExpirationTime?: string;
285 size?: string | number;
286 softDeleteTime?: string;
287 storageClass?: string;
288 temporaryHold?: boolean | null;
289 timeCreated?: string;
290 timeDeleted?: string;
291 timeStorageClassUpdated?: string;
292 updated?: string;
293}
294export declare class RequestError extends Error {
295 code?: string;
296 errors?: Error[];
297}
298export declare enum FileExceptionMessages {
299 EXPIRATION_TIME_NA = "An expiration time is not available.",
300 DESTINATION_NO_NAME = "Destination file should have a name.",
301 INVALID_VALIDATION_FILE_RANGE = "Cannot use validation with file ranges (start/end).",
302 MD5_NOT_AVAILABLE = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects.",
303 EQUALS_CONDITION_TWO_ELEMENTS = "Equals condition must be an array of 2 elements.",
304 STARTS_WITH_TWO_ELEMENTS = "StartsWith condition must be an array of 2 elements.",
305 CONTENT_LENGTH_RANGE_MIN_MAX = "ContentLengthRange must have numeric min & max fields.",
306 DOWNLOAD_MISMATCH = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again.",
307 UPLOAD_MISMATCH_DELETE_FAIL = "The uploaded data did not match the data from the server.\n As a precaution, we attempted to delete the file, but it was not successful.\n To be sure the content is the same, you should try removing the file manually,\n then uploading the file again.\n \n\nThe delete attempt failed with this message:\n\n ",
308 UPLOAD_MISMATCH = "The uploaded data did not match the data from the server.\n As a precaution, the file has been deleted.\n To be sure the content is the same, you should try uploading the file again.",
309 MD5_RESUMED_UPLOAD = "MD5 cannot be used with a continued resumable upload as MD5 cannot be extended from an existing value",
310 MISSING_RESUME_CRC32C_FINAL_UPLOAD = "The CRC32C is missing for the final portion of a resumed upload, which is required for validation. Please provide `resumeCRC32C` if validation is required, or disable `validation`."
311}
312/**
313 * A File object is created from your {@link Bucket} object using
314 * {@link Bucket#file}.
315 *
316 * @class
317 */
318declare class File extends ServiceObject<File, FileMetadata> {
319 #private;
320 acl: Acl;
321 crc32cGenerator: CRC32CValidatorGenerator;
322 bucket: Bucket;
323 storage: Storage;
324 kmsKeyName?: string;
325 userProject?: string;
326 signer?: URLSigner;
327 name: string;
328 generation?: number;
329 parent: Bucket;
330 private encryptionKey?;
331 private encryptionKeyBase64?;
332 private encryptionKeyHash?;
333 private encryptionKeyInterceptor?;
334 private instanceRetryValue?;
335 instancePreconditionOpts?: PreconditionOptions;
336 /**
337 * Cloud Storage uses access control lists (ACLs) to manage object and
338 * bucket access. ACLs are the mechanism you use to share objects with other
339 * users and allow other users to access your buckets and objects.
340 *
341 * An ACL consists of one or more entries, where each entry grants permissions
342 * to an entity. Permissions define the actions that can be performed against
343 * an object or bucket (for example, `READ` or `WRITE`); the entity defines
344 * who the permission applies to (for example, a specific user or group of
345 * users).
346 *
347 * The `acl` object on a File instance provides methods to get you a list of
348 * the ACLs defined on your bucket, as well as set, update, and delete them.
349 *
350 * See {@link http://goo.gl/6qBBPO| About Access Control lists}
351 *
352 * @name File#acl
353 * @mixes Acl
354 *
355 * @example
356 * ```
357 * const {Storage} = require('@google-cloud/storage');
358 * const storage = new Storage();
359 * const myBucket = storage.bucket('my-bucket');
360 *
361 * const file = myBucket.file('my-file');
362 * //-
363 * // Make a file publicly readable.
364 * //-
365 * const options = {
366 * entity: 'allUsers',
367 * role: storage.acl.READER_ROLE
368 * };
369 *
370 * file.acl.add(options, function(err, aclObject) {});
371 *
372 * //-
373 * // If the callback is omitted, we'll return a Promise.
374 * //-
375 * file.acl.add(options).then(function(data) {
376 * const aclObject = data[0];
377 * const apiResponse = data[1];
378 * });
379 * ```
380 */
381 /**
382 * The API-formatted resource description of the file.
383 *
384 * Note: This is not guaranteed to be up-to-date when accessed. To get the
385 * latest record, call the `getMetadata()` method.
386 *
387 * @name File#metadata
388 * @type {object}
389 */
390 /**
391 * The file's name.
392 * @name File#name
393 * @type {string}
394 */
395 /**
396 * @callback Crc32cGeneratorToStringCallback
397 * A method returning the CRC32C as a base64-encoded string.
398 *
399 * @returns {string}
400 *
401 * @example
402 * Hashing the string 'data' should return 'rth90Q=='
403 *
404 * ```js
405 * const buffer = Buffer.from('data');
406 * crc32c.update(buffer);
407 * crc32c.toString(); // 'rth90Q=='
408 * ```
409 **/
410 /**
411 * @callback Crc32cGeneratorValidateCallback
412 * A method validating a base64-encoded CRC32C string.
413 *
414 * @param {string} [value] base64-encoded CRC32C string to validate
415 * @returns {boolean}
416 *
417 * @example
418 * Should return `true` if the value matches, `false` otherwise
419 *
420 * ```js
421 * const buffer = Buffer.from('data');
422 * crc32c.update(buffer);
423 * crc32c.validate('DkjKuA=='); // false
424 * crc32c.validate('rth90Q=='); // true
425 * ```
426 **/
427 /**
428 * @callback Crc32cGeneratorUpdateCallback
429 * A method for passing `Buffer`s for CRC32C generation.
430 *
431 * @param {Buffer} [data] data to update CRC32C value with
432 * @returns {undefined}
433 *
434 * @example
435 * Hashing buffers from 'some ' and 'text\n'
436 *
437 * ```js
438 * const buffer1 = Buffer.from('some ');
439 * crc32c.update(buffer1);
440 *
441 * const buffer2 = Buffer.from('text\n');
442 * crc32c.update(buffer2);
443 *
444 * crc32c.toString(); // 'DkjKuA=='
445 * ```
446 **/
447 /**
448 * @typedef {object} CRC32CValidator
449 * @property {Crc32cGeneratorToStringCallback}
450 * @property {Crc32cGeneratorValidateCallback}
451 * @property {Crc32cGeneratorUpdateCallback}
452 */
453 /**
454 * @callback Crc32cGeneratorCallback
455 * @returns {CRC32CValidator}
456 */
457 /**
458 * @typedef {object} FileOptions Options passed to the File constructor.
459 * @property {string} [encryptionKey] A custom encryption key.
460 * @property {number} [generation] Generation to scope the file to.
461 * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this
462 * object, if the object is encrypted by such a key. Limited availability;
463 * usable only by enabled projects.
464 * @property {string} [userProject] The ID of the project which will be
465 * billed for all requests made from File object.
466 * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C}
467 */
468 /**
469 * Constructs a file object.
470 *
471 * @param {Bucket} bucket The Bucket instance this file is
472 * attached to.
473 * @param {string} name The name of the remote file.
474 * @param {FileOptions} [options] Configuration options.
475 * @example
476 * ```
477 * const {Storage} = require('@google-cloud/storage');
478 * const storage = new Storage();
479 * const myBucket = storage.bucket('my-bucket');
480 *
481 * const file = myBucket.file('my-file');
482 * ```
483 */
484 constructor(bucket: Bucket, name: string, options?: FileOptions);
485 /**
486 * The object's Cloud Storage URI (`gs://`)
487 *
488 * @example
489 * ```ts
490 * const {Storage} = require('@google-cloud/storage');
491 * const storage = new Storage();
492 * const bucket = storage.bucket('my-bucket');
493 * const file = bucket.file('image.png');
494 *
495 * // `gs://my-bucket/image.png`
496 * const href = file.cloudStorageURI.href;
497 * ```
498 */
499 get cloudStorageURI(): URL;
500 /**
501 * A helper method for determining if a request should be retried based on preconditions.
502 * This should only be used for methods where the idempotency is determined by
503 * `ifGenerationMatch`
504 * @private
505 *
506 * A request should not be retried under the following conditions:
507 * - if precondition option `ifGenerationMatch` is not set OR
508 * - if `idempotencyStrategy` is set to `RetryNever`
509 */
510 private shouldRetryBasedOnPreconditionAndIdempotencyStrat;
511 copy(destination: string | Bucket | File, options?: CopyOptions): Promise<CopyResponse>;
512 copy(destination: string | Bucket | File, callback: CopyCallback): void;
513 copy(destination: string | Bucket | File, options: CopyOptions, callback: CopyCallback): void;
514 /**
515 * @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream.
516 * @property {string} [userProject] The ID of the project which will be
517 * billed for the request.
518 * @property {string|boolean} [validation] Possible values: `"md5"`,
519 * `"crc32c"`, or `false`. By default, data integrity is validated with a
520 * CRC32c checksum. You may use MD5 if preferred, but that hash is not
521 * supported for composite objects. An error will be raised if MD5 is
522 * specified but is not available. You may also choose to skip validation
523 * completely, however this is **not recommended**.
524 * @property {number} [start] A byte offset to begin the file's download
525 * from. Default is 0. NOTE: Byte ranges are inclusive; that is,
526 * `options.start = 0` and `options.end = 999` represent the first 1000
527 * bytes in a file or object. NOTE: when specifying a byte range, data
528 * integrity is not available.
529 * @property {number} [end] A byte offset to stop reading the file at.
530 * NOTE: Byte ranges are inclusive; that is, `options.start = 0` and
531 * `options.end = 999` represent the first 1000 bytes in a file or object.
532 * NOTE: when specifying a byte range, data integrity is not available.
533 * @property {boolean} [decompress=true] Disable auto decompression of the
534 * received data. By default this option is set to `true`.
535 * Applicable in cases where the data was uploaded with
536 * `gzip: true` option. See {@link File#createWriteStream}.
537 */
538 /**
539 * Create a readable stream to read the contents of the remote file. It can be
540 * piped to a writable stream or listened to for 'data' events to read a
541 * file's contents.
542 *
543 * In the unlikely event there is a mismatch between what you downloaded and
544 * the version in your Bucket, your error handler will receive an error with
545 * code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best
546 * recourse is to try downloading the file again.
547 *
548 * NOTE: Readable streams will emit the `end` event when the file is fully
549 * downloaded.
550 *
551 * @param {CreateReadStreamOptions} [options] Configuration options.
552 * @returns {ReadableStream}
553 *
554 * @example
555 * ```
556 * //-
557 * // <h4>Downloading a File</h4>
558 * //
559 * // The example below demonstrates how we can reference a remote file, then
560 * // pipe its contents to a local file. This is effectively creating a local
561 * // backup of your remote data.
562 * //-
563 * const {Storage} = require('@google-cloud/storage');
564 * const storage = new Storage();
565 * const bucket = storage.bucket('my-bucket');
566 *
567 * const fs = require('fs');
568 * const remoteFile = bucket.file('image.png');
569 * const localFilename = '/Users/stephen/Photos/image.png';
570 *
571 * remoteFile.createReadStream()
572 * .on('error', function(err) {})
573 * .on('response', function(response) {
574 * // Server connected and responded with the specified status and headers.
575 * })
576 * .on('end', function() {
577 * // The file is fully downloaded.
578 * })
579 * .pipe(fs.createWriteStream(localFilename));
580 *
581 * //-
582 * // To limit the downloaded data to only a byte range, pass an options
583 * // object.
584 * //-
585 * const logFile = myBucket.file('access_log');
586 * logFile.createReadStream({
587 * start: 10000,
588 * end: 20000
589 * })
590 * .on('error', function(err) {})
591 * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));
592 *
593 * //-
594 * // To read a tail byte range, specify only `options.end` as a negative
595 * // number.
596 * //-
597 * const logFile = myBucket.file('access_log');
598 * logFile.createReadStream({
599 * end: -100
600 * })
601 * .on('error', function(err) {})
602 * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));
603 * ```
604 */
605 createReadStream(options?: CreateReadStreamOptions): Readable;
606 createResumableUpload(options?: CreateResumableUploadOptions): Promise<CreateResumableUploadResponse>;
607 createResumableUpload(options: CreateResumableUploadOptions, callback: CreateResumableUploadCallback): void;
608 createResumableUpload(callback: CreateResumableUploadCallback): void;
609 /**
610 * @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream().
611 * @property {string} [contentType] Alias for
612 * `options.metadata.contentType`. If set to `auto`, the file name is used
613 * to determine the contentType.
614 * @property {string|boolean} [gzip] If true, automatically gzip the file.
615 * If set to `auto`, the contentType is used to determine if the file
616 * should be gzipped. This will set `options.metadata.contentEncoding` to
617 * `gzip` if necessary.
618 * @property {object} [metadata] See the examples below or
619 * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}
620 * for more details.
621 * @property {number} [offset] The starting byte of the upload stream, for
622 * resuming an interrupted upload. Defaults to 0.
623 * @property {string} [predefinedAcl] Apply a predefined set of access
624 * controls to this object.
625 *
626 * Acceptable values are:
627 * - **`authenticatedRead`** - Object owner gets `OWNER` access, and
628 * `allAuthenticatedUsers` get `READER` access.
629 *
630 * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
631 * project team owners get `OWNER` access.
632 *
633 * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
634 * team owners get `READER` access.
635 *
636 * - **`private`** - Object owner gets `OWNER` access.
637 *
638 * - **`projectPrivate`** - Object owner gets `OWNER` access, and project
639 * team members get access according to their roles.
640 *
641 * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
642 * get `READER` access.
643 * @property {boolean} [private] Make the uploaded file private. (Alias for
644 * `options.predefinedAcl = 'private'`)
645 * @property {boolean} [public] Make the uploaded file public. (Alias for
646 * `options.predefinedAcl = 'publicRead'`)
647 * @property {boolean} [resumable] Force a resumable upload. NOTE: When
648 * working with streams, the file format and size is unknown until it's
649 * completely consumed. Because of this, it's best for you to be explicit
650 * for what makes sense given your input.
651 * @property {number} [timeout=60000] Set the HTTP request timeout in
652 * milliseconds. This option is not available for resumable uploads.
653 * Default: `60000`
654 * @property {string} [uri] The URI for an already-created resumable
655 * upload. See {@link File#createResumableUpload}.
656 * @property {string} [userProject] The ID of the project which will be
657 * billed for the request.
658 * @property {string|boolean} [validation] Possible values: `"md5"`,
659 * `"crc32c"`, or `false`. By default, data integrity is validated with a
660 * CRC32c checksum. You may use MD5 if preferred, but that hash is not
661 * supported for composite objects. An error will be raised if MD5 is
662 * specified but is not available. You may also choose to skip validation
663 * completely, however this is **not recommended**. In addition to specifying
664 * validation type, providing `metadata.crc32c` or `metadata.md5Hash` will
665 * cause the server to perform validation in addition to client validation.
666 * NOTE: Validation is automatically skipped for objects that were
667 * uploaded using the `gzip` option and have already compressed content.
668 */
669 /**
670 * Create a writable stream to overwrite the contents of the file in your
671 * bucket.
672 *
673 * A File object can also be used to create files for the first time.
674 *
675 * Resumable uploads are automatically enabled and must be shut off explicitly
676 * by setting `options.resumable` to `false`.
677 *
678 *
679 * <p class="notice">
680 * There is some overhead when using a resumable upload that can cause
681 * noticeable performance degradation while uploading a series of small
682 * files. When uploading files less than 10MB, it is recommended that the
683 * resumable feature is disabled.
684 * </p>
685 *
686 * NOTE: Writable streams will emit the `finish` event when the file is fully
687 * uploaded.
688 *
689 * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload Upload Options (Simple or Resumable)}
690 * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects: insert API Documentation}
691 *
692 * @param {CreateWriteStreamOptions} [options] Configuration options.
693 * @returns {WritableStream}
694 *
695 * @example
696 * ```
697 * const fs = require('fs');
698 * const {Storage} = require('@google-cloud/storage');
699 * const storage = new Storage();
700 * const myBucket = storage.bucket('my-bucket');
701 *
702 * const file = myBucket.file('my-file');
703 *
704 * //-
705 * // <h4>Uploading a File</h4>
706 * //
707 * // Now, consider a case where we want to upload a file to your bucket. You
708 * // have the option of using {@link Bucket#upload}, but that is just
709 * // a convenience method which will do the following.
710 * //-
711 * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
712 * .pipe(file.createWriteStream())
713 * .on('error', function(err) {})
714 * .on('finish', function() {
715 * // The file upload is complete.
716 * });
717 *
718 * //-
719 * // <h4>Uploading a File with gzip compression</h4>
720 * //-
721 * fs.createReadStream('/Users/stephen/site/index.html')
722 * .pipe(file.createWriteStream({ gzip: true }))
723 * .on('error', function(err) {})
724 * .on('finish', function() {
725 * // The file upload is complete.
726 * });
727 *
728 * //-
729 * // Downloading the file with `createReadStream` will automatically decode
730 * // the file.
731 * //-
732 *
733 * //-
734 * // <h4>Uploading a File with Metadata</h4>
735 * //
736 * // One last case you may run into is when you want to upload a file to your
737 * // bucket and set its metadata at the same time. Like above, you can use
738 * // {@link Bucket#upload} to do this, which is just a wrapper around
739 * // the following.
740 * //-
741 * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
742 * .pipe(file.createWriteStream({
743 * metadata: {
744 * contentType: 'image/jpeg',
745 * metadata: {
746 * custom: 'metadata'
747 * }
748 * }
749 * }))
750 * .on('error', function(err) {})
751 * .on('finish', function() {
752 * // The file upload is complete.
753 * });
754 * ```
755 *
756 * //-
757 * // <h4>Continuing a Resumable Upload</h4>
758 * //
759 * // One can capture a `uri` from a resumable upload to reuse later.
760 * // Additionally, for validation, one can also capture and pass `crc32c`.
761 * //-
762 * let uri: string | undefined = undefined;
763 * let resumeCRC32C: string | undefined = undefined;
764 *
765 * fs.createWriteStream()
766 * .on('uri', link => {uri = link})
767 * .on('crc32', crc32c => {resumeCRC32C = crc32c});
768 *
769 * // later...
770 * fs.createWriteStream({uri, resumeCRC32C});
771 */
772 createWriteStream(options?: CreateWriteStreamOptions): Writable;
773 /**
774 * Delete the object.
775 *
776 * @param {function=} callback - The callback function.
777 * @param {?error} callback.err - An error returned while making this request.
778 * @param {object} callback.apiResponse - The full API response.
779 */
780 delete(options?: DeleteOptions): Promise<[r.Response]>;
781 delete(options: DeleteOptions, callback: DeleteCallback): void;
782 delete(callback: DeleteCallback): void;
783 download(options?: DownloadOptions): Promise<DownloadResponse>;
784 download(options: DownloadOptions, callback: DownloadCallback): void;
785 download(callback: DownloadCallback): void;
786 /**
787 * The Storage API allows you to use a custom key for server-side encryption.
788 *
789 * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}
790 *
791 * @param {string|buffer} encryptionKey An AES-256 encryption key.
792 * @returns {File}
793 *
794 * @example
795 * ```
796 * const crypto = require('crypto');
797 * const {Storage} = require('@google-cloud/storage');
798 * const storage = new Storage();
799 * const myBucket = storage.bucket('my-bucket');
800 *
801 * const encryptionKey = crypto.randomBytes(32);
802 *
803 * const fileWithCustomEncryption = myBucket.file('my-file');
804 * fileWithCustomEncryption.setEncryptionKey(encryptionKey);
805 *
806 * const fileWithoutCustomEncryption = myBucket.file('my-file');
807 *
808 * fileWithCustomEncryption.save('data', function(err) {
809 * // Try to download with the File object that hasn't had
810 * // `setEncryptionKey()` called:
811 * fileWithoutCustomEncryption.download(function(err) {
812 * // We will receive an error:
813 * // err.message === 'Bad Request'
814 *
815 * // Try again with the File object we called `setEncryptionKey()` on:
816 * fileWithCustomEncryption.download(function(err, contents) {
817 * // contents.toString() === 'data'
818 * });
819 * });
820 * });
821 *
822 * ```
823 * @example <caption>include:samples/encryption.js</caption>
824 * region_tag:storage_upload_encrypted_file
825 * Example of uploading an encrypted file:
826 *
827 * @example <caption>include:samples/encryption.js</caption>
828 * region_tag:storage_download_encrypted_file
829 * Example of downloading an encrypted file:
830 */
831 setEncryptionKey(encryptionKey: string | Buffer): this;
832 /**
833 * Gets a reference to a Cloud Storage {@link File} file from the provided URL in string format.
834 * @param {string} publicUrlOrGsUrl the URL as a string. Must be of the format gs://bucket/file
835 * or https://storage.googleapis.com/bucket/file.
836 * @param {Storage} storageInstance an instance of a Storage object.
837 * @param {FileOptions} [options] Configuration options
838 * @returns {File}
839 */
840 static from(publicUrlOrGsUrl: string, storageInstance: Storage, options?: FileOptions): File;
841 get(options?: GetFileOptions): Promise<GetResponse<File>>;
842 get(callback: InstanceResponseCallback<File>): void;
843 get(options: GetFileOptions, callback: InstanceResponseCallback<File>): void;
844 getExpirationDate(): Promise<GetExpirationDateResponse>;
845 getExpirationDate(callback: GetExpirationDateCallback): void;
846 generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options): Promise<GenerateSignedPostPolicyV2Response>;
847 generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options, callback: GenerateSignedPostPolicyV2Callback): void;
848 generateSignedPostPolicyV2(callback: GenerateSignedPostPolicyV2Callback): void;
849 generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options): Promise<GenerateSignedPostPolicyV4Response>;
850 generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options, callback: GenerateSignedPostPolicyV4Callback): void;
851 generateSignedPostPolicyV4(callback: GenerateSignedPostPolicyV4Callback): void;
852 getSignedUrl(cfg: GetSignedUrlConfig): Promise<GetSignedUrlResponse>;
853 getSignedUrl(cfg: GetSignedUrlConfig, callback: GetSignedUrlCallback): void;
854 isPublic(): Promise<IsPublicResponse>;
855 isPublic(callback: IsPublicCallback): void;
856 makePrivate(options?: MakeFilePrivateOptions): Promise<MakeFilePrivateResponse>;
857 makePrivate(callback: MakeFilePrivateCallback): void;
858 makePrivate(options: MakeFilePrivateOptions, callback: MakeFilePrivateCallback): void;
859 makePublic(): Promise<MakeFilePublicResponse>;
860 makePublic(callback: MakeFilePublicCallback): void;
861 /**
862 * The public URL of this File
863 * Use {@link File#makePublic} to enable anonymous access via the returned URL.
864 *
865 * @returns {string}
866 *
867 * @example
868 * ```
869 * const {Storage} = require('@google-cloud/storage');
870 * const storage = new Storage();
871 * const bucket = storage.bucket('albums');
872 * const file = bucket.file('my-file');
873 *
874 * // publicUrl will be "https://storage.googleapis.com/albums/my-file"
875 * const publicUrl = file.publicUrl();
876 * ```
877 */
878 publicUrl(): string;
879 move(destination: string | Bucket | File, options?: MoveOptions): Promise<MoveResponse>;
880 move(destination: string | Bucket | File, callback: MoveCallback): void;
881 move(destination: string | Bucket | File, options: MoveOptions, callback: MoveCallback): void;
882 rename(destinationFile: string | File, options?: RenameOptions): Promise<RenameResponse>;
883 rename(destinationFile: string | File, callback: RenameCallback): void;
884 rename(destinationFile: string | File, options: RenameOptions, callback: RenameCallback): void;
885 /**
886 * @typedef {object} RestoreOptions Options for File#restore(). See an
887 * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}.
888 * @param {string} [userProject] The ID of the project which will be
889 * billed for the request.
890 * @param {number} [generation] If present, selects a specific revision of this object.
891 * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'.
892 * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource
893 * matches the value used in the precondition.
894 * If the values don't match, the request fails with a 412 Precondition Failed response.
895 * @param {string | number} [ifGenerationNotMatch] Request proceeds if the generation of the target resource does
896 * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response.
897 * @param {string | number} [ifMetagenerationMatch] Request proceeds if the meta-generation of the target resource
898 * matches the value used in the precondition.
899 * If the values don't match, the request fails with a 412 Precondition Failed response.
900 * @param {string | number} [ifMetagenerationNotMatch] Request proceeds if the meta-generation of the target resource does
901 * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response.
902 */
903 /**
904 * Restores a soft-deleted file
905 * @param {RestoreOptions} options Restore options.
906 * @returns {Promise<File>}
907 */
908 restore(options: RestoreOptions): Promise<File>;
909 request(reqOpts: DecorateRequestOptions): Promise<RequestResponse>;
910 request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
911 rotateEncryptionKey(options?: RotateEncryptionKeyOptions): Promise<RotateEncryptionKeyResponse>;
912 rotateEncryptionKey(callback: RotateEncryptionKeyCallback): void;
913 rotateEncryptionKey(options: RotateEncryptionKeyOptions, callback: RotateEncryptionKeyCallback): void;
914 save(data: SaveData, options?: SaveOptions): Promise<void>;
915 save(data: SaveData, callback: SaveCallback): void;
916 save(data: SaveData, options: SaveOptions, callback: SaveCallback): void;
917 setMetadata(metadata: FileMetadata, options?: SetMetadataOptions): Promise<SetMetadataResponse<FileMetadata>>;
918 setMetadata(metadata: FileMetadata, callback: MetadataCallback<FileMetadata>): void;
919 setMetadata(metadata: FileMetadata, options: SetMetadataOptions, callback: MetadataCallback<FileMetadata>): void;
920 setStorageClass(storageClass: string, options?: SetStorageClassOptions): Promise<SetStorageClassResponse>;
921 setStorageClass(storageClass: string, options: SetStorageClassOptions, callback: SetStorageClassCallback): void;
922 setStorageClass(storageClass: string, callback?: SetStorageClassCallback): void;
923 /**
924 * Set a user project to be billed for all requests made from this File
925 * object.
926 *
927 * @param {string} userProject The user project.
928 *
929 * @example
930 * ```
931 * const {Storage} = require('@google-cloud/storage');
932 * const storage = new Storage();
933 * const bucket = storage.bucket('albums');
934 * const file = bucket.file('my-file');
935 *
936 * file.setUserProject('grape-spaceship-123');
937 * ```
938 */
939 setUserProject(userProject: string): void;
940 /**
941 * This creates a resumable-upload upload stream.
942 *
943 * @param {Duplexify} stream - Duplexify stream of data to pipe to the file.
944 * @param {object=} options - Configuration object.
945 *
946 * @private
947 */
948 startResumableUpload_(dup: Duplexify, options?: CreateResumableUploadOptions): void;
949 /**
950 * Takes a readable stream and pipes it to a remote file. Unlike
951 * `startResumableUpload_`, which uses the resumable upload technique, this
952 * method uses a simple upload (all or nothing).
953 *
954 * @param {Duplexify} dup - Duplexify stream of data to pipe to the file.
955 * @param {object=} options - Configuration object.
956 *
957 * @private
958 */
959 startSimpleUpload_(dup: Duplexify, options?: CreateWriteStreamOptions): void;
960 disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions): void;
961 private getBufferFromReadable;
962}
963/**
964 * Reference to the {@link File} class.
965 * @name module:@google-cloud/storage.File
966 * @see File
967 */
968export { File };
969
\No newline at end of file