node_modules ignore

This commit is contained in:
2025-05-08 23:43:47 +02:00
parent e19d52f172
commit 4574544c9f
65041 changed files with 10593536 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
import { CLIContext, type CloudCliConfig } from '../types';
declare const buildLogsServiceFactory: ({ logger }: CLIContext) => (url: string, token: string, cliConfig: CloudCliConfig) => Promise<unknown>;
export { buildLogsServiceFactory };
//# sourceMappingURL=build-logs.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"build-logs.d.ts","sourceRoot":"","sources":["../../src/services/build-logs.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAE3D,QAAA,MAAM,uBAAuB,eAAgB,UAAU,WAClC,MAAM,SAAS,MAAM,aAAa,cAAc,qBAqEpE,CAAC;AAEF,OAAO,EAAE,uBAAuB,EAAE,CAAC"}

View File

@@ -0,0 +1,67 @@
'use strict';
var EventSource = require('eventsource');
const buildLogsServiceFactory = ({ logger })=>{
return async (url, token, cliConfig)=>{
const CONN_TIMEOUT = Number(cliConfig.buildLogsConnectionTimeout);
const MAX_RETRIES = Number(cliConfig.buildLogsMaxRetries);
return new Promise((resolve, reject)=>{
let timeoutId = null;
let retries = 0;
const connect = (url)=>{
const spinner = logger.spinner('Connecting to server to get build logs');
spinner.start();
const es = new EventSource(`${url}`, {
headers: {
Authorization: `Bearer ${token}`
}
});
const clearExistingTimeout = ()=>{
if (timeoutId) {
clearTimeout(timeoutId);
}
};
const resetTimeout = ()=>{
clearExistingTimeout();
timeoutId = setTimeout(()=>{
if (spinner.isSpinning) {
spinner.fail('We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue.');
}
es.close();
reject(new Error('Connection timed out'));
}, CONN_TIMEOUT);
};
es.onopen = resetTimeout;
es.addEventListener('finished', (event)=>{
const data = JSON.parse(event.data);
logger.log(data.msg);
es.close();
clearExistingTimeout();
resolve(null);
});
es.addEventListener('log', (event)=>{
if (spinner.isSpinning) {
spinner.succeed();
}
resetTimeout();
const data = JSON.parse(event.data);
logger.log(data.msg);
});
es.onerror = async ()=>{
retries += 1;
if (retries > MAX_RETRIES) {
spinner.fail('We were unable to connect to the server to get build logs at this time.');
es.close();
clearExistingTimeout(); // Important to clear the event loop from remaining timeout - avoid to wait for nothing while the timeout is running
reject(new Error('Max retries reached'));
}
};
};
connect(url);
});
};
};
exports.buildLogsServiceFactory = buildLogsServiceFactory;
//# sourceMappingURL=build-logs.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,65 @@
import EventSource from 'eventsource';
const buildLogsServiceFactory = ({ logger })=>{
return async (url, token, cliConfig)=>{
const CONN_TIMEOUT = Number(cliConfig.buildLogsConnectionTimeout);
const MAX_RETRIES = Number(cliConfig.buildLogsMaxRetries);
return new Promise((resolve, reject)=>{
let timeoutId = null;
let retries = 0;
const connect = (url)=>{
const spinner = logger.spinner('Connecting to server to get build logs');
spinner.start();
const es = new EventSource(`${url}`, {
headers: {
Authorization: `Bearer ${token}`
}
});
const clearExistingTimeout = ()=>{
if (timeoutId) {
clearTimeout(timeoutId);
}
};
const resetTimeout = ()=>{
clearExistingTimeout();
timeoutId = setTimeout(()=>{
if (spinner.isSpinning) {
spinner.fail('We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue.');
}
es.close();
reject(new Error('Connection timed out'));
}, CONN_TIMEOUT);
};
es.onopen = resetTimeout;
es.addEventListener('finished', (event)=>{
const data = JSON.parse(event.data);
logger.log(data.msg);
es.close();
clearExistingTimeout();
resolve(null);
});
es.addEventListener('log', (event)=>{
if (spinner.isSpinning) {
spinner.succeed();
}
resetTimeout();
const data = JSON.parse(event.data);
logger.log(data.msg);
});
es.onerror = async ()=>{
retries += 1;
if (retries > MAX_RETRIES) {
spinner.fail('We were unable to connect to the server to get build logs at this time.');
es.close();
clearExistingTimeout(); // Important to clear the event loop from remaining timeout - avoid to wait for nothing while the timeout is running
reject(new Error('Max retries reached'));
}
};
};
connect(url);
});
};
};
export { buildLogsServiceFactory };
//# sourceMappingURL=build-logs.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,96 @@
import { type AxiosResponse } from 'axios';
import type { CLIContext, CloudCliConfig, TrackPayload } from '../types';
export declare const VERSION = "v1";
export type ProjectInfo = {
id: string;
name: string;
targetEnvironment?: string;
displayName?: string;
nodeVersion?: string;
region?: string;
plan?: string;
url?: string;
};
export type EnvironmentInfo = Record<string, unknown>;
export type EnvironmentDetails = {
name: string;
hasLiveDeployment: boolean;
hasPendingDeployment: boolean;
};
export type ProjectInput = Omit<ProjectInfo, 'id'>;
export type DeployResponse = {
build_id: string;
image: string;
};
export type ListProjectsResponse = {
data: {
data: string;
};
};
export type ListEnvironmentsResponse = {
data: {
data: EnvironmentInfo[] | Record<string, never>;
};
};
export type ListLinkProjectsResponse = {
data: {
data: ProjectInfo[] | Record<string, never>;
};
};
export type ListLinkEnvironmentsResponse = {
data: {
data: EnvironmentDetails[] | Record<string, never>;
};
};
export type GetProjectResponse = {
data: {
displayName: string;
updatedAt: string;
suspendedAt?: string;
isTrial: boolean;
environments: string[];
environmentsDetails: EnvironmentDetails[];
};
metadata: {
dashboardUrls: {
project: string;
deployments: string;
};
};
};
export interface CloudApiService {
deploy(deployInput: {
filePath: string;
project: {
name: string;
targetEnvironment?: string;
};
}, { onUploadProgress, }: {
onUploadProgress: (progressEvent: {
loaded: number;
total?: number;
}) => void;
}): Promise<AxiosResponse<DeployResponse>>;
createProject(createProjectInput: ProjectInput): Promise<{
data: ProjectInput;
status: number;
}>;
getUserInfo(): Promise<AxiosResponse>;
config(): Promise<AxiosResponse<CloudCliConfig>>;
listProjects(): Promise<AxiosResponse<ListProjectsResponse>>;
listLinkProjects(): Promise<AxiosResponse<ListLinkProjectsResponse>>;
listEnvironments(project: {
name: string;
}): Promise<AxiosResponse<ListEnvironmentsResponse>>;
listLinkEnvironments(project: {
name: string;
}): Promise<AxiosResponse<ListLinkEnvironmentsResponse>>;
getProject(project: {
name: string;
}): Promise<AxiosResponse<GetProjectResponse>>;
track(event: string, payload?: TrackPayload): Promise<AxiosResponse<void>>;
}
export declare function cloudApiFactory({ logger }: {
logger: CLIContext['logger'];
}, token?: string): Promise<CloudApiService>;
//# sourceMappingURL=cli-api.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cli-api.d.ts","sourceRoot":"","sources":["../../src/services/cli-api.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAIlD,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAKzE,eAAO,MAAM,OAAO,OAAO,CAAC;AAE5B,MAAM,MAAM,WAAW,GAAG;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEtD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,iBAAiB,EAAE,OAAO,CAAC;IAC3B,oBAAoB,EAAE,OAAO,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;AAEnD,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE;QACJ,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;CACH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,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC;IAE1C,aAAa,CAAC,kBAAkB,EAAE,YAAY,GAAG,OAAO,CAAC;QACvD,IAAI,EAAE,YAAY,CAAC;QACnB,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC,CAAC;IAEH,WAAW,IAAI,OAAO,CAAC,aAAa,CAAC,CAAC;IAEtC,MAAM,IAAI,OAAO,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC;IAEjD,YAAY,IAAI,OAAO,CAAC,aAAa,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAE7D,gBAAgB,IAAI,OAAO,CAAC,aAAa,CAAC,wBAAwB,CAAC,CAAC,CAAC;IAErE,gBAAgB,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,aAAa,CAAC,wBAAwB,CAAC,CAAC,CAAC;IAE9F,oBAAoB,CAAC,OAAO,EAAE;QAC5B,IAAI,EAAE,MAAM,CAAC;KACd,GAAG,OAAO,CAAC,aAAa,CAAC,4BAA4B,CAAC,CAAC,CAAC;IAEzD,UAAU,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,aAAa,CAAC,kBAAkB,CAAC,CAAC,CAAC;IAElF,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;CAC5E;AAED,wBAAsB,eAAe,CACnC,EAAE,MAAM,EAAE,EAAE;IAAE,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,CAAA;CAAE,EAC5C,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,eAAe,CAAC,CAyK1B"}

