Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@hubspot/local-dev-lib

Package Overview
Dependencies
Maintainers
23
Versions
87
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hubspot/local-dev-lib - npm Package Compare versions

Comparing version 0.0.5 to 0.0.6

api/customObjects.d.ts

38

config/CLIConfiguration.d.ts

@@ -1,3 +0,3 @@

import { CLIConfig } from '../types/Config';
import { CLIAccount, FlatAccountFields, OauthTokenInfo } from '../types/Accounts';
import { CLIConfig_NEW, Environment } from '../types/Config';
import { CLIAccount_NEW, FlatAccountFields_NEW } from '../types/Accounts';
import { CLIOptions } from '../types/CLIOptions';

@@ -9,26 +9,31 @@ import { LogCallbacksArg } from '../types/LogCallbacks';

useEnvConfig: boolean;
config: CLIConfig | null;
config: CLIConfig_NEW | null;
active: boolean;
constructor();
init(options?: CLIOptions): void;
load(): CLIConfig | null;
setActive(isActive: boolean): void;
isActive(): boolean;
init(options?: CLIOptions): CLIConfig_NEW | null;
load(): CLIConfig_NEW | null;
configIsEmpty(): boolean;
delete(): void;
write(updatedConfig?: CLIConfig): CLIConfig | null;
write(updatedConfig?: CLIConfig_NEW): CLIConfig_NEW | null;
validate(logCallbacks?: LogCallbacksArg<typeof validateLogCallbackKeys>): boolean;
getAccount(nameOrId: string | number | undefined): CLIAccount | null;
getAccountId(nameOrId: string | number): number | null;
getAccount(nameOrId: string | number | undefined): CLIAccount_NEW | null;
isConfigFlagEnabled(flag: keyof CLIConfig_NEW, defaultValue?: boolean): boolean;
getAccountId(nameOrId?: string | number): number | null;
getDefaultAccount(): string | number | null;
getResolvedDefaultAccountForCWD(nameOrId: string | number): CLIAccount | null;
getResolvedDefaultAccountForCWD(nameOrId: string | number): CLIAccount_NEW | null;
getConfigAccountIndex(accountId: number): number;
getConfigForAccount(accountId?: number): CLIAccount_NEW | null;
isAccountInConfig(nameOrId: string | number): boolean;
getAndLoadConfigIfNeeded(options?: CLIOptions): CLIConfig;
getEnv(nameOrId?: string | number): string;
getAndLoadConfigIfNeeded(options?: CLIOptions): CLIConfig_NEW;
getEnv(nameOrId?: string | number): Environment;
/**
* @throws {Error}
*/
updateAccount(updatedAccountFields: FlatAccountFields<OauthTokenInfo>, writeUpdate?: boolean): CLIAccount | null;
updateAccount(updatedAccountFields: Partial<FlatAccountFields_NEW>, writeUpdate?: boolean): FlatAccountFields_NEW | null;
/**
* @throws {Error}
*/
updateDefaultAccount(defaultAccount: string | number): CLIConfig | null;
updateDefaultAccount(defaultAccount: string | number): CLIConfig_NEW | null;
/**

@@ -45,13 +50,14 @@ * @throws {Error}

*/
updateDefaultMode(defaultMode: string): CLIConfig | null;
updateDefaultMode(defaultMode: string): CLIConfig_NEW | null;
/**
* @throws {Error}
*/
updateHttpTimeout(timeout: string): CLIConfig | null;
updateHttpTimeout(timeout: string): CLIConfig_NEW | null;
/**
* @throws {Error}
*/
updateAllowUsageTracking(isEnabled: boolean): CLIConfig | null;
updateAllowUsageTracking(isEnabled: boolean): CLIConfig_NEW | null;
isTrackingAllowed(): boolean;
}
declare const _default: CLIConfiguration;
export default _default;

@@ -6,7 +6,9 @@ "use strict";

const environment_1 = require("./environment");
const environment_2 = require("../lib/environment");
const configFile_1 = require("./configFile");
const text_1 = require("../lib/text");
const constants_1 = require("../constants");
const environments_1 = require("../constants/environments");
const auth_1 = require("../constants/auth");
const config_1 = require("../constants/config");
const files_1 = require("../constants/files");
const i18nKey = 'config.cliConfiguration';

@@ -26,2 +28,3 @@ const validateLogCallbackKeys = [

config;
active;
constructor() {

@@ -31,6 +34,15 @@ this.options = {};

this.config = null;
this.active = false;
}
setActive(isActive) {
this.active = isActive;
}
isActive() {
return this.active;
}
init(options = {}) {
this.options = options;
this.load();
this.setActive(true);
return this.config;
}

@@ -164,2 +176,8 @@ load() {

}
isConfigFlagEnabled(flag, defaultValue = false) {
if (this.config && typeof this.config[flag] !== 'undefined') {
return Boolean(this.config[flag]);
}
return defaultValue;
}
getAccountId(nameOrId) {

@@ -190,2 +208,9 @@ const account = this.getAccount(nameOrId);

}
getConfigForAccount(accountId) {
if (this.config) {
this.config.accounts.find(account => account.accountId === accountId) ||
null;
}
return null;
}
isAccountInConfig(nameOrId) {

@@ -208,3 +233,3 @@ return (!!this.config && this.config.accounts && !!this.getAccountId(nameOrId));

}
return constants_1.ENVIRONMENTS.PROD;
return environments_1.ENVIRONMENTS.PROD;
}

@@ -227,3 +252,3 @@ /*

const currentAccountConfig = this.getAccount(accountId);
let auth;
let auth = {};
if (clientId || clientSecret || scopes || tokenInfo) {

@@ -249,5 +274,4 @@ auth = {

}
const updatedEnv = (0, environment_1.getValidEnv)(env || (currentAccountConfig && currentAccountConfig.env), false);
const updatedDefaultMode = defaultMode &&
defaultMode.toLowerCase();
const updatedEnv = (0, environment_2.getValidEnv)(env || (currentAccountConfig && currentAccountConfig.env));
const updatedDefaultMode = defaultMode && defaultMode.toLowerCase();
safelyApplyUpdates('name', name);

@@ -263,3 +287,3 @@ safelyApplyUpdates('env', updatedEnv);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
safelyApplyUpdates('defaultMode', config_1.DEFAULT_MODES[updatedDefaultMode]);
safelyApplyUpdates('defaultMode', files_1.MODE[updatedDefaultMode]);
}

@@ -321,3 +345,3 @@ safelyApplyUpdates('personalAccessKey', personalAccessKey);

if (accountId) {
this.updateAccount({ accountId, name: newName });
this.updateAccount({ accountId, name: newName, env: this.getEnv() });
}

@@ -359,3 +383,3 @@ if (accountConfigToRename.name === this.getDefaultAccount()) {

}
const ALL_MODES = Object.values(config_1.DEFAULT_MODES);
const ALL_MODES = Object.values(files_1.MODE);
if (!defaultMode || !ALL_MODES.find(m => m === defaultMode)) {

@@ -402,3 +426,9 @@ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.updateDefaultMode`, {

}
isTrackingAllowed() {
if (!this.config) {
return true;
}
return this.config.allowUsageTracking !== false;
}
}
exports.default = new CLIConfiguration();

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

import { CLIConfig } from '../types/Config';
import { CLIConfig_NEW } from '../types/Config';
export declare function getConfigFilePath(): string;

@@ -13,10 +13,10 @@ export declare function configFileExists(): boolean;

*/
export declare function parseConfig(configSource: string): CLIConfig;
export declare function parseConfig(configSource: string): CLIConfig_NEW;
/**
* @throws {Error}
*/
export declare function loadConfigFromFile(): CLIConfig | null;
export declare function loadConfigFromFile(): CLIConfig_NEW | null;
/**
* @throws {Error}
*/
export declare function writeConfigToFile(config: CLIConfig): void;
export declare function writeConfigToFile(config: CLIConfig_NEW): void;

