@engineers/gcloud-storage 0.0.0-temp

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.mjs +293 -0
  2. package/package.json +34 -0
package/index.mjs ADDED
@@ -0,0 +1,293 @@
1
+ // src/index.ts
2
+ import {
3
+ Storage
4
+ } from "@google-cloud/storage";
5
+ import { mkdirSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+ import stripJsonComments from "strip-json-comments";
8
+ import { URL } from "node:url";
9
+
10
+ // ../javascript/src/objects.ts
11
+ function objectType(object) {
12
+ return Object.prototype.toString.call(object).replace("[object ", "").replace("]", "").toLowerCase();
13
+ }
14
+
15
+ // ../javascript/src/string.ts
16
+ function cleanString(value, options = {}) {
17
+ let opts = {
18
+ // remove '//' comments
19
+ // it is better to disable this option to avoid removing comment-like strings by mistake
20
+ // suc as `https://`
21
+ removeComments: false,
22
+ // remove break lines for multi-line string
23
+ removeBreakLines: true,
24
+ // trim each line of the multi-line string
25
+ trim: false,
26
+ ...options
27
+ };
28
+ if (opts.removeComments)
29
+ value = value.replace(/\s*\/\/.*$/gm, "");
30
+ if (opts.removeBreakLines)
31
+ value = value.split("\n").map((line) => opts.trim ? line.trim() : line).join("");
32
+ if (opts.trim)
33
+ value = value.trim();
34
+ return value;
35
+ }
36
+
37
+ // ../javascript/src/regex.ts
38
+ function escape(value) {
39
+ return value.replace(/[$()*+./?[\\\]^{|}]/g, "\\$&");
40
+ }
41
+ function clean(value, options = {}) {
42
+ value = cleanString(value, options);
43
+ return options.escape ? escape(value) : value;
44
+ }
45
+ function toRegExp(value, optionsOrFlags = {}) {
46
+ let opts = {
47
+ delimiter: "",
48
+ ...typeof optionsOrFlags === "string" ? { flags: optionsOrFlags } : optionsOrFlags
49
+ };
50
+ if (typeof value === "string") {
51
+ value = clean(value, opts);
52
+ } else if (Array.isArray(value)) {
53
+ value = value.map(
54
+ (element) => (
55
+ // we don't need to escape a RegExp pattern, only escape strings
56
+ `(?:${element instanceof RegExp ? element.source : clean(element.toString(), opts)})`
57
+ )
58
+ ).join(opts.delimiter);
59
+ } else if (value instanceof RegExp) {
60
+ } else {
61
+ throw new TypeError(`value ${value} must be of type Pattern`);
62
+ }
63
+ return new RegExp(value, opts.flags);
64
+ }
65
+
66
+ // ../javascript/src/patterns.ts
67
+ var ipv4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|\d)\.?){4}$/;
68
+ var v6segment = "[a-fA-F\\d]{1,4}";
69
+ var ipv6 = toRegExp(
70
+ `(?:(?:${v6segment}:){7}(?:${v6segment}|:)|(?:${v6segment}:){6}(?:${ipv4}|:${v6segment}|:)|(?:${v6segment}:){5}(?::${ipv4}|(?::${v6segment}){1,2}|:)| (?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${ipv4}|(?::${v6segment}){1,3}|:)| (?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${ipv4}|(?::${v6segment}){1,4}|:)|(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${ipv4}|(?::${v6segment}){1,5}|:)|(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${ipv4}|(?::${v6segment}){1,6}|:)|(?::(?:(?::${v6segment}){0,5}:${ipv4}|(?::${v6segment}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?`,
71
+ { removeComments: false }
72
+ );
73
+ var ip = toRegExp([ipv4, ipv6], { delimiter: "|" });
74
+ var rootDomain = /^([\dA-Za-z][\dA-Za-z-]{2,62})\.(\w{2,3})(?:\.([A-Za-z]{2}))?$/;
75
+ var domain = toRegExp(
76
+ [
77
+ // subdomain
78
+ // todo: RegExp captures the latest group match only, instead of capturing all of the repeating patterns
79
+ // https://stackoverflow.com/a/37004214/12577650
80
+ /^((?:([\dA-Za-z][\dA-Za-z-]{0,62})+\.)*)/,
81
+ // remove the first '^' from '^---' or '(?:^---)'
82
+ rootDomain.source.replace("^", "")
83
+ ],
84
+ { delimiter: "" }
85
+ );
86
+ var email = toRegExp([/^([a-z]+\w+)@/, domain.source.replace("^", "")], {
87
+ delimiter: ""
88
+ });
89
+ var unallowedUrlChars = ` "'\`
90
+ <>[\\]`;
91
+ var tdl = "com|net|org";
92
+ var link = toRegExp(
93
+ `((?:ftp|https?://[^${unallowedUrlChars}]+)|(?:[^${unallowedUrlChars}\\/]+\\.(?:${tdl})(?:\\.[a-z]{2}){0,1}))(?::d+)?(?:/[^${unallowedUrlChars}]+)*`,
94
+ { flags: "gi" }
95
+ );
96
+ var plainLink = toRegExp(
97
+ [
98
+ link,
99
+ // doesn't followed by '*</a>', i.e: doesn't exist inside <a> tag (plain links only)
100
+ // https://stackoverflow.com/a/68188492/12577650
101
+ `(?![^<]*</a>)`
102
+ ],
103
+ { delimiter: "" }
104
+ );
105
+
106
+ // src/index.ts
107
+ var src_default = class {
108
+ storage;
109
+ bucket;
110
+ rootPath;
111
+ /**
112
+ * creates a new bucket
113
+ *
114
+ * @function constructor
115
+ * @param options
116
+ * @param bucket
117
+ */
118
+ // todo: if(bucket instanceof admin.Bucket)this.bucket=bucket
119
+ // constructor();
120
+ constructor(options) {
121
+ let opts = { ...options };
122
+ if (!opts.keyFile && !opts.keyFilename && !opts.credentials && process.env.gcloud_service_account_storage) {
123
+ opts.credentials = JSON.parse(process.env.gcloud_service_account_storage);
124
+ }
125
+ this.storage = new Storage(opts);
126
+ if (opts.bucket.includes("/")) {
127
+ let parts = opts.bucket.split("/");
128
+ opts.bucket = parts.shift();
129
+ this.rootPath = parts.join("/");
130
+ }
131
+ this.bucket = this.storage.bucket(opts.bucket);
132
+ }
133
+ /**
134
+ * uploads a file to the current bucket
135
+ *
136
+ * @function upload
137
+ * @param file file path
138
+ * @param path
139
+ * @param options UploadOptions object or destination path as string
140
+ * @returns Promise<UploadResponse>; //UploadResponse=[File, API request]
141
+ */
142
+ // todo: upload / download a folder
143
+ upload(path, options) {
144
+ let opts = {
145
+ ...typeof options === "string" ? { destination: options } : options || {}
146
+ };
147
+ if (this.rootPath && opts?.destination) {
148
+ opts.destination = `${this.rootPath}/${opts.destination}`;
149
+ }
150
+ return this.bucket.upload(path.toString(), opts);
151
+ }
152
+ /**
153
+ * downloads a file
154
+ *
155
+ * @function download
156
+ * @param file file path
157
+ * @param options DownloadOptions object or destination as string
158
+ * @returns Promise that resolves to:
159
+ * - void: if options.destination used
160
+ * - Buffer: if options.encoding is undefined
161
+ * - Array or plain object: if the file is json
162
+ * - string: otherwise
163
+ */
164
+ // todo: if(!options.destination)return th content as Promise<Buffer | ...>
165
+ // otherwise write the content into a local destination and return boolean
166
+ download(file, options) {
167
+ if (typeof file === "string" || file instanceof Buffer || file instanceof URL) {
168
+ file = this.bucket.file(
169
+ this.rootPath ? `${this.rootPath}/${file.toString()}` : file.toString()
170
+ );
171
+ }
172
+ let opts = Object.assign(
173
+ { encoding: null },
174
+ typeof options === "string" ? { destination: options } : options || {}
175
+ );
176
+ if (opts.destination) {
177
+ mkdirSync(dirname(opts.destination), { recursive: true });
178
+ }
179
+ return file.download({ ...opts }).then((result) => {
180
+ if (opts.destination) {
181
+ return;
182
+ }
183
+ let data = result[0];
184
+ if (opts.encoding === void 0) {
185
+ return data;
186
+ }
187
+ let dataString = data.toString();
188
+ try {
189
+ return file.name.slice(-5) === ".json" ? JSON.parse(stripJsonComments(dataString)) : dataString;
190
+ } catch {
191
+ return dataString;
192
+ }
193
+ });
194
+ }
195
+ /**
196
+ * download all files from a directory that match the provided filter
197
+ *
198
+ * @param destination the local path to download the files to
199
+ * @param directory the directory to be downloaded
200
+ * @param filter a pattern or function to filter the files to be downloaded
201
+ * @param options
202
+ * @param options.start download all files starting from the specified one (paginating behavior) (default is the first file)
203
+ * @param options.end download all files until the specified file (default is the last file)
204
+ * @returns a map of {file: result}
205
+ */
206
+ downloadAll(destination, directory, filter, options = {}) {
207
+ options = Object.assign({ start: 0, end: void 0 }, options || {});
208
+ let results = {};
209
+ if (!filter) {
210
+ filter = (file) => true;
211
+ } else if (filter instanceof RegExp) {
212
+ filter = (file) => filter.test(file);
213
+ }
214
+ if (this.rootPath) {
215
+ directory = `${this.rootPath}/${directory}`;
216
+ }
217
+ return this.bucket.getFiles({ prefix: directory?.toString() }).then((files) => files[0].filter((file) => filter(file.name))).then(
218
+ (files) => Promise.all(
219
+ files.slice(options.start, options.end).map(
220
+ (file) => this.download(file, {
221
+ destination: `${destination.toString()}/${file.name}`
222
+ }).then((result) => {
223
+ results[file.name] = true;
224
+ }).catch((error) => {
225
+ results[file.name] = false;
226
+ })
227
+ )
228
+ ).then(() => results)
229
+ );
230
+ }
231
+ /**
232
+ * writes a content to a file in the bucket
233
+ *
234
+ * @param path bucket path
235
+ * @param content the content to be written. if no content provided, an empty file is created
236
+ * @param options
237
+ * @returns the original content
238
+ */
239
+ write(path, content = "", options) {
240
+ if (this.rootPath) {
241
+ path = `${this.rootPath}/${path}`;
242
+ }
243
+ return this.bucket.file(path.toString()).save(
244
+ ["array", "object"].includes(objectType(content)) ? JSON.stringify(content) : content,
245
+ options
246
+ ).then(() => content);
247
+ }
248
+ // eslint-disable-next-line no-secrets/no-secrets
249
+ // https://stackoverflow.com/a/64539948/12577650
250
+ delete(path, options) {
251
+ if (this.rootPath) {
252
+ path = `${this.rootPath}/${path}`;
253
+ }
254
+ return this.bucket.file(path.toString()).delete(options);
255
+ }
256
+ /**
257
+ * check if a file exists in the bucket
258
+ * this method works with files only, not folders
259
+ * folders doesn't actually exist
260
+ * https://cloud.google.com/storage/docs/folders
261
+ *
262
+ * @param path file path
263
+ * @param options
264
+ * @returns boolean
265
+ */
266
+ exists(path, options) {
267
+ if (this.rootPath) {
268
+ path = `/${this.rootPath}/${path}`;
269
+ }
270
+ return this.bucket.file(path.toString()).exists(options).then((result) => result[0]);
271
+ }
272
+ /**
273
+ * create a new bucket, and optionally add labels to it
274
+ * add the desired labels as key-value pairs to metaData.labels
275
+ * https://cloud.google.com/storage/docs/using-bucket-labels#storage-modify-bucket-label-nodejs
276
+ *
277
+ * @param bucketName
278
+ * @param metaData
279
+ * @returns
280
+ */
281
+ create(bucketName, metaData) {
282
+ let { labels, ...meta } = metaData || {};
283
+ return this.storage.createBucket(bucketName, meta).then((result) => {
284
+ this.bucket.name = bucketName;
285
+ return labels ? this.bucket.setLabels(labels).then(() => result) : result;
286
+ });
287
+ }
288
+ // todo: read(file:string):Buffer
289
+ // todo: delete folder
290
+ };
291
+ export {
292
+ src_default as default
293
+ };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@engineers/gcloud-storage",
3
+ "version": "0.0.0-temp",
4
+ "type": "module",
5
+ "private": false,
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/its-dibo/dibo.git"
9
+ },
10
+ "homepage": "https://github.com/its-dibo/dibo#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/its-dibo/dibo/issues",
13
+ "email": "sh.eldeeb.2010+github@gmail.com"
14
+ },
15
+ "license": "MIT",
16
+ "author": "Sherif Eldeeb <sh.eldeeb.2010+github@gmail.com> (https://github.com/its-dibo)",
17
+ "funding": [
18
+ {
19
+ "type": "paypal",
20
+ "url": "https://paypal.me/group99001"
21
+ },
22
+ {
23
+ "type": "patreon",
24
+ "url": "https://www.patreon.com/GoogleDev"
25
+ }
26
+ ],
27
+ "description": "google cloud storage",
28
+ "dependencies": {
29
+ "@google-cloud/storage": "^6.10.1"
30
+ },
31
+ "imports": {
32
+ "#*": "./*"
33
+ }
34
+ }