View File

@@ -0,0 +1,146 @@
'use strict';
var axios = require('axios');
var fse = require('fs-extra');
var os = require('os');
var api = require('../config/api.js');
var local = require('../config/local.js');
var _package = require('../package.json.js');
const VERSION = 'v1';
async function cloudApiFactory({ logger }, token) {
const localConfig = await local.getLocalConfig();
const customHeaders = {
'x-device-id': localConfig.installId,
'x-app-version': _package.default.version,
'x-os-name': os.type(),
'x-os-version': os.version(),
'x-language': Intl.DateTimeFormat().resolvedOptions().locale,
'x-node-version': process.versions.node
};
const axiosCloudAPI = axios.create({
baseURL: `${api.apiConfig.apiBaseUrl}/${VERSION}`,
headers: {
'Content-Type': 'application/json',
...customHeaders
}
});
if (token) {
axiosCloudAPI.defaults.headers.Authorization = `Bearer ${token}`;
}
return {
deploy ({ filePath, project }, { onUploadProgress }) {
return axiosCloudAPI.post(`/deploy/${project.name}`, {
file: fse.createReadStream(filePath),
targetEnvironment: project.targetEnvironment
}, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress
});
},
async createProject ({ name, nodeVersion, region, plan }) {
const response = await axiosCloudAPI.post('/project', {
projectName: name,
region,
nodeVersion,
plan
});
return {
data: {
id: response.data.id,
name: response.data.name,
nodeVersion: response.data.nodeVersion,
region: response.data.region
},
status: response.status
};
},
getUserInfo () {
return axiosCloudAPI.get('/user');
},
async config () {
try {
const response = await axiosCloudAPI.get('/config');
if (response.status !== 200) {
throw new Error('Error fetching cloud CLI config from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again.");
throw error;
}
},
async listProjects () {
try {
const response = await axiosCloudAPI.get('/projects');
if (response.status !== 200) {
throw new Error('Error fetching cloud projects from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
throw error;
}
},
async listLinkProjects () {
try {
const response = await axiosCloudAPI.get('/projects-linkable');
if (response.status !== 200) {
throw new Error('Error fetching cloud projects from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
throw error;
}
},
async listEnvironments ({ name }) {
try {
const response = await axiosCloudAPI.get(`/projects/${name}/environments`);
if (response.status !== 200) {
throw new Error('Error fetching cloud environments from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
throw error;
}
},
async listLinkEnvironments ({ name }) {
try {
const response = await axiosCloudAPI.get(`/projects/${name}/environments-linkable`);
if (response.status !== 200) {
throw new Error('Error fetching cloud environments from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
throw error;
}
},
async getProject ({ name }) {
try {
const response = await axiosCloudAPI.get(`/projects/${name}`);
if (response.status !== 200) {
throw new Error("Error fetching project's details.");
}
return response;
} catch (error) {
logger.debug("🥲 Oops! There was a problem retrieving your project's details. Please try again.");
throw error;
}
},
track (event, payload = {}) {
return axiosCloudAPI.post('/track', {
event,
payload
});
}
};
}
exports.VERSION = VERSION;
exports.cloudApiFactory = cloudApiFactory;
//# sourceMappingURL=cli-api.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,143 @@
import axios from 'axios';
import fse__default from 'fs-extra';
import os from 'os';
import { apiConfig } from '../config/api.mjs';
import { getLocalConfig } from '../config/local.mjs';
import packageJson from '../package.json.mjs';
const VERSION = 'v1';
async function cloudApiFactory({ logger }, token) {
const localConfig = await getLocalConfig();
const customHeaders = {
'x-device-id': localConfig.installId,
'x-app-version': packageJson.version,
'x-os-name': os.type(),
'x-os-version': os.version(),
'x-language': Intl.DateTimeFormat().resolvedOptions().locale,
'x-node-version': process.versions.node
};
const axiosCloudAPI = axios.create({
baseURL: `${apiConfig.apiBaseUrl}/${VERSION}`,
headers: {
'Content-Type': 'application/json',
...customHeaders
}
});
if (token) {
axiosCloudAPI.defaults.headers.Authorization = `Bearer ${token}`;
}
return {
deploy ({ filePath, project }, { onUploadProgress }) {
return axiosCloudAPI.post(`/deploy/${project.name}`, {
file: fse__default.createReadStream(filePath),
targetEnvironment: project.targetEnvironment
}, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress
});
},
async createProject ({ name, nodeVersion, region, plan }) {
const response = await axiosCloudAPI.post('/project', {
projectName: name,
region,
nodeVersion,
plan
});
return {
data: {
id: response.data.id,
name: response.data.name,
nodeVersion: response.data.nodeVersion,
region: response.data.region
},
status: response.status
};
},
getUserInfo () {
return axiosCloudAPI.get('/user');
},
async config () {
try {
const response = await axiosCloudAPI.get('/config');
if (response.status !== 200) {
throw new Error('Error fetching cloud CLI config from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again.");
throw error;
}
},
async listProjects () {
try {
const response = await axiosCloudAPI.get('/projects');
if (response.status !== 200) {
throw new Error('Error fetching cloud projects from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
throw error;
}
},
async listLinkProjects () {
try {
const response = await axiosCloudAPI.get('/projects-linkable');
if (response.status !== 200) {
throw new Error('Error fetching cloud projects from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
throw error;
}
},
async listEnvironments ({ name }) {
try {
const response = await axiosCloudAPI.get(`/projects/${name}/environments`);
if (response.status !== 200) {
throw new Error('Error fetching cloud environments from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
throw error;
}
},
async listLinkEnvironments ({ name }) {
try {
const response = await axiosCloudAPI.get(`/projects/${name}/environments-linkable`);
if (response.status !== 200) {
throw new Error('Error fetching cloud environments from the server.');
}
return response;
} catch (error) {
logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
throw error;
}
},
async getProject ({ name }) {
try {
const response = await axiosCloudAPI.get(`/projects/${name}`);
if (response.status !== 200) {
throw new Error("Error fetching project's details.");
}
return response;
} catch (error) {
logger.debug("🥲 Oops! There was a problem retrieving your project's details. Please try again.");
throw error;
}
},
track (event, payload = {}) {
return axiosCloudAPI.post('/track', {
event,
payload
});
}
};
}
export { VERSION, cloudApiFactory };
//# sourceMappingURL=cli-api.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
export { cloudApiFactory } from './cli-api';
export * as local from './strapi-info-save';
export { tokenServiceFactory } from './token';
export { createLogger } from './logger';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,KAAK,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC"}

View File

@@ -0,0 +1,14 @@
'use strict';
var cliApi = require('./cli-api.js');
var strapiInfoSave = require('./strapi-info-save.js');
var token = require('./token.js');
var logger = require('./logger.js');
exports.cloudApiFactory = cliApi.cloudApiFactory;
exports.local = strapiInfoSave;
exports.tokenServiceFactory = token.tokenServiceFactory;
exports.createLogger = logger.createLogger;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;"}

View File

@@ -0,0 +1,6 @@
export { cloudApiFactory } from './cli-api.mjs';
import * as strapiInfoSave from './strapi-info-save.mjs';
export { strapiInfoSave as local };
export { tokenServiceFactory } from './token.mjs';
export { createLogger } from './logger.mjs';
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}

View File

@@ -0,0 +1,22 @@
import ora from 'ora';
import * as cliProgress from 'cli-progress';
export interface LoggerOptions {
silent?: boolean;
debug?: boolean;
timestamp?: boolean;
}
export interface Logger {
warnings: number;
errors: number;
debug: (...args: unknown[]) => void;
info: (...args: unknown[]) => void;
success: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
log: (...args: unknown[]) => void;
spinner: (text: string) => Pick<ora.Ora, 'succeed' | 'fail' | 'start' | 'text' | 'isSpinning'>;
progressBar: (totalSize: number, text: string) => Pick<cliProgress.SingleBar, 'start' | 'stop' | 'update'>;
}
declare const createLogger: (options?: LoggerOptions) => Logger;
export { createLogger };
//# sourceMappingURL=logger.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/services/logger.ts"],"names":[],"mappings":"AAGA,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,KAAK,WAAW,MAAM,cAAc,CAAC;AAE5C,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,MAAM;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IACpC,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IACnC,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IACtC,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IACnC,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IACpC,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IAClC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,YAAY,CAAC,CAAC;IAC/F,WAAW,EAAE,CACX,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,KACT,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC,CAAC;CAC/D;AAMD,QAAA,MAAM,YAAY,aAAa,aAAa,KAAQ,MAqInD,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}

View File

@@ -0,0 +1,128 @@
'use strict';
var chalk = require('chalk');
var stringify = require('fast-safe-stringify');
var ora = require('ora');
var cliProgress = require('cli-progress');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var cliProgress__namespace = /*#__PURE__*/_interopNamespaceDefault(cliProgress);
const stringifyArg = (arg)=>{
return typeof arg === 'object' ? stringify(arg) : arg;
};
const createLogger = (options = {})=>{
const { silent = false, debug = false, timestamp = true } = options;
const state = {
errors: 0,
warning: 0
};
return {
get warnings () {
return state.warning;
},
get errors () {
return state.errors;
},
async debug (...args) {
if (silent || !debug) {
return;
}
console.log(chalk.cyan(`[DEBUG]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
info (...args) {
if (silent) {
return;
}
console.info(chalk.blue(`[INFO]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
log (...args) {
if (silent) {
return;
}
console.info(chalk.blue(`${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
success (...args) {
if (silent) {
return;
}
console.info(chalk.green(`[SUCCESS]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
warn (...args) {
state.warning += 1;
if (silent) {
return;
}
console.warn(chalk.yellow(`[WARN]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
error (...args) {
state.errors += 1;
if (silent) {
return;
}
console.error(chalk.red(`[ERROR]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
// @ts-expect-error returning a subpart of ora is fine because the types tell us what is what.
spinner (text) {
if (silent) {
return {
succeed () {
return this;
},
fail () {
return this;
},
start () {
return this;
},
text: '',
isSpinning: false
};
}
return ora(text);
},
progressBar (totalSize, text) {
if (silent) {
return {
start () {
return this;
},
stop () {
return this;
},
update () {
return this;
}
};
}
const progressBar = new cliProgress__namespace.SingleBar({
format: `${text ? `${text} |` : ''}${chalk.green('{bar}')}| {percentage}%`,
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true,
forceRedraw: true
});
progressBar.start(totalSize, 0);
return progressBar;
}
};
};
exports.createLogger = createLogger;
//# sourceMappingURL=logger.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,107 @@
import chalk from 'chalk';
import stringify from 'fast-safe-stringify';
import ora from 'ora';
import * as cliProgress from 'cli-progress';
const stringifyArg = (arg)=>{
return typeof arg === 'object' ? stringify(arg) : arg;
};
const createLogger = (options = {})=>{
const { silent = false, debug = false, timestamp = true } = options;
const state = {
errors: 0,
warning: 0
};
return {
get warnings () {
return state.warning;
},
get errors () {
return state.errors;
},
async debug (...args) {
if (silent || !debug) {
return;
}
console.log(chalk.cyan(`[DEBUG]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
info (...args) {
if (silent) {
return;
}
console.info(chalk.blue(`[INFO]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
log (...args) {
if (silent) {
return;
}
console.info(chalk.blue(`${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
success (...args) {
if (silent) {
return;
}
console.info(chalk.green(`[SUCCESS]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
warn (...args) {
state.warning += 1;
if (silent) {
return;
}
console.warn(chalk.yellow(`[WARN]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
error (...args) {
state.errors += 1;
if (silent) {
return;
}
console.error(chalk.red(`[ERROR]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
},
// @ts-expect-error returning a subpart of ora is fine because the types tell us what is what.
spinner (text) {
if (silent) {
return {
succeed () {
return this;
},
fail () {
return this;
},
start () {
return this;
},
text: '',
isSpinning: false
};
}
return ora(text);
},
progressBar (totalSize, text) {
if (silent) {
return {
start () {
return this;
},
stop () {
return this;
},
update () {
return this;
}
};
}
const progressBar = new cliProgress.SingleBar({
format: `${text ? `${text} |` : ''}${chalk.green('{bar}')}| {percentage}%`,
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true,
forceRedraw: true
});
progressBar.start(totalSize, 0);
return progressBar;
}
};
};
export { createLogger };
//# sourceMappingURL=logger.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import type { CLIContext, CloudCliConfig } from '../types';
export declare function notificationServiceFactory({ logger }: CLIContext): (url: string, token: string, cliConfig: CloudCliConfig) => void;
//# sourceMappingURL=notification.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"notification.d.ts","sourceRoot":"","sources":["../../src/services/notification.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAS3D,wBAAgB,0BAA0B,CAAC,EAAE,MAAM,EAAE,EAAE,UAAU,SAClD,MAAM,SAAS,MAAM,aAAa,cAAc,UAmC9D"}

View File

@@ -0,0 +1,37 @@
'use strict';
var EventSource = require('eventsource');
function notificationServiceFactory({ logger }) {
return (url, token, cliConfig)=>{
const CONN_TIMEOUT = Number(cliConfig.notificationsConnectionTimeout);
const es = new EventSource(url, {
headers: {
Authorization: `Bearer ${token}`
}
});
let timeoutId;
const resetTimeout = ()=>{
clearTimeout(timeoutId);
timeoutId = setTimeout(()=>{
logger.log('We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment.');
es.close();
}, CONN_TIMEOUT); // 5 minutes
};
es.onopen = resetTimeout;
es.onmessage = (event)=>{
resetTimeout();
const data = JSON.parse(event.data);
if (data.message) {
logger.log(data.message);
}
// Close connection when a specific event is received
if (data.event === 'deploymentFinished' || data.event === 'deploymentFailed') {
es.close();
}
};
};
}
exports.notificationServiceFactory = notificationServiceFactory;
//# sourceMappingURL=notification.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"notification.js","sources":["../../src/services/notification.ts"],"sourcesContent":["import EventSource from 'eventsource';\nimport type { CLIContext, CloudCliConfig } from '../types';\n\ntype Event = {\n type: string;\n data: string;\n lastEventId: string;\n origin: string;\n};\n\nexport function notificationServiceFactory({ logger }: CLIContext) {\n return (url: string, token: string, cliConfig: CloudCliConfig) => {\n const CONN_TIMEOUT = Number(cliConfig.notificationsConnectionTimeout);\n\n const es = new EventSource(url, {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n let timeoutId: NodeJS.Timeout;\n\n const resetTimeout = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n logger.log(\n 'We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment.'\n );\n es.close();\n }, CONN_TIMEOUT); // 5 minutes\n };\n\n es.onopen = resetTimeout;\n es.onmessage = (event: Event) => {\n resetTimeout();\n const data = JSON.parse(event.data);\n\n if (data.message) {\n logger.log(data.message);\n }\n\n // Close connection when a specific event is received\n if (data.event === 'deploymentFinished' || data.event === 'deploymentFailed') {\n es.close();\n }\n };\n };\n}\n"],"names":["notificationServiceFactory","logger","url","token","cliConfig","CONN_TIMEOUT","Number","notificationsConnectionTimeout","es","EventSource","headers","Authorization","timeoutId","resetTimeout","clearTimeout","setTimeout","log","close","onopen","onmessage","event","data","JSON","parse","message"],"mappings":";;;;AAUO,SAASA,0BAAAA,CAA2B,EAAEC,MAAM,EAAc,EAAA;IAC/D,OAAO,CAACC,KAAaC,KAAeC,EAAAA,SAAAA,GAAAA;QAClC,MAAMC,YAAAA,GAAeC,MAAOF,CAAAA,SAAAA,CAAUG,8BAA8B,CAAA;QAEpE,MAAMC,EAAAA,GAAK,IAAIC,WAAAA,CAAYP,GAAK,EAAA;YAC9BQ,OAAS,EAAA;AACPC,gBAAAA,aAAAA,EAAe,CAAC,OAAO,EAAER,KAAAA,CAAM;AACjC;AACF,SAAA,CAAA;QACA,IAAIS,SAAAA;AAEJ,QAAA,MAAMC,YAAe,GAAA,IAAA;YACnBC,YAAaF,CAAAA,SAAAA,CAAAA;AACbA,YAAAA,SAAAA,GAAYG,UAAW,CAAA,IAAA;AACrBd,gBAAAA,MAAAA,CAAOe,GAAG,CACR,6HAAA,CAAA;AAEFR,gBAAAA,EAAAA,CAAGS,KAAK,EAAA;AACV,aAAA,EAAGZ;AACL,SAAA;AAEAG,QAAAA,EAAAA,CAAGU,MAAM,GAAGL,YAAAA;QACZL,EAAGW,CAAAA,SAAS,GAAG,CAACC,KAAAA,GAAAA;AACdP,YAAAA,YAAAA,EAAAA;AACA,YAAA,MAAMQ,IAAOC,GAAAA,IAAAA,CAAKC,KAAK,CAACH,MAAMC,IAAI,CAAA;YAElC,IAAIA,IAAAA,CAAKG,OAAO,EAAE;gBAChBvB,MAAOe,CAAAA,GAAG,CAACK,IAAAA,CAAKG,OAAO,CAAA;AACzB;;AAGA,YAAA,IAAIH,KAAKD,KAAK,KAAK,wBAAwBC,IAAKD,CAAAA,KAAK,KAAK,kBAAoB,EAAA;AAC5EZ,gBAAAA,EAAAA,CAAGS,KAAK,EAAA;AACV;AACF,SAAA;AACF,KAAA;AACF;;;;"}

View File

@@ -0,0 +1,35 @@
import EventSource from 'eventsource';
function notificationServiceFactory({ logger }) {
return (url, token, cliConfig)=>{
const CONN_TIMEOUT = Number(cliConfig.notificationsConnectionTimeout);
const es = new EventSource(url, {
headers: {
Authorization: `Bearer ${token}`
}
});
let timeoutId;
const resetTimeout = ()=>{
clearTimeout(timeoutId);
timeoutId = setTimeout(()=>{
logger.log('We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment.');
es.close();
}, CONN_TIMEOUT); // 5 minutes
};
es.onopen = resetTimeout;
es.onmessage = (event)=>{
resetTimeout();
const data = JSON.parse(event.data);
if (data.message) {
logger.log(data.message);
}
// Close connection when a specific event is received
if (data.event === 'deploymentFinished' || data.event === 'deploymentFailed') {
es.close();
}
};
};
}
export { notificationServiceFactory };
//# sourceMappingURL=notification.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"notification.mjs","sources":["../../src/services/notification.ts"],"sourcesContent":["import EventSource from 'eventsource';\nimport type { CLIContext, CloudCliConfig } from '../types';\n\ntype Event = {\n type: string;\n data: string;\n lastEventId: string;\n origin: string;\n};\n\nexport function notificationServiceFactory({ logger }: CLIContext) {\n return (url: string, token: string, cliConfig: CloudCliConfig) => {\n const CONN_TIMEOUT = Number(cliConfig.notificationsConnectionTimeout);\n\n const es = new EventSource(url, {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n let timeoutId: NodeJS.Timeout;\n\n const resetTimeout = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n logger.log(\n 'We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment.'\n );\n es.close();\n }, CONN_TIMEOUT); // 5 minutes\n };\n\n es.onopen = resetTimeout;\n es.onmessage = (event: Event) => {\n resetTimeout();\n const data = JSON.parse(event.data);\n\n if (data.message) {\n logger.log(data.message);\n }\n\n // Close connection when a specific event is received\n if (data.event === 'deploymentFinished' || data.event === 'deploymentFailed') {\n es.close();\n }\n };\n };\n}\n"],"names":["notificationServiceFactory","logger","url","token","cliConfig","CONN_TIMEOUT","Number","notificationsConnectionTimeout","es","EventSource","headers","Authorization","timeoutId","resetTimeout","clearTimeout","setTimeout","log","close","onopen","onmessage","event","data","JSON","parse","message"],"mappings":";;AAUO,SAASA,0BAAAA,CAA2B,EAAEC,MAAM,EAAc,EAAA;IAC/D,OAAO,CAACC,KAAaC,KAAeC,EAAAA,SAAAA,GAAAA;QAClC,MAAMC,YAAAA,GAAeC,MAAOF,CAAAA,SAAAA,CAAUG,8BAA8B,CAAA;QAEpE,MAAMC,EAAAA,GAAK,IAAIC,WAAAA,CAAYP,GAAK,EAAA;YAC9BQ,OAAS,EAAA;AACPC,gBAAAA,aAAAA,EAAe,CAAC,OAAO,EAAER,KAAAA,CAAM;AACjC;AACF,SAAA,CAAA;QACA,IAAIS,SAAAA;AAEJ,QAAA,MAAMC,YAAe,GAAA,IAAA;YACnBC,YAAaF,CAAAA,SAAAA,CAAAA;AACbA,YAAAA,SAAAA,GAAYG,UAAW,CAAA,IAAA;AACrBd,gBAAAA,MAAAA,CAAOe,GAAG,CACR,6HAAA,CAAA;AAEFR,gBAAAA,EAAAA,CAAGS,KAAK,EAAA;AACV,aAAA,EAAGZ;AACL,SAAA;AAEAG,QAAAA,EAAAA,CAAGU,MAAM,GAAGL,YAAAA;QACZL,EAAGW,CAAAA,SAAS,GAAG,CAACC,KAAAA,GAAAA;AACdP,YAAAA,YAAAA,EAAAA;AACA,YAAA,MAAMQ,IAAOC,GAAAA,IAAAA,CAAKC,KAAK,CAACH,MAAMC,IAAI,CAAA;YAElC,IAAIA,IAAAA,CAAKG,OAAO,EAAE;gBAChBvB,MAAOe,CAAAA,GAAG,CAACK,IAAAA,CAAKG,OAAO,CAAA;AACzB;;AAGA,YAAA,IAAIH,KAAKD,KAAK,KAAK,wBAAwBC,IAAKD,CAAAA,KAAK,KAAK,kBAAoB,EAAA;AAC5EZ,gBAAAA,EAAAA,CAAGS,KAAK,EAAA;AACV;AACF,SAAA;AACF,KAAA;AACF;;;;"}

View File

@@ -0,0 +1,25 @@
import type { ProjectInfo } from './cli-api';
export declare const LOCAL_SAVE_FILENAME = ".strapi-cloud.json";
export type LocalSave = {
project?: Omit<ProjectInfo, 'id'>;
};
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
export type LocalPatch = {
project?: DeepPartial<Omit<ProjectInfo, 'id'>>;
};
export declare function save(data: LocalSave, { directoryPath }?: {
directoryPath?: string;
}): Promise<void>;
export declare function retrieve({ directoryPath, }?: {
directoryPath?: string;
}): Promise<LocalSave>;
export declare function patch(patchData: LocalPatch, { directoryPath }?: {
directoryPath?: string;
}): Promise<void>;
export declare function deleteConfig({ directoryPath }?: {
directoryPath?: string;
}): Promise<void>;
export {};
//# sourceMappingURL=strapi-info-save.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"strapi-info-save.d.ts","sourceRoot":"","sources":["../../src/services/strapi-info-save.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAE7C,eAAO,MAAM,mBAAmB,uBAAuB,CAAC;AAExD,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,CAAC,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;CACnC,CAAC;AAGF,KAAK,WAAW,CAAC,CAAC,IAAI;KACnB,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAChE,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,OAAO,CAAC,EAAE,WAAW,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC;CAChD,CAAC;AAKF,wBAAsB,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,iBAK7F;AAED,wBAAsB,QAAQ,CAAC,EAC7B,aAAa,GACd,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAOtD;AAED,wBAAsB,KAAK,CACzB,SAAS,EAAE,UAAU,EACrB,EAAE,aAAa,EAAE,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,iBASnD;AAED,wBAAsB,YAAY,CAAC,EAAE,aAAa,EAAE,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,iBAMpF"}

View File

@@ -0,0 +1,53 @@
'use strict';
var fse = require('fs-extra');
var path = require('path');
var lodash = require('lodash');
const LOCAL_SAVE_FILENAME = '.strapi-cloud.json';
const getFilePath = (directoryPath)=>path.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
async function save(data, { directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
// Ensure the directory exists and creates it if not
await fse.ensureDir(path.dirname(pathToFile));
await fse.writeJson(pathToFile, data, {
encoding: 'utf8'
});
}
async function retrieve({ directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
const pathExists = await fse.pathExists(pathToFile);
if (!pathExists) {
return {};
}
return fse.readJSON(pathToFile, {
encoding: 'utf8'
});
}
async function patch(patchData, { directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
const existingData = await retrieve({
directoryPath
});
if (!existingData) {
throw new Error('No configuration data found to patch.');
}
const newData = lodash.merge(existingData, patchData);
await fse.writeJson(pathToFile, newData, {
encoding: 'utf8'
});
}
async function deleteConfig({ directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
const pathExists = await fse.pathExists(pathToFile);
if (pathExists) {
await fse.remove(pathToFile);
}
}
exports.LOCAL_SAVE_FILENAME = LOCAL_SAVE_FILENAME;
exports.deleteConfig = deleteConfig;
exports.patch = patch;
exports.retrieve = retrieve;
exports.save = save;
//# sourceMappingURL=strapi-info-save.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"strapi-info-save.js","sources":["../../src/services/strapi-info-save.ts"],"sourcesContent":["import fse from 'fs-extra';\nimport path from 'path';\nimport { merge } from 'lodash';\nimport type { ProjectInfo } from './cli-api';\n\nexport const LOCAL_SAVE_FILENAME = '.strapi-cloud.json';\n\nexport type LocalSave = {\n project?: Omit<ProjectInfo, 'id'>;\n};\n\n// Utility type for making all properties optional recursively\ntype DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type LocalPatch = {\n project?: DeepPartial<Omit<ProjectInfo, 'id'>>;\n};\n\nconst getFilePath = (directoryPath?: string): string =>\n path.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);\n\nexport async function save(data: LocalSave, { directoryPath }: { directoryPath?: string } = {}) {\n const pathToFile = getFilePath(directoryPath);\n // Ensure the directory exists and creates it if not\n await fse.ensureDir(path.dirname(pathToFile));\n await fse.writeJson(pathToFile, data, { encoding: 'utf8' });\n}\n\nexport async function retrieve({\n directoryPath,\n}: { directoryPath?: string } = {}): Promise<LocalSave> {\n const pathToFile = getFilePath(directoryPath);\n const pathExists = await fse.pathExists(pathToFile);\n if (!pathExists) {\n return {};\n }\n return fse.readJSON(pathToFile, { encoding: 'utf8' });\n}\n\nexport async function patch(\n patchData: LocalPatch,\n { directoryPath }: { directoryPath?: string } = {}\n) {\n const pathToFile = getFilePath(directoryPath);\n const existingData = await retrieve({ directoryPath });\n if (!existingData) {\n throw new Error('No configuration data found to patch.');\n }\n const newData = merge(existingData, patchData);\n await fse.writeJson(pathToFile, newData, { encoding: 'utf8' });\n}\n\nexport async function deleteConfig({ directoryPath }: { directoryPath?: string } = {}) {\n const pathToFile = getFilePath(directoryPath);\n const pathExists = await fse.pathExists(pathToFile);\n if (pathExists) {\n await fse.remove(pathToFile);\n }\n}\n"],"names":["LOCAL_SAVE_FILENAME","getFilePath","directoryPath","path","join","process","cwd","save","data","pathToFile","fse","ensureDir","dirname","writeJson","encoding","retrieve","pathExists","readJSON","patch","patchData","existingData","Error","newData","merge","deleteConfig","remove"],"mappings":";;;;;;AAKO,MAAMA,sBAAsB;AAenC,MAAMC,WAAAA,GAAc,CAACC,aACnBC,GAAAA,IAAAA,CAAKC,I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;AAAO,KAAA,CAAA;AAC9D;AAEO,eAAeU,YAAa,CAAA,EAAEtB,aAAa,EAA8B,GAAG,EAAE,EAAA;AACnF,IAAA,MAAMO,aAAaR,WAAYC,CAAAA,aAAAA,CAAAA;AAC/B,IAAA,MAAMc,UAAa,GAAA,MAAMN,GAAIM,CAAAA,UAAU,CAACP,UAAAA,CAAAA;AACxC,IAAA,IAAIO,UAAY,EAAA;QACd,MAAMN,GAAAA,CAAIe,MAAM,CAAChB,UAAAA,CAAAA;AACnB;AACF;;;;;;;;"}

View File

@@ -0,0 +1,47 @@
import fse__default from 'fs-extra';
import path__default from 'path';
import { merge } from 'lodash';
const LOCAL_SAVE_FILENAME = '.strapi-cloud.json';
const getFilePath = (directoryPath)=>path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
async function save(data, { directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
// Ensure the directory exists and creates it if not
await fse__default.ensureDir(path__default.dirname(pathToFile));
await fse__default.writeJson(pathToFile, data, {
encoding: 'utf8'
});
}
async function retrieve({ directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
const pathExists = await fse__default.pathExists(pathToFile);
if (!pathExists) {
return {};
}
return fse__default.readJSON(pathToFile, {
encoding: 'utf8'
});
}
async function patch(patchData, { directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
const existingData = await retrieve({
directoryPath
});
if (!existingData) {
throw new Error('No configuration data found to patch.');
}
const newData = merge(existingData, patchData);
await fse__default.writeJson(pathToFile, newData, {
encoding: 'utf8'
});
}
async function deleteConfig({ directoryPath } = {}) {
const pathToFile = getFilePath(directoryPath);
const pathExists = await fse__default.pathExists(pathToFile);
if (pathExists) {
await fse__default.remove(pathToFile);
}
}
export { LOCAL_SAVE_FILENAME, deleteConfig, patch, retrieve, save };
//# sourceMappingURL=strapi-info-save.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"strapi-info-save.mjs","sources":["../../src/services/strapi-info-save.ts"],"sourcesContent":["import fse from 'fs-extra';\nimport path from 'path';\nimport { merge } from 'lodash';\nimport type { ProjectInfo } from './cli-api';\n\nexport const LOCAL_SAVE_FILENAME = '.strapi-cloud.json';\n\nexport type LocalSave = {\n project?: Omit<ProjectInfo, 'id'>;\n};\n\n// Utility type for making all properties optional recursively\ntype DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type LocalPatch = {\n project?: DeepPartial<Omit<ProjectInfo, 'id'>>;\n};\n\nconst getFilePath = (directoryPath?: string): string =>\n path.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);\n\nexport async function save(data: LocalSave, { directoryPath }: { directoryPath?: string } = {}) {\n const pathToFile = getFilePath(directoryPath);\n // Ensure the directory exists and creates it if not\n await fse.ensureDir(path.dirname(pathToFile));\n await fse.writeJson(pathToFile, data, { encoding: 'utf8' });\n}\n\nexport async function retrieve({\n directoryPath,\n}: { directoryPath?: string } = {}): Promise<LocalSave> {\n const pathToFile = getFilePath(directoryPath);\n const pathExists = await fse.pathExists(pathToFile);\n if (!pathExists) {\n return {};\n }\n return fse.readJSON(pathToFile, { encoding: 'utf8' });\n}\n\nexport async function patch(\n patchData: LocalPatch,\n { directoryPath }: { directoryPath?: string } = {}\n) {\n const pathToFile = getFilePath(directoryPath);\n const existingData = await retrieve({ directoryPath });\n if (!existingData) {\n throw new Error('No configuration data found to patch.');\n }\n const newData = merge(existingData, patchData);\n await fse.writeJson(pathToFile, newData, { encoding: 'utf8' });\n}\n\nexport async function deleteConfig({ directoryPath }: { directoryPath?: string } = {}) {\n const pathToFile = getFilePath(directoryPath);\n const pathExists = await fse.pathExists(pathToFile);\n if (pathExists) {\n await fse.remove(pathToFile);\n }\n}\n"],"names":["LOCAL_SAVE_FILENAME","getFilePath","directoryPath","path","join","process","cwd","save","data","pathToFile","fse","ensureDir","dirname","writeJson","encoding","retrieve","pathExists","readJSON","patch","patchData","existingData","Error","newData","merge","deleteConfig","remove"],"mappings":";;;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,IAAA,MAAMT,YAAIG,CAAAA,SAAS,CAACJ,UAAAA,EAAYa,OAAS,EAAA;QAAER,QAAU,EAAA;AAAO,KAAA,CAAA;AAC9D;AAEO,eAAeU,YAAa,CAAA,EAAEtB,aAAa,EAA8B,GAAG,EAAE,EAAA;AACnF,IAAA,MAAMO,aAAaR,WAAYC,CAAAA,aAAAA,CAAAA;AAC/B,IAAA,MAAMc,UAAa,GAAA,MAAMN,YAAIM,CAAAA,UAAU,CAACP,UAAAA,CAAAA;AACxC,IAAA,IAAIO,UAAY,EAAA;QACd,MAAMN,YAAAA,CAAIe,MAAM,CAAChB,UAAAA,CAAAA;AACnB;AACF;;;;"}

View File

@@ -0,0 +1,12 @@
import type { CLIContext } from '../types';
export declare function tokenServiceFactory({ logger }: {
logger: CLIContext['logger'];
}): Promise<{
saveToken: (str: string) => Promise<void>;
retrieveToken: () => Promise<string | undefined>;
validateToken: (idToken: string, jwksUrl: string) => Promise<void>;
isTokenValid: (token: string) => Promise<boolean>;
eraseToken: () => Promise<void>;
getValidToken: (ctx: CLIContext, loginAction: (ctx: CLIContext) => Promise<boolean>) => Promise<string | null>;
}>;
//# sourceMappingURL=token.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/services/token.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAkB,UAAU,EAAE,MAAM,UAAU,CAAC;AAS3D,wBAAsB,mBAAmB,CAAC,EAAE,MAAM,EAAE,EAAE;IAAE,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,CAAA;CAAE;qBAGtD,MAAM;;6BA6BE,MAAM,WAAW,MAAM,KAAG,QAAQ,IAAI,CAAC;0BA6C1C,MAAM;;yBAoClC,UAAU,eACF,CAAC,GAAG,EAAE,UAAU,KAAK,QAAQ,OAAO,CAAC;GAyBrD"}

View File

@@ -0,0 +1,126 @@
'use strict';
var jwksClient = require('jwks-rsa');
var jwt = require('jsonwebtoken');
var local = require('../config/local.js');
var cliApi = require('./cli-api.js');
let cliConfig;
async function tokenServiceFactory({ logger }) {
const cloudApiService = await cliApi.cloudApiFactory({
logger
});
async function saveToken(str) {
const appConfig = await local.getLocalConfig();
if (!appConfig) {
logger.error('There was a problem saving your token. Please try again.');
return;
}
appConfig.token = str;
try {
await local.saveLocalConfig(appConfig);
} catch (e) {
logger.debug(e);
logger.error('There was a problem saving your token. Please try again.');
}
}
async function retrieveToken() {
const appConfig = await local.getLocalConfig();
if (appConfig.token) {
// check if token is still valid
if (await isTokenValid(appConfig.token)) {
return appConfig.token;
}
}
return undefined;
}
async function validateToken(idToken, jwksUrl) {
const client = jwksClient({
jwksUri: jwksUrl
});
// Get the Key from the JWKS using the token header's Key ID (kid)
const getKey = (header, callback)=>{
client.getSigningKey(header.kid, (e, key)=>{
if (e) {
callback(e);
} else if (key) {
const publicKey = 'publicKey' in key ? key.publicKey : key.rsaPublicKey;
callback(null, publicKey);
} else {
callback(new Error('Key not found'));
}
});
};
const decodedToken = jwt.decode(idToken, {
complete: true
});
if (!decodedToken) {
if (typeof idToken === 'undefined' || idToken === '') {
logger.warn('You need to be logged in to use this feature. Please log in and try again.');
} else {
logger.error('There seems to be a problem with your login information. Please try logging in again.');
}
return Promise.reject(new Error('Invalid token'));
}
// Verify the JWT token signature using the JWKS Key
return new Promise((resolve, reject)=>{
jwt.verify(idToken, getKey, (err)=>{
if (err) {
reject(err);
}
if (decodedToken.payload.exp < Math.floor(Date.now() / 1000)) {
reject(new Error('Token is expired'));
}
resolve();
});
});
}
async function isTokenValid(token) {
try {
const config = await cloudApiService.config();
cliConfig = config.data;
if (token) {
await validateToken(token, cliConfig.jwksUrl);
return true;
}
return false;
} catch (e) {
logger.debug(e);
return false;
}
}
async function eraseToken() {
const appConfig = await local.getLocalConfig();
if (!appConfig) {
return;
}
delete appConfig.token;
try {
await local.saveLocalConfig(appConfig);
} catch (e) {
logger.debug(e);
logger.error('There was an issue removing your login information. Please try logging out again.');
throw e;
}
}
async function getValidToken(ctx, loginAction) {
let token = await retrieveToken();
while(!token || !await isTokenValid(token)){
logger.log(token ? 'Oops! Your token seems expired or invalid. Please login again.' : "We couldn't find a valid token. You need to be logged in to use this feature.");
if (!await loginAction(ctx)) return null;
token = await retrieveToken();
}
return token;
}
return {
saveToken,
retrieveToken,
validateToken,
isTokenValid,
eraseToken,
getValidToken
};
}
exports.tokenServiceFactory = tokenServiceFactory;
//# sourceMappingURL=token.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,124 @@
import jwksClient from 'jwks-rsa';
import jwt from 'jsonwebtoken';
import { getLocalConfig, saveLocalConfig } from '../config/local.mjs';
import { cloudApiFactory } from './cli-api.mjs';
let cliConfig;
async function tokenServiceFactory({ logger }) {
const cloudApiService = await cloudApiFactory({
logger
});
async function saveToken(str) {
const appConfig = await getLocalConfig();
if (!appConfig) {
logger.error('There was a problem saving your token. Please try again.');
return;
}
appConfig.token = str;
try {
await saveLocalConfig(appConfig);
} catch (e) {
logger.debug(e);
logger.error('There was a problem saving your token. Please try again.');
}
}
async function retrieveToken() {
const appConfig = await getLocalConfig();
if (appConfig.token) {
// check if token is still valid
if (await isTokenValid(appConfig.token)) {
return appConfig.token;
}
}
return undefined;
}
async function validateToken(idToken, jwksUrl) {
const client = jwksClient({
jwksUri: jwksUrl
});
// Get the Key from the JWKS using the token header's Key ID (kid)
const getKey = (header, callback)=>{
client.getSigningKey(header.kid, (e, key)=>{
if (e) {
callback(e);
} else if (key) {
const publicKey = 'publicKey' in key ? key.publicKey : key.rsaPublicKey;
callback(null, publicKey);
} else {
callback(new Error('Key not found'));
}
});
};
const decodedToken = jwt.decode(idToken, {
complete: true
});
if (!decodedToken) {
if (typeof idToken === 'undefined' || idToken === '') {
logger.warn('You need to be logged in to use this feature. Please log in and try again.');
} else {
logger.error('There seems to be a problem with your login information. Please try logging in again.');
}
return Promise.reject(new Error('Invalid token'));
}
// Verify the JWT token signature using the JWKS Key
return new Promise((resolve, reject)=>{
jwt.verify(idToken, getKey, (err)=>{
if (err) {
reject(err);
}
if (decodedToken.payload.exp < Math.floor(Date.now() / 1000)) {
reject(new Error('Token is expired'));
}
resolve();
});
});
}
async function isTokenValid(token) {
try {
const config = await cloudApiService.config();
cliConfig = config.data;
if (token) {
await validateToken(token, cliConfig.jwksUrl);
return true;
}
return false;
} catch (e) {
logger.debug(e);
return false;
}
}
async function eraseToken() {
const appConfig = await getLocalConfig();
if (!appConfig) {
return;
}
delete appConfig.token;
try {
await saveLocalConfig(appConfig);
} catch (e) {
logger.debug(e);
logger.error('There was an issue removing your login information. Please try logging out again.');
throw e;
}
}
async function getValidToken(ctx, loginAction) {
let token = await retrieveToken();
while(!token || !await isTokenValid(token)){
logger.log(token ? 'Oops! Your token seems expired or invalid. Please login again.' : "We couldn't find a valid token. You need to be logged in to use this feature.");
if (!await loginAction(ctx)) return null;
token = await retrieveToken();
}
return token;
}
return {
saveToken,
retrieveToken,
validateToken,
isTokenValid,
eraseToken,
getValidToken
};
}
export { tokenServiceFactory };
//# sourceMappingURL=token.mjs.map

File diff suppressed because one or more lines are too long