@vtex/api 1.9.3 → 1.9.4

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 (76) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/lib/Apps.d.ts +66 -0
  3. package/lib/Apps.js +211 -0
  4. package/lib/Billing.d.ts +18 -0
  5. package/lib/Billing.js +27 -0
  6. package/lib/Builder.d.ts +40 -0
  7. package/lib/Builder.js +80 -0
  8. package/lib/Events.d.ts +6 -0
  9. package/lib/Events.js +19 -0
  10. package/lib/HttpClient/context.d.ts +9 -0
  11. package/lib/HttpClient/context.js +2 -0
  12. package/lib/HttpClient/index.d.ts +92 -0
  13. package/lib/HttpClient/index.js +121 -0
  14. package/lib/HttpClient/middlewares/cache.d.ts +16 -0
  15. package/lib/HttpClient/middlewares/cache.js +85 -0
  16. package/lib/HttpClient/middlewares/metrics.d.ts +3 -0
  17. package/lib/HttpClient/middlewares/metrics.js +41 -0
  18. package/lib/HttpClient/middlewares/notFound.d.ts +7 -0
  19. package/lib/HttpClient/middlewares/notFound.js +28 -0
  20. package/lib/HttpClient/middlewares/recorder.d.ts +3 -0
  21. package/lib/HttpClient/middlewares/recorder.js +26 -0
  22. package/lib/HttpClient/middlewares/request.d.ts +3 -0
  23. package/lib/HttpClient/middlewares/request.js +39 -0
  24. package/lib/ID.d.ts +23 -0
  25. package/lib/ID.js +46 -0
  26. package/lib/IODataSource.d.ts +23 -0
  27. package/lib/IODataSource.js +43 -0
  28. package/lib/Logger.d.ts +20 -0
  29. package/lib/Logger.js +62 -0
  30. package/lib/Metadata.d.ts +27 -0
  31. package/lib/Metadata.js +53 -0
  32. package/lib/Registry.d.ts +52 -0
  33. package/lib/Registry.js +112 -0
  34. package/lib/Router.d.ts +35 -0
  35. package/lib/Router.js +52 -0
  36. package/lib/VBase.d.ts +40 -0
  37. package/lib/VBase.js +82 -0
  38. package/lib/Workspaces.d.ts +17 -0
  39. package/lib/Workspaces.js +39 -0
  40. package/lib/caches/CacheLayer.d.ts +7 -0
  41. package/lib/caches/CacheLayer.js +2 -0
  42. package/lib/caches/DiskCache.d.ts +17 -0
  43. package/lib/caches/DiskCache.js +75 -0
  44. package/lib/caches/LRUCache.d.ts +16 -0
  45. package/lib/caches/LRUCache.js +49 -0
  46. package/lib/caches/LRUDiskCache.d.ts +21 -0
  47. package/lib/caches/LRUDiskCache.js +132 -0
  48. package/lib/caches/MultilayeredCache.d.ts +14 -0
  49. package/lib/caches/MultilayeredCache.js +76 -0
  50. package/lib/caches/index.d.ts +6 -0
  51. package/lib/caches/index.js +9 -0
  52. package/lib/caches/typings.d.ts +48 -0
  53. package/lib/caches/typings.js +2 -0
  54. package/lib/constants.d.ts +1 -0
  55. package/lib/constants.js +3 -0
  56. package/lib/index.d.ts +19 -0
  57. package/lib/index.js +21 -0
  58. package/lib/metrics/metricsAccumulator.d.ts +27 -0
  59. package/lib/metrics/metricsAccumulator.js +80 -0
  60. package/lib/metrics/metricsLogger.d.ts +6 -0
  61. package/lib/metrics/metricsLogger.js +2 -0
  62. package/lib/responses.d.ts +95 -0
  63. package/lib/responses.js +2 -0
  64. package/lib/runtime.d.ts +27 -0
  65. package/lib/runtime.js +2 -0
  66. package/lib/utils/AppId.d.ts +19 -0
  67. package/lib/utils/AppId.js +42 -0
  68. package/lib/utils/Time.d.ts +4 -0
  69. package/lib/utils/Time.js +7 -0
  70. package/lib/utils/index.d.ts +2 -0
  71. package/lib/utils/index.js +7 -0
  72. package/lib/utils/json.d.ts +5 -0
  73. package/lib/utils/json.js +18 -0
  74. package/lib/utils/log.d.ts +3 -0
  75. package/lib/utils/log.js +20 -0
  76. package/package.json +1 -1
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const IODataSource_1 = require("./IODataSource");
4
+ const appId = process.env.VTEX_APP_ID;
5
+ const [runningAppName] = appId ? appId.split('@') : [''];
6
+ const routes = {
7
+ Bucket: (bucket) => `/buckets/${runningAppName}/${bucket}`,
8
+ Metadata: (bucket) => `${routes.Bucket(bucket)}/metadata`,
9
+ MetadataKey: (bucket, key) => `${routes.Metadata(bucket)}/${key}`,
10
+ };
11
+ class Metadata extends IODataSource_1.IODataSource {
12
+ constructor(context, options = {}) {
13
+ super(context, options);
14
+ this.service = 'router';
15
+ this.httpClientFactory = IODataSource_1.forWorkspace;
16
+ this.getBuckets = (bucket) => {
17
+ return this.http.get(routes.Bucket(bucket));
18
+ };
19
+ this.list = (bucket, includeValue, limit, nextMarker) => {
20
+ const query = { value: includeValue, _limit: 10 };
21
+ if (limit && limit > 0) {
22
+ query._limit = limit;
23
+ }
24
+ if (nextMarker) {
25
+ query._marker = nextMarker;
26
+ }
27
+ return this.http.get(routes.Metadata(bucket), { params: query });
28
+ };
29
+ this.listAll = (bucket, includeValue) => {
30
+ const query = { value: includeValue, _limit: 1000 };
31
+ return this.http.get(routes.Metadata(bucket), { params: query });
32
+ };
33
+ this.get = (bucket, key) => {
34
+ return this.http.get(routes.MetadataKey(bucket, key));
35
+ };
36
+ this.save = (bucket, key, data) => {
37
+ return this.http.put(routes.MetadataKey(bucket, key), data);
38
+ };
39
+ this.saveAll = (bucket, data) => {
40
+ return this.http.put(routes.Metadata(bucket), data);
41
+ };
42
+ this.delete = (bucket, key) => {
43
+ return this.http.delete(routes.MetadataKey(bucket, key));
44
+ };
45
+ this.deleteAll = (bucket) => {
46
+ return this.http.delete(routes.Metadata(bucket));
47
+ };
48
+ if (runningAppName === '') {
49
+ throw new Error(`Invalid path to access Metadata. Variable VTEX_APP_ID is not available.`);
50
+ }
51
+ }
52
+ }
53
+ exports.Metadata = Metadata;
@@ -0,0 +1,52 @@
1
+ /// <reference types="node" />
2
+ import { IncomingMessage } from 'http';
3
+ import { Readable, Writable } from 'stream';
4
+ import { ZlibOptions } from 'zlib';
5
+ import { HttpClientFactory, IODataSource } from './IODataSource';
6
+ import { AppBundlePublished, AppFilesList, AppManifest } from './responses';
7
+ export declare class Registry extends IODataSource {
8
+ protected httpClientFactory: HttpClientFactory;
9
+ protected service: string;
10
+ publishApp: (files: File[], tag?: string | undefined, { zlib }?: ZipOptions) => Promise<AppBundlePublished>;
11
+ listApps: () => Promise<RegistryAppsList>;
12
+ listVersionsByApp: (app: string) => Promise<RegistryAppVersionsList>;
13
+ deprecateApp: (app: string, version: string) => Promise<void>;
14
+ getAppManifest: (app: string, version: string, opts?: AppsManifestOptions | undefined) => Promise<AppManifest>;
15
+ listAppFiles: (app: string, version: string, opts?: ListAppFilesOptions | undefined) => Promise<AppFilesList>;
16
+ getAppFile: (app: string, version: string, path: string) => Promise<{
17
+ data: Buffer;
18
+ headers: any;
19
+ }>;
20
+ getAppFileStream: (app: string, version: string, path: string) => Promise<IncomingMessage>;
21
+ getAppBundle: (app: string, version: string, bundlePath: string, generatePackageJson: boolean) => Promise<Readable>;
22
+ unpackAppBundle: (app: string, version: string, bundlePath: string, unpackPath: string, generatePackageJson: boolean) => Promise<Writable>;
23
+ resolveDependenciesWithManifest: (manifest: AppManifest, filter?: string) => Promise<Record<string, string[]>>;
24
+ }
25
+ interface ZipOptions {
26
+ zlib?: ZlibOptions;
27
+ }
28
+ export interface AppsManifestOptions {
29
+ resolveDeps: boolean;
30
+ }
31
+ export interface ListAppFilesOptions {
32
+ prefix: string;
33
+ }
34
+ export interface RegistryAppsListItem {
35
+ partialIdentifier: string;
36
+ location: string;
37
+ }
38
+ export interface RegistryAppsList {
39
+ data: RegistryAppsListItem[];
40
+ }
41
+ export interface RegistryAppVersionsListItem {
42
+ versionIdentifier: string;
43
+ location: string;
44
+ }
45
+ export interface RegistryAppVersionsList {
46
+ data: RegistryAppVersionsListItem[];
47
+ }
48
+ export interface File {
49
+ path: string;
50
+ content: any;
51
+ }
52
+ export {};
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ const archiver = require("archiver");
12
+ const qs_1 = require("qs");
13
+ const tar_fs_1 = require("tar-fs");
14
+ const zlib_1 = require("zlib");
15
+ const constants_1 = require("./constants");
16
+ const HttpClient_1 = require("./HttpClient");
17
+ const IODataSource_1 = require("./IODataSource");
18
+ const EMPTY_OBJECT = {};
19
+ const routes = {
20
+ App: (app) => `${routes.Registry}/${app}`,
21
+ AppBundle: (app, version, path) => `${routes.AppVersion(app, version)}/bundle/${path}`,
22
+ AppFile: (app, version, path) => `${routes.AppFiles(app, version)}/${path}`,
23
+ AppFiles: (app, version) => `${routes.AppVersion(app, version)}/files`,
24
+ AppVersion: (app, version) => `${routes.App(app)}/${version}`,
25
+ Publish: '/v2/registry',
26
+ Registry: '/registry',
27
+ ResolveDependenciesWithManifest: '/v2/registry/_resolve',
28
+ };
29
+ const forWorkspaceMaster = ({ service, context, options }) => (service && context)
30
+ ? HttpClient_1.HttpClient.forWorkspace(service, Object.assign({}, context, { workspace: constants_1.DEFAULT_WORKSPACE }), options || {})
31
+ : undefined;
32
+ const paramsSerializer = (params) => {
33
+ return qs_1.stringify(params, { arrayFormat: 'repeat' });
34
+ };
35
+ class Registry extends IODataSource_1.IODataSource {
36
+ constructor() {
37
+ super(...arguments);
38
+ this.httpClientFactory = forWorkspaceMaster;
39
+ this.service = 'apps';
40
+ this.publishApp = (files, tag, { zlib } = {}) => __awaiter(this, void 0, void 0, function* () {
41
+ if (!(files[0] && files[0].path && files[0].content)) {
42
+ throw new Error('Argument files must be an array of {path, content}, where content can be a String, a Buffer or a ReadableStream.');
43
+ }
44
+ const indexOfManifest = files.findIndex(({ path }) => path === 'manifest.json');
45
+ if (indexOfManifest === -1) {
46
+ throw new Error('No manifest.json file found in files.');
47
+ }
48
+ const zip = archiver('zip', { zlib });
49
+ // Throw stream errors so they reject the promise chain.
50
+ zip.on('error', (e) => {
51
+ throw e;
52
+ });
53
+ const request = this.http.post(routes.Publish, zip, {
54
+ headers: { 'Content-Type': 'application/zip' },
55
+ params: tag ? { tag } : EMPTY_OBJECT,
56
+ });
57
+ files.forEach(({ content, path }) => zip.append(content, { name: path }));
58
+ const finalize = zip.finalize();
59
+ try {
60
+ const [response] = yield Promise.all([request, finalize]);
61
+ response.bundleSize = zip.pointer();
62
+ return response;
63
+ }
64
+ catch (e) {
65
+ e.bundleSize = zip.pointer();
66
+ throw e;
67
+ }
68
+ });
69
+ this.listApps = () => {
70
+ return this.http.get(routes.Registry);
71
+ };
72
+ this.listVersionsByApp = (app) => {
73
+ return this.http.get(routes.App(app));
74
+ };
75
+ this.deprecateApp = (app, version) => {
76
+ return this.http.patch(routes.AppVersion(app, version), { deprecated: true });
77
+ };
78
+ this.getAppManifest = (app, version, opts) => {
79
+ return this.http.get(routes.AppVersion(app, version), { params: opts });
80
+ };
81
+ this.listAppFiles = (app, version, opts) => {
82
+ return this.http.get(routes.AppFiles(app, version), { params: opts });
83
+ };
84
+ this.getAppFile = (app, version, path) => {
85
+ return this.http.getBuffer(routes.AppFile(app, version, path));
86
+ };
87
+ this.getAppFileStream = (app, version, path) => {
88
+ return this.http.getStream(routes.AppFile(app, version, path));
89
+ };
90
+ this.getAppBundle = (app, version, bundlePath, generatePackageJson) => {
91
+ const params = generatePackageJson && { _packageJSONEngine: 'npm', _packageJSONFilter: 'vtex.render-builder@x' };
92
+ return this.http.getStream(routes.AppBundle(app, version, bundlePath), {
93
+ headers: {
94
+ Accept: 'application/x-gzip',
95
+ 'Accept-Encoding': 'gzip',
96
+ },
97
+ params,
98
+ });
99
+ };
100
+ this.unpackAppBundle = (app, version, bundlePath, unpackPath, generatePackageJson) => {
101
+ return this.getAppBundle(app, version, bundlePath, generatePackageJson)
102
+ .then(stream => stream
103
+ .pipe(zlib_1.createGunzip())
104
+ .pipe(tar_fs_1.extract(unpackPath)));
105
+ };
106
+ this.resolveDependenciesWithManifest = (manifest, filter = '') => {
107
+ const params = { filter };
108
+ return this.http.post(routes.ResolveDependenciesWithManifest, manifest, { params, paramsSerializer });
109
+ };
110
+ }
111
+ }
112
+ exports.Registry = Registry;
@@ -0,0 +1,35 @@
1
+ import { InstanceOptions, IOContext } from './HttpClient';
2
+ export declare class Router {
3
+ private http;
4
+ private account;
5
+ private workspace;
6
+ constructor(ioContext: IOContext, opts?: InstanceOptions);
7
+ listAvailableIoVersions: () => Promise<AvaiableIO[]>;
8
+ getInstalledIoVersion: () => Promise<AvaiableIO>;
9
+ installIo: (version: string) => Promise<void>;
10
+ listAvailableServices: () => Promise<AvailableServices>;
11
+ getAvailableVersions: (name: string) => Promise<AvailableServiceVersions>;
12
+ listInstalledServices: () => Promise<InstalledService[]>;
13
+ installService: (name: string, version: string) => Promise<void>;
14
+ }
15
+ export interface AvaiableIO {
16
+ version: string;
17
+ tested: boolean;
18
+ services: {
19
+ [service: string]: string;
20
+ };
21
+ }
22
+ export declare type InstalledIO = AvaiableIO;
23
+ export interface AvailableServiceVersions {
24
+ versions: {
25
+ [region: string]: string[];
26
+ };
27
+ }
28
+ export interface AvailableServices {
29
+ [service: string]: AvailableServiceVersions;
30
+ }
31
+ export interface InstalledService {
32
+ name: string;
33
+ version: string;
34
+ serviceIsolation: number;
35
+ }
package/lib/Router.js ADDED
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const HttpClient_1 = require("./HttpClient");
4
+ const routes = {
5
+ AvailableIoVersions: '/_io',
6
+ AvailableServiceVersions: (service) => `${routes.AvailableServices}/${service}`,
7
+ AvailableServices: '/_services',
8
+ InstalledIoVersion: (account, workspace) => `/${account}/${workspace}/io`,
9
+ InstalledService: (account, workspace, name) => `/${routes.InstalledServices(account, workspace)}/services/${name}`,
10
+ InstalledServices: (account, workspace) => `/${account}/${workspace}/services`,
11
+ };
12
+ class Router {
13
+ constructor(ioContext, opts = {}) {
14
+ this.listAvailableIoVersions = () => {
15
+ return this.http.get(routes.AvailableIoVersions);
16
+ };
17
+ this.getInstalledIoVersion = () => {
18
+ if (!this.account || !this.workspace) {
19
+ throw new Error('Missing client parameters: {account, workspace}');
20
+ }
21
+ return this.http.get(routes.InstalledIoVersion(this.account, this.workspace));
22
+ };
23
+ this.installIo = (version) => {
24
+ if (!this.account || !this.workspace) {
25
+ throw new Error('Missing client parameters: {account, workspace}');
26
+ }
27
+ return this.http.put(routes.InstalledIoVersion(this.account, this.workspace), { version });
28
+ };
29
+ this.listAvailableServices = () => {
30
+ return this.http.get(routes.AvailableServices);
31
+ };
32
+ this.getAvailableVersions = (name) => {
33
+ return this.http.get(routes.AvailableServiceVersions(name));
34
+ };
35
+ this.listInstalledServices = () => {
36
+ if (!this.account || !this.workspace) {
37
+ throw new Error('Missing client parameters: {account, workspace}');
38
+ }
39
+ return this.http.get(routes.InstalledServices(this.account, this.workspace));
40
+ };
41
+ this.installService = (name, version) => {
42
+ if (!this.account || !this.workspace) {
43
+ throw new Error('Missing client parameters: {account, workspace}');
44
+ }
45
+ return this.http.post(routes.InstalledServices(this.account, this.workspace), { name, version });
46
+ };
47
+ this.account = ioContext.account;
48
+ this.workspace = ioContext.workspace;
49
+ this.http = HttpClient_1.HttpClient.forRoot('router', ioContext, opts);
50
+ }
51
+ }
52
+ exports.Router = Router;
package/lib/VBase.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /// <reference types="node" />
2
+ import { IncomingMessage } from 'http';
3
+ import { Readable } from 'stream';
4
+ import { InstanceOptions, IOContext } from './HttpClient';
5
+ import { IODataSource } from './IODataSource';
6
+ import { BucketMetadata, FileListItem } from './responses';
7
+ export declare class VBase extends IODataSource {
8
+ protected httpClientFactory: import("./IODataSource").HttpClientFactory;
9
+ protected service: string;
10
+ constructor(context?: IOContext, options?: InstanceOptions);
11
+ getBucket: (bucket: string) => Promise<BucketMetadata>;
12
+ resetBucket: (bucket: string) => Promise<import("./HttpClient").IOResponse<void>>;
13
+ listFiles: (bucket: string, opts?: string | VBaseOptions | undefined) => Promise<BucketFileList>;
14
+ getFile: (bucket: string, path: string) => Promise<{
15
+ data: Buffer;
16
+ headers: any;
17
+ }>;
18
+ getJSON: <T>(bucket: string, path: string, nullIfNotFound?: boolean | undefined) => Promise<T>;
19
+ getFileStream: (bucket: string, path: string) => Promise<IncomingMessage>;
20
+ saveFile: (bucket: string, path: string, stream: Readable, gzip?: boolean, ttl?: number | undefined) => Promise<void>;
21
+ saveJSON: <T>(bucket: string, path: string, data: T) => Promise<void>;
22
+ saveZippedContent: (bucket: string, path: string, stream: Readable) => Promise<void>;
23
+ deleteFile: (bucket: string, path: string) => Promise<import("./HttpClient").IOResponse<void>>;
24
+ private saveContent;
25
+ }
26
+ export interface BucketFileList {
27
+ data: FileListItem[];
28
+ next: string;
29
+ smartCacheHeaders: any;
30
+ }
31
+ export interface VBaseOptions {
32
+ prefix?: string;
33
+ _next?: string;
34
+ _limit?: number;
35
+ }
36
+ export interface VBaseSaveOptions {
37
+ gzip?: boolean;
38
+ unzip?: boolean;
39
+ ttl?: number;
40
+ }
package/lib/VBase.js ADDED
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const mime = require("mime-types");
4
+ const path_1 = require("path");
5
+ const zlib_1 = require("zlib");
6
+ const IODataSource_1 = require("./IODataSource");
7
+ const appId = process.env.VTEX_APP_ID;
8
+ const [runningAppName] = appId ? appId.split('@') : [''];
9
+ const routes = {
10
+ Bucket: (bucket) => `/buckets/${runningAppName}/${bucket}`,
11
+ File: (bucket, path) => `${routes.Bucket(bucket)}/files/${path}`,
12
+ Files: (bucket) => `${routes.Bucket(bucket)}/files`,
13
+ };
14
+ const isVBaseOptions = (opts) => {
15
+ return typeof opts !== 'string' && !(opts instanceof String);
16
+ };
17
+ class VBase extends IODataSource_1.IODataSource {
18
+ constructor(context, options = {}) {
19
+ super(context, options);
20
+ this.httpClientFactory = IODataSource_1.forWorkspace;
21
+ this.service = 'vbase';
22
+ this.getBucket = (bucket) => {
23
+ return this.http.get(routes.Bucket(bucket));
24
+ };
25
+ this.resetBucket = (bucket) => {
26
+ return this.http.delete(routes.Files(bucket));
27
+ };
28
+ this.listFiles = (bucket, opts) => {
29
+ let params = {};
30
+ if (isVBaseOptions(opts)) {
31
+ params = opts;
32
+ }
33
+ else if (opts) {
34
+ params = { prefix: opts };
35
+ }
36
+ return this.http.get(routes.Files(bucket), { params });
37
+ };
38
+ this.getFile = (bucket, path) => {
39
+ return this.http.getBuffer(routes.File(bucket, path));
40
+ };
41
+ this.getJSON = (bucket, path, nullIfNotFound) => {
42
+ return this.http.get(routes.File(bucket, path), { nullIfNotFound });
43
+ };
44
+ this.getFileStream = (bucket, path) => {
45
+ return this.http.getStream(routes.File(bucket, path));
46
+ };
47
+ this.saveFile = (bucket, path, stream, gzip = true, ttl) => {
48
+ return this.saveContent(bucket, path, stream, { gzip, ttl });
49
+ };
50
+ this.saveJSON = (bucket, path, data) => {
51
+ const headers = { 'Content-Type': 'application/json' };
52
+ return this.http.put(routes.File(bucket, path), data, { headers });
53
+ };
54
+ this.saveZippedContent = (bucket, path, stream) => {
55
+ return this.saveContent(bucket, path, stream, { unzip: true });
56
+ };
57
+ this.deleteFile = (bucket, path) => {
58
+ return this.http.delete(routes.File(bucket, path));
59
+ };
60
+ this.saveContent = (bucket, path, stream, opts = {}) => {
61
+ if (!stream.pipe || !stream.on) {
62
+ throw new Error(`Argument stream must be a readable stream`);
63
+ }
64
+ const params = opts.unzip ? { unzip: opts.unzip } : {};
65
+ const headers = {};
66
+ let finalStream = stream;
67
+ headers['Content-Type'] = mime.contentType(path_1.basename(path)) || 'application/octet-stream';
68
+ if (opts.gzip) {
69
+ headers['Content-Encoding'] = 'gzip';
70
+ finalStream = stream.pipe(zlib_1.createGzip());
71
+ }
72
+ if (opts.ttl && Number.isInteger(opts.ttl)) {
73
+ headers['X-VTEX-TTL'] = opts.ttl;
74
+ }
75
+ return this.http.put(routes.File(bucket, path), finalStream, { headers, params });
76
+ };
77
+ if (runningAppName === '') {
78
+ throw new Error(`Invalid path to access Vbase. Variable VTEX_APP_ID is not available.`);
79
+ }
80
+ }
81
+ }
82
+ exports.VBase = VBase;
@@ -0,0 +1,17 @@
1
+ import { IODataSource } from './IODataSource';
2
+ export declare class Workspaces extends IODataSource {
3
+ protected service: string;
4
+ protected httpClientFactory: import("./IODataSource").HttpClientFactory;
5
+ list: (account: string) => Promise<WorkspaceMetadata[]>;
6
+ get: (account: string, workspace: string) => Promise<WorkspaceMetadata>;
7
+ set: (account: string, workspace: string, metadata: Partial<WorkspaceMetadata>) => Promise<void>;
8
+ create: (account: string, workspace: string) => Promise<void>;
9
+ delete: (account: string, workspace: string) => Promise<import("./HttpClient").IOResponse<void>>;
10
+ reset: (account: string, workspace: string, metadata?: Partial<WorkspaceMetadata>) => Promise<void>;
11
+ promote: (account: string, workspace: string) => Promise<void>;
12
+ }
13
+ export interface WorkspaceMetadata {
14
+ name: string;
15
+ weight: number;
16
+ production: boolean;
17
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("./constants");
4
+ const IODataSource_1 = require("./IODataSource");
5
+ const routes = {
6
+ Account: (account) => `/${account}`,
7
+ Promote: (account) => `${routes.Workspace(account, constants_1.DEFAULT_WORKSPACE)}/_promote`,
8
+ Workspace: (account, workspace) => `${routes.Account(account)}/${workspace}`,
9
+ };
10
+ class Workspaces extends IODataSource_1.IODataSource {
11
+ constructor() {
12
+ super(...arguments);
13
+ this.service = 'router';
14
+ this.httpClientFactory = IODataSource_1.forRoot;
15
+ this.list = (account) => {
16
+ return this.http.get(routes.Account(account));
17
+ };
18
+ this.get = (account, workspace) => {
19
+ return this.http.get(routes.Workspace(account, workspace));
20
+ };
21
+ this.set = (account, workspace, metadata) => {
22
+ return this.http.put(routes.Workspace(account, workspace), metadata);
23
+ };
24
+ this.create = (account, workspace) => {
25
+ return this.http.post(routes.Account(account), { name: workspace });
26
+ };
27
+ this.delete = (account, workspace) => {
28
+ return this.http.delete(routes.Workspace(account, workspace));
29
+ };
30
+ this.reset = (account, workspace, metadata = {}) => {
31
+ const params = { reset: true };
32
+ return this.http.put(routes.Workspace(account, workspace), metadata, { params });
33
+ };
34
+ this.promote = (account, workspace) => {
35
+ return this.http.put(routes.Promote(account), { workspace });
36
+ };
37
+ }
38
+ }
39
+ exports.Workspaces = Workspaces;
@@ -0,0 +1,7 @@
1
+ import { FetchResult } from './typings';
2
+ export interface CacheLayer<K, V> {
3
+ get(key: K, fetcher?: () => Promise<FetchResult<V>>): Promise<V | void> | V | void;
4
+ has(key: K): Promise<boolean> | boolean;
5
+ set(key: K, value: V, maxAge?: number | void): Promise<boolean> | boolean;
6
+ getStats?(name?: string): any;
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,17 @@
1
+ import { CacheLayer } from './CacheLayer';
2
+ import { DiskStats } from './typings';
3
+ import { outputJSON, readJSON } from 'fs-extra';
4
+ export declare class DiskCache<V> implements CacheLayer<string, V> {
5
+ private cachePath;
6
+ private readFile;
7
+ private writeFile;
8
+ private hits;
9
+ private total;
10
+ private lock;
11
+ constructor(cachePath: string, readFile?: typeof readJSON, writeFile?: typeof outputJSON);
12
+ has: (key: string) => boolean;
13
+ getStats: (name?: string) => DiskStats;
14
+ get: (key: string) => Promise<void | V>;
15
+ set: (key: string, value: V) => Promise<boolean>;
16
+ private getPathKey;
17
+ }
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ const fs_extra_1 = require("fs-extra");
12
+ const path_1 = require("path");
13
+ const ReadWriteLock = require("rwlock");
14
+ class DiskCache {
15
+ constructor(cachePath, readFile = fs_extra_1.readJSON, writeFile = fs_extra_1.outputJSON) {
16
+ this.cachePath = cachePath;
17
+ this.readFile = readFile;
18
+ this.writeFile = writeFile;
19
+ this.hits = 0;
20
+ this.total = 0;
21
+ this.has = (key) => {
22
+ const pathKey = this.getPathKey(key);
23
+ return fs_extra_1.pathExistsSync(pathKey);
24
+ };
25
+ this.getStats = (name = 'disk-cache') => {
26
+ const stats = {
27
+ hits: this.hits,
28
+ name,
29
+ total: this.total,
30
+ };
31
+ this.hits = 0;
32
+ this.total = 0;
33
+ return stats;
34
+ };
35
+ this.get = (key) => __awaiter(this, void 0, void 0, function* () {
36
+ const pathKey = this.getPathKey(key);
37
+ this.total += 1;
38
+ const data = yield new Promise(resolve => {
39
+ this.lock.readLock(key, (release) => __awaiter(this, void 0, void 0, function* () {
40
+ try {
41
+ const fileData = yield this.readFile(pathKey);
42
+ release();
43
+ this.hits += 1;
44
+ resolve(fileData);
45
+ }
46
+ catch (e) {
47
+ release();
48
+ resolve(undefined);
49
+ }
50
+ }));
51
+ });
52
+ return data;
53
+ });
54
+ this.set = (key, value) => __awaiter(this, void 0, void 0, function* () {
55
+ const pathKey = this.getPathKey(key);
56
+ const failure = yield new Promise(resolve => {
57
+ this.lock.writeLock(key, (release) => __awaiter(this, void 0, void 0, function* () {
58
+ try {
59
+ const writePromise = yield this.writeFile(pathKey, value);
60
+ release();
61
+ resolve(writePromise);
62
+ }
63
+ catch (e) {
64
+ release();
65
+ resolve(true);
66
+ }
67
+ }));
68
+ });
69
+ return !failure;
70
+ });
71
+ this.getPathKey = (key) => path_1.join(this.cachePath, key);
72
+ this.lock = new ReadWriteLock();
73
+ }
74
+ }
75
+ exports.DiskCache = DiskCache;
@@ -0,0 +1,16 @@
1
+ import * as LRU from 'lru-cache';
2
+ import { CacheLayer } from './CacheLayer';
3
+ import { FetchResult, LRUStats } from './typings';
4
+ export declare class LRUCache<K, V> implements CacheLayer<K, V> {
5
+ private multilayer;
6
+ private storage;
7
+ private hits;
8
+ private total;
9
+ private disposed;
10
+ constructor(options: LRU.Options);
11
+ get: (key: K) => void | V;
12
+ getOrSet: (key: K, fetcher?: (() => Promise<FetchResult<V>>) | undefined) => Promise<void | V>;
13
+ set: (key: K, value: V, maxAge?: number | undefined) => boolean;
14
+ has: (key: K) => boolean;
15
+ getStats: (name?: string) => LRUStats;
16
+ }
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ const LRU = require("lru-cache");
12
+ const MultilayeredCache_1 = require("./MultilayeredCache");
13
+ class LRUCache {
14
+ constructor(options) {
15
+ this.get = (key) => {
16
+ const value = this.storage.get(key);
17
+ if (this.storage.has(key)) {
18
+ this.hits += 1;
19
+ }
20
+ this.total += 1;
21
+ return value;
22
+ };
23
+ this.getOrSet = (key, fetcher) => __awaiter(this, void 0, void 0, function* () { return this.multilayer.get(key, fetcher); });
24
+ this.set = (key, value, maxAge) => this.storage.set(key, value, maxAge);
25
+ this.has = (key) => this.storage.has(key);
26
+ this.getStats = (name = 'lru-cache') => {
27
+ const stats = {
28
+ disposedItems: this.disposed,
29
+ hitRate: this.total > 0 ? this.hits / this.total : undefined,
30
+ hits: this.hits,
31
+ itemCount: this.storage.itemCount,
32
+ length: this.storage.length,
33
+ max: this.storage.max,
34
+ name,
35
+ total: this.total,
36
+ };
37
+ this.hits = 0;
38
+ this.total = 0;
39
+ this.disposed = 0;
40
+ return stats;
41
+ };
42
+ this.hits = 0;
43
+ this.total = 0;
44
+ this.disposed = 0;
45
+ this.storage = new LRU(Object.assign({}, options, { dispose: () => this.disposed += 1 }));
46
+ this.multilayer = new MultilayeredCache_1.MultilayeredCache([this]);
47
+ }
48
+ }
49
+ exports.LRUCache = LRUCache;