mirror of
https://github.com/usebruno/bruno.git
synced 2026-07-08 14:35:03 +00:00
feat(variables): persist scripted variable changes by default + re-enable disabled scripting APIs (#8315)
* feat(variables): add variable persistence with scripting feat(collections): implement script-driven update for collection variables, ensuring direct root modification and draft synchronization feat(collections): enhance script variable management with baseline tracking and draft preservation * feat(variables): add runtime variable updates and optimize disk writes by implementing dirty flags fix(collections): handle errors during environment persistence in script execution feat(collections): implement baseline clearing for script execution and optimize variable update handling feat(tests): add default persistence tests for environment variables and update runtime variable handling refactor(collections): streamline variable update handling and improve draft management by removing redundant comments and optimizing code clarity test(collection-vars): add verification for draft edits and script variable visibility in collection settings UI refactor(collection-vars): update header value selection logic for improved clarity and accuracy in draft isolation tests * feat(global-environments): enhance global environment updates to resolve stale active UIDs and improve persistence logic - Updated the `updateGlobalEnvironments` reducer to handle stale active UIDs by matching against environment names. - Improved the logic for setting global environments and active UIDs to ensure consistency after disk reloads. - Removed outdated tests related to persisted values in favor of more relevant assertions for environment variable handling. * feat(variables): enhance typed value handling and persistence in global and collection environments - Added tests to infer data types (number, boolean, object) when setting environment and collection variables. - Updated the logic to preserve existing data types when variables are not modified by scripts. - Implemented dirty flags to track changes in typed variables, ensuring accurate persistence across sessions. - Refactored related tests to verify the correct behavior of typed variables in various scenarios. * refactor(variables): streamline data type inference and enhance deletion methods - Removed redundant data type inference logic from global and collection variable updates to simplify the codebase. - Updated deletion methods in the Bru class to use Object.keys for improved resilience against user-defined properties. - Added tests to ensure deletion methods function correctly even when properties are shadowed. - Enhanced clarity in draft merge tests by standardizing keyboard shortcuts for selecting all text. * fix(tests): correct variable naming and improve environment panel interactions - Updated test cases to reflect the correct variable name 'wasSaved' instead of 'was-saved'. - Modified environment panel interaction to remove forced click, enhancing test reliability. - Added a utility function to close the environment panel in safe mode tests for better readability and maintainability. * feat(runtime): enhance variable management and cleanup logic - Introduced a new method to clear script-driven variable baselines for collections, ensuring no stale data leaks into new requests. - Updated the handling of runtime variables in the Bru class to track changes with a new dirty flag, improving state management. - Refactored the application of script environment variables to prevent direct mutations, ensuring immutability and cleaner state updates. - Enhanced the response handling in the script runtime to conditionally include runtime variables based on their dirty state. * feat(variables): improve request handling and state management for collections and environments - Enhanced event listeners to clear global environment baselines on both 'testrun-started' and 'request-queued' events, preventing stale data issues. - Updated global environment and collection variable update events to ignore stale updates from superseded requests, ensuring accurate state management. - Refactored the Bru class to optimize variable management, including checks for existing keys before updates and deletions, improving performance and reliability. - Introduced request UID tracking to maintain consistency across variable updates during concurrent requests. * refactor(collections): update action to clear script variable baselines - Replaced the dispatch of `_clearScriptGlobalEnvBaseline` with `clearScriptVariableBaselines` to improve clarity and maintainability in the Redux action handling for collections. * feat(environments): introduce getScriptModifiedKeys utility for improved variable management - Added a new utility function, `getScriptModifiedKeys`, to identify keys modified by scripts relative to a baseline, enhancing the handling of data types during variable updates. - Updated the application of script environment variables to prevent overwriting user-defined draft changes during no-op writes. - Refactored related logic in collections and global environments to utilize the new utility, ensuring accurate state management and improved clarity in the Redux slices. * refactor(global-environments): simplify active UID resolution logic in updateGlobalEnvironments reducer - Streamlined the logic for resolving the active global environment UID by consolidating conditions into a more concise format. - Removed outdated comments to enhance code clarity and maintainability. - Updated tests to ensure accurate resolution of active UIDs based on incoming environment data. * refactor(tests): remove outdated comments and streamline environment variable row expectations - Eliminated comments related to state sync and inference issues to enhance code clarity. - Adjusted expectations for environment variable row rendering in tests, focusing on relevant assertions. * feat(tests): add comprehensive tests for secret variable persistence in environments - Introduced new test cases to validate the preservation of secret variables when updated via scripts in both collection and global environments. - Implemented tests to ensure that secret values are encrypted before storage and can be correctly decrypted for subsequent requests. - Added fixtures and environment configurations for testing secret variable behavior in both bru and yml formats. - Enhanced utility functions for managing environment configurations and interactions within the test suite. * feat(tests): enhance environment variable tests and add global variable persistence - Updated MultiLineEditor and SingleLineEditor components to include data-testid for secret reveal toggle buttons, improving testability. - Introduced new tests for global environment variable persistence, ensuring non-secret variables survive app restarts and are correctly interpolated. - Added fixtures for workspace and collections to support the new global variable tests, enhancing the overall test coverage for environment management. - Refactored utility functions to streamline interactions with environment variables in tests. * refactor(collections): optimize environment and collection saving logic - Simplified the persistence logic for active environments by directly constructing the environment copy, reducing unnecessary cloning. - Updated the collection saving process to utilize the fresh collection state, ensuring accurate data is saved without drafts. - Enhanced error handling during the save operations to improve reliability and maintainability. * feat(tests): implement collection variable persistence tests - Added multiple test cases to validate the persistence of collection variables across app restarts, including typed values and multiple variable settings. - Created new fixtures for collection variables to support the tests, ensuring accurate simulation of variable management scenarios. - Enhanced the existing collection management logic to ensure that variables are correctly set and deleted as per the test requirements. * feat(tests): add tests for typed global environment variable persistence - Introduced a new test suite to validate the persistence of typed global environment variables across app restarts, ensuring correct data types are maintained. - Created a fixture for the test collection to simulate setting global variables with various data types, including number, boolean, object, and string. - Enhanced the test logic to verify that the environment file reflects the correct state before and after application restarts. * fix(tests): update request tab close interaction in variable persistence tests * fix(tests): improve hover interaction for collection actions in runner tests - Updated the hover logic for revealing collection actions to handle sidebar re-renders more reliably. - Replaced one-shot hover with a polling mechanism to ensure visibility of actions, enhancing test stability. * refactor(environments): streamline environment variable handling and remove ephemeral metadata logic - Simplified the comparison logic for environment variables by removing unnecessary ephemeral metadata handling. - Updated the saving process to directly use the environment variables without stripping metadata, enhancing clarity and maintainability. - Removed outdated comments and unused utility functions related to ephemeral variables, improving code cleanliness. * fix(ipc): update persistActiveEnvironment to handle requestUid for stale updates - Modified the persistActiveEnvironment function to accept a requestUid parameter, allowing for better management of stale updates. - Enhanced the logic to prevent disk writes for superseded requests, improving data integrity during environment persistence. * refactor(bru): remove unused envName variable in deleteAllEnvVars method - Eliminated the envName variable from the deleteAllEnvVars method, simplifying the logic for deleting environment variables. - Cleaned up the method by removing unnecessary checks related to the envName, enhancing code clarity and maintainability. * fix(bru): prevent deletion of internal __name__ variable in deleteEnvVar method - Added a check in the deleteEnvVar method to silently ignore attempts to delete the internal __name__ variable, preserving its integrity. - Updated tests to verify that the __name__ variable remains unchanged when deleteEnvVar is called with this key. - Enhanced runtime tests to ensure compatibility with QuickJS by confirming that environment variables set with persist options are handled correctly. * feat(tests): add legacy support test for environment variable persistence - Introduced a new test suite to validate that the legacy argument for setting environment variables with persistence is still functional in version 4. - Created a fixture to simulate the legacy syntax, ensuring that the variable is correctly persisted on disk without errors. - Enhanced integration testing to confirm that the legacy behavior aligns with the current implementation, maintaining backward compatibility. * test(tests): enhance legacy environment variable persistence tests for safe and developer modes - Updated the test suite for `bru.setEnvVar` to verify that the legacy persist flag is correctly handled in both safe and developer modes. - Introduced a helper function to streamline the verification process and ensure consistent behavior across different execution contexts. - Adjusted the test logic to reset the environment state between mode switches, maintaining test integrity. - Improved hover interaction in multiple persistent variable tests to ensure reliable visibility of actions during execution. * fix(EnvironmentVariablesTable): correct change detection logic for environment variables - Updated the logic for determining changes in environment variables to compare active current and saved values instead of previously used variablesToSave and savedValues. - This change ensures accurate detection of modifications before saving, improving user feedback when no changes are present. * test(tests): enhance secret variable persistence tests for environment configurations - Updated the test suites for `bru.setEnvVar` and `bru.setGlobalEnvVar` to include interactions with the secrets tab, ensuring visibility of secret variables during various states of the environment. - Added checks to confirm that the eye toggle functionality correctly reveals the values of secret variables after setting and overwriting them. - Improved test coverage for secret variable persistence, validating that the expected values are displayed in both collection and global environment contexts.
This commit is contained in:
@@ -3,9 +3,6 @@ import { mockDataFunctions } from '@usebruno/common';
|
||||
const CodeMirror = require('codemirror');
|
||||
|
||||
// Static API hints - Bruno JavaScript API (subgrouped by category)
|
||||
// TODO: Restore the commented-out APIs once the UI update fixes are live.
|
||||
// Currently these APIs only work within the request lifecycle but fail to update the UI tables.
|
||||
// e.g., setCollectionVar only sets the variable in the request lifecycle, fails to update the table in the UI.
|
||||
const STATIC_API_HINTS = {
|
||||
req: [
|
||||
'req',
|
||||
@@ -109,13 +106,12 @@ const STATIC_API_HINTS = {
|
||||
'bru.getEnvVar(key)',
|
||||
'bru.getFolderVar(key)',
|
||||
'bru.getCollectionVar(key)',
|
||||
// 'bru.setCollectionVar(key, value)',
|
||||
'bru.setCollectionVar(key, value)',
|
||||
'bru.hasCollectionVar(key)',
|
||||
// 'bru.deleteCollectionVar(key)',
|
||||
// 'bru.deleteAllCollectionVars()',
|
||||
// 'bru.getAllCollectionVars()',
|
||||
'bru.deleteCollectionVar(key)',
|
||||
'bru.deleteAllCollectionVars()',
|
||||
'bru.getAllCollectionVars()',
|
||||
'bru.setEnvVar(key, value)',
|
||||
'bru.setEnvVar(key, value, options)',
|
||||
'bru.deleteEnvVar(key)',
|
||||
'bru.getAllEnvVars()',
|
||||
'bru.deleteAllEnvVars()',
|
||||
@@ -139,9 +135,9 @@ const STATIC_API_HINTS = {
|
||||
'bru.hasGlobalEnvVar(key)',
|
||||
'bru.getGlobalEnvVar(key)',
|
||||
'bru.setGlobalEnvVar(key, value)',
|
||||
// 'bru.deleteGlobalEnvVar(key)',
|
||||
'bru.deleteGlobalEnvVar(key)',
|
||||
'bru.getAllGlobalEnvVars()',
|
||||
// 'bru.deleteAllGlobalEnvVars()',
|
||||
'bru.deleteAllGlobalEnvVars()',
|
||||
'bru.runner',
|
||||
'bru.runner.setNextRequest(requestName)',
|
||||
'bru.runner.skipRequest()',
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { cloneDeep, isEqual, sortBy, filter, map, isString, findIndex, find, each, get } from 'lodash';
|
||||
import { uuid } from 'utils/common';
|
||||
import { buildPersistedEnvVariables } from 'utils/environments';
|
||||
import { sortByNameThenSequence } from 'utils/common/index';
|
||||
import path from 'utils/common/path';
|
||||
import { isRequestTagsIncluded } from '@usebruno/common';
|
||||
@@ -603,11 +602,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
|
||||
collectionToSave.version = '1';
|
||||
collectionToSave.items = [];
|
||||
collectionToSave.activeEnvironmentUid = collection.activeEnvironmentUid;
|
||||
// Save environments without runtime metadata (ephemeral/persistedValue)
|
||||
collectionToSave.environments = (collection.environments || []).map((env) => ({
|
||||
...env,
|
||||
variables: buildPersistedEnvVariables(env?.variables, { mode: 'save' })
|
||||
}));
|
||||
collectionToSave.environments = collection.environments || [];
|
||||
|
||||
collectionToSave.root = {
|
||||
request: {}
|
||||
|
||||
@@ -1,34 +1,6 @@
|
||||
import { isEqual } from 'lodash';
|
||||
import { uuid } from './common/index';
|
||||
|
||||
const isPersistableEnvVarForMerge = (persistedNames) => (v) => {
|
||||
return !v?.ephemeral || v?.persistedValue !== undefined || (v?.name && persistedNames.has(v.name));
|
||||
};
|
||||
|
||||
const toPersistedEnvVarForMerge = (persistedNames) => (v) => {
|
||||
const { ephemeral, persistedValue, ...rest } = v || {};
|
||||
if (v?.ephemeral && persistedValue !== undefined && !(v?.name && persistedNames.has(v.name))) {
|
||||
return { ...rest, value: persistedValue };
|
||||
}
|
||||
return rest;
|
||||
};
|
||||
|
||||
const toPersistedEnvVarForSave = (v) => {
|
||||
const { ephemeral, persistedValue, ...rest } = v || {};
|
||||
return rest;
|
||||
};
|
||||
|
||||
// mode 'save': commit the visible value (Save button).
|
||||
// mode 'merge': commit only allowed vars — non-ephemeral, ephemerals with
|
||||
// persistedValue, or names explicitly persisted this run.
|
||||
export const buildPersistedEnvVariables = (variables, { mode, persistedNames } = {}) => {
|
||||
const src = Array.isArray(variables) ? variables : [];
|
||||
if (mode === 'merge') {
|
||||
const names = persistedNames instanceof Set ? persistedNames : new Set();
|
||||
return src.filter(isPersistableEnvVarForMerge(names)).map(toPersistedEnvVarForMerge(names));
|
||||
}
|
||||
return src.map(toPersistedEnvVarForSave);
|
||||
};
|
||||
|
||||
export const buildEnvVariable = ({ envVariable: obj, withUuid = false }) => {
|
||||
const isSecret = !!obj.secret;
|
||||
let envVariable = {
|
||||
@@ -53,6 +25,84 @@ export const buildEnvVariable = ({ envVariable: obj, withUuid = false }) => {
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply script-produced environment variables onto a variables array.
|
||||
*
|
||||
* With baseline: only applies values the script changed relative to the snapshot (preserves draft edits).
|
||||
* Without baseline: direct apply — overwrites all values from script output.
|
||||
* Disabled variables are always preserved; script writes target the enabled slot only — if no
|
||||
* enabled var with `key` exists, a new enabled one is inserted (any same-named disabled var is left intact).
|
||||
*
|
||||
* Pure: does not mutate the input array or its entries. Returns a new array of new objects.
|
||||
*/
|
||||
export const applyScriptEnvVars = (variables, scriptVars, baseline, { skipKeys = [] } = {}) => {
|
||||
const scriptVarNames = new Set(Object.keys(scriptVars));
|
||||
const skip = new Set(skipKeys);
|
||||
const next = (variables || []).map((v) => ({ ...v }));
|
||||
|
||||
if (baseline) {
|
||||
Object.entries(scriptVars).forEach(([key, value]) => {
|
||||
if (skip.has(key)) return;
|
||||
const isNew = !(key in baseline);
|
||||
// Deep-equal so object/array typed vars whose structurally-equal value is re-written by the
|
||||
// script aren't treated as modifications (and thus don't clobber draft edits).
|
||||
const isModified = !isNew && !isEqual(baseline[key], value);
|
||||
|
||||
if (isNew || isModified) {
|
||||
// Target only the enabled slot — a draft-disabled var with the same name must be preserved.
|
||||
const existing = next.find((v) => v.name === key && v.enabled);
|
||||
if (existing) {
|
||||
existing.value = value;
|
||||
} else {
|
||||
next.push({ uid: uuid(), name: key, value, type: 'text', secret: false, enabled: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return next.filter((v) => {
|
||||
if (!v.enabled) return true;
|
||||
if (v.name in baseline && !scriptVarNames.has(v.name)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
Object.entries(scriptVars).forEach(([key, value]) => {
|
||||
if (skip.has(key)) return;
|
||||
const existing = next.find((v) => v.name === key && v.enabled);
|
||||
if (existing) {
|
||||
existing.value = value;
|
||||
} else {
|
||||
next.push({ uid: uuid(), name: key, value, type: 'text', secret: false, enabled: true });
|
||||
}
|
||||
});
|
||||
|
||||
return next.filter((v) => !v.enabled || scriptVarNames.has(v.name));
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the set of keys the script actually modified relative to a baseline (or all script keys
|
||||
* when no baseline is supplied — direct-apply mode). Used by the slice reducers to scope dataType
|
||||
* re-inference to vars that actually changed; without this the dataType loop would clobber a user's
|
||||
* draft-only typed value edit on every no-op script re-run.
|
||||
*/
|
||||
export const getScriptModifiedKeys = (scriptVars, baseline, { skipKeys = [] } = {}) => {
|
||||
const skip = new Set(skipKeys);
|
||||
const out = new Set();
|
||||
Object.entries(scriptVars || {}).forEach(([key, value]) => {
|
||||
if (skip.has(key)) return;
|
||||
if (baseline) {
|
||||
const isNew = !(key in baseline);
|
||||
if (!isNew && isEqual(baseline[key], value)) return;
|
||||
}
|
||||
out.add(key);
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Strips the UID from an environment variable for comparison purposes.
|
||||
* This is useful when comparing variables where UIDs may differ but the actual data is the same.
|
||||
*/
|
||||
export const stripEnvVarUid = (variable) => {
|
||||
const { name, value, type, enabled, secret, dataType } = variable;
|
||||
const result = { name, value, type, enabled, secret };
|
||||
|
||||
@@ -3,7 +3,7 @@ jest.mock('nanoid', () => ({
|
||||
customAlphabet: () => () => 'aaaaaaaaaaaaaaaaaaaa1'
|
||||
}));
|
||||
|
||||
import { buildEnvVariable, stripEnvVarUid, buildPersistedEnvVariables } from './environments';
|
||||
import { applyScriptEnvVars, buildEnvVariable, stripEnvVarUid } from './environments';
|
||||
|
||||
describe('buildEnvVariable — dataType preservation for env export/import', () => {
|
||||
it('preserves non-string datatypes on non-secret variables', () => {
|
||||
@@ -55,6 +55,238 @@ describe('stripEnvVarUid — datatype-aware comparison key', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyScriptEnvVars', () => {
|
||||
const v = (name, value, enabled = true) => ({
|
||||
uid: `uid-${name}`,
|
||||
name,
|
||||
value,
|
||||
type: 'text',
|
||||
secret: false,
|
||||
enabled
|
||||
});
|
||||
|
||||
describe('direct-apply mode (no baseline)', () => {
|
||||
it('updates the value of an existing variable', () => {
|
||||
const result = applyScriptEnvVars([v('host', 'old')], { host: 'new' }, null);
|
||||
expect(result.find((x) => x.name === 'host').value).toBe('new');
|
||||
});
|
||||
|
||||
it('appends variables present in scriptVars but not in the array', () => {
|
||||
const result = applyScriptEnvVars([v('host', 'h')], { host: 'h', token: 'abc' }, null);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result.find((x) => x.name === 'token')).toMatchObject({
|
||||
name: 'token',
|
||||
value: 'abc',
|
||||
type: 'text',
|
||||
secret: false,
|
||||
enabled: true
|
||||
});
|
||||
});
|
||||
|
||||
it('removes enabled variables missing from scriptVars (script deleted them)', () => {
|
||||
const result = applyScriptEnvVars([v('host', 'h'), v('stale', 'remove-me')], { host: 'h' }, null);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('host');
|
||||
});
|
||||
|
||||
it('preserves disabled variables even if missing from scriptVars', () => {
|
||||
const result = applyScriptEnvVars([v('host', 'h'), v('keep', 'k', false)], { host: 'h' }, null);
|
||||
expect(result.map((x) => x.name).sort()).toEqual(['host', 'keep']);
|
||||
});
|
||||
|
||||
it('honors skipKeys — entries are neither applied nor used for the removal filter', () => {
|
||||
const result = applyScriptEnvVars(
|
||||
[v('host', 'h')],
|
||||
{ host: 'h', __name__: 'Test' },
|
||||
null,
|
||||
{ skipKeys: ['__name__'] }
|
||||
);
|
||||
// __name__ is not pushed as a new var even though it appeared in scriptVars
|
||||
expect(result.find((x) => x.name === '__name__')).toBeUndefined();
|
||||
// host is still present (it IS in scriptVarNames, which is built before skipKeys is applied)
|
||||
expect(result.find((x) => x.name === 'host')).toBeDefined();
|
||||
});
|
||||
|
||||
it('preserves typed (non-string) values without coercion', () => {
|
||||
const result = applyScriptEnvVars([], { count: 42, flag: true, cfg: { k: 1 } }, null);
|
||||
expect(result.find((x) => x.name === 'count').value).toBe(42);
|
||||
expect(result.find((x) => x.name === 'flag').value).toBe(true);
|
||||
expect(result.find((x) => x.name === 'cfg').value).toEqual({ k: 1 });
|
||||
});
|
||||
|
||||
it('returns an empty array when both inputs are empty', () => {
|
||||
expect(applyScriptEnvVars([], {}, null)).toEqual([]);
|
||||
});
|
||||
|
||||
it('preserves dataType on an existing var when only its value is updated', () => {
|
||||
const existing = [{ ...v('count', 41), dataType: 'number' }];
|
||||
const result = applyScriptEnvVars(existing, { count: 42 }, null);
|
||||
const out = result.find((x) => x.name === 'count');
|
||||
expect(out.value).toBe(42);
|
||||
expect(out.dataType).toBe('number');
|
||||
});
|
||||
|
||||
it('does NOT attach a dataType to newly-pushed vars — that is the caller\'s responsibility', () => {
|
||||
// applyScriptEnvVars never calls getDataTypeFromValue; the slice that owns the
|
||||
// dispatch (scriptEnvironmentUpdateEvent / globalEnvironmentsUpdateEvent /
|
||||
// collectionVariablesUpdateEvent) infers and attaches dataType after this merge.
|
||||
const result = applyScriptEnvVars([], { count: 42, flag: true, cfg: { k: 1 } }, null);
|
||||
expect(result.find((x) => x.name === 'count').dataType).toBeUndefined();
|
||||
expect(result.find((x) => x.name === 'flag').dataType).toBeUndefined();
|
||||
expect(result.find((x) => x.name === 'cfg').dataType).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('baseline-diff mode (preserves draft edits)', () => {
|
||||
it('does NOT overwrite a draft edit when the script value matches the baseline (unchanged)', () => {
|
||||
const draftVars = [v('host', 'draft-edit')];
|
||||
const baseline = { host: 'saved-value' };
|
||||
const scriptVars = { host: 'saved-value' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
expect(result.find((x) => x.name === 'host').value).toBe('draft-edit');
|
||||
});
|
||||
|
||||
it('overwrites the draft value when the script value differs from baseline (modified)', () => {
|
||||
const draftVars = [v('host', 'draft-edit')];
|
||||
const baseline = { host: 'saved-value' };
|
||||
const scriptVars = { host: 'script-new-value' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
expect(result.find((x) => x.name === 'host').value).toBe('script-new-value');
|
||||
});
|
||||
|
||||
it('adds variables that appear in scriptVars but not in baseline (new)', () => {
|
||||
const draftVars = [v('host', 'h')];
|
||||
const baseline = { host: 'h' };
|
||||
const scriptVars = { host: 'h', fresh: 'from-script' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
expect(result.find((x) => x.name === 'fresh')).toMatchObject({
|
||||
name: 'fresh',
|
||||
value: 'from-script',
|
||||
enabled: true
|
||||
});
|
||||
});
|
||||
|
||||
it('removes variables that were in baseline but missing from scriptVars (script deleted)', () => {
|
||||
const draftVars = [v('host', 'h'), v('wasSaved', 'value')];
|
||||
const baseline = { host: 'h', wasSaved: 'value' };
|
||||
const scriptVars = { host: 'h' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
expect(result.find((x) => x.name === 'wasSaved')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves draft-only variables (not in baseline, not in scriptVars)', () => {
|
||||
const draftVars = [v('host', 'h'), v('draft-only', 'user-added')];
|
||||
const baseline = { host: 'h' };
|
||||
const scriptVars = { host: 'h' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
expect(result.find((x) => x.name === 'draft-only')).toMatchObject({
|
||||
name: 'draft-only',
|
||||
value: 'user-added'
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves disabled variables even when they would otherwise be removed', () => {
|
||||
const draftVars = [v('host', 'h'), v('disabled', 'keep', false)];
|
||||
const baseline = { host: 'h', disabled: 'keep' };
|
||||
const scriptVars = { host: 'h' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
// 'disabled' is in baseline and missing from scriptVars, but it's disabled so it stays
|
||||
expect(result.find((x) => x.name === 'disabled')).toMatchObject({ name: 'disabled', enabled: false });
|
||||
});
|
||||
|
||||
it('honors skipKeys — does not modify or add skipped entries', () => {
|
||||
const draftVars = [v('host', 'h')];
|
||||
const baseline = { host: 'h' };
|
||||
const scriptVars = { host: 'h', __name__: 'Test' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline, { skipKeys: ['__name__'] });
|
||||
expect(result.find((x) => x.name === '__name__')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves dataType on an existing var when only its value is updated', () => {
|
||||
const draftVars = [{ ...v('count', 41), dataType: 'number' }];
|
||||
const baseline = { count: 40 };
|
||||
const scriptVars = { count: 42 };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
const out = result.find((x) => x.name === 'count');
|
||||
expect(out.value).toBe(42);
|
||||
expect(out.dataType).toBe('number');
|
||||
});
|
||||
|
||||
it('preserves dataType on a disabled typed var that the script does not touch', () => {
|
||||
const draftVars = [v('host', 'h'), { ...v('flag', false, false), dataType: 'boolean' }];
|
||||
const baseline = { host: 'h', flag: false };
|
||||
const scriptVars = { host: 'h' };
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
const out = result.find((x) => x.name === 'flag');
|
||||
expect(out).toMatchObject({ name: 'flag', enabled: false, dataType: 'boolean' });
|
||||
});
|
||||
|
||||
it('combined: script adds, modifies, deletes; draft edits to unchanged vars are preserved', () => {
|
||||
const draftVars = [
|
||||
v('host', 'draft-host'), // user-edited, script will leave value matching baseline
|
||||
v('token', 'draft-token'), // user-edited, script will override
|
||||
v('stale', 'draft-stale'), // script will delete (was in baseline)
|
||||
v('draft-only', 'user-added') // user-only, not in baseline
|
||||
];
|
||||
const baseline = {
|
||||
host: 'saved-host',
|
||||
token: 'saved-token',
|
||||
stale: 'saved-stale'
|
||||
};
|
||||
const scriptVars = {
|
||||
host: 'saved-host', // unchanged from baseline → draft 'draft-host' wins
|
||||
token: 'script-new-token', // modified → script wins
|
||||
added: 'from-script' // new → added
|
||||
};
|
||||
|
||||
const result = applyScriptEnvVars(draftVars, scriptVars, baseline);
|
||||
const byName = Object.fromEntries(result.map((x) => [x.name, x.value]));
|
||||
expect(byName).toEqual({
|
||||
'host': 'draft-host',
|
||||
'token': 'script-new-token',
|
||||
'added': 'from-script',
|
||||
'draft-only': 'user-added'
|
||||
});
|
||||
expect(result.find((x) => x.name === 'stale')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('secret flag preservation', () => {
|
||||
const secretVar = (name, value, enabled = true) => ({
|
||||
uid: `uid-${name}`,
|
||||
name,
|
||||
value,
|
||||
type: 'text',
|
||||
secret: true,
|
||||
enabled
|
||||
});
|
||||
|
||||
it('preserves secret: true when script updates an enabled secret var (baseline mode)', () => {
|
||||
const result = applyScriptEnvVars(
|
||||
[secretVar('apiToken', 'old')],
|
||||
{ apiToken: 'new' },
|
||||
{ apiToken: 'old' }
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({ name: 'apiToken', value: 'new', secret: true, enabled: true });
|
||||
});
|
||||
|
||||
it('preserves secret: true in direct-apply (no baseline) mode', () => {
|
||||
const result = applyScriptEnvVars([secretVar('apiToken', 'old')], { apiToken: 'new' }, null);
|
||||
expect(result[0]).toMatchObject({ name: 'apiToken', value: 'new', secret: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Env export → import round-trip via JSON', () => {
|
||||
it('preserves dataType across export → JSON.stringify → JSON.parse → import for every supported type', () => {
|
||||
const reduxEnvVars = [
|
||||
@@ -89,61 +321,3 @@ describe('Env export → import round-trip via JSON', () => {
|
||||
expect(reimported[5]).toMatchObject({ name: 'token', value: '', secret: true, dataType: 'number' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildPersistedEnvVariables — save mode', () => {
|
||||
// Regression guard: save mode must commit the visible value of an ephemeral
|
||||
// var, not roll it back to persistedValue.
|
||||
it('keeps the visible value when an ephemeral var has a persistedValue', () => {
|
||||
const variables = [
|
||||
{
|
||||
name: 'apiKey',
|
||||
value: 'testvalue',
|
||||
type: 'text',
|
||||
enabled: true,
|
||||
secret: true,
|
||||
ephemeral: true,
|
||||
persistedValue: 'test'
|
||||
}
|
||||
];
|
||||
|
||||
expect(buildPersistedEnvVariables(variables, { mode: 'save' })).toEqual([
|
||||
{ name: 'apiKey', value: 'testvalue', type: 'text', enabled: true, secret: true }
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps the visible value for a non-secret ephemeral var too', () => {
|
||||
const variables = [
|
||||
{
|
||||
name: 'host',
|
||||
value: 'localhost-from-script',
|
||||
type: 'text',
|
||||
enabled: true,
|
||||
secret: false,
|
||||
ephemeral: true,
|
||||
persistedValue: 'localhost'
|
||||
}
|
||||
];
|
||||
|
||||
expect(buildPersistedEnvVariables(variables, { mode: 'save' })).toEqual([
|
||||
{ name: 'host', value: 'localhost-from-script', type: 'text', enabled: true, secret: false }
|
||||
]);
|
||||
});
|
||||
|
||||
it('strips ephemeral/persistedValue from non-ephemeral vars', () => {
|
||||
const variables = [
|
||||
{
|
||||
name: 'plain',
|
||||
value: 'v',
|
||||
type: 'text',
|
||||
enabled: true,
|
||||
secret: false,
|
||||
ephemeral: false,
|
||||
persistedValue: 'leftover'
|
||||
}
|
||||
];
|
||||
|
||||
expect(buildPersistedEnvVariables(variables, { mode: 'save' })).toEqual([
|
||||
{ name: 'plain', value: 'v', type: 'text', enabled: true, secret: false }
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user