Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

feat: recursive environment variable resolution

Andrew Bastin7fc757d79469
diff --git a/packages/hoppscotch-app/helpers/templating.ts b/packages/hoppscotch-app/helpers/templating.ts
index 64f9556be..0c4a9667c 100644
--- a/packages/hoppscotch-app/helpers/templating.ts
+++ b/packages/hoppscotch-app/helpers/templating.ts
@@ -1,25 +1,87 @@
+import * as E from "fp-ts/Either"
+import { pipe } from "fp-ts/function"
import { Environment } from "~/newstore/environments"
-export function parseBodyEnvVariables(
+const REGEX_ENV_VAR = /<<([^>]*)>>/g // "<<myVariable>>"
+
+/**
+ * How much times can we expand environment variables
+ */
+const ENV_MAX_EXPAND_LIMIT = 10
+
+/**
+ * Error state when there is a suspected loop while
+ * recursively expanding variables
+ */
+const ENV_EXPAND_LOOP = "ENV_EXPAND_LOOP" as const
+
+export function parseBodyEnvVariablesE(
body: string,
env: Environment["variables"]
) {
- return body.replace(/<<\w+>>/g, (key) => {
- const found = env.find((envVar) => envVar.key === key.replace(/[<>]/g, ""))
- return found ? found.value : key
- })
+ let result = body
+ let depth = 0
+
+ while (result.match(REGEX_ENV_VAR) != null && depth <= ENV_MAX_EXPAND_LIMIT) {
+ result = result.replace(/<<\w+>>/g, (key) => {
+ const found = env.find(
+ (envVar) => envVar.key === key.replace(/[<>]/g, "")
+ )
+ return found ? found.value : key
+ })
+
+ depth++
+ }
+
+ return depth > ENV_MAX_EXPAND_LIMIT
+ ? E.left(ENV_EXPAND_LOOP)
+ : E.right(result)
}
-export function parseTemplateString(
+/**
+ * @deprecated Use `parseBodyEnvVariablesE` instead.
+ */
+export const parseBodyEnvVariables = (
+ body: string,
+ env: Environment["variables"]
+) =>
+ pipe(
+ parseBodyEnvVariablesE(body, env),
+ E.getOrElse(() => body)
+ )
+
+export function parseTemplateStringE(
str: string,
variables: Environment["variables"]
) {
if (!variables || !str) {
- return str
+ return E.right(str)
}
- const searchTerm = /<<([^>]*)>>/g // "<<myVariable>>"
- return decodeURI(encodeURI(str)).replace(
- searchTerm,
- (_, p1) => variables.find((x) => x.key === p1)?.value || ""
- )
+
+ let result = str
+ let depth = 0
+
+ while (result.match(REGEX_ENV_VAR) != null && depth <= ENV_MAX_EXPAND_LIMIT) {
+ result = decodeURI(encodeURI(result)).replace(
+ REGEX_ENV_VAR,
+ (_, p1) => variables.find((x) => x.key === p1)?.value || ""
+ )
+ depth++
+ }
+
+ return depth > ENV_MAX_EXPAND_LIMIT
+ ? E.left(ENV_EXPAND_LOOP)
+ : E.right(result)
}
+
+/**
+ * @deprecated Use `parseTemplateStringE` instead
+ */
+export const parseTemplateString = (
+ str: string,
+ variables: Environment["variables"]
+) =>
+ pipe(
+ parseTemplateStringE(str, variables),
+ E.getOrElse(() => str)
+ )