UNPKG

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