@@ -14,7 +14,7 @@ "use strict";

const standardErrors_1 = require("../errors/standardErrors");
const constants_1 = require("../constants");
const config_1 = require("../constants/config");
const configUtils_1 = require("./configUtils");
const i18nKey = 'config.configFile';
function getConfigFilePath() {
return path_1.default.join(os_1.default.homedir(), constants_1.HUBSPOT_CONFIGURATION_FOLDER, constants_1.HUBSPOT_CONFIGURATION_FILE);
return path_1.default.join(os_1.default.homedir(), config_1.HUBSPOT_CONFIGURATION_FOLDER, config_1.HUBSPOT_CONFIGURATION_FILE);
}

@@ -21,0 +21,0 @@ exports.getConfigFilePath = getConfigFilePath;

@@ -1,9 +0,9 @@

import { CLIConfig } from '../types/Config';
import { AuthType, CLIAccount } from '../types/Accounts';
export declare function getOrderedAccount(unorderedAccount: CLIAccount): CLIAccount;
export declare function getOrderedConfig(unorderedConfig: CLIConfig): CLIConfig;
import { CLIConfig_NEW, Environment } from '../types/Config';
import { AuthType, CLIAccount_NEW } from '../types/Accounts';
export declare function getOrderedAccount(unorderedAccount: CLIAccount_NEW): CLIAccount_NEW;
export declare function getOrderedConfig(unorderedConfig: CLIConfig_NEW): CLIConfig_NEW;
type PersonalAccessKeyOptions = {
accountId: number;
personalAccessKey: string;
env: string;
env: Environment;
};

@@ -16,3 +16,3 @@ type OAuthOptions = {

scopes: Array<string>;
env: string;
env: Environment;
};

@@ -22,5 +22,5 @@ type APIKeyOptions = {

apiKey: string;
env: string;
env: Environment;
};
export declare function generateConfig(type: AuthType, options: PersonalAccessKeyOptions | OAuthOptions | APIKeyOptions): CLIConfig | null;
export declare function generateConfig(type: AuthType, options: PersonalAccessKeyOptions | OAuthOptions | APIKeyOptions): CLIConfig_NEW | null;
export {};

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

import { CLIConfig } from '../types/Config';
export declare function getValidEnv(env?: string | null, useProdDefault?: boolean): string | undefined;
export declare function loadConfigFromEnvironment(): CLIConfig | null;
import { CLIConfig_NEW } from '../types/Config';
export declare function loadConfigFromEnvironment(): CLIConfig_NEW | null;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadConfigFromEnvironment = exports.getValidEnv = void 0;
exports.loadConfigFromEnvironment = void 0;
const logger_1 = require("../utils/logger");
const constants_1 = require("../constants");
const environments_1 = require("../constants/environments");
const auth_1 = require("../constants/auth");
const configUtils_1 = require("./configUtils");
function getValidEnv(env, useProdDefault = true) {
if (typeof env === 'string' && env.toLowerCase() === constants_1.ENVIRONMENTS.QA) {
return constants_1.ENVIRONMENTS.QA;
}
return useProdDefault ? constants_1.ENVIRONMENTS.PROD : undefined;
}
exports.getValidEnv = getValidEnv;
const environment_1 = require("../lib/environment");
function getConfigVariablesFromEnv() {
const env = process.env;
return {
apiKey: env[constants_1.ENVIRONMENT_VARIABLES.HUBSPOT_API_KEY],
clientId: env[constants_1.ENVIRONMENT_VARIABLES.HUBSPOT_CLIENT_ID],
clientSecret: env[constants_1.ENVIRONMENT_VARIABLES.HUBSPOT_CLIENT_SECRET],
personalAccessKey: env[constants_1.ENVIRONMENT_VARIABLES.HUBSPOT_PERSONAL_ACCESS_KEY],
accountId: parseInt(env[constants_1.ENVIRONMENT_VARIABLES.HUBSPOT_ACCOUNT_ID], 10),
refreshToken: env[constants_1.ENVIRONMENT_VARIABLES.HUBSPOT_REFRESH_TOKEN],
env: getValidEnv(env[constants_1.ENVIRONMENT_VARIABLES.HUBSPOT_ENVIRONMENT]),
apiKey: env[environments_1.ENVIRONMENT_VARIABLES.HUBSPOT_API_KEY],
clientId: env[environments_1.ENVIRONMENT_VARIABLES.HUBSPOT_CLIENT_ID],
clientSecret: env[environments_1.ENVIRONMENT_VARIABLES.HUBSPOT_CLIENT_SECRET],
personalAccessKey: env[environments_1.ENVIRONMENT_VARIABLES.HUBSPOT_PERSONAL_ACCESS_KEY],
accountId: parseInt(env[environments_1.ENVIRONMENT_VARIABLES.HUBSPOT_ACCOUNT_ID], 10),
refreshToken: env[environments_1.ENVIRONMENT_VARIABLES.HUBSPOT_REFRESH_TOKEN],
env: (0, environment_1.getValidEnv)(env[environments_1.ENVIRONMENT_VARIABLES.HUBSPOT_ENVIRONMENT]),
};

@@ -34,3 +28,3 @@ }

if (!env) {
(0, logger_1.debug)('environment.loadConfig.env');
(0, logger_1.debug)('environment.loadConfig.missingEnv');
return null;

@@ -37,0 +31,0 @@ }

@@ -25,1 +25,14 @@ export declare const API_KEY_AUTH_METHOD: {

}];
export declare const AUTH_METHODS: {
api: {
readonly value: "apikey";
readonly name: "API Key";
};
oauth: {
readonly value: "oauth2";
readonly name: "OAuth2";
};
};
export declare const SCOPE_GROUPS: {
CMS_FUNCTIONS: string;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAUTH_SCOPES = exports.DEFAULT_OAUTH_SCOPES = exports.PERSONAL_ACCESS_KEY_AUTH_METHOD = exports.OAUTH_AUTH_METHOD = exports.API_KEY_AUTH_METHOD = void 0;
exports.SCOPE_GROUPS = exports.AUTH_METHODS = exports.OAUTH_SCOPES = exports.DEFAULT_OAUTH_SCOPES = exports.PERSONAL_ACCESS_KEY_AUTH_METHOD = exports.OAUTH_AUTH_METHOD = exports.API_KEY_AUTH_METHOD = void 0;
exports.API_KEY_AUTH_METHOD = {

@@ -32,1 +32,8 @@ value: 'apikey',

];
exports.AUTH_METHODS = {
api: exports.API_KEY_AUTH_METHOD,
oauth: exports.OAUTH_AUTH_METHOD,
};
exports.SCOPE_GROUPS = {
CMS_FUNCTIONS: 'cms.functions.read_write',
};
export declare const DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME = "hubspot.config.yml";
export declare const HUBSPOT_CONFIGURATION_FOLDER = ".hubspot";
export declare const HUBSPOT_CONFIGURATION_FILE = "config.yml";
export declare const DEFAULT_MODES: {
readonly draft: "draft";
readonly publish: "publish";
};
export declare const MIN_HTTP_TIMEOUT = 3000;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MIN_HTTP_TIMEOUT = exports.DEFAULT_MODES = exports.HUBSPOT_CONFIGURATION_FILE = exports.HUBSPOT_CONFIGURATION_FOLDER = exports.DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME = void 0;
exports.MIN_HTTP_TIMEOUT = exports.HUBSPOT_CONFIGURATION_FILE = exports.HUBSPOT_CONFIGURATION_FOLDER = exports.DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME = void 0;
// NOTE this is the legacy config file name (We still need to keep it around though)

@@ -8,6 +8,2 @@ exports.DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME = 'hubspot.config.yml';

exports.HUBSPOT_CONFIGURATION_FILE = 'config.yml';
exports.DEFAULT_MODES = {
draft: 'draft',
publish: 'publish',
};
exports.MIN_HTTP_TIMEOUT = 3000;

@@ -11,4 +11,5 @@ export declare const ENVIRONMENTS: {

readonly HUBSPOT_ACCOUNT_ID: "HUBSPOT_ACCOUNT_ID";
readonly HUBSPOT_PORTAL_ID: "HUBSPOT_PORTAL_ID";
readonly HUBSPOT_REFRESH_TOKEN: "HUBSPOT_REFRESH_TOKEN";
readonly HUBSPOT_ENVIRONMENT: "HUBSPOT_ENVIRONMENT";
};

@@ -14,4 +14,5 @@ "use strict";

HUBSPOT_ACCOUNT_ID: 'HUBSPOT_ACCOUNT_ID',
HUBSPOT_PORTAL_ID: 'HUBSPOT_PORTAL_ID',
HUBSPOT_REFRESH_TOKEN: 'HUBSPOT_REFRESH_TOKEN',
HUBSPOT_ENVIRONMENT: 'HUBSPOT_ENVIRONMENT',
};
export declare const ALLOWED_EXTENSIONS: Set<string>;
export declare const HUBL_EXTENSIONS: Set<string>;
export declare const MODULE_EXTENSION = "module";
export declare const FUNCTIONS_EXTENSION = "functions";
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MODULE_EXTENSION = exports.ALLOWED_EXTENSIONS = void 0;
exports.FUNCTIONS_EXTENSION = exports.MODULE_EXTENSION = exports.HUBL_EXTENSIONS = exports.ALLOWED_EXTENSIONS = void 0;
exports.ALLOWED_EXTENSIONS = new Set([

@@ -18,2 +18,3 @@ 'css',

'eot',
'otf',
'ttf',

@@ -24,2 +25,4 @@ 'woff',

]);
exports.HUBL_EXTENSIONS = new Set(['css', 'html', 'js']);
exports.MODULE_EXTENSION = 'module';
exports.FUNCTIONS_EXTENSION = 'functions';

@@ -6,1 +6,17 @@ export declare const STAT_TYPES: {

};
export declare const MODE: {
readonly draft: "draft";
readonly publish: "publish";
};
export declare const DEFAULT_MODE: "publish";
export declare const FILE_UPLOAD_RESULT_TYPES: {
readonly SUCCESS: "SUCCESS";
readonly FAILURE: "FAILURE";
};
export declare const FILE_TYPES: {
readonly other: "otherFiles";
readonly module: "moduleFiles";
readonly cssAndJs: "cssAndJsFiles";
readonly template: "templateFiles";
readonly json: "jsonFiles";
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.STAT_TYPES = void 0;
exports.FILE_TYPES = exports.FILE_UPLOAD_RESULT_TYPES = exports.DEFAULT_MODE = exports.MODE = exports.STAT_TYPES = void 0;
exports.STAT_TYPES = {

@@ -9,1 +9,17 @@ FILE: 'file',

};
exports.MODE = {
draft: 'draft',
publish: 'publish',
};
exports.DEFAULT_MODE = exports.MODE.publish;
exports.FILE_UPLOAD_RESULT_TYPES = {
SUCCESS: 'SUCCESS',
FAILURE: 'FAILURE',
};
exports.FILE_TYPES = {
other: 'otherFiles',
module: 'moduleFiles',
cssAndJs: 'cssAndJsFiles',
template: 'templateFiles',
json: 'jsonFiles',
};

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

import { BaseError } from '../types/Error';
type FileSystemErrorContext = {
filepath: string;
write?: boolean;
read?: boolean;
};
import { BaseError, FileSystemErrorContext } from '../types/Error';
export declare function throwFileSystemError(error: BaseError, context: FileSystemErrorContext): void;
export {};

@@ -1,3 +0,9 @@

import { BaseError } from '../types/Error';
export declare class HubSpotAuthError extends Error implements BaseError {
import { StatusCodeError } from '../types/Error';
export declare class HubSpotAuthError extends Error {
statusCode?: number;
category?: string;
subCategory?: string;
constructor(message: string, { cause }: {
cause?: Partial<StatusCodeError>;
});
}

@@ -5,3 +5,17 @@ "use strict";

class HubSpotAuthError extends Error {
statusCode;
category;
subCategory;
constructor(message, { cause = {} }) {
super(message);
this.name = 'HubSpotAuthError';
this.statusCode = cause.statusCode;
this.category = cause?.response?.body?.category || undefined;
this.subCategory =
(cause.response &&
cause.response.body &&
cause.response.body.subCategory) ||
undefined;
}
}
exports.HubSpotAuthError = HubSpotAuthError;

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

import { BaseError } from '../types/Error';
import { BaseError, StatusCodeError } from '../types/Error';
export declare function isSystemError(err: BaseError): boolean;

@@ -19,2 +19,8 @@ export declare function isFatalError(err: BaseError): boolean;

*/
export declare function throwAuthErrorWithMessage(identifier: string, interpolation?: {
[key: string]: string | number;
}, cause?: StatusCodeError): never;
/**
* @throws
*/
export declare function throwError(error: BaseError): never;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.throwError = exports.throwTypeErrorWithMessage = exports.throwErrorWithMessage = exports.isFatalError = exports.isSystemError = void 0;
exports.throwError = exports.throwAuthErrorWithMessage = exports.throwTypeErrorWithMessage = exports.throwErrorWithMessage = exports.isFatalError = exports.isSystemError = void 0;
const HubSpotAuthError_1 = require("./HubSpotAuthError");
const lang_1 = require("../utils/lang");
const apiErrors_1 = require("./apiErrors");
function isSystemError(err) {

@@ -14,2 +15,9 @@ return err.errno != null && err.code != null && err.syscall != null;

exports.isFatalError = isFatalError;
function genericThrowErrorWithMessage(ErrorType, identifier, interpolation, cause) {
const message = (0, lang_1.i18n)(`errors.${identifier}`, interpolation);
if (cause) {
throw new ErrorType(message, { cause });
}
throw new ErrorType(message);
}
/**

@@ -19,7 +27,3 @@ * @throws

function throwErrorWithMessage(identifier, interpolation, cause) {
const message = (0, lang_1.i18n)(`errors.${identifier}`, interpolation);
if (cause) {
throw new Error(message, { cause });
}
throw new Error(message);
genericThrowErrorWithMessage(Error, identifier, interpolation, cause);
}

@@ -31,21 +35,14 @@ exports.throwErrorWithMessage = throwErrorWithMessage;

function throwTypeErrorWithMessage(identifier, interpolation, cause) {
const message = (0, lang_1.i18n)(`errors.${identifier}`, interpolation);
if (cause) {
throw new TypeError(message, { cause });
}
throw new TypeError(message);
genericThrowErrorWithMessage(TypeError, identifier, interpolation, cause);
}
exports.throwTypeErrorWithMessage = throwTypeErrorWithMessage;
function throwStatusCodeError(error) {
const { statusCode, message, response } = error;
const errorData = JSON.stringify({
statusCode,
message,
url: response.request.href,
method: response.request.method,
response: response.body,
headers: response.headers,
});
throw new Error(errorData, { cause: error });
/**
* @throws
*/
function throwAuthErrorWithMessage(identifier, interpolation, cause) {
genericThrowErrorWithMessage(
// @ts-expect-error HubSpotAuthError is not callable
HubSpotAuthError_1.HubSpotAuthError, identifier, interpolation, cause);
}
exports.throwAuthErrorWithMessage = throwAuthErrorWithMessage;
/**

@@ -56,3 +53,3 @@ * @throws

if (error.name === 'StatusCodeError') {
throwStatusCodeError(error);
(0, apiErrors_1.throwStatusCodeError)(error);
}

@@ -59,0 +56,0 @@ else {

@@ -8,3 +8,4 @@ export declare class FieldsJs {

outputPath?: string;
constructor(projectDir: string, filePath: string, rootWriteDir?: string, fieldOptions?: string);
toJSON?: () => JSON;
constructor(projectDir: string, filePath: string, rootWriteDir?: string | null, fieldOptions?: string);
init(): Promise<this>;

@@ -11,0 +12,0 @@ convertFieldsJs(writeDir: string): Promise<string | void>;

@@ -12,6 +12,6 @@ "use strict";

const escapeRegExp_1 = require("../../utils/escapeRegExp");
const modules_1 = require("../../utils/modules");
const modules_1 = require("../../utils/cms/modules");
const logger_1 = require("../../utils/logger");
const standardErrors_1 = require("../../errors/standardErrors");
const i18nKey = 'utils.handleFieldsJs';
const i18nKey = 'cms.handleFieldsJs';
class FieldsJs {

@@ -24,2 +24,3 @@ projectDir;

outputPath;
toJSON;
constructor(projectDir, filePath, rootWriteDir, fieldOptions = '') {

@@ -32,3 +33,3 @@ this.projectDir = projectDir;

this.rootWriteDir =
rootWriteDir === undefined
rootWriteDir === undefined || rootWriteDir === null
? createTmpDirSync('hubspot-temp-fieldsjs-output-')

@@ -35,0 +36,0 @@ : rootWriteDir;

@@ -14,3 +14,3 @@ "use strict";

const logger_1 = require("../../utils/logger");
const modules_1 = require("../../utils/modules");
const modules_1 = require("../../utils/cms/modules");
// Ids for testing

@@ -110,3 +110,3 @@ exports.ValidationIds = {

if (!options.allowExistingDir && fs_extra_1.default.existsSync(destPath)) {
(0, standardErrors_1.throwErrorWithMessage)('modules.createModule', {
(0, standardErrors_1.throwErrorWithMessage)('modules.writeModuleMeta', {
path: destPath,

@@ -124,4 +124,4 @@ });

});
await (0, github_1.downloadGithubRepoContents)('cms-sample-assets', 'modules/Sample.module', destPath, moduleFileFilter);
await (0, github_1.downloadGithubRepoContents)('HubSpot/cms-sample-assets', 'modules/Sample.module', destPath, '', moduleFileFilter);
}
exports.createModule = createModule;

@@ -10,3 +10,3 @@ "use strict";

const environments_1 = require("../../constants/environments");
const CLIConfiguration_1 = __importDefault(require("../../config/CLIConfiguration"));
const config_1 = require("../../config");
function getThemeJSONPath(path) {

@@ -32,5 +32,5 @@ return (0, findup_sync_1.default)('theme.json', {

return;
const baseUrl = (0, urls_1.getHubSpotWebsiteOrigin)(CLIConfiguration_1.default.getEnv() === 'qa' ? environments_1.ENVIRONMENTS.QA : environments_1.ENVIRONMENTS.PROD);
const baseUrl = (0, urls_1.getHubSpotWebsiteOrigin)((0, config_1.getEnv)(accountId) === 'qa' ? environments_1.ENVIRONMENTS.QA : environments_1.ENVIRONMENTS.PROD);
return `${baseUrl}/theme-previewer/${accountId}/edit/${encodeURIComponent(themeName)}`;
}
exports.getThemePreviewUrl = getThemePreviewUrl;

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

export declare function getValidEnv(env: string, maskedProductionValue?: string): string;
import { Environment } from '../types/Config';
export declare function getValidEnv(env?: Environment | null, maskedProductionValue?: Environment): Environment;
import { GITHUB_RELEASE_TYPES } from '../constants/github';
import { GithubReleaseData } from '../types/Github';
import { ValueOf } from '../types/Utils';

@@ -7,3 +8,5 @@ import { LogCallbacksArg } from '../types/LogCallbacks';

}
export declare function fetchJsonFromRepository(repoName: string, filePath: string): Promise<JSON>;
type RepoPath = `${string}/${string}`;
export declare function fetchJsonFromRepository(repoPath: RepoPath, filePath: string, ref: string): Promise<JSON>;
export declare function fetchReleaseData(repoPath: RepoPath, tag?: string): Promise<GithubReleaseData>;
type CloneGithubRepoOptions = {

@@ -16,4 +19,4 @@ themeVersion?: string;

declare const cloneGithubRepoCallbackKeys: string[];
export declare function cloneGithubRepo(dest: string, type: string, repoName: string, sourceDir: string, options?: CloneGithubRepoOptions, logCallbacks?: LogCallbacksArg<typeof cloneGithubRepoCallbackKeys>): Promise<boolean>;
export declare function downloadGithubRepoContents(repoName: string, contentPath: string, dest: string, filter?: (contentPiecePath: string, downloadPath: string) => boolean): Promise<void>;
export declare function cloneGithubRepo(dest: string, type: string, repoPath: RepoPath, sourceDir: string, options?: CloneGithubRepoOptions, logCallbacks?: LogCallbacksArg<typeof cloneGithubRepoCallbackKeys>): Promise<boolean>;
export declare function downloadGithubRepoContents(repoPath: RepoPath, contentPath: string, dest: string, ref?: string, filter?: (contentPiecePath: string, downloadPath: string) => boolean): Promise<void>;
export {};

@@ -6,3 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadGithubRepoContents = exports.cloneGithubRepo = exports.fetchJsonFromRepository = void 0;
exports.downloadGithubRepoContents = exports.cloneGithubRepo = exports.fetchReleaseData = exports.fetchJsonFromRepository = void 0;
const axios_1 = __importDefault(require("axios"));

@@ -15,12 +15,12 @@ const path_1 = __importDefault(require("path"));

const github_1 = require("../constants/github");
const requestOptions_1 = require("../http/requestOptions");
const getAxiosConfig_1 = require("../http/getAxiosConfig");
const GITHUB_AUTH_HEADERS = {
authorization: global && global.githubToken ? `Bearer ${global.githubToken}` : null,
};
async function fetchJsonFromRepository(repoName, filePath) {
async function fetchJsonFromRepository(repoPath, filePath, ref) {
try {
const URI = `https://raw.githubusercontent.com/HubSpot/${repoName}/${filePath}`;
(0, logger_1.debug)('github.fetchJsonFromRepository', { uri: URI });
const { data } = await axios_1.default.get(URI, {
headers: { ...requestOptions_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
const URL = `https://raw.githubusercontent.com/${repoPath}/${ref}/${filePath}`;
(0, logger_1.debug)('github.fetchJsonFromRepository', { url: URL });
const { data } = await axios_1.default.get(URL, {
headers: { ...getAxiosConfig_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
});

@@ -34,3 +34,3 @@ return data;

exports.fetchJsonFromRepository = fetchJsonFromRepository;
async function fetchReleaseData(repoName, tag = '') {
async function fetchReleaseData(repoPath, tag = '') {
tag = tag.trim().toLowerCase();

@@ -41,7 +41,7 @@ if (tag.length && tag[0] !== 'v') {

const URI = tag
? `https://api.github.com/repos/HubSpot/${repoName}/releases/tags/${tag}`
: `https://api.github.com/repos/HubSpot/${repoName}/releases/latest`;
? `https://api.github.com/repos/${repoPath}/releases/tags/${tag}`
: `https://api.github.com/repos/${repoPath}/releases/latest`;
try {
const { data } = await axios_1.default.get(URI, {
headers: { ...requestOptions_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
headers: { ...getAxiosConfig_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
});

@@ -55,11 +55,12 @@ return data;

}
async function downloadGithubRepoZip(repoName, tag = '', releaseType = github_1.GITHUB_RELEASE_TYPES.RELEASE, ref) {
exports.fetchReleaseData = fetchReleaseData;
async function downloadGithubRepoZip(repoPath, tag = '', releaseType = github_1.GITHUB_RELEASE_TYPES.RELEASE, ref) {
try {
let zipUrl;
if (releaseType === github_1.GITHUB_RELEASE_TYPES.REPOSITORY) {
(0, logger_1.debug)('github.downloadGithubRepoZip.fetching', { releaseType, repoName });
zipUrl = `https://api.github.com/repos/HubSpot/${repoName}/zipball${ref ? `/${ref}` : ''}`;
(0, logger_1.debug)('github.downloadGithubRepoZip.fetching', { releaseType, repoPath });
zipUrl = `https://api.github.com/repos/${repoPath}/zipball${ref ? `/${ref}` : ''}`;
}
else {
const releaseData = await fetchReleaseData(repoName, tag);
const releaseData = await fetchReleaseData(repoPath, tag);
zipUrl = releaseData.zipball_url;

@@ -70,3 +71,3 @@ const { name } = releaseData;

const { data } = await axios_1.default.get(zipUrl, {
headers: { ...requestOptions_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
headers: { ...getAxiosConfig_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
});

@@ -81,7 +82,8 @@ (0, logger_1.debug)('github.downloadGithubRepoZip.completed');

const cloneGithubRepoCallbackKeys = ['success'];
async function cloneGithubRepo(dest, type, repoName, sourceDir, options = {}, logCallbacks) {
async function cloneGithubRepo(dest, type, repoPath, sourceDir, options = {}, logCallbacks) {
const logger = (0, logger_1.makeTypedLogger)(logCallbacks, 'github.cloneGithubRepo');
const { themeVersion, projectVersion, releaseType, ref } = options;
const tag = projectVersion || themeVersion;
const zip = await downloadGithubRepoZip(repoName, tag, releaseType, ref);
const zip = await downloadGithubRepoZip(repoPath, tag, releaseType, ref);
const repoName = repoPath.split('/')[1];
const success = await (0, archive_1.extractZipArchive)(zip, repoName, dest, { sourceDir });

@@ -94,6 +96,7 @@ if (success) {

exports.cloneGithubRepo = cloneGithubRepo;
async function getGitHubRepoContentsAtPath(repoName, path) {
const contentsRequestUrl = `https://api.github.com/repos/HubSpot/${repoName}/contents/${path}`;
async function getGitHubRepoContentsAtPath(repoPath, path, ref) {
const refQuery = ref ? `?ref=${ref}` : '';
const contentsRequestUrl = `https://api.github.com/repos/${repoPath}/contents/${path}${refQuery}`;
const response = await axios_1.default.get(contentsRequestUrl, {
headers: { ...requestOptions_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
headers: { ...getAxiosConfig_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
});

@@ -104,11 +107,11 @@ return response.data;

const resp = await axios_1.default.get(downloadUrl, {
headers: { ...requestOptions_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
headers: { ...getAxiosConfig_1.DEFAULT_USER_AGENT_HEADERS, ...GITHUB_AUTH_HEADERS },
});
fs_extra_1.default.writeFileSync(dest, resp.data, 'utf8');
}
// Writes files from a HubSpot public repository to the destination folder
async function downloadGithubRepoContents(repoName, contentPath, dest, filter) {
// Writes files from a public repository to the destination folder
async function downloadGithubRepoContents(repoPath, contentPath, dest, ref, filter) {
fs_extra_1.default.ensureDirSync(path_1.default.dirname(dest));
try {
const contentsResp = await getGitHubRepoContentsAtPath(repoName, contentPath);
const contentsResp = await getGitHubRepoContentsAtPath(repoPath, contentPath, ref);
const downloadContent = async (contentPiece) => {

@@ -127,3 +130,9 @@ const { path: contentPiecePath, download_url } = contentPiece;

};
const contentPromises = contentsResp.map(downloadContent);
let contentPromises;
if (Array.isArray(contentsResp)) {
contentPromises = contentsResp.map(downloadContent);
}
else {
contentPromises = [downloadContent(contentsResp)];
}
Promise.all(contentPromises);

@@ -133,3 +142,3 @@ }

const error = e;
if (error.error.message) {
if (error?.error?.message) {
(0, standardErrors_1.throwErrorWithMessage)('github.downloadGithubRepoContents', {

@@ -136,0 +145,0 @@ errorMessage: error.error.message,

@@ -9,3 +9,2 @@ "use strict";

const path_1 = __importDefault(require("path"));
const findup_sync_1 = __importDefault(require("findup-sync"));
const git_1 = require("../utils/git");

@@ -15,49 +14,5 @@ const config_1 = require("../constants/config");

const GITIGNORE_FILE = '.gitignore';
// Get all .gitignore files since they can cascade down directory structures
function getGitignoreFiles(configPath) {
const gitDir = (0, git_1.getGitComparisonDir)();
const files = [];
if (!gitDir) {
// Not in git
return files;
}
// Start findup from config dir
let cwd = configPath && path_1.default.dirname(configPath);
while (cwd) {
const ignorePath = (0, findup_sync_1.default)(GITIGNORE_FILE, { cwd });
const ignorePathComparisonDir = (0, git_1.makeComparisonDir)(ignorePath);
const gitComparisonDir = (0, git_1.makeComparisonDir)(gitDir);
if (ignorePath &&
ignorePathComparisonDir &&
gitComparisonDir &&
ignorePathComparisonDir.startsWith(gitComparisonDir)) {
const file = path_1.default.resolve(ignorePath);
files.push(file);
cwd = path_1.default.resolve(path_1.default.dirname(file) + '..');
}
else {
cwd = null;
}
}
return files;
}
function checkGitInclusion(configPath) {
const result = {
inGit: false,
configIgnored: false,
gitignoreFiles: [],
};
if ((0, git_1.isConfigPathInGitRepo)(configPath)) {
result.inGit = true;
result.gitignoreFiles = getGitignoreFiles(configPath);
if ((0, git_1.configFilenameIsIgnoredByGitignore)(result.gitignoreFiles, configPath)) {
// Found ignore statement in .gitignore that matches config filename
result.configIgnored = true;
}
}
return result;
}
function checkAndAddConfigToGitignore(configPath) {
try {
const { configIgnored, gitignoreFiles } = checkGitInclusion(configPath);
const { configIgnored, gitignoreFiles } = (0, git_1.checkGitInclusion)(configPath);
if (configIgnored)

@@ -64,0 +19,0 @@ return;

@@ -9,3 +9,4 @@ /// <reference types="node" />

export declare function getExt(filepath: string): string;
export declare function isAllowedExtension(filepath: string): boolean;
export declare function getAllowedExtensions(allowList?: Array<string>): Set<string>;
export declare function isAllowedExtension(filepath: string, allowList?: Array<string>): boolean;
export declare function getAbsoluteFilePath(_path: string): string;

@@ -6,3 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getAbsoluteFilePath = exports.isAllowedExtension = exports.getExt = exports.getCwd = exports.splitHubSpotPath = exports.splitLocalPath = exports.convertToLocalFileSystemPath = exports.convertToUnixPath = void 0;
exports.getAbsoluteFilePath = exports.isAllowedExtension = exports.getAllowedExtensions = exports.getExt = exports.getCwd = exports.splitHubSpotPath = exports.splitLocalPath = exports.convertToLocalFileSystemPath = exports.convertToUnixPath = void 0;
const path_1 = __importDefault(require("path"));

@@ -77,5 +77,10 @@ const unixify_1 = __importDefault(require("unixify"));

exports.getExt = getExt;
function isAllowedExtension(filepath) {
function getAllowedExtensions(allowList = []) {
return new Set([...Array.from(extensions_1.ALLOWED_EXTENSIONS), ...allowList]);
}
exports.getAllowedExtensions = getAllowedExtensions;
function isAllowedExtension(filepath, allowList = []) {
const ext = getExt(filepath);
return extensions_1.ALLOWED_EXTENSIONS.has(ext);
const allowedExtensions = getAllowedExtensions(allowList);
return allowedExtensions.has(ext);
}

@@ -82,0 +87,0 @@ exports.isAllowedExtension = isAllowedExtension;

{
"name": "@hubspot/local-dev-lib",
"version": "0.0.5",
"version": "0.0.6",
"description": "Provides library functionality for HubSpot local development tooling, including the HubSpot CLI",
"main": "dist/index.js",
"main": "lib/index.js",
"repository": {

@@ -15,3 +15,3 @@ "type": "git",

"scripts": {
"build": "tsc --rootDir . --outdir dist && yarn copy-files",
"build": "rm -rf ./dist/ && tsc --rootDir . --outdir dist && yarn copy-files",
"check-main": "branch=$(git rev-parse --abbrev-ref HEAD) && [ $branch = main ] || (echo 'Error: New release can only be published on main branch' && exit 1)",

@@ -21,6 +21,6 @@ "copy-files": "cp -r lang dist/lang",

"local-dev": "yarn build && cd dist && yarn link && cd .. && tsc --watch --rootDir . --outdir dist",
"_postinstall": "husky install",
"postinstall": "husky install",
"prepack": "pinst --disable",
"postpack": "pinst --enable",
"prettier:write": "prettier --write ./**/*.{js,json}",
"prettier:write": "prettier --write ./**/*.{ts,js,json}",
"pub": "cd dist && npm publish --tag latest && cd ..",

@@ -31,6 +31,8 @@ "push": "git push --atomic origin main v$npm_package_version",

"release:patch": "yarn check-main && yarn version --patch && yarn build && yarn pub && yarn push",
"test": "jest"
"test": "jest --silent"
},
"license": "Apache-2.0",
"devDependencies": {
"@types/content-disposition": "^0.5.5",
"@types/debounce": "^1.2.1",
"@types/findup-sync": "^4.0.2",

@@ -41,2 +43,3 @@ "@types/fs-extra": "^11.0.1",

"@types/node": "^18.14.2",
"@types/prettier": "^3.0.0",
"@types/unixify": "^1.0.0",

@@ -49,3 +52,2 @@ "@typescript-eslint/eslint-plugin": "^5.54.0",

"pinst": "^3.0.0",
"prettier": "^2.8.4",
"ts-jest": "^29.0.5",

@@ -55,20 +57,29 @@ "typescript": "^4.9.5"

"exports": {
".": "./lib/index.js",
"./cms": "./lib/cms",
"./constants": "./constants",
"./github": "./lib/github.js",
"./path": "./lib/path.js"
"./*": "./lib/*.js",
"./api/*": "./api/*.js",
"./errors/*": "./errors/*.js",
"./http": "./http/index.js",
"./config": "./config/index.js",
"./constants/*": "./constants/*.js",
"./logger": "./lib/logging/logger.js"
},
"dependencies": {
"axios": "^1.3.5",
"chokidar": "^3.5.3",
"content-disposition": "^0.5.4",
"extract-zip": "^2.0.1",
"findup-sync": "^5.0.0",
"fs-extra": "^11.1.0",
"ignore": "^5.1.4",
"js-yaml": "^4.1.0",
"moment": "^2.29.4",
"p-queue": "^6.0.2",
"prettier": "^3.0.3",
"semver": "^6.3.0",
"table": "^6.8.1",
"unixify": "^1.0.0"
},
"engines": {
"node": ">=18.0.0"
"node": ">=16.20.0"
}
}

@@ -1,11 +0,13 @@

import { DEFAULT_MODES } from '../constants/config';
import { ValueOf } from './Utils';
import { Mode } from './Files';
import { Environment } from './Config';
export type AuthType = 'personalaccesskey' | 'apikey' | 'oauth2';
export interface CLIAccount {
export interface CLIAccount_NEW {
name?: string;
accountId: number;
defaultMode?: ValueOf<typeof DEFAULT_MODES>;
env?: string;
defaultMode?: Mode;
env: Environment;
authType?: AuthType;
auth?: object;
auth?: {
tokenInfo?: TokenInfo;
};
sandboxAccountType?: string | null;

@@ -16,31 +18,61 @@ parentAccountId?: number | null;

}
export type PersonalAccessKeyTokenInfo = {
accessToken: string;
expiresAt: string;
};
export type OauthTokenInfo = {
export interface CLIAccount_DEPRECATED {
name?: string;
portalId?: number;
defaultMode?: Mode;
env: Environment;
authType?: AuthType;
auth?: {
tokenInfo?: TokenInfo;
};
sandboxAccountType?: string | null;
parentAccountId?: number | null;
apiKey?: string;
personalAccessKey?: string;
}
export type CLIAccount = CLIAccount_NEW | CLIAccount_DEPRECATED;
export type TokenInfo = {
accessToken?: string;
expiresAt?: string;
refreshToken?: string;
};
export interface PersonalAccessKeyAccount extends CLIAccount {
export interface PersonalAccessKeyAccount_NEW extends CLIAccount_NEW {
authType: 'personalaccesskey';
auth?: {
tokenInfo: PersonalAccessKeyTokenInfo;
};
personalAccessKey: string;
}
export interface OAuthAccount extends CLIAccount {
export interface PersonalAccessKeyAccount_DEPRECATED extends CLIAccount_DEPRECATED {
authType: 'personalaccesskey';
personalAccessKey: string;
}
export type PersonalAccessKeyAccount = PersonalAccessKeyAccount_NEW | PersonalAccessKeyAccount_DEPRECATED;
export interface OAuthAccount_NEW extends CLIAccount_NEW {
authType: 'oauth2';
auth?: {
auth: {
clientId?: string;
clientSecret?: string;
scopes?: Array<string>;
tokenInfo?: OauthTokenInfo;
tokenInfo?: TokenInfo;
};
}
export interface APIKeyAccount extends CLIAccount {
export interface OAuthAccount_DEPRECATED extends CLIAccount_DEPRECATED {
authType: 'oauth2';
auth: {
clientId?: string;
clientSecret?: string;
scopes?: Array<string>;
tokenInfo?: TokenInfo;
};
}
export type OAuthAccount = OAuthAccount_NEW | OAuthAccount_DEPRECATED;
export interface APIKeyAccount_NEW extends CLIAccount_NEW {
authType: 'apikey';
apiKey: string;
}
export interface FlatAccountFields<T extends OauthTokenInfo | PersonalAccessKeyTokenInfo> extends CLIAccount {
tokenInfo?: T;
export interface APIKeyAccount_DEPRECATED extends CLIAccount_DEPRECATED {
authType: 'apikey';
apiKey: string;
}
export type APIKeyAccount = APIKeyAccount_NEW | APIKeyAccount_DEPRECATED;
export interface FlatAccountFields_NEW extends CLIAccount_NEW {
tokenInfo?: TokenInfo;
clientId?: string;

@@ -52,1 +84,14 @@ clientSecret?: string;

}
export interface FlatAccountFields_DEPRECATED extends CLIAccount_DEPRECATED {
tokenInfo?: TokenInfo;
clientId?: string;
clientSecret?: string;
scopes?: Array<string>;
apiKey?: string;
personalAccessKey?: string;
}
export type FlatAccountFields = FlatAccountFields_NEW | FlatAccountFields_DEPRECATED;
export type ScopeData = {
portalScopesInGroup: Array<string>;
userScopesInGroup: Array<string>;
};
export interface CLIOptions {
silenceErrors?: boolean;
useEnv?: boolean;
}
export type WriteConfigOptions = {
path?: string;
source?: string;
};

@@ -1,4 +0,6 @@

import { CLIAccount } from './Accounts';
export interface CLIConfig {
accounts: Array<CLIAccount>;
import { ENVIRONMENTS } from '../constants/environments';
import { CLIAccount_NEW, CLIAccount_DEPRECATED } from './Accounts';
import { ValueOf } from './Utils';
export interface CLIConfig_NEW {
accounts: Array<CLIAccount_NEW>;
allowUsageTracking?: boolean;

@@ -8,4 +10,15 @@ defaultAccount?: string | number;

httpTimeout?: number;
env?: string;
env?: Environment;
httpUseLocalhost?: boolean;
}
export interface CLIConfig_DEPRECATED {
portals: Array<CLIAccount_DEPRECATED>;
allowUsageTracking?: boolean;
defaultPortal?: string | number;
defaultMode?: string;
httpTimeout?: number;
env?: Environment;
httpUseLocalhost?: boolean;
}
export type CLIConfig = CLIConfig_NEW | CLIConfig_DEPRECATED;
export type Environment = ValueOf<typeof ENVIRONMENTS> | '';

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

import { HttpMethod } from './Api';
export interface BaseError extends Error {

@@ -9,7 +10,11 @@ name: string;

statusCode?: number;
error?: BaseError;
errors?: Array<BaseError>;
}
export interface StatusCodeError extends BaseError {
name: 'StatusCodeError';
statusCode: number;
name: string;
statusCode?: number;
message: string;
category?: string;
subCategory?: string;
response: {

@@ -21,3 +26,6 @@ request: {

body: {
[key: string]: string;
message?: string;
errors?: Array<StatusCodeError>;
category?: string;
subCategory?: string;
};

@@ -27,8 +35,25 @@ headers: {

};
statusCode: number;
};
}
export interface GithubError extends BaseError {
error: {
message?: string;
options?: {
method: HttpMethod;
};
errorTokens?: {
line: number;
};
error?: StatusCodeError;
errors?: Array<StatusCodeError>;
}
export type FileSystemErrorContext = {
filepath: string;
write?: boolean;
read?: boolean;
accountId?: number;
};
export type StatusCodeErrorContext = {
accountId?: number;
request?: string;
payload?: string;
projectName?: string;
};
export type OptionalError = BaseError | null | undefined;
import { ValueOf } from '../types/Utils';
import { STAT_TYPES } from '../constants/files';
import { STAT_TYPES, FILE_TYPES, FILE_UPLOAD_RESULT_TYPES } from '../constants/files';
import { MODE } from '../constants/files';
import { HttpOptions } from './Http';
import { StatusCodeError } from './Error';
export type StatType = ValueOf<typeof STAT_TYPES>;

@@ -9,1 +12,30 @@ export type FileData = {

};
export type FileMapperNode = {
name: string;
createdAt: number;
updatedAt: number;
source: string | null;
path: string;
folder: boolean;
children: Array<FileMapperNode>;
};
export type Mode = ValueOf<typeof MODE>;
export type FileMapperOptions = Omit<HttpOptions, 'url'>;
export type FileMapperInputOptions = {
staging?: boolean;
assetVersion?: string;
overwrite?: boolean;
};
export type FileType = ValueOf<typeof FILE_TYPES>;
type ResultType = ValueOf<typeof FILE_UPLOAD_RESULT_TYPES>;
export type UploadFolderResults = {
resultType: ResultType;
error: StatusCodeError | null;
file: string;
};
export type FileTree = {
source?: string;
path: string;
children: Array<FileTree>;
};
export {};

@@ -58,2 +58,8 @@ type GithubAuthor = {

};
export interface GithubSourceData {
branch: string;
owner: string;
repositoryName: string;
source: string;
}
export {};

@@ -1,4 +0,9 @@

export declare function makeComparisonDir(filepath: string | null): string | null;
export declare const getGitComparisonDir: () => string | null;
export declare function isConfigPathInGitRepo(configPath: string): boolean;
export declare function configFilenameIsIgnoredByGitignore(ignoreFiles: Array<string>, configPath: string): boolean;
type GitInclusionResult = {
inGit: boolean;
configIgnored: boolean;
gitignoreFiles: Array<string>;
};
export declare function checkGitInclusion(configPath: string): GitInclusionResult;
export {};

@@ -6,7 +6,8 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.configFilenameIsIgnoredByGitignore = exports.isConfigPathInGitRepo = exports.getGitComparisonDir = exports.makeComparisonDir = void 0;
const fs_extra_1 = require("fs-extra");
exports.checkGitInclusion = exports.configFilenameIsIgnoredByGitignore = exports.isConfigPathInGitRepo = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const ignore_1 = __importDefault(require("ignore"));
const findup_sync_1 = __importDefault(require("findup-sync"));
const GITIGNORE_FILE = '.gitignore';
function makeComparisonDir(filepath) {

@@ -18,7 +19,36 @@ if (typeof filepath !== 'string')

}
exports.makeComparisonDir = makeComparisonDir;
const getGitComparisonDir = () => makeComparisonDir((0, findup_sync_1.default)('.git'));
exports.getGitComparisonDir = getGitComparisonDir;
function getGitComparisonDir() {
return makeComparisonDir((0, findup_sync_1.default)('.git'));
}
// Get all .gitignore files since they can cascade down directory structures
function getGitignoreFiles(configPath) {
const gitDir = getGitComparisonDir();
const files = [];
if (!gitDir) {
// Not in git
return files;
}
// Start findup from config dir
let cwd = configPath && path_1.default.dirname(configPath);
while (cwd) {
const ignorePath = (0, findup_sync_1.default)(GITIGNORE_FILE, { cwd });
const cmpIgnorePath = makeComparisonDir(ignorePath);
const cmpGitDir = makeComparisonDir(gitDir);
if (ignorePath &&
cmpIgnorePath &&
cmpGitDir &&
// Stop findup after .git dir is reached
cmpIgnorePath.startsWith(cmpGitDir)) {
const file = path_1.default.resolve(ignorePath);
files.push(file);
cwd = path_1.default.resolve(path_1.default.dirname(file) + '..');
}
else {
cwd = null;
}
}
return files;
}
function isConfigPathInGitRepo(configPath) {
const gitDir = (0, exports.getGitComparisonDir)();
const gitDir = getGitComparisonDir();
if (!gitDir)

@@ -34,3 +64,3 @@ return false;

return ignoreFiles.some(gitignore => {
const gitignoreContents = (0, fs_extra_1.readFileSync)(gitignore).toString();
const gitignoreContents = fs_extra_1.default.readFileSync(gitignore).toString();
const gitignoreConfig = (0, ignore_1.default)().add(gitignoreContents);

@@ -44,1 +74,18 @@ if (gitignoreConfig.ignores(path_1.default.relative(path_1.default.dirname(gitignore), configPath))) {

exports.configFilenameIsIgnoredByGitignore = configFilenameIsIgnoredByGitignore;
function checkGitInclusion(configPath) {
const result = {
inGit: false,
configIgnored: false,
gitignoreFiles: [],
};
if (isConfigPathInGitRepo(configPath)) {
result.inGit = true;
result.gitignoreFiles = getGitignoreFiles(configPath);
if (configFilenameIsIgnoredByGitignore(result.gitignoreFiles, configPath)) {
// Found ignore statement in .gitignore that matches config filename
result.configIgnored = true;
}
}
return result;
}
exports.checkGitInclusion = checkGitInclusion;

@@ -0,1 +1,4 @@

type LanguageObject = {
[key: string]: LanguageObject | string;
};
type InterpolationData = {

@@ -8,2 +11,3 @@ [identifier: string]: string | number;

}): string;
export declare const setLangData: (newLocale: string, newLangObj: LanguageObject) => void;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.i18n = exports.interpolate = void 0;
exports.setLangData = exports.i18n = exports.interpolate = void 0;
const path_1 = require("path");

@@ -75,2 +75,5 @@ const fs_extra_1 = require("fs-extra");

function i18n(lookupDotNotation, options = {}) {
if (!languageObj) {
loadLanguageFromYaml();
}
if (typeof lookupDotNotation !== 'string') {

@@ -84,2 +87,6 @@ throw new Error(`i18n must be passed a string value for lookupDotNotation, received ${typeof lookupDotNotation}`);

exports.i18n = i18n;
loadLanguageFromYaml();
const setLangData = (newLocale, newLangObj) => {
locale = newLocale;
languageObj = newLangObj;
};
exports.setLangData = setLangData;

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc