insomnia/packages/insomnia-app/app/templating/utils.js

238 lines
6.4 KiB
JavaScript
Raw Normal View History

// @flow
Version Control (beta) (#1439) * VCS proof of concept underway! * Stuff * Some things * Replace deprecated Electron makeSingleInstance * Rename `window` variables so not to be confused with window object * Don't unnecessarily update request when URL does not change * Regenerate package-lock * Fix tests + ESLint * Publish - insomnia-app@1.0.49 - insomnia-cookies@0.0.12 - insomnia-httpsnippet@1.16.18 - insomnia-importers@2.0.13 - insomnia-libcurl@0.0.23 - insomnia-prettify@0.1.7 - insomnia-url@0.1.6 - insomnia-xpath@1.0.9 - insomnia-plugin-base64@1.0.6 - insomnia-plugin-cookie-jar@1.0.8 - insomnia-plugin-core-themes@1.0.5 - insomnia-plugin-default-headers@1.1.9 - insomnia-plugin-file@1.0.7 - insomnia-plugin-hash@1.0.7 - insomnia-plugin-jsonpath@1.0.12 - insomnia-plugin-now@1.0.11 - insomnia-plugin-os@1.0.13 - insomnia-plugin-prompt@1.1.9 - insomnia-plugin-request@1.0.18 - insomnia-plugin-response@1.0.16 - insomnia-plugin-uuid@1.0.10 * Broken but w/e * Some tweaks * Big refactor. Create local snapshots and push done * POC merging and a lot of improvements * Lots of work done on initial UI/UX * Fix old tests * Atomic writes and size-based batches * Update StageEntry definition once again to be better * Factor out GraphQL query logic * Merge algorithm, history modal, other minor things * Fix test * Merge, checkout, revert w/ user changes now work * Force UI to refresh when switching branches changes active request * Rough draft pull() and some cleanup * E2EE stuff and some refactoring * Add ability to share project with team and fixed tests * VCS now created in root component and better remote project handling * Remove unused definition * Publish - insomnia-account@0.0.2 - insomnia-app@1.1.1 - insomnia-cookies@0.0.14 - insomnia-httpsnippet@1.16.20 - insomnia-importers@2.0.15 - insomnia-libcurl@0.0.25 - insomnia-prettify@0.1.9 - insomnia-sync@0.0.2 - insomnia-url@0.1.8 - insomnia-xpath@1.0.11 - insomnia-plugin-base64@1.0.8 - insomnia-plugin-cookie-jar@1.0.10 - insomnia-plugin-core-themes@1.0.7 - insomnia-plugin-file@1.0.9 - insomnia-plugin-hash@1.0.9 - insomnia-plugin-jsonpath@1.0.14 - insomnia-plugin-now@1.0.13 - insomnia-plugin-os@1.0.15 - insomnia-plugin-prompt@1.1.11 - insomnia-plugin-request@1.0.20 - insomnia-plugin-response@1.0.18 - insomnia-plugin-uuid@1.0.12 * Move some deps around * Fix Flow errors * Update package.json * Fix eslint errors * Fix tests * Update deps * bootstrap insomnia-sync * TRy fixing appveyor * Try something else * Bump lerna * try powershell * Try again * Fix imports * Fixed errors * sync types refactor * Show remote projects in workspace dropdown * Improved pulling of non-local workspaces * Loading indicators and some tweaks * Clean up sync staging modal * Some sync improvements: - No longer store stage - Upgrade Electron - Sync UI/UX improvements * Fix snyc tests * Upgraded deps and hot loader tweaks (it's broken for some reason) * Fix tests * Branches dialog, network refactoring, some tweaks * Fixed merging when other branch is empty * A bunch of small fixes from real testing * Fixed pull merge logic * Fix tests * Some bug fixes * A few small tweaks * Conflict resolution and other improvements * Fix tests * Add revert changes * Deal with duplicate projects per workspace * Some tweaks and accessibility improvements * Tooltip accessibility * Fix API endpoint * Fix tests * Remove jest dep from insomnia-importers
2019-04-18 00:50:03 +00:00
import type { PluginArgumentEnumOption } from './extensions';
export type NunjucksParsedTagArg = {
Version Control (beta) (#1439) * VCS proof of concept underway! * Stuff * Some things * Replace deprecated Electron makeSingleInstance * Rename `window` variables so not to be confused with window object * Don't unnecessarily update request when URL does not change * Regenerate package-lock * Fix tests + ESLint * Publish - insomnia-app@1.0.49 - insomnia-cookies@0.0.12 - insomnia-httpsnippet@1.16.18 - insomnia-importers@2.0.13 - insomnia-libcurl@0.0.23 - insomnia-prettify@0.1.7 - insomnia-url@0.1.6 - insomnia-xpath@1.0.9 - insomnia-plugin-base64@1.0.6 - insomnia-plugin-cookie-jar@1.0.8 - insomnia-plugin-core-themes@1.0.5 - insomnia-plugin-default-headers@1.1.9 - insomnia-plugin-file@1.0.7 - insomnia-plugin-hash@1.0.7 - insomnia-plugin-jsonpath@1.0.12 - insomnia-plugin-now@1.0.11 - insomnia-plugin-os@1.0.13 - insomnia-plugin-prompt@1.1.9 - insomnia-plugin-request@1.0.18 - insomnia-plugin-response@1.0.16 - insomnia-plugin-uuid@1.0.10 * Broken but w/e * Some tweaks * Big refactor. Create local snapshots and push done * POC merging and a lot of improvements * Lots of work done on initial UI/UX * Fix old tests * Atomic writes and size-based batches * Update StageEntry definition once again to be better * Factor out GraphQL query logic * Merge algorithm, history modal, other minor things * Fix test * Merge, checkout, revert w/ user changes now work * Force UI to refresh when switching branches changes active request * Rough draft pull() and some cleanup * E2EE stuff and some refactoring * Add ability to share project with team and fixed tests * VCS now created in root component and better remote project handling * Remove unused definition * Publish - insomnia-account@0.0.2 - insomnia-app@1.1.1 - insomnia-cookies@0.0.14 - insomnia-httpsnippet@1.16.20 - insomnia-importers@2.0.15 - insomnia-libcurl@0.0.25 - insomnia-prettify@0.1.9 - insomnia-sync@0.0.2 - insomnia-url@0.1.8 - insomnia-xpath@1.0.11 - insomnia-plugin-base64@1.0.8 - insomnia-plugin-cookie-jar@1.0.10 - insomnia-plugin-core-themes@1.0.7 - insomnia-plugin-file@1.0.9 - insomnia-plugin-hash@1.0.9 - insomnia-plugin-jsonpath@1.0.14 - insomnia-plugin-now@1.0.13 - insomnia-plugin-os@1.0.15 - insomnia-plugin-prompt@1.1.11 - insomnia-plugin-request@1.0.20 - insomnia-plugin-response@1.0.18 - insomnia-plugin-uuid@1.0.12 * Move some deps around * Fix Flow errors * Update package.json * Fix eslint errors * Fix tests * Update deps * bootstrap insomnia-sync * TRy fixing appveyor * Try something else * Bump lerna * try powershell * Try again * Fix imports * Fixed errors * sync types refactor * Show remote projects in workspace dropdown * Improved pulling of non-local workspaces * Loading indicators and some tweaks * Clean up sync staging modal * Some sync improvements: - No longer store stage - Upgrade Electron - Sync UI/UX improvements * Fix snyc tests * Upgraded deps and hot loader tweaks (it's broken for some reason) * Fix tests * Branches dialog, network refactoring, some tweaks * Fixed merging when other branch is empty * A bunch of small fixes from real testing * Fixed pull merge logic * Fix tests * Some bug fixes * A few small tweaks * Conflict resolution and other improvements * Fix tests * Add revert changes * Deal with duplicate projects per workspace * Some tweaks and accessibility improvements * Tooltip accessibility * Fix API endpoint * Fix tests * Remove jest dep from insomnia-importers
2019-04-18 00:50:03 +00:00
type:
| 'string'
| 'number'
| 'boolean'
| 'number'
| 'variable'
| 'expression'
| 'enum'
| 'file'
| 'model',
encoding?: 'base64',
value: string | number | boolean,
defaultValue?: string | number | boolean,
forceVariable?: boolean,
2018-03-29 17:59:32 +00:00
placeholder?: string,
help?: string,
displayName?: string,
quotedBy?: '"' | "'",
validate?: (value: any) => string,
hide?: (Array<NunjucksParsedTagArg>) => boolean,
Version Control (beta) (#1439) * VCS proof of concept underway! * Stuff * Some things * Replace deprecated Electron makeSingleInstance * Rename `window` variables so not to be confused with window object * Don't unnecessarily update request when URL does not change * Regenerate package-lock * Fix tests + ESLint * Publish - insomnia-app@1.0.49 - insomnia-cookies@0.0.12 - insomnia-httpsnippet@1.16.18 - insomnia-importers@2.0.13 - insomnia-libcurl@0.0.23 - insomnia-prettify@0.1.7 - insomnia-url@0.1.6 - insomnia-xpath@1.0.9 - insomnia-plugin-base64@1.0.6 - insomnia-plugin-cookie-jar@1.0.8 - insomnia-plugin-core-themes@1.0.5 - insomnia-plugin-default-headers@1.1.9 - insomnia-plugin-file@1.0.7 - insomnia-plugin-hash@1.0.7 - insomnia-plugin-jsonpath@1.0.12 - insomnia-plugin-now@1.0.11 - insomnia-plugin-os@1.0.13 - insomnia-plugin-prompt@1.1.9 - insomnia-plugin-request@1.0.18 - insomnia-plugin-response@1.0.16 - insomnia-plugin-uuid@1.0.10 * Broken but w/e * Some tweaks * Big refactor. Create local snapshots and push done * POC merging and a lot of improvements * Lots of work done on initial UI/UX * Fix old tests * Atomic writes and size-based batches * Update StageEntry definition once again to be better * Factor out GraphQL query logic * Merge algorithm, history modal, other minor things * Fix test * Merge, checkout, revert w/ user changes now work * Force UI to refresh when switching branches changes active request * Rough draft pull() and some cleanup * E2EE stuff and some refactoring * Add ability to share project with team and fixed tests * VCS now created in root component and better remote project handling * Remove unused definition * Publish - insomnia-account@0.0.2 - insomnia-app@1.1.1 - insomnia-cookies@0.0.14 - insomnia-httpsnippet@1.16.20 - insomnia-importers@2.0.15 - insomnia-libcurl@0.0.25 - insomnia-prettify@0.1.9 - insomnia-sync@0.0.2 - insomnia-url@0.1.8 - insomnia-xpath@1.0.11 - insomnia-plugin-base64@1.0.8 - insomnia-plugin-cookie-jar@1.0.10 - insomnia-plugin-core-themes@1.0.7 - insomnia-plugin-file@1.0.9 - insomnia-plugin-hash@1.0.9 - insomnia-plugin-jsonpath@1.0.14 - insomnia-plugin-now@1.0.13 - insomnia-plugin-os@1.0.15 - insomnia-plugin-prompt@1.1.11 - insomnia-plugin-request@1.0.20 - insomnia-plugin-response@1.0.18 - insomnia-plugin-uuid@1.0.12 * Move some deps around * Fix Flow errors * Update package.json * Fix eslint errors * Fix tests * Update deps * bootstrap insomnia-sync * TRy fixing appveyor * Try something else * Bump lerna * try powershell * Try again * Fix imports * Fixed errors * sync types refactor * Show remote projects in workspace dropdown * Improved pulling of non-local workspaces * Loading indicators and some tweaks * Clean up sync staging modal * Some sync improvements: - No longer store stage - Upgrade Electron - Sync UI/UX improvements * Fix snyc tests * Upgraded deps and hot loader tweaks (it's broken for some reason) * Fix tests * Branches dialog, network refactoring, some tweaks * Fixed merging when other branch is empty * A bunch of small fixes from real testing * Fixed pull merge logic * Fix tests * Some bug fixes * A few small tweaks * Conflict resolution and other improvements * Fix tests * Add revert changes * Deal with duplicate projects per workspace * Some tweaks and accessibility improvements * Tooltip accessibility * Fix API endpoint * Fix tests * Remove jest dep from insomnia-importers
2019-04-18 00:50:03 +00:00
model?: string,
options?: Array<PluginArgumentEnumOption>,
itemTypes?: Array<string>,
extensions?: Array<string>,
};
export type NunjucksParsedTag = {
name: string,
args: Array<NunjucksParsedTagArg>,
rawValue?: string,
displayName?: string,
description?: string,
disablePreview?: (Array<NunjucksParsedTagArg>) => boolean,
};
/**
* Get list of paths to all primitive types in nested object
* @param {object} obj - object to analyse
* @param {String} [prefix] - base path to prefix to all paths
* @returns {Array} - list of paths
*/
2018-10-17 16:42:33 +00:00
export function getKeys(obj: any, prefix: string = ''): Array<{ name: string, value: any }> {
let allKeys = [];
const typeOfObj = Object.prototype.toString.call(obj);
if (typeOfObj === '[object Array]') {
for (let i = 0; i < obj.length; i++) {
allKeys = [...allKeys, ...getKeys(obj[i], `${prefix}[${i}]`)];
}
} else if (typeOfObj === '[object Object]') {
const keys = Object.keys(obj);
for (const key of keys) {
const newPrefix = prefix ? `${prefix}.${key}` : key;
allKeys = [...allKeys, ...getKeys(obj[key], newPrefix)];
}
2017-07-14 19:34:14 +00:00
} else if (typeOfObj === '[object Function]') {
// Ignore functions
} else if (prefix) {
2018-06-25 17:42:50 +00:00
allKeys.push({ name: prefix, value: obj });
}
return allKeys;
}
/**
* Parse a Nunjucks tag string into a usable abject
* @param {string} tagStr - the template string for the tag
* @return {object} parsed tag data
*/
2018-06-25 17:42:50 +00:00
export function tokenizeTag(tagStr: string): NunjucksParsedTag {
// ~~~~~~~~ //
// Sanitize //
// ~~~~~~~~ //
const withoutEnds = tagStr
.trim()
.replace(/^{%/, '')
.replace(/%}$/, '')
.trim();
const nameMatch = withoutEnds.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*/);
const name = nameMatch ? nameMatch[0] : withoutEnds;
const argsStr = withoutEnds.slice(name.length);
// ~~~~~~~~~~~~~ //
// Tokenize Args //
// ~~~~~~~~~~~~~ //
const args = [];
let quotedBy = null;
let currentArg = null;
for (let i = 0; i < argsStr.length + 1; i++) {
// Adding an "invisible" at the end helps us terminate the last arg
const c = argsStr.charAt(i) || ',';
// Do nothing if we're still on a space o comma
if (currentArg === null && c.match(/[\s,]/)) {
continue;
}
// Start a new single-quoted string
if (currentArg === null && c === "'") {
currentArg = '';
quotedBy = "'";
continue;
}
// Start a new double-quoted string
if (currentArg === null && c === '"') {
currentArg = '';
quotedBy = '"';
continue;
}
// Start a new unquoted string
if (currentArg === null) {
currentArg = c;
quotedBy = null;
continue;
}
const endQuoted = quotedBy && c === quotedBy;
const endUnquoted = !quotedBy && c === ',';
const argCompleted = endQuoted || endUnquoted;
// Append current char to argument
if (!argCompleted && currentArg !== null) {
if (c === '\\') {
// Handle backslashes
i += 1;
currentArg += argsStr.charAt(i);
} else {
currentArg += c;
}
}
// End current argument
if (currentArg !== null && argCompleted) {
let arg;
if (quotedBy) {
2018-06-25 17:42:50 +00:00
arg = { type: 'string', value: currentArg, quotedBy };
} else if (['true', 'false'].includes(currentArg)) {
2018-06-25 17:42:50 +00:00
arg = { type: 'boolean', value: currentArg.toLowerCase() === 'true' };
} else if (currentArg.match(/^\d*\.?\d*$/)) {
2018-06-25 17:42:50 +00:00
arg = { type: 'number', value: currentArg };
} else if (currentArg.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*$/)) {
2018-06-25 17:42:50 +00:00
arg = { type: 'variable', value: currentArg };
} else {
2018-06-25 17:42:50 +00:00
arg = { type: 'expression', value: currentArg };
}
args.push(arg);
currentArg = null;
quotedBy = null;
}
}
2018-06-25 17:42:50 +00:00
return { name, args };
}
/** Convert a tokenized tag back into a Nunjucks string */
2018-06-25 17:42:50 +00:00
export function unTokenizeTag(tagData: NunjucksParsedTag): string {
const args = [];
for (const arg of tagData.args) {
if (['string', 'model', 'file'].includes(arg.type)) {
const q = arg.quotedBy || "'";
const re = new RegExp(`([^\\\\])${q}`, 'g');
const str = arg.value.toString().replace(re, `$1\\${q}`);
args.push(`${q}${str}${q}`);
} else if (arg.type === 'boolean') {
args.push(arg.value ? 'true' : 'false');
} else {
args.push(arg.value);
}
}
const argsStr = args.join(', ');
return `{% ${tagData.name} ${argsStr} %}`;
}
/** Get the default Nunjucks string for an extension */
2018-10-17 16:42:33 +00:00
export function getDefaultFill(name: string, args: Array<NunjucksParsedTagArg>): string {
const stringArgs: Array<string> = (args || []).map(argDefinition => {
switch (argDefinition.type) {
case 'enum':
2018-06-25 17:42:50 +00:00
const { defaultValue, options } = argDefinition;
Version Control (beta) (#1439) * VCS proof of concept underway! * Stuff * Some things * Replace deprecated Electron makeSingleInstance * Rename `window` variables so not to be confused with window object * Don't unnecessarily update request when URL does not change * Regenerate package-lock * Fix tests + ESLint * Publish - insomnia-app@1.0.49 - insomnia-cookies@0.0.12 - insomnia-httpsnippet@1.16.18 - insomnia-importers@2.0.13 - insomnia-libcurl@0.0.23 - insomnia-prettify@0.1.7 - insomnia-url@0.1.6 - insomnia-xpath@1.0.9 - insomnia-plugin-base64@1.0.6 - insomnia-plugin-cookie-jar@1.0.8 - insomnia-plugin-core-themes@1.0.5 - insomnia-plugin-default-headers@1.1.9 - insomnia-plugin-file@1.0.7 - insomnia-plugin-hash@1.0.7 - insomnia-plugin-jsonpath@1.0.12 - insomnia-plugin-now@1.0.11 - insomnia-plugin-os@1.0.13 - insomnia-plugin-prompt@1.1.9 - insomnia-plugin-request@1.0.18 - insomnia-plugin-response@1.0.16 - insomnia-plugin-uuid@1.0.10 * Broken but w/e * Some tweaks * Big refactor. Create local snapshots and push done * POC merging and a lot of improvements * Lots of work done on initial UI/UX * Fix old tests * Atomic writes and size-based batches * Update StageEntry definition once again to be better * Factor out GraphQL query logic * Merge algorithm, history modal, other minor things * Fix test * Merge, checkout, revert w/ user changes now work * Force UI to refresh when switching branches changes active request * Rough draft pull() and some cleanup * E2EE stuff and some refactoring * Add ability to share project with team and fixed tests * VCS now created in root component and better remote project handling * Remove unused definition * Publish - insomnia-account@0.0.2 - insomnia-app@1.1.1 - insomnia-cookies@0.0.14 - insomnia-httpsnippet@1.16.20 - insomnia-importers@2.0.15 - insomnia-libcurl@0.0.25 - insomnia-prettify@0.1.9 - insomnia-sync@0.0.2 - insomnia-url@0.1.8 - insomnia-xpath@1.0.11 - insomnia-plugin-base64@1.0.8 - insomnia-plugin-cookie-jar@1.0.10 - insomnia-plugin-core-themes@1.0.7 - insomnia-plugin-file@1.0.9 - insomnia-plugin-hash@1.0.9 - insomnia-plugin-jsonpath@1.0.14 - insomnia-plugin-now@1.0.13 - insomnia-plugin-os@1.0.15 - insomnia-plugin-prompt@1.1.11 - insomnia-plugin-request@1.0.20 - insomnia-plugin-response@1.0.18 - insomnia-plugin-uuid@1.0.12 * Move some deps around * Fix Flow errors * Update package.json * Fix eslint errors * Fix tests * Update deps * bootstrap insomnia-sync * TRy fixing appveyor * Try something else * Bump lerna * try powershell * Try again * Fix imports * Fixed errors * sync types refactor * Show remote projects in workspace dropdown * Improved pulling of non-local workspaces * Loading indicators and some tweaks * Clean up sync staging modal * Some sync improvements: - No longer store stage - Upgrade Electron - Sync UI/UX improvements * Fix snyc tests * Upgraded deps and hot loader tweaks (it's broken for some reason) * Fix tests * Branches dialog, network refactoring, some tweaks * Fixed merging when other branch is empty * A bunch of small fixes from real testing * Fixed pull merge logic * Fix tests * Some bug fixes * A few small tweaks * Conflict resolution and other improvements * Fix tests * Add revert changes * Deal with duplicate projects per workspace * Some tweaks and accessibility improvements * Tooltip accessibility * Fix API endpoint * Fix tests * Remove jest dep from insomnia-importers
2019-04-18 00:50:03 +00:00
const fallback = options && options.length ? options[0].value : '';
const value = defaultValue !== undefined ? String(defaultValue) : String(fallback);
return `'${value}'`;
case 'number':
return `${parseFloat(argDefinition.defaultValue) || 0}`;
case 'boolean':
return argDefinition.defaultValue ? 'true' : 'false';
case 'string':
case 'file':
case 'model':
return `'${(argDefinition.defaultValue: any) || ''}'`;
default:
return "''";
}
});
return `${name} ${stringArgs.join(', ')}`;
}
export function encodeEncoding(value: string, encoding: 'base64'): string {
if (typeof value !== 'string') {
return value;
}
if (encoding === 'base64') {
const encodedValue = Buffer.from(value, 'utf8').toString('base64');
return `b64::${encodedValue}::46b`;
}
return value;
}
export function decodeEncoding(value: string): string {
if (typeof value !== 'string') {
return value;
}
const results = value.match(/^b64::(.+)::46b$/);
if (results) {
return Buffer.from(results[1], 'base64').toString('utf8');
}
return value;
}