Socket
Socket
Sign inDemoInstall

@google-cloud/storage

Package Overview
Dependencies
Maintainers
4
Versions
183
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@google-cloud/storage - npm Package Compare versions

Comparing version 2.1.0 to 2.2.0

build/src/storage.d.ts

64

build/src/acl.d.ts

@@ -17,5 +17,48 @@ /*!

import { DecorateRequestOptions, BodyResponseCallback } from '@google-cloud/common';
interface AccessControlObject {
import * as r from 'request';
export interface AclOptions {
pathPrefix: string;
request: typeof r;
}
export declare type GetAclResponse = [AccessControlObject | AccessControlObject[], r.Response];
export interface GetAclCallback {
(err: Error | null, acl?: AccessControlObject | AccessControlObject[] | null, apiResponse?: r.Response): void;
}
export interface GetAclOptions {
entity: string;
generation?: number;
userProject?: string;
}
export interface UpdateAclOptions {
entity: string;
role: string;
generation?: number;
userProject?: string;
}
export declare type UpdateAclResponse = [AccessControlObject, r.Response];
export interface UpdateAclCallback {
(err: Error | null, acl?: AccessControlObject | null, apiResponse?: r.Response): void;
}
export interface AddAclOptions {
entity: string;
role: string;
generation?: number;
userProject?: string;
}
export declare type AddAclResponse = [AccessControlObject, r.Response];
export interface AddAclCallback {
(err: Error | null, acl?: AccessControlObject | null, apiResponse?: r.Response): void;
}
export declare type RemoveAclResponse = [r.Response];
export interface RemoveAclCallback {
(err: Error | null, apiResponse?: r.Response): void;
}
export interface RemoveAclOptions {
entity: string;
generation?: number;
userProject?: string;
}
export interface AccessControlObject {
entity: string;
role: string;
projectTeam: string;

@@ -238,4 +281,4 @@ }

pathPrefix: string;
request_: any;
constructor(options: any);
request_: typeof r;
constructor(options: AclOptions);
/**

@@ -314,3 +357,4 @@ * @typedef {array} AddAclResponse

*/
add(options: any, callback?: any): void;
add(options: AddAclOptions): Promise<AddAclResponse>;
add(options: AddAclOptions, callback: AddAclCallback): void;
/**

@@ -376,3 +420,4 @@ * @typedef {array} RemoveAclResponse

*/
delete(options: any, callback?: any): void;
delete(options: RemoveAclOptions): Promise<RemoveAclResponse>;
delete(options: RemoveAclOptions, callback: RemoveAclCallback): void;
/**

@@ -461,3 +506,5 @@ * @typedef {array} GetAclResponse

*/
get(options: any, callback?: any): void;
get(options?: GetAclOptions): Promise<GetAclResponse>;
get(options: GetAclOptions, callback: GetAclCallback): void;
get(callback: GetAclCallback): void;
/**

@@ -520,3 +567,4 @@ * @typedef {array} UpdateAclResponse

*/
update(options: any, callback?: any): void;
update(options: UpdateAclOptions): Promise<UpdateAclResponse>;
update(options: UpdateAclOptions, callback: UpdateAclCallback): void;
/**

@@ -527,3 +575,3 @@ * Transform API responses to a consistent object format.

*/
makeAclObject_(accessControlObject: any): AccessControlObject;
makeAclObject_(accessControlObject: AccessControlObject): AccessControlObject;
/**

@@ -530,0 +578,0 @@ * Patch requests up to the bucket's request object.

340

build/src/acl.js

@@ -21,3 +21,2 @@ /*!

const extend = require("extend");
const is = require("is");
/**

@@ -195,2 +194,3 @@ * Attach functionality to a {@link Storage.acl} instance. This will add an

const roleGroup = role.toLowerCase() + 's';
// tslint:disable-next-line:no-any
this[roleGroup] = entities.reduce((acc, entity) => {

@@ -205,28 +205,31 @@ const isPrefix = entity.charAt(entity.length - 1) === '-';

// more complex API of specifying an `entity` and `role`.
acc[method] = (entityId, options, callback) => {
let apiEntity;
if (is.fn(options)) {
callback = options;
options = {};
}
if (isPrefix) {
apiEntity = entity + entityId;
}
else {
// If the entity is not a prefix, it is a special entity group that
// does not require further details. The accessor methods only
// accept a callback.
apiEntity = entity;
callback = entityId;
}
options = extend({
entity: apiEntity,
role,
}, options);
const args = [options];
if (is.fn(callback)) {
args.push(callback);
}
return this[accessMethod].apply(this, args);
};
// tslint:disable-next-line:no-any
acc[method] =
(entityId, options, callback) => {
let apiEntity;
if (typeof options === 'function') {
callback = options;
options = {};
}
if (isPrefix) {
apiEntity = entity + entityId;
}
else {
// If the entity is not a prefix, it is a special entity group
// that does not require further details. The accessor methods
// only accept a callback.
apiEntity = entity;
callback = entityId;
}
options = extend({
entity: apiEntity,
role,
}, options);
const args = [options];
if (typeof callback === 'function') {
args.push(callback);
}
// tslint:disable-next-line:no-any
return this[accessMethod].apply(this, args);
};
});

@@ -297,75 +300,2 @@ return acc;

}
/**
* @typedef {array} AddAclResponse
* @property {object} 0 The Acl Objects.
* @property {object} 1 The full API response.
*/
/**
* @callback AddAclCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The Acl Objects.
* @param {object} apiResponse The full API response.
*/
/**
* Add access controls on a {@link Bucket} or {@link File}.
*
* @see [BucketAccessControls: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert}
* @see [ObjectAccessControls: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert}
*
* @param {object} options Configuration options.
* @param {string} options.entity Whose permissions will be added.
* @param {string} options.role Permissions allowed for the defined entity.
* See {@link https://cloud.google.com/storage/docs/access-control Access
* Control}.
* @param {number} [options.generation] **File Objects Only** Select a specific
* revision of this file (as opposed to the latest version, the default).
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {AddAclCallback} [callback] Callback function.
* @returns {Promise<AddAclResponse>}
*
* @example
* const storage = require('@google-cloud/storage')();
* const myBucket = storage.bucket('my-bucket');
* const myFile = myBucket.file('my-file');
*
* const options = {
* entity: 'user-useremail@example.com',
* role: gcs.acl.OWNER_ROLE
* };
*
* myBucket.acl.add(options, function(err, aclObject, apiResponse) {});
*
* //-
* // For file ACL operations, you can also specify a `generation` property.
* // Here is how you would grant ownership permissions to a user on a
* specific
* // revision of a file.
* //-
* myFile.acl.add({
* entity: 'user-useremail@example.com',
* role: gcs.acl.OWNER_ROLE,
* generation: 1
* }, function(err, aclObject, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* myBucket.acl.add(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_add_file_owner
* Example of adding an owner to a file:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_add_bucket_owner
* Example of adding an owner to a bucket:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_add_bucket_default_owner
* Example of adding a default owner to a bucket:
*/
add(options, callback) {

@@ -395,62 +325,2 @@ const query = {};

}
/**
* @typedef {array} RemoveAclResponse
* @property {object} 0 The full API response.
*/
/**
* @callback RemoveAclCallback
* @param {?Error} err Request error, if any.
* @param {object} apiResponse The full API response.
*/
/**
* Delete access controls on a {@link Bucket} or {@link File}.
*
* @see [BucketAccessControls: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/delete}
* @see [ObjectAccessControls: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete}
*
* @param {object} options Configuration object.
* @param {string} options.entity Whose permissions will be revoked.
* @param {int} [options.generation] **File Objects Only** Select a specific
* revision of this file (as opposed to the latest version, the default).
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {RemoveAclCallback} callback The callback function.
* @returns {Promise<RemoveAclResponse>}
*
* @example
* const storage = require('@google-cloud/storage')();
* const myBucket = storage.bucket('my-bucket');
* const myFile = myBucket.file('my-file');
*
* myBucket.acl.delete({
* entity: 'user-useremail@example.com'
* }, function(err, apiResponse) {});
*
* //-
* // For file ACL operations, you can also specify a `generation` property.
* //-
* myFile.acl.delete({
* entity: 'user-useremail@example.com',
* generation: 1
* }, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* myFile.acl.delete().then(function(data) {
* const apiResponse = data[0];
* });
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_remove_bucket_owner
* Example of removing an owner from a bucket:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_remove_bucket_default_owner
* Example of removing a default owner from a bucket:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_remove_file_owner
* Example of removing an owner from a bucket:
*/
delete(options, callback) {

@@ -472,93 +342,8 @@ const query = {};

}
/**
* @typedef {array} GetAclResponse
* @property {object|object[]} 0 Single or array of Acl Objects.
* @property {object} 1 The full API response.
*/
/**
* @callback GetAclCallback
* @param {?Error} err Request error, if any.
* @param {object|object[]} acl Single or array of Acl Objects.
* @param {object} apiResponse The full API response.
*/
/**
* Get access controls on a {@link Bucket} or {@link File}. If
* an entity is omitted, you will receive an array of all applicable access
* controls.
*
* @see [BucketAccessControls: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get}
* @see [ObjectAccessControls: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get}
*
* @param {object|function} [options] Configuration options. If you want to
* receive a list of all access controls, pass the callback function as
* the only argument.
* @param {string} [options.entity] Whose permissions will be fetched.
* @param {number} [options.generation] **File Objects Only** Select a specific
* revision of this file (as opposed to the latest version, the default).
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {GetAclCallback} [callback] Callback function.
* @returns {Promise<GetAclResponse>}
*
* @example
* const storage = require('@google-cloud/storage')();
* const myBucket = storage.bucket('my-bucket');
* const myFile = myBucket.file('my-file');
*
* myBucket.acl.get({
* entity: 'user-useremail@example.com'
* }, function(err, aclObject, apiResponse) {});
*
* //-
* // Get all access controls.
* //-
* myBucket.acl.get(function(err, aclObjects, apiResponse) {
* // aclObjects = [
* // {
* // entity: 'user-useremail@example.com',
* // role: 'owner'
* // }
* // ]
* });
*
* //-
* // For file ACL operations, you can also specify a `generation` property.
* //-
* myFile.acl.get({
* entity: 'user-useremail@example.com',
* generation: 1
* }, function(err, aclObject, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* myBucket.acl.get().then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_print_file_acl
* Example of printing a file's ACL:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_print_file_acl_for_user
* Example of printing a file's ACL for a specific user:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_print_bucket_acl
* Example of printing a bucket's ACL:
*
* @example <caption>include:samples/acl.js</caption>
* region_tag:storage_print_bucket_acl_for_user
* Example of printing a bucket's ACL for a specific user:
*/
get(options, callback) {
get(optionsOrCallback, cb) {
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : null;
const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
let path = '';
const query = {};
if (is.fn(options)) {
callback = options;
options = null;
}
else {
if (options) {
path = '/' + encodeURIComponent(options.entity);

@@ -590,59 +375,2 @@ if (options.generation) {

}
/**
* @typedef {array} UpdateAclResponse
* @property {object} 0 The updated Acl Objects.
* @property {object} 1 The full API response.
*/
/**
* @callback UpdateAclCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The updated Acl Objects.
* @param {object} apiResponse The full API response.
*/
/**
* Update access controls on a {@link Bucket} or {@link File}.
*
* @see [BucketAccessControls: update API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/update}
* @see [ObjectAccessControls: update API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/update}
*
* @param {object} options Configuration options.
* @param {string} options.entity Whose permissions will be updated.
* @param {string} options.role Permissions allowed for the defined entity.
* See {@link Storage.acl}.
* @param {number} [options.generation] **File Objects Only** Select a specific
* revision of this file (as opposed to the latest version, the default).
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {UpdateAclCallback} [callback] Callback function.
* @returns {Promise<UpdateAclResponse>}
*
* @example
* const storage = require('@google-cloud/storage')();
* const myBucket = storage.bucket('my-bucket');
* const myFile = myBucket.file('my-file');
*
* const options = {
* entity: 'user-useremail@example.com',
* role: gcs.acl.WRITER_ROLE
* };
*
* myBucket.acl.update(options, function(err, aclObject, apiResponse) {});
*
* //-
* // For file ACL operations, you can also specify a `generation` property.
* //-
* myFile.acl.update({
* entity: 'user-useremail@example.com',
* role: gcs.acl.WRITER_ROLE,
* generation: 1
* }, function(err, aclObject, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* myFile.acl.update(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
*/
update(options, callback) {

@@ -649,0 +377,0 @@ const query = {};

@@ -25,7 +25,6 @@ /**

const fs = require("fs");
const is = require("is");
const mime = require("mime-types");
const path = require("path");
const snakeize = require('snakeize');
const request = require("request");
const teeny_request_1 = require("teeny-request");
const acl_1 = require("./acl");

@@ -69,3 +68,3 @@ const file_1 = require("./file");

* @method Bucket#create
* @param {CreateBucketOptions} [metadata] Metadata to set for the bucket.
* @param {CreateBucketRequest} [metadata] Metadata to set for the bucket.
* @param {CreateBucketCallback} [callback] Callback function.

@@ -100,3 +99,3 @@ * @returns {Promise<CreateBucketResponse>}

methods,
requestModule: request,
requestModule: teeny_request_1.teenyRequest,
});

@@ -118,3 +117,3 @@ this.name = name;

combine(sources, destination, optionsOrCallback, callback) {
if (!is.array(sources) || sources.length < 2) {
if (!Array.isArray(sources) || sources.length < 2) {
throw new Error('You must provide at least two source files.');

@@ -156,3 +155,2 @@ }

},
// tslint:disable-next-line:no-any
sourceObjects: sources.map(source => {

@@ -178,6 +176,6 @@ const sourceObject = {

createChannel(id, config, optionsOrCallback, callback) {
if (!is.string(id)) {
if (typeof id !== 'string') {
throw new Error('An ID is required to create a channel.');
}
if (!is.string(config.address)) {
if (typeof config.address !== 'string') {
throw new Error('An address is required to create a channel.');

@@ -219,7 +217,8 @@ }

}
if (is.object(topic) && common_1.util.isCustomType(topic, 'pubsub/topic')) {
const topicIsObject = topic !== null && typeof topic === 'object';
if (topicIsObject && common_1.util.isCustomType(topic, 'pubsub/topic')) {
// tslint:disable-next-line:no-any
topic = topic.name;
}
if (!is.string(topic)) {
if (typeof topic !== 'string') {
throw new Error('A valid topic name is required.');

@@ -285,3 +284,3 @@ }

const deleteFile = (file, callback) => {
file.delete(query, (err) => {
file.delete(query, err => {
if (err) {

@@ -317,3 +316,3 @@ if (query.force) {

}
const deleteLabels = labels => {
const deleteLabels = (labels) => {
const nullLabelMap = labels.reduce((nullLabelMap, labelKey) => {

@@ -361,3 +360,3 @@ nullLabelMap[labelKey] = null;

options = options || {};
this.get(options, err => {
this.get(options, (err) => {
if (err) {

@@ -429,3 +428,3 @@ if (err.code === 404) {

const args = [];
if (!is.empty(options)) {
if (Object.keys(options).length > 0) {
args.push(options);

@@ -544,30 +543,5 @@ }

}
/**
* Lock a previously-defined retention policy. This will prevent changes to
* the policy.
*
* @throws {Error} if a metageneration is not provided.
*
* @param {Number|String} metageneration The bucket's metageneration. This is
* accesssible from calling {@link File#getMetadata}.
* @param {SetBucketMetadataCallback} [callback] Callback function.
* @returns {Promise<SetBucketMetadataResponse>}
*
* @example
* const storage = require('@google-cloud/storage')();
* const bucket = storage.bucket('albums');
*
* const metageneration = 2;
*
* bucket.lock(metageneration, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.lock(metageneration).then(function(data) {
* const apiResponse = data[0];
* });
*/
lock(metageneration, callback) {
if (!is.number(metageneration) && !is.string(metageneration)) {
const metatype = typeof metageneration;
if (metatype !== 'number' && metatype !== 'string') {
throw new Error('A metageneration must be provided.');

@@ -583,96 +557,8 @@ }

}
/**
* @typedef {array} MakeBucketPrivateResponse
* @property {File[]} 0 List of files made private.
*/
/**
* @callback MakeBucketPrivateCallback
* @param {?Error} err Request error, if any.
* @param {File[]} files List of files made private.
*/
/**
* Make the bucket listing private.
*
* You may also choose to make the contents of the bucket private by
* specifying `includeFiles: true`. This will automatically run
* {@link File#makePrivate} for every file in the bucket.
*
* When specifying `includeFiles: true`, use `force: true` to delay execution
* of your callback until all files have been processed. By default, the
* callback is executed after the first error. Use `force` to queue such
* errors until all files have been processed, after which they will be
* returned as an array as the first argument to your callback.
*
* NOTE: This may cause the process to be long-running and use a high number
* of requests. Use with caution.
*
* @see [Buckets: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch}
*
* @param {object} [options] Configuration options.
* @param {boolean} [options.includeFiles=false] Make each file in the bucket
* private.
* @param {boolean} [options.force] Queue errors occurred while making files
* private until all files have been processed.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {MakeBucketPrivateCallback} [callback] Callback function.
* @returns {Promise<MakeBucketPrivateResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* //-
* // Make the bucket private.
* //-
* bucket.makePrivate(function(err) {});
*
* //-
* // Make the bucket and its contents private.
* //-
* const opts = {
* includeFiles: true
* };
*
* bucket.makePrivate(opts, function(err, files) {
* // `err`:
* // The first error to occur, otherwise null.
* //
* // `files`:
* // Array of files successfully made private in the bucket.
* });
*
* //-
* // Make the bucket and its contents private, using force to suppress errors
* // until all files have been processed.
* //-
* const opts = {
* includeFiles: true,
* force: true
* };
*
* bucket.makePrivate(opts, function(errors, files) {
* // `errors`:
* // Array of errors if any occurred, otherwise null.
* //
* // `files`:
* // Array of files successfully made private in the bucket.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.makePrivate(opts).then(function(data) {
* const files = data[0];
* });
*/
makePrivate(options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
options = options || {};
makePrivate(optionsOrCallback, callback) {
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
options.private = true;
const setPredefinedAcl = done => {
const setPredefinedAcl = (done) => {
const query = {

@@ -690,3 +576,3 @@ predefinedAcl: 'projectPrivate',

};
const makeFilesPrivate = done => {
const makeFilesPrivate = (done) => {
if (!options.includeFiles) {

@@ -700,94 +586,8 @@ done();

}
/**
* @typedef {array} MakeBucketPublicResponse
* @property {File[]} 0 List of files made public.
*/
/**
* @callback MakeBucketPublicCallback
* @param {?Error} err Request error, if any.
* @param {File[]} files List of files made public.
*/
/**
* Make the bucket publicly readable.
*
* You may also choose to make the contents of the bucket publicly readable by
* specifying `includeFiles: true`. This will automatically run
* {@link File#makePublic} for every file in the bucket.
*
* When specifying `includeFiles: true`, use `force: true` to delay execution
* of your callback until all files have been processed. By default, the
* callback is executed after the first error. Use `force` to queue such
* errors until all files have been processed, after which they will be
* returned as an array as the first argument to your callback.
*
* NOTE: This may cause the process to be long-running and use a high number
* of requests. Use with caution.
*
* @see [Buckets: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch}
*
* @param {object} [options] Configuration options.
* @param {boolean} [options.includeFiles=false] Make each file in the bucket
* publicly readable.
* @param {boolean} [options.force] Queue errors occurred while making files
* public until all files have been processed.
* @param {MakeBucketPublicCallback} [callback] Callback function.
* @returns {Promise<MakeBucketPublicResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* //-
* // Make the bucket publicly readable.
* //-
* bucket.makePublic(function(err) {});
*
* //-
* // Make the bucket and its contents publicly readable.
* //-
* const opts = {
* includeFiles: true
* };
*
* bucket.makePublic(opts, function(err, files) {
* // `err`:
* // The first error to occur, otherwise null.
* //
* // `files`:
* // Array of files successfully made public in the bucket.
* });
*
* //-
* // Make the bucket and its contents publicly readable, using force to
* // suppress errors until all files have been processed.
* //-
* const opts = {
* includeFiles: true,
* force: true
* };
*
* bucket.makePublic(opts, function(errors, files) {
* // `errors`:
* // Array of errors if any occurred, otherwise null.
* //
* // `files`:
* // Array of files successfully made public in the bucket.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.makePublic(opts).then(function(data) {
* const files = data[0];
* });
*/
makePublic(options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
options = options || {};
options.public = true;
const addAclPermissions = done => {
makePublic(optionsOrCallback, callback) {
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
const req = extend(true, { public: true }, options);
const addAclPermissions = (done) => {
// Allow reading bucket contents while preserving original permissions.

@@ -799,3 +599,3 @@ this.acl.add({

};
const addDefaultAclPermissions = done => {
const addDefaultAclPermissions = (done) => {
this.acl.default.add({

@@ -806,10 +606,12 @@ entity: 'allUsers',

};
const makeFilesPublic = done => {
if (!options.includeFiles) {
const makeFilesPublic = (done) => {
if (!req.includeFiles) {
done();
return;
}
this.makeAllFilesPublicPrivate_(options, done);
this.makeAllFilesPublicPrivate_(req, done);
};
async.series([addAclPermissions, addDefaultAclPermissions, makeFilesPublic], callback);
// tslint:disable-next-line:no-any
async
.series([addAclPermissions, addDefaultAclPermissions, makeFilesPublic], callback);
}

@@ -835,22 +637,2 @@ /**

}
/**
* Remove an already-existing retention policy from this bucket, if it is not
* locked.
*
* @param {SetBucketMetadataCallback} [callback] Callback function.
* @returns {Promise<SetBucketMetadataResponse>}
*
* @example
* const storage = require('@google-cloud/storage')();
* const bucket = storage.bucket('albums');
*
* bucket.removeRetentionPeriod(function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.removeRetentionPeriod().then(function(data) {
* const apiResponse = data[0];
* });
*/
removeRetentionPeriod(callback) {

@@ -867,131 +649,13 @@ this.setMetadata({

}
/**
* @typedef {array} SetLabelsResponse
* @property {object} 0 The bucket metadata.
*/
/**
* @callback SetLabelsCallback
* @param {?Error} err Request error, if any.
* @param {object} metadata The bucket metadata.
*/
/**
* Set labels on the bucket.
*
* This makes an underlying call to {@link Bucket#setMetadata}, which
* is a PATCH request. This means an individual label can be overwritten, but
* unmentioned labels will not be touched.
*
* @param {object<string, string>} labels Labels to set on the bucket.
* @param {object} [options] Configuration options.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {SetLabelsCallback} [callback] Callback function.
* @returns {Promise<SetLabelsResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* const labels = {
* labelone: 'labelonevalue',
* labeltwo: 'labeltwovalue'
* };
*
* bucket.setLabels(labels, function(err, metadata) {
* if (!err) {
* // Labels set successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.setLabels(labels).then(function(data) {
* const metadata = data[0];
* });
*/
setLabels(labels, options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
setLabels(labels, optionsOrCallback, callback) {
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
callback = callback || common_1.util.noop;
this.setMetadata({ labels }, options, callback);
}
/**
* @typedef {array} SetBucketMetadataResponse
* @property {object} 0 The bucket metadata.
*/
/**
* @callback SetBucketMetadataCallback
* @param {?Error} err Request error, if any.
* @param {object} metadata The bucket metadata.
*/
/**
* Set the bucket's metadata.
*
* @see [Buckets: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch}
*
* @param {object<string, *>} metadata The metadata you wish to set.
* @param {object} [options] Configuration options.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {SetBucketMetadataCallback} [callback] Callback function.
* @returns {Promise<SetBucketMetadataResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* //-
* // Set website metadata field on the bucket.
* //-
* const metadata = {
* website: {
* mainPageSuffix: 'http://example.com',
* notFoundPage: 'http://example.com/404.html'
* }
* };
*
* bucket.setMetadata(metadata, function(err, apiResponse) {});
*
* //-
* // Enable versioning for your bucket.
* //-
* bucket.setMetadata({
* versioning: {
* enabled: true
* }
* }, function(err, apiResponse) {});
*
* //-
* // Enable KMS encryption for objects within this bucket.
* //-
* bucket.setMetadata({
* encryption: {
* defaultKmsKeyName: 'projects/grape-spaceship-123/...'
* }
* }, function(err, apiResponse) {});
*
* //-
* // Set the default event-based hold value for new objects in this bucket.
* //-
* bucket.setMetadata({
* defaultEventBasedHold: true
* }, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.setMetadata(metadata).then(function(data) {
* const apiResponse = data[0];
* });
*/
setMetadata(metadata, options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
setMetadata(metadata, optionsOrCallback, callback) {
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
callback = callback || common_1.util.noop;

@@ -1012,37 +676,2 @@ this.request({

}
/**
* Lock all objects contained in the bucket, based on their creation time. Any
* attempt to overwrite or delete objects younger than the retention period
* will result in a `PERMISSION_DENIED` error.
*
* An unlocked retention policy can be modified or removed from the bucket via
* {@link File#removeRetentionPeriod} and {@link File#setRetentionPeriod}. A
* locked retention policy cannot be removed or shortened in duration for the
* lifetime of the bucket. Attempting to remove or decrease period of a locked
* retention policy will result in a `PERMISSION_DENIED` error. You can still
* increase the policy.
*
* @param {*} duration In seconds, the minimum retention time for all objects
* contained in this bucket.
* @param {SetBucketMetadataCallback} [callback] Callback function.
* @returns {Promise<SetBucketMetadataResponse>}
*
* @example
* const storage = require('@google-cloud/storage')();
* const bucket = storage.bucket('albums');
*
* const DURATION_SECONDS = 15780000; // 6 months.
*
* //-
* // Lock the objects in this bucket for 6 months.
* //-
* bucket.setRetentionPeriod(DURATION_SECONDS, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.setRetentionPeriod(DURATION_SECONDS).then(function(data) {
* const apiResponse = data[0];
* });
*/
setRetentionPeriod(duration, callback) {

@@ -1055,39 +684,6 @@ this.setMetadata({

}
/**
* @callback SetStorageClassCallback
* @param {?Error} err Request error, if any.
*/
/**
* Set the default storage class for new files in this bucket.
*
* @see [Storage Classes]{@link https://cloud.google.com/storage/docs/storage-classes}
*
* @param {string} storageClass The new storage class. (`multi_regional`,
* `regional`, `standard`, `nearline`, `coldline`, or
* `durable_reduced_availability`)
* @param {object} [options] Configuration options.
* @param {string} [options.userProject] - The ID of the project which will be
* billed for the request.
* @param {SetStorageClassCallback} [callback] Callback function.
* @returns {Promise}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* bucket.setStorageClass('regional', function(err, apiResponse) {
* if (err) {
* // Error handling omitted.
* }
*
* // The storage class was updated successfully.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.setStorageClass('regional').then(function() {});
*/
setStorageClass(storageClass, options, callback) {
setStorageClass(storageClass, optionsOrCallback, callback) {
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
// In case we get input like `storageClass`, convert to `storage_class`.

@@ -1117,212 +713,10 @@ storageClass = storageClass.replace(/-/g, '_')

}
/**
* @typedef {array} UploadResponse
* @property {object} 0 The uploaded {@link File}.
* @property {object} 1 The full API response.
*/
/**
* @callback UploadCallback
* @param {?Error} err Request error, if any.
* @param {object} metadata The uploaded {@link File}.
* @param {object} apiResponse The full API response.
*/
/**
* Upload a file to the bucket. This is a convenience method that wraps
* {@link File#createWriteStream}.
*
* You can specify whether or not an upload is resumable by setting
* `options.resumable`. *Resumable uploads are enabled by default if your
* input file is larger than 5 MB.*
*
* For faster crc32c computation, you must manually install
* [`fast-crc32c`](http://www.gitnpm.com/fast-crc32c):
*
* $ npm install --save fast-crc32c
*
* @see [Upload Options (Simple or Resumable)]{@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#uploads}
* @see [Objects: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert}
*
* @param {string} pathString The fully qualified path to the file you
* wish to upload to your bucket.
* @param {object} [options] Configuration options.
* @param {string|File} [options.destination] The place to save
* your file. If given a string, the file will be uploaded to the bucket
* using the string as a filename. When given a File object, your local
* file will be uploaded to the File object's bucket and under the File
* object's name. Lastly, when this argument is omitted, the file is uploaded
* to your bucket using the name of the local file.
* @param {string} [options.encryptionKey] A custom encryption key. See
* [Customer-supplied Encryption
* Keys](https://cloud.google.com/storage/docs/encryption#customer-supplied).
* @param {boolean} [options.gzip] Automatically gzip the file. This will set
* `options.metadata.contentEncoding` to `gzip`.
* @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will
* be used to encrypt the object. Must be in the format:
* `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
* @param {object} [options.metadata] See an
* [Objects: insert request
* body](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON).
* @param {string} [options.offset] The starting byte of the upload stream, for
* resuming an interrupted upload. Defaults to 0.
* @param {string} [options.predefinedAcl] Apply a predefined set of access
* controls to this object.
*
* Acceptable values are:
* - **`authenticatedRead`** - Object owner gets `OWNER` access, and
* `allAuthenticatedUsers` get `READER` access.
*
* - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
* project team owners get `OWNER` access.
*
* - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
* team owners get `READER` access.
*
* - **`private`** - Object owner gets `OWNER` access.
*
* - **`projectPrivate`** - Object owner gets `OWNER` access, and project
* team members get access according to their roles.
*
* - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
* get `READER` access.
* @param {boolean} [options.private] Make the uploaded file private. (Alias for
* `options.predefinedAcl = 'private'`)
* @param {boolean} [options.public] Make the uploaded file public. (Alias for
* `options.predefinedAcl = 'publicRead'`)
* @param {boolean} [options.resumable] Force a resumable upload. (default:
* true for files larger than 5 MB).
* @param {string} [options.uri] The URI for an already-created resumable
* upload. See {@link File#createResumableUpload}.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {string|boolean} [options.validation] Possible values: `"md5"`,
* `"crc32c"`, or `false`. By default, data integrity is validated with an
* MD5 checksum for maximum reliability. CRC32c will provide better
* performance with less reliability. You may also choose to skip
* validation completely, however this is **not recommended**.
* @param {UploadCallback} [callback] Callback function.
* @returns {Promise<UploadResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('albums');
*
* //-
* // Upload a file from a local path.
* //-
* bucket.upload('/local/path/image.png', function(err, file, apiResponse) {
* // Your bucket now contains:
* // - "image.png" (with the contents of `/local/path/image.png')
*
* // `file` is an instance of a File object that refers to your new file.
* });
*
*
* //-
* // It's not always that easy. You will likely want to specify the filename
* // used when your new file lands in your bucket.
* //
* // You may also want to set metadata or customize other options.
* //-
* const options = {
* destination: 'new-image.png',
* resumable: true,
* validation: 'crc32c',
* metadata: {
* metadata: {
* event: 'Fall trip to the zoo'
* }
* }
* };
*
* bucket.upload('local-image.png', options, function(err, file) {
* // Your bucket now contains:
* // - "new-image.png" (with the contents of `local-image.png')
*
* // `file` is an instance of a File object that refers to your new file.
* });
*
* //-
* // You can also have a file gzip'd on the fly.
* //-
* bucket.upload('index.html', { gzip: true }, function(err, file) {
* // Your bucket now contains:
* // - "index.html" (automatically compressed with gzip)
*
* // Downloading the file with `file.download` will automatically decode
* the
* // file.
* });
*
* //-
* // You may also re-use a File object, {File}, that references
* // the file you wish to create or overwrite.
* //-
* const options = {
* destination: bucket.file('existing-file.png'),
* resumable: false
* };
*
* bucket.upload('local-img.png', options, function(err, newFile) {
* // Your bucket now contains:
* // - "existing-file.png" (with the contents of `local-img.png')
*
* // Note:
* // The `newFile` parameter is equal to `file`.
* });
*
* //-
* // To use
* // <a
* href="https://cloud.google.com/storage/docs/encryption#customer-supplied">
* // Customer-supplied Encryption Keys</a>, provide the `encryptionKey`
* option.
* //-
* const crypto = require('crypto');
* const encryptionKey = crypto.randomBytes(32);
*
* bucket.upload('img.png', {
* encryptionKey: encryptionKey
* }, function(err, newFile) {
* // `img.png` was uploaded with your custom encryption key.
*
* // `newFile` is already configured to use the encryption key when making
* // operations on the remote object.
*
* // However, to use your encryption key later, you must create a `File`
* // instance with the `key` supplied:
* const file = bucket.file('img.png', {
* encryptionKey: encryptionKey
* });
*
* // Or with `file#setEncryptionKey`:
* const file = bucket.file('img.png');
* file.setEncryptionKey(encryptionKey);
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.upload('local-image.png').then(function(data) {
* const file = data[0];
* });
*
* To upload a file from a URL, use {@link File#createWriteStream}.
*
* @example <caption>include:samples/files.js</caption>
* region_tag:storage_upload_file
* Another example:
*
* @example <caption>include:samples/encryption.js</caption>
* region_tag:storage_upload_encrypted_file
* Example of uploading an encrypted file:
*/
upload(pathString, options, callback) {
upload(pathString, optionsOrCallback, callback) {
// tslint:disable-next-line:no-any
if (global['GCLOUD_SANDBOX_ENV']) {
return;
}
if (is.fn(options)) {
callback = options;
options = {};
}
let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
options = extend({

@@ -1335,3 +729,4 @@ metadata: {},

}
else if (is.string(options.destination)) {
else if (options.destination != null &&
typeof options.destination === 'string') {
// Use the string as the name of the file.

@@ -1355,3 +750,3 @@ newFile = this.file(options.destination, {

}
if (is.boolean(options.resumable)) {
if (options.resumable != null && typeof options.resumable === 'boolean') {
upload();

@@ -1380,25 +775,9 @@ }

}
/**
* Iterate over all of a bucket's files, calling `file.makePublic()` (public)
* or `file.makePrivate()` (private) on each.
*
* Operations are performed in parallel, up to 10 at once. The first error
* breaks the loop, and will execute the provided callback with it. Specify
* `{ force: true }` to suppress the errors.
*
* @private
*
* @param {object} options] Configuration options.
* @param {boolean} [options.force] Suppress errors until all files have been
* processed.
* @param {boolean} [options.private] Make files private.
* @param {boolean} [options.public] Make files public.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {function} callback Callback function.
*/
makeAllFilesPublicPrivate_(options, callback) {
makeAllFilesPublicPrivate_(optionsOrCallback, callback) {
const MAX_PARALLEL_LIMIT = 10;
const errors = [];
const updatedFiles = [];
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
this.getFiles(options, (err, files) => {

@@ -1410,3 +789,3 @@ if (err) {

const processFile = (file, callback) => {
const processedCallback = err => {
const processedCallback = (err) => {
if (err) {

@@ -1432,3 +811,3 @@ if (options.force) {

// Iterate through each file and make it public or private.
async.eachLimit(files, MAX_PARALLEL_LIMIT, processFile, err => {
async.eachLimit(files, MAX_PARALLEL_LIMIT, processFile, (err) => {
if (err || errors.length > 0) {

@@ -1435,0 +814,0 @@ callback(err || errors, updatedFiles);

@@ -18,3 +18,3 @@ /*!

import * as request from 'request';
import { Storage } from '.';
import { Storage } from './storage';
import { Response } from 'request';

@@ -21,0 +21,0 @@ /**

@@ -20,3 +20,3 @@ /*!

const promisify_1 = require("@google-cloud/promisify");
const request = require("request");
const teeny_request_1 = require("teeny-request");
/**

@@ -49,3 +49,3 @@ * Create a channel object to interact with a Cloud Storage channel.

},
requestModule: request,
requestModule: teeny_request_1.teenyRequest,
};

@@ -52,0 +52,0 @@ super(config);

@@ -16,4 +16,91 @@ /*!

*/
import * as r from 'request';
import { Bucket } from './bucket';
/**
* @typedef {object} GetPolicyOptions
* @property {string} [userProject] The ID of the project which will be billed for
* the request.
*/
export interface GetPolicyOptions {
userProject?: string;
}
/**
* @typedef {array} GetPolicyResponse
* @property {object} 0 The policy.
* @property {object} 1 The full API response.
*/
export declare type GetPolicyResponse = [Policy, r.Response];
/**
* @callback GetPolicyCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The policy.
* @param {object} apiResponse The full API response.
*/
export interface GetPolicyCallback {
(err?: Error | null, acl?: Policy, apiResponse?: r.Response): void;
}
/**
* @typedef {object} SetPolicyOptions
* @param {string} [userProject] The ID of the project which will be
* billed for the request.
*/
export interface SetPolicyOptions {
userProject?: string;
}
/**
* @typedef {array} SetPolicyResponse
* @property {object} 0 The policy.
* @property {object} 1 The full API response.
*/
export declare type SetPolicyResponse = [Policy, r.Response];
/**
* @callback SetPolicyCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The policy.
* @param {object} apiResponse The full API response.
*/
export interface SetPolicyCallback {
(err?: Error | null, acl?: Policy, apiResponse?: object): void;
}
/**
* @typedef {object} Policy
* @property {array} policy.bindings Bindings associate members with roles.
* @property {string} [policy.etag] Etags are used to perform a read-modify-write.
*/
export interface Policy {
bindings: PolicyBinding[];
etag?: string;
}
export interface PolicyBinding {
role: string;
members: string[];
}
/**
* @typedef {array} TestIamPermissionsResponse
* @property {object} 0 A subset of permissions that the caller is allowed.
* @property {object} 1 The full API response.
*/
export declare type TestIamPermissionsResponse = [{
[key: string]: boolean;
}, r.Response];
/**
* @callback TestIamPermissionsCallback
* @param {?Error} err Request error, if any.
* @param {object} acl A subset of permissions that the caller is allowed.
* @param {object} apiResponse The full API response.
*/
export interface TestIamPermissionsCallback {
(err?: Error | null, acl?: {
[key: string]: boolean;
} | null, apiResponse?: r.Response): void;
}
/**
* @typedef {object} TestIamPermissionsOptions Configuration options for Iam#testPermissions().
* @param {string} [userProject] The ID of the project which will be
* billed for the request.
*/
export interface TestIamPermissionsOptions {
userProject?: string;
}
/**
* Get and set IAM policies for your Cloud Storage bucket.

@@ -40,18 +127,2 @@ *

/**
* @typedef {object} GetPolicyRequest
* @property {string} userProject The ID of the project which will be billed for
* the request.
*/
/**
* @typedef {array} GetPolicyResponse
* @property {object} 0 The policy.
* @property {object} 1 The full API response.
*/
/**
* @callback GetPolicyCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The policy.
* @param {object} apiResponse The full API response.
*/
/**
* Get the IAM policy.

@@ -83,15 +154,6 @@ *

*/
getPolicy(options: any, callback?: any): void;
getPolicy(options?: GetPolicyOptions): Promise<GetPolicyResponse>;
getPolicy(options: GetPolicyOptions, callback: GetPolicyCallback): void;
getPolicy(callback: GetPolicyCallback): void;
/**
* @typedef {array} SetPolicyResponse
* @property {object} 0 The policy.
* @property {object} 1 The full API response.
*/
/**
* @callback SetPolicyCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The policy.
* @param {object} apiResponse The full API response.
*/
/**
* Set the IAM policy.

@@ -101,8 +163,4 @@ *

*
* @param {object} policy The policy.
* @param {array} policy.bindings Bindings associate members with roles.
* @param {string} [policy.etag] Etags are used to perform a read-modify-write.
* @param {object} [options] Configuration opbject.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {Policy} policy The policy.
* @param {SetPolicyOptions} [options] Configuration opbject.
* @param {SetPolicyCallback} callback Callback function.

@@ -147,15 +205,6 @@ * @returns {Promise<SetPolicyResponse>}

*/
setPolicy(policy: any, options: any, callback?: any): void;
setPolicy(policy: Policy, options?: SetPolicyOptions): Promise<SetPolicyResponse>;
setPolicy(policy: Policy, callback: SetPolicyCallback): void;
setPolicy(policy: Policy, options: SetPolicyOptions, callback: SetPolicyCallback): void;
/**
* @typedef {array} TestIamPermissionsResponse
* @property {object[]} 0 A subset of permissions that the caller is allowed.
* @property {object} 1 The full API response.
*/
/**
* @callback TestIamPermissionsCallback
* @param {?Error} err Request error, if any.
* @param {object[]} acl A subset of permissions that the caller is allowed.
* @param {object} apiResponse The full API response.
*/
/**
* Test a set of permissions for a resource.

@@ -166,5 +215,3 @@ *

* @param {string|string[]} permissions The permission(s) to test for.
* @param {object} [options] Configuration object.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {TestIamPermissionsOptions} [options] Configuration object.
* @param {TestIamPermissionsCallback} [callback] Callback function.

@@ -216,4 +263,6 @@ * @returns {Promise<TestIamPermissionsResponse>}

*/
testPermissions(permissions: any, options: any, callback?: any): void;
testPermissions(permissions: string | string[], options?: TestIamPermissionsOptions): Promise<TestIamPermissionsResponse>;
testPermissions(permissions: string | string[], callback: TestIamPermissionsCallback): void;
testPermissions(permissions: string | string[], options: TestIamPermissionsOptions, callback: TestIamPermissionsCallback): void;
}
export { Iam };

@@ -21,3 +21,3 @@ /*!

const extend = require("extend");
const is = require("is");
const util_1 = require("./util");
/**

@@ -45,124 +45,14 @@ * Get and set IAM policies for your Cloud Storage bucket.

}
/**
* @typedef {object} GetPolicyRequest
* @property {string} userProject The ID of the project which will be billed for
* the request.
*/
/**
* @typedef {array} GetPolicyResponse
* @property {object} 0 The policy.
* @property {object} 1 The full API response.
*/
/**
* @callback GetPolicyCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The policy.
* @param {object} apiResponse The full API response.
*/
/**
* Get the IAM policy.
*
* @param {GetPolicyRequest} [options] Request options.
* @param {GetPolicyCallback} [callback] Callback function.
* @returns {Promise<GetPolicyResponse>}
*
* @see [Buckets: setIamPolicy API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('my-bucket');
* bucket.iam.getPolicy(function(err, policy, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.iam.getPolicy().then(function(data) {
* const policy = data[0];
* const apiResponse = data[1];
* });
*
* @example <caption>include:samples/iam.js</caption>
* region_tag:storage_view_bucket_iam_members
* Example of retrieving a bucket's IAM policy:
*/
getPolicy(options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
getPolicy(optionsOrCallback, callback) {
const { options, callback: cb } = util_1.normalize(optionsOrCallback, callback);
this.request_({
uri: '/iam',
qs: options,
}, callback);
}, cb);
}
/**
* @typedef {array} SetPolicyResponse
* @property {object} 0 The policy.
* @property {object} 1 The full API response.
*/
/**
* @callback SetPolicyCallback
* @param {?Error} err Request error, if any.
* @param {object} acl The policy.
* @param {object} apiResponse The full API response.
*/
/**
* Set the IAM policy.
*
* @throws {Error} If no policy is provided.
*
* @param {object} policy The policy.
* @param {array} policy.bindings Bindings associate members with roles.
* @param {string} [policy.etag] Etags are used to perform a read-modify-write.
* @param {object} [options] Configuration opbject.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {SetPolicyCallback} callback Callback function.
* @returns {Promise<SetPolicyResponse>}
*
* @see [Buckets: setIamPolicy API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy}
* @see [IAM Roles](https://cloud.google.com/iam/docs/understanding-roles)
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('my-bucket');
*
* const myPolicy = {
* bindings: [
* {
* role: 'roles/storage.admin',
* members:
* ['serviceAccount:myotherproject@appspot.gserviceaccount.com']
* }
* ]
* };
*
* bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.iam.setPolicy(myPolicy).then(function(data) {
* const policy = data[0];
* const apiResponse = data[1];
* });
*
* @example <caption>include:samples/iam.js</caption>
* region_tag:storage_add_bucket_iam_member
* Example of adding to a bucket's IAM policy:
*
* @example <caption>include:samples/iam.js</caption>
* region_tag:storage_remove_bucket_iam_member
* Example of removing from a bucket's IAM policy:
*/
setPolicy(policy, options, callback) {
if (!is.object(policy)) {
setPolicy(policy, optionsOrCallback, callback) {
if (policy === null || typeof policy !== 'object') {
throw new Error('A policy object is required.');
}
if (is.fn(options)) {
callback = options;
options = {};
}
const { options, callback: cb } = util_1.normalize(optionsOrCallback, callback);
this.request_({

@@ -175,96 +65,28 @@ method: 'PUT',

qs: options,
}, callback);
}, cb);
}
/**
* @typedef {array} TestIamPermissionsResponse
* @property {object[]} 0 A subset of permissions that the caller is allowed.
* @property {object} 1 The full API response.
*/
/**
* @callback TestIamPermissionsCallback
* @param {?Error} err Request error, if any.
* @param {object[]} acl A subset of permissions that the caller is allowed.
* @param {object} apiResponse The full API response.
*/
/**
* Test a set of permissions for a resource.
*
* @throws {Error} If permissions are not provided.
*
* @param {string|string[]} permissions The permission(s) to test for.
* @param {object} [options] Configuration object.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {TestIamPermissionsCallback} [callback] Callback function.
* @returns {Promise<TestIamPermissionsResponse>}
*
* @see [Buckets: testIamPermissions API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const bucket = storage.bucket('my-bucket');
*
* //-
* // Test a single permission.
* //-
* const test = 'storage.buckets.delete';
*
* bucket.iam.testPermissions(test, function(err, permissions, apiResponse) {
* console.log(permissions);
* // {
* // "storage.buckets.delete": true
* // }
* });
*
* //-
* // Test several permissions at once.
* //-
* const tests = [
* 'storage.buckets.delete',
* 'storage.buckets.get'
* ];
*
* bucket.iam.testPermissions(tests, function(err, permissions) {
* console.log(permissions);
* // {
* // "storage.buckets.delete": false,
* // "storage.buckets.get": true
* // }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* bucket.iam.testPermissions(test).then(function(data) {
* const permissions = data[0];
* const apiResponse = data[1];
* });
*/
testPermissions(permissions, options, callback) {
if (!is.array(permissions) && !is.string(permissions)) {
testPermissions(permissions, optionsOrCallback, callback) {
if (!Array.isArray(permissions) && typeof permissions !== 'string') {
throw new Error('Permissions are required.');
}
if (is.fn(options)) {
callback = options;
options = {};
}
options = extend({
permissions: arrify(permissions),
const { options, callback: cb } = util_1.normalize(optionsOrCallback, callback);
const permissionsArray = arrify(permissions);
const req = extend({
permissions: permissionsArray,
}, options);
this.request_({
uri: '/iam/testPermissions',
qs: options,
qs: req,
useQuerystring: true,
}, (err, resp) => {
if (err) {
callback(err, null, resp);
cb(err, null, resp);
return;
}
const availablePermissions = arrify(resp.permissions);
const permissionsHash = permissions.reduce((acc, permission) => {
const permissionsHash = permissionsArray.reduce((acc, permission) => {
acc[permission] = availablePermissions.indexOf(permission) > -1;
return acc;
}, {});
callback(null, permissionsHash, resp);
cb(null, permissionsHash, resp);
});

@@ -271,0 +93,0 @@ }

@@ -16,479 +16,3 @@ /**

*/
import { Service, GoogleAuthOptions, CreateOptions } from '@google-cloud/common';
import * as request from 'request';
import { Bucket } from './bucket';
import { Channel } from './channel';
import { File } from './file';
export interface StorageOptions extends GoogleAuthOptions {
autoRetry?: boolean;
maxRetries?: number;
promise?: typeof Promise;
}
export interface BucketOptions extends CreateOptions {
location?: string;
kmsKeyName?: string;
userProject?: string;
}
export interface CreateBucketRequest {
coldline?: boolean;
dra?: boolean;
multiRegional?: boolean;
nearline?: boolean;
regional?: boolean;
requesterPays?: boolean;
retentionPolicy?: object;
userProject?: string;
}
export interface BucketCallback {
(err: Error | null, bucket?: Bucket | null, apiResponse?: request.Response): void;
}
/**
* @typedef {object} ClientConfig
* @property {string} [projectId] The project ID from the Google Developer's
* Console, e.g. 'grape-spaceship-123'. We will also check the environment
* variable `GCLOUD_PROJECT` for your project ID. If your app is running in
* an environment which supports {@link
* https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application
* Application Default Credentials}, your project ID will be detected
* automatically.
* @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key
* downloaded from the Google Developers Console. If you provide a path to a
* JSON file, the `projectId` option above is not necessary. NOTE: .pem and
* .p12 require you to specify the `email` option as well.
* @property {string} [email] Account email address. Required when using a .pem
* or .p12 keyFilename.
* @property {object} [credentials] Credentials object.
* @property {string} [credentials.client_email]
* @property {string} [credentials.private_key]
* @property {boolean} [autoRetry=true] Automatically retry requests if the
* response is related to rate limits or certain intermittent server errors.
* We will exponentially backoff subsequent requests by default.
* @property {number} [maxRetries=3] Maximum number of automatic retries
* attempted before returning the error.
* @property {Constructor} [promise] Custom promise module to use instead of
* native Promises.
*/
/*! Developer Documentation
*
* Invoke this method to create a new Storage object bound with pre-determined
* configuration options. For each object that can be created (e.g., a bucket),
* there is an equivalent static and instance method. While they are classes,
* they can be instantiated without use of the `new` keyword.
*/
/**
* <h4>ACLs</h4>
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share files with other users
* and allow other users to access your buckets and files.
*
* To learn more about ACLs, read this overview on
* [Access Control](https://cloud.google.com/storage/docs/access-control).
*
* @see [Cloud Storage overview]{@link https://cloud.google.com/storage/docs/overview}
* @see [Access Control]{@link https://cloud.google.com/storage/docs/access-control}
*
* @class
* @hideconstructor
*
* @example <caption>Create a client that uses Application Default Credentials
* (ADC)</caption> const {Storage} = require('@google-cloud/storage'); const
* storage = new Storage();
*
* @example <caption>Create a client with explicit credentials</caption>
* storage');/storage');
* const storage = new Storage({
* projectId: 'your-project-id',
* keyFilename: '/path/to/keyfile.json'
* });
*
* @param {ClientConfig} [options] Configuration options.
*/
declare class Storage extends Service {
/**
* {@link Bucket} class.
*
* @name Storage.Bucket
* @see Bucket
* @type {Constructor}
*/
static Bucket: typeof Bucket;
/**
* {@link Channel} class.
*
* @name Storage.Channel
* @see Channel
* @type {Constructor}
*/
static Channel: typeof Channel;
/**
* {@link File} class.
*
* @name Storage.File
* @see File
* @type {Constructor}
*/
static File: typeof File;
/**
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share objects with other
* users and allow other users to access your buckets and objects.
*
* This object provides constants to refer to the three permission levels that
* can be granted to an entity:
*
* - `gcs.acl.OWNER_ROLE` - ("OWNER")
* - `gcs.acl.READER_ROLE` - ("READER")
* - `gcs.acl.WRITER_ROLE` - ("WRITER")
*
* @see [About Access Control Lists]{@link https://cloud.google.com/storage/docs/access-control/lists}
*
* @name Storage.acl
* @type {object}
* @property {string} OWNER_ROLE
* @property {string} READER_ROLE
* @property {string} WRITER_ROLE
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const albums = storage.bucket('albums');
*
* //-
* // Make all of the files currently in a bucket publicly readable.
* //-
* const options = {
* entity: 'allUsers',
* role: storage.acl.READER_ROLE
* };
*
* albums.acl.add(options, function(err, aclObject) {});
*
* //-
* // Make any new objects added to a bucket publicly readable.
* //-
* albums.acl.default.add(options, function(err, aclObject) {});
*
* //-
* // Grant a user ownership permissions to a bucket.
* //-
* albums.acl.add({
* entity: 'user-useremail@example.com',
* role: storage.acl.OWNER_ROLE
* }, function(err, aclObject) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* albums.acl.add(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
*/
static acl: {
OWNER_ROLE: string;
READER_ROLE: string;
WRITER_ROLE: string;
};
/**
* Reference to {@link Storage.acl}.
*
* @name Storage#acl
* @see Storage.acl
*/
acl: typeof Storage.acl;
/**
* Get {@link Bucket} objects for all of the buckets in your project as
* a readable object stream.
*
* @method Storage#getBucketsStream
* @param {GetBucketsRequest} [query] Query object for listing buckets.
* @returns {ReadableStream} A readable stream that emits {@link Bucket} instances.
*
* @example
* storage.getBucketsStream()
* .on('error', console.error)
* .on('data', function(bucket) {
* // bucket is a Bucket object.
* })
* .on('end', function() {
* // All buckets retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* storage.getBucketsStream()
* .on('data', function(bucket) {
* this.end();
* });
*/
getBucketsStream: any;
constructor(options?: StorageOptions);
/**
* Get a reference to a Cloud Storage bucket.
*
* @param {string} name Name of the bucket.
* @param {object} [options] Configuration object.
* @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to
* encrypt objects inserted into this bucket, if no encryption method is
* specified.
* @param {string} [options.userProject] User project to be billed for all
* requests made from this Bucket object.
* @returns {Bucket}
* @see Bucket
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const albums = storage.bucket('albums');
* const photos = storage.bucket('photos');
*/
bucket(name: string, options?: BucketOptions): Bucket;
/**
* Reference a channel to receive notifications about changes to your bucket.
*
* @param {string} id The ID of the channel.
* @param {string} resourceId The resource ID of the channel.
* @returns {Channel}
* @see Channel
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const channel = storage.channel('id', 'resource-id');
*/
channel(id: string, resourceId: string): Channel;
/**
* Metadata to set for the bucket.
*
* @typedef {object} CreateBucketRequest
* @property {boolean} [coldline=false] Specify the storage class as Coldline.
* @property {boolean} [dra=false] Specify the storage class as Durable Reduced
* Availability.
* @property {boolean} [multiRegional=false] Specify the storage class as
* Multi-Regional.
* @property {boolean} [nearline=false] Specify the storage class as Nearline.
* @property {boolean} [regional=false] Specify the storage class as Regional.
* @property {boolean} [requesterPays=false] **Early Access Testers Only**
* Force the use of the User Project metadata field to assign operational
* costs when an operation is made on a Bucket and its objects.
* @property {string} [userProject] The ID of the project which will be billed
* for the request.
*/
/**
* @typedef {array} CreateBucketResponse
* @property {Bucket} 0 The new {@link Bucket}.
* @property {object} 1 The full API response.
*/
/**
* @callback CreateBucketCallback
* @param {?Error} err Request error, if any.
* @param {Bucket} bucket The new {@link Bucket}.
* @param {object} apiResponse The full API response.
*/
/**
* Create a bucket.
*
* Cloud Storage uses a flat namespace, so you can't create a bucket with
* a name that is already in use. For more information, see
* [Bucket Naming
* Guidelines](https://cloud.google.com/storage/docs/bucketnaming.html#requirements).
*
* @see [Buckets: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/insert}
* @see [Storage Classes]{@link https://cloud.google.com/storage/docs/storage-classes}
*
* @param {string} name Name of the bucket to create.
* @param {CreateBucketRequest} [metadata] Metadata to set for the bucket.
* @param {CreateBucketCallback} [callback] Callback function.
* @returns {Promise<CreateBucketResponse>}
* @throws {Error} If a name is not provided.
* @see Bucket#create
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const callback = function(err, bucket, apiResponse) {
* // `bucket` is a Bucket object.
* };
*
* storage.createBucket('new-bucket', callback);
*
* //-
* // Create a bucket in a specific location and region. <em>See the <a
* // href="https://cloud.google.com/storage/docs/json_api/v1/buckets/insert">
* // Official JSON API docs</a> for complete details on the `location`
* option.
* // </em>
* //-
* const metadata = {
* location: 'US-CENTRAL1',
* regional: true
* };
*
* storage.createBucket('new-bucket', metadata, callback);
*
* //-
* // Create a bucket with a retention policy of 6 months.
* //-
* const metadata = {
* retentionPolicy: {
* retentionPeriod: 15780000 // 6 months in seconds.
* }
* };
*
* storage.createBucket('new-bucket', metadata, callback);
*
* //-
* // Enable versioning on a new bucket.
* //-
* const metadata = {
* versioning: {
* enabled: true
* }
* };
*
* storage.createBucket('new-bucket', metadata, callback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* storage.createBucket('new-bucket').then(function(data) {
* const bucket = data[0];
* const apiResponse = data[1];
* });
*
* @example <caption>include:samples/buckets.js</caption>
* region_tag:storage_create_bucket
* Another example:
*/
createBucket(name: string, callback: BucketCallback): void;
createBucket(name: string, metadata: CreateBucketRequest, callback: BucketCallback): void;
/**
* Query object for listing buckets.
*
* @typedef {object} GetBucketsRequest
* @property {boolean} [autoPaginate=true] Have pagination handled
* automatically.
* @property {number} [maxApiCalls] Maximum number of API calls to make.
* @property {number} [maxResults] Maximum number of items plus prefixes to
* return.
* @property {string} [pageToken] A previously-returned page token
* representing part of the larger set of results to view.
* @property {string} [userProject] The ID of the project which will be billed
* for the request.
*/
/**
* @typedef {array} GetBucketsResponse
* @property {Bucket[]} 0 Array of {@link Bucket} instances.
*/
/**
* @callback GetBucketsCallback
* @param {?Error} err Request error, if any.
* @param {Bucket[]} buckets Array of {@link Bucket} instances.
*/
/**
* Get Bucket objects for all of the buckets in your project.
*
* @see [Buckets: list API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/list}
*
* @param {GetBucketsRequest} [query] Query object for listing buckets.
* @param {GetBucketsCallback} [callback] Callback function.
* @returns {Promise<GetBucketsResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* storage.getBuckets(function(err, buckets) {
* if (!err) {
* // buckets is an array of Bucket objects.
* }
* });
*
* //-
* // To control how many API requests are made and page through the results
* // manually, set `autoPaginate` to `false`.
* //-
* const callback = function(err, buckets, nextQuery, apiResponse) {
* if (nextQuery) {
* // More results exist.
* storage.getBuckets(nextQuery, callback);
* }
*
* // The `metadata` property is populated for you with the metadata at the
* // time of fetching.
* buckets[0].metadata;
*
* // However, in cases where you are concerned the metadata could have
* // changed, use the `getMetadata` method.
* buckets[0].getMetadata(function(err, metadata, apiResponse) {});
* };
*
* storage.getBuckets({
* autoPaginate: false
* }, callback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* storage.getBuckets().then(function(data) {
* const buckets = data[0];
* });
*
* @example <caption>include:samples/buckets.js</caption>
* region_tag:storage_list_buckets
* Another example:
*/
getBuckets(query: any, callback?: any): void;
/**
* @typedef {array} GetServiceAccountResponse
* @property {object} 0 The service account resource.
* @property {object} 1 The full
* [API
* response](https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource).
*/
/**
* @callback GetServiceAccountCallback
* @param {?Error} err Request error, if any.
* @param {object} serviceAccount The serviceAccount resource.
* @param {string} serviceAccount.emailAddress The service account email
* address.
* @param {object} apiResponse The full
* [API
* response](https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource).
*/
/**
* Get the email address of this project's Google Cloud Storage service
* account.
*
* @see [Projects.serviceAccount: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount/get}
* @see [Projects.serviceAccount Resource]{@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource}
*
* @param {object} [options] Configuration object.
* @param {string} [options.userProject] User project to be billed for this
* request.
* @param {GetServiceAccountCallback} [callback] Callback function.
* @returns {Promise<GetServiceAccountResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
*
* storage.getServiceAccount(function(err, serviceAccount, apiResponse) {
* if (!err) {
* const serviceAccountEmail = serviceAccount.emailAddress;
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* storage.getServiceAccount().then(function(data) {
* const serviceAccountEmail = data[0].emailAddress;
* const apiResponse = data[1];
* });
*/
getServiceAccount(options: any, callback?: any): void;
}
/**
* The `@google-cloud/storage` package has a single named export which is the

@@ -524,3 +48,8 @@ * {@link Storage} (ES6) class, which should be instantiated with `new`.

*/
export { Storage };
export { Bucket, File, Channel };
export { AccessControlObject, AclOptions, AddAclCallback, AddAclOptions, AddAclResponse, GetAclCallback, GetAclOptions, GetAclResponse, RemoveAclCallback, RemoveAclOptions, RemoveAclResponse, UpdateAclCallback, UpdateAclOptions, UpdateAclResponse } from './acl';
export { Bucket, BucketExistsCallback, BucketExistsOptions, BucketExistsResponse, BucketLockCallback, BucketLockResponse, CombineCallback, CombineOptions, CombineResponse, CreateChannelCallback, CreateChannelConfig, CreateChannelOptions, CreateChannelResponse, CreateNotificationCallback, CreateNotificationOptions, CreateNotificationResponse, DeleteBucketCallback, DeleteBucketOptions, DeleteBucketResponse, DeleteFilesCallback, DeleteFilesOptions, DeleteLabelsCallback, DeleteLabelsResponse, DisableRequesterPaysCallback, DisableRequesterPaysResponse, EnableRequesterPaysCallback, EnableRequesterPaysResponse, GetBucketCallback, GetBucketMetadataCallback, GetBucketMetadataOptions, GetBucketMetadataResponse, GetBucketOptions, GetBucketResponse, GetFilesCallback, GetFilesOptions, GetLabelsCallback, GetLabelsOptions, GetLabelsResponse, GetNotificationsCallback, GetNotificationsOptions, GetNotificationsResponse, Labels, MakeBucketPrivateCallback, MakeBucketPrivateOptions, MakeBucketPrivateResponse, MakeBucketPublicCallback, MakeBucketPublicOptions, MakeBucketPublicResponse, SetBucketMetadataCallback, SetBucketMetadataOptions, SetBucketMetadataResponse, SetBucketStorageClassCallback, SetBucketStorageClassOptions, SetLabelsCallback, SetLabelsOptions, SetLabelsResponse, UploadCallback, UploadOptions, UploadResponse } from './bucket';
export { Channel, StopCallback } from './channel';
export { CopyCallback, CopyOptions, CopyResponse, CreateReadStreamOptions, CreateResumableUploadCallback, CreateResumableUploadOptions, CreateResumableUploadResponse, CreateWriteStreamOptions, DeleteFileCallback, DeleteFileOptions, DeleteFileResponse, DownloadCallback, DownloadOptions, DownloadResponse, EncryptionKeyOptions, File, FileExistsCallback, FileExistsOptions, FileExistsResponse, FileOptions, GetExpirationDateCallback, GetExpirationDateResponse, GetFileCallback, GetFileMetadataCallback, GetFileMetadataOptions, GetFileMetadataResponse, GetFileOptions, GetFileResponse, GetSignedPolicyCallback, GetSignedPolicyOptions, GetSignedPolicyResponse, GetSignedUrlCallback, GetSignedUrlConfig, GetSignedUrlResponse, MakeFilePrivateCallback, MakeFilePrivateOptions, MakeFilePrivateResponse, MakeFilePublicCallback, MakeFilePublicResponse, MoveCallback, MoveOptions, MoveResponse, PolicyDocument, PredefinedAcl, RotateEncryptionKeyCallback, RotateEncryptionKeyOptions, RotateEncryptionKeyResponse, SaveCallback, SaveOptions, SetFileMetadataCallback, SetFileMetadataOptions, SetFileMetadataResponse, SetStorageClassCallback, SetStorageClassOptions, SetStorageClassResponse } from './file';
export { GetPolicyCallback, GetPolicyOptions, GetPolicyResponse, Iam, Policy, SetPolicyCallback, SetPolicyOptions, SetPolicyResponse, TestIamPermissionsCallback, TestIamPermissionsOptions, TestIamPermissionsResponse } from './iam';
export { DeleteNotificationCallback, DeleteNotificationOptions, GetNotificationCallback, GetNotificationMetadataCallback, GetNotificationMetadataOptions, GetNotificationMetadataResponse, GetNotificationOptions, GetNotificationResponse, Notification } from './notification';
export { BucketCallback, BucketOptions, CreateBucketQuery, CreateBucketRequest, GetBucketsCallback, GetBucketsRequest, GetBucketsResponse, GetServiceAccountCallback, GetServiceAccountOptions, GetServiceAccountResponse, ServiceAccount, Storage, StorageOptions } from './storage';

@@ -0,1 +1,2 @@

"use strict";
/**

@@ -16,469 +17,15 @@ * Copyright 2014-2017 Google Inc. All Rights Reserved.

*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const arrify = require("arrify");
const common_1 = require("@google-cloud/common");
const paginator_1 = require("@google-cloud/paginator");
const promisify_1 = require("@google-cloud/promisify");
const extend = require("extend");
const request = require("request");
const bucket_1 = require("./bucket");
var bucket_1 = require("./bucket");
exports.Bucket = bucket_1.Bucket;
const channel_1 = require("./channel");
var channel_1 = require("./channel");
exports.Channel = channel_1.Channel;
const file_1 = require("./file");
var file_1 = require("./file");
exports.File = file_1.File;
/**
* @typedef {object} ClientConfig
* @property {string} [projectId] The project ID from the Google Developer's
* Console, e.g. 'grape-spaceship-123'. We will also check the environment
* variable `GCLOUD_PROJECT` for your project ID. If your app is running in
* an environment which supports {@link
* https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application
* Application Default Credentials}, your project ID will be detected
* automatically.
* @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key
* downloaded from the Google Developers Console. If you provide a path to a
* JSON file, the `projectId` option above is not necessary. NOTE: .pem and
* .p12 require you to specify the `email` option as well.
* @property {string} [email] Account email address. Required when using a .pem
* or .p12 keyFilename.
* @property {object} [credentials] Credentials object.
* @property {string} [credentials.client_email]
* @property {string} [credentials.private_key]
* @property {boolean} [autoRetry=true] Automatically retry requests if the
* response is related to rate limits or certain intermittent server errors.
* We will exponentially backoff subsequent requests by default.
* @property {number} [maxRetries=3] Maximum number of automatic retries
* attempted before returning the error.
* @property {Constructor} [promise] Custom promise module to use instead of
* native Promises.
*/
/*! Developer Documentation
*
* Invoke this method to create a new Storage object bound with pre-determined
* configuration options. For each object that can be created (e.g., a bucket),
* there is an equivalent static and instance method. While they are classes,
* they can be instantiated without use of the `new` keyword.
*/
/**
* <h4>ACLs</h4>
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share files with other users
* and allow other users to access your buckets and files.
*
* To learn more about ACLs, read this overview on
* [Access Control](https://cloud.google.com/storage/docs/access-control).
*
* @see [Cloud Storage overview]{@link https://cloud.google.com/storage/docs/overview}
* @see [Access Control]{@link https://cloud.google.com/storage/docs/access-control}
*
* @class
* @hideconstructor
*
* @example <caption>Create a client that uses Application Default Credentials
* (ADC)</caption> const {Storage} = require('@google-cloud/storage'); const
* storage = new Storage();
*
* @example <caption>Create a client with explicit credentials</caption>
* storage');/storage');
* const storage = new Storage({
* projectId: 'your-project-id',
* keyFilename: '/path/to/keyfile.json'
* });
*
* @param {ClientConfig} [options] Configuration options.
*/
class Storage extends common_1.Service {
constructor(options = {}) {
const config = {
baseUrl: 'https://www.googleapis.com/storage/v1',
projectIdRequired: false,
scopes: [
'https://www.googleapis.com/auth/iam',
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/devstorage.full_control',
],
packageJson: require('../../package.json'),
requestModule: request,
};
super(config, options);
/**
* Reference to {@link Storage.acl}.
*
* @name Storage#acl
* @see Storage.acl
*/
this.acl = Storage.acl;
this.getBucketsStream = paginator_1.paginator.streamify('getBuckets');
}
/**
* Get a reference to a Cloud Storage bucket.
*
* @param {string} name Name of the bucket.
* @param {object} [options] Configuration object.
* @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to
* encrypt objects inserted into this bucket, if no encryption method is
* specified.
* @param {string} [options.userProject] User project to be billed for all
* requests made from this Bucket object.
* @returns {Bucket}
* @see Bucket
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const albums = storage.bucket('albums');
* const photos = storage.bucket('photos');
*/
bucket(name, options) {
if (!name) {
throw new Error('A bucket name is needed to use Cloud Storage.');
}
return new bucket_1.Bucket(this, name, options);
}
/**
* Reference a channel to receive notifications about changes to your bucket.
*
* @param {string} id The ID of the channel.
* @param {string} resourceId The resource ID of the channel.
* @returns {Channel}
* @see Channel
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const channel = storage.channel('id', 'resource-id');
*/
channel(id, resourceId) {
return new channel_1.Channel(this, id, resourceId);
}
createBucket(name, metadataOrCallback, callback) {
if (!name) {
throw new Error('A name is required to create a bucket.');
}
let metadata;
if (!callback) {
callback = metadataOrCallback;
metadata = {};
}
else {
metadata = metadataOrCallback;
}
const body = extend({}, metadata, {
name,
});
const storageClasses = {
coldline: 'COLDLINE',
dra: 'DURABLE_REDUCED_AVAILABILITY',
multiRegional: 'MULTI_REGIONAL',
nearline: 'NEARLINE',
regional: 'REGIONAL',
};
Object.keys(storageClasses).forEach(storageClass => {
if (body[storageClass]) {
body.storageClass = storageClasses[storageClass];
delete body[storageClass];
}
});
if (body.requesterPays) {
body.billing = {
requesterPays: body.requesterPays,
};
delete body.requesterPays;
}
const query = {
project: this.projectId,
};
if (body.userProject) {
query.userProject = body.userProject;
delete body.userProject;
}
this.request({
method: 'POST',
uri: '/b',
qs: query,
json: body,
}, (err, resp) => {
if (err) {
callback(err, null, resp);
return;
}
const bucket = this.bucket(name);
bucket.metadata = resp;
callback(null, bucket, resp);
});
}
/**
* Query object for listing buckets.
*
* @typedef {object} GetBucketsRequest
* @property {boolean} [autoPaginate=true] Have pagination handled
* automatically.
* @property {number} [maxApiCalls] Maximum number of API calls to make.
* @property {number} [maxResults] Maximum number of items plus prefixes to
* return.
* @property {string} [pageToken] A previously-returned page token
* representing part of the larger set of results to view.
* @property {string} [userProject] The ID of the project which will be billed
* for the request.
*/
/**
* @typedef {array} GetBucketsResponse
* @property {Bucket[]} 0 Array of {@link Bucket} instances.
*/
/**
* @callback GetBucketsCallback
* @param {?Error} err Request error, if any.
* @param {Bucket[]} buckets Array of {@link Bucket} instances.
*/
/**
* Get Bucket objects for all of the buckets in your project.
*
* @see [Buckets: list API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/list}
*
* @param {GetBucketsRequest} [query] Query object for listing buckets.
* @param {GetBucketsCallback} [callback] Callback function.
* @returns {Promise<GetBucketsResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* storage.getBuckets(function(err, buckets) {
* if (!err) {
* // buckets is an array of Bucket objects.
* }
* });
*
* //-
* // To control how many API requests are made and page through the results
* // manually, set `autoPaginate` to `false`.
* //-
* const callback = function(err, buckets, nextQuery, apiResponse) {
* if (nextQuery) {
* // More results exist.
* storage.getBuckets(nextQuery, callback);
* }
*
* // The `metadata` property is populated for you with the metadata at the
* // time of fetching.
* buckets[0].metadata;
*
* // However, in cases where you are concerned the metadata could have
* // changed, use the `getMetadata` method.
* buckets[0].getMetadata(function(err, metadata, apiResponse) {});
* };
*
* storage.getBuckets({
* autoPaginate: false
* }, callback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* storage.getBuckets().then(function(data) {
* const buckets = data[0];
* });
*
* @example <caption>include:samples/buckets.js</caption>
* region_tag:storage_list_buckets
* Another example:
*/
getBuckets(query, callback) {
if (!callback) {
callback = query;
query = {};
}
query.project = query.project || this.projectId;
this.request({
uri: '/b',
qs: query,
}, (err, resp) => {
if (err) {
callback(err, null, null, resp);
return;
}
const buckets = arrify(resp.items).map(bucket => {
const bucketInstance = this.bucket(bucket.id);
bucketInstance.metadata = bucket;
return bucketInstance;
});
let nextQuery = null;
if (resp.nextPageToken) {
nextQuery = extend({}, query, { pageToken: resp.nextPageToken });
}
callback(null, buckets, nextQuery, resp);
});
}
/**
* @typedef {array} GetServiceAccountResponse
* @property {object} 0 The service account resource.
* @property {object} 1 The full
* [API
* response](https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource).
*/
/**
* @callback GetServiceAccountCallback
* @param {?Error} err Request error, if any.
* @param {object} serviceAccount The serviceAccount resource.
* @param {string} serviceAccount.emailAddress The service account email
* address.
* @param {object} apiResponse The full
* [API
* response](https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource).
*/
/**
* Get the email address of this project's Google Cloud Storage service
* account.
*
* @see [Projects.serviceAccount: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount/get}
* @see [Projects.serviceAccount Resource]{@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource}
*
* @param {object} [options] Configuration object.
* @param {string} [options.userProject] User project to be billed for this
* request.
* @param {GetServiceAccountCallback} [callback] Callback function.
* @returns {Promise<GetServiceAccountResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
*
* storage.getServiceAccount(function(err, serviceAccount, apiResponse) {
* if (!err) {
* const serviceAccountEmail = serviceAccount.emailAddress;
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* storage.getServiceAccount().then(function(data) {
* const serviceAccountEmail = data[0].emailAddress;
* const apiResponse = data[1];
* });
*/
getServiceAccount(options, callback) {
if (!callback) {
callback = options;
options = {};
}
this.request({
uri: `/projects/${this.projectId}/serviceAccount`,
qs: options,
}, (err, resp) => {
if (err) {
callback(err, null, resp);
return;
}
const camelCaseResponse = {};
for (const prop in resp) {
if (resp.hasOwnProperty(prop)) {
const camelCaseProp = prop.replace(/_(\w)/g, (_, match) => match.toUpperCase());
camelCaseResponse[camelCaseProp] = resp[prop];
}
}
callback(null, camelCaseResponse, resp);
});
}
}
/**
* {@link Bucket} class.
*
* @name Storage.Bucket
* @see Bucket
* @type {Constructor}
*/
Storage.Bucket = bucket_1.Bucket;
/**
* {@link Channel} class.
*
* @name Storage.Channel
* @see Channel
* @type {Constructor}
*/
Storage.Channel = channel_1.Channel;
/**
* {@link File} class.
*
* @name Storage.File
* @see File
* @type {Constructor}
*/
Storage.File = file_1.File;
/**
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share objects with other
* users and allow other users to access your buckets and objects.
*
* This object provides constants to refer to the three permission levels that
* can be granted to an entity:
*
* - `gcs.acl.OWNER_ROLE` - ("OWNER")
* - `gcs.acl.READER_ROLE` - ("READER")
* - `gcs.acl.WRITER_ROLE` - ("WRITER")
*
* @see [About Access Control Lists]{@link https://cloud.google.com/storage/docs/access-control/lists}
*
* @name Storage.acl
* @type {object}
* @property {string} OWNER_ROLE
* @property {string} READER_ROLE
* @property {string} WRITER_ROLE
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const albums = storage.bucket('albums');
*
* //-
* // Make all of the files currently in a bucket publicly readable.
* //-
* const options = {
* entity: 'allUsers',
* role: storage.acl.READER_ROLE
* };
*
* albums.acl.add(options, function(err, aclObject) {});
*
* //-
* // Make any new objects added to a bucket publicly readable.
* //-
* albums.acl.default.add(options, function(err, aclObject) {});
*
* //-
* // Grant a user ownership permissions to a bucket.
* //-
* albums.acl.add({
* entity: 'user-useremail@example.com',
* role: storage.acl.OWNER_ROLE
* }, function(err, aclObject) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* albums.acl.add(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
*/
Storage.acl = {
OWNER_ROLE: 'OWNER',
READER_ROLE: 'READER',
WRITER_ROLE: 'WRITER',
};
exports.Storage = Storage;
/*! Developer Documentation
*
* These methods can be auto-paginated.
*/
paginator_1.paginator.extend(Storage, 'getBuckets');
/*! Developer Documentation
*
* All async methods (except for streams) will return a Promise in the event
* that a callback is omitted.
*/
promisify_1.promisifyAll(Storage, {
exclude: ['bucket', 'channel'],
});
var iam_1 = require("./iam");
exports.Iam = iam_1.Iam;
var notification_1 = require("./notification");
exports.Notification = notification_1.Notification;
var storage_1 = require("./storage");
exports.Storage = storage_1.Storage;
//# sourceMappingURL=index.js.map

@@ -20,4 +20,3 @@ /*!

const promisify_1 = require("@google-cloud/promisify");
const is = require("is");
const request = require("request");
const teeny_request_1 = require("teeny-request");
/**

@@ -124,3 +123,3 @@ * A Notification object is created from your {@link Bucket} object using

methods,
requestModule: request,
requestModule: teeny_request_1.teenyRequest,
});

@@ -159,3 +158,3 @@ }

const args = [];
if (!is.empty(options)) {
if (Object.keys(options).length > 0) {
args.push(options);

@@ -162,0 +161,0 @@ }

@@ -16,5 +16,5 @@ /*!

*/
export declare function normalize<T = {}, U = Function>(optionsOrCallback?: {} | Function, cb?: Function): {
export declare function normalize<T = {}, U = Function>(optionsOrCallback?: T | U, cb?: U): {
options: T;
callback: Function;
callback: U;
};

@@ -7,2 +7,42 @@ # Changelog

## v2.2.0
### Bug Fixes
- fix: re-enable typescript types ([#484](https://github.com/googleapis/nodejs-storage/pull/484))
### Dependencies
- fix(deps): update dependency @google-cloud/common to ^0.26.0 (edited) ([#480](https://github.com/googleapis/nodejs-storage/pull/480))
- chore: Remove 'is' dependency ([#462](https://github.com/googleapis/nodejs-storage/pull/462))
- chore: upgrade teeny-request to 3.11.0 with type definitions ([#457](https://github.com/googleapis/nodejs-storage/pull/457))
- feat: use small HTTP dependency ([#416](https://github.com/googleapis/nodejs-storage/pull/416))
### Documentation
- docs: Minor docs correction ([#465](https://github.com/googleapis/nodejs-storage/pull/465))
### Internal / Testing Changes
- chore: remove old issue template ([#485](https://github.com/googleapis/nodejs-storage/pull/485))
- chore(typescript): enable noImplicitAny ([#483](https://github.com/googleapis/nodejs-storage/pull/483))
- chore(typescript): improve typescript types and update tests ([#482](https://github.com/googleapis/nodejs-storage/pull/482))
- build: run tests on node11 ([#481](https://github.com/googleapis/nodejs-storage/pull/481))
- chores(build): do not collect sponge.xml from windows builds ([#478](https://github.com/googleapis/nodejs-storage/pull/478))
- chores(build): run codecov on continuous builds ([#476](https://github.com/googleapis/nodejs-storage/pull/476))
- chore: update new issue template ([#475](https://github.com/googleapis/nodejs-storage/pull/475))
- fix: enable noImplicitAny for src/bucket.ts ([#472](https://github.com/googleapis/nodejs-storage/pull/472))
- fix(tests): use unique prefix for system tests to avoid collision with another run ([#468](https://github.com/googleapis/nodejs-storage/pull/468))
- fix: improve the types ([#467](https://github.com/googleapis/nodejs-storage/pull/467))
- chore: move class Storage to storage.ts, create index.ts that contains all exports ([#464](https://github.com/googleapis/nodejs-storage/pull/464))
- chore: add types to many unit tests ([#463](https://github.com/googleapis/nodejs-storage/pull/463))
- fix: Annotate Iam types ([#461](https://github.com/googleapis/nodejs-storage/pull/461))
- fix: complete bucket.ts noImplicitAny ([#460](https://github.com/googleapis/nodejs-storage/pull/460))
- fix: improve the types on acl.ts ([#459](https://github.com/googleapis/nodejs-storage/pull/459))
- fix: improve types (7) ([#458](https://github.com/googleapis/nodejs-storage/pull/458))
- fix: improve the types ([#453](https://github.com/googleapis/nodejs-storage/pull/453))
- chore: update build config ([#455](https://github.com/googleapis/nodejs-storage/pull/455))
- fix: improve typescript types in src/file.ts ([#450](https://github.com/googleapis/nodejs-storage/pull/450))
- build: fix codecov uploading on Kokoro ([#451](https://github.com/googleapis/nodejs-storage/pull/451))
- test: Attempt to re-enable iam#testPermissions ([#429](https://github.com/googleapis/nodejs-storage/pull/429))
- chore(deps): update dependency sinon to v7 ([#449](https://github.com/googleapis/nodejs-storage/pull/449))
- Re-generate library using /synth.py ([#448](https://github.com/googleapis/nodejs-storage/pull/448))
- Correct parameter name. ([#446](https://github.com/googleapis/nodejs-storage/pull/446))
## v2.1.0

@@ -9,0 +49,0 @@

{
"name": "@google-cloud/storage",
"description": "Cloud Storage Client Library for Node.js",
"version": "2.1.0",
"version": "2.2.0",
"license": "Apache-2.0",

@@ -12,2 +12,3 @@ "author": "Google Inc.",

"main": "./build/src/index.js",
"types": "./build/src/index.d.ts",
"files": [

@@ -82,3 +83,3 @@ "build/src",

"dependencies": {
"@google-cloud/common": "^0.24.0",
"@google-cloud/common": "^0.26.0",
"@google-cloud/paginator": "^0.1.0",

@@ -94,3 +95,2 @@ "@google-cloud/promisify": "^0.3.0",

"hash-stream-validation": "^0.2.1",
"is": "^3.0.1",
"mime": "^2.2.0",

@@ -100,5 +100,5 @@ "mime-types": "^2.0.8",

"pumpify": "^1.5.1",
"request": "^2.88.0",
"snakeize": "^0.1.0",
"stream-events": "^1.0.1",
"teeny-request": "^3.11.0",
"through2": "^2.0.0",

@@ -114,4 +114,4 @@ "xdg-basedir": "^3.0.0"

"@types/concat-stream": "^1.6.0",
"@types/configstore": "^2.1.1",
"@types/extend": "^3.0.0",
"@types/is": "0.0.20",
"@types/mime": "^2.0.0",

@@ -121,2 +121,3 @@ "@types/mime-types": "^2.1.0",

"@types/nock": "^9.3.0",
"@types/node-fetch": "^2.1.2",
"@types/once": "^1.4.0",

@@ -128,2 +129,3 @@ "@types/proxyquire": "^1.3.28",

"@types/tmp": "0.0.33",
"@types/uuid": "^3.4.4",
"@types/xdg-basedir": "^2.0.0",

@@ -146,3 +148,2 @@ "codecov": "^3.0.0",

"prettier": "^1.7.0",
"prop-assign": "^1.0.0",
"proxyquire": "^2.0.0",

@@ -149,0 +150,0 @@ "source-map-support": "^0.5.6",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc