From 8c663fdb3ed3fbe0a8c253d74eb6a4d0adda8ae5 Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Thu, 1 Aug 2024 17:51:22 -0700 Subject: [PATCH] chore: add getEnv helper --- src/gptscript.ts | 17 +++++++++++++++++ tests/gptscript.test.ts | 13 ++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/gptscript.ts b/src/gptscript.ts index b6bc29f..71e45f6 100644 --- a/src/gptscript.ts +++ b/src/gptscript.ts @@ -2,6 +2,7 @@ import http from "http" import path from "path" import child_process from "child_process" import {fileURLToPath} from "url" +import {gunzipSync} from "zlib"; export interface GlobalOpts { APIKey?: string @@ -809,6 +810,22 @@ export interface PromptResponse { responses: Record } +export function getEnv(key: string, def: string = ''): string { + let v = process.env[key] || '' + if (v == '') { + return def + } + + if (v.startsWith('{"_gz":"') && v.endsWith('"}')) { + try { + return gunzipSync(Buffer.from(v.slice(8, -2), 'base64')).toString('utf8') + } catch (e) { + } + } + + return v +} + function getCmdPath(): string { if (process.env.GPTSCRIPT_BIN) { return process.env.GPTSCRIPT_BIN diff --git a/tests/gptscript.test.ts b/tests/gptscript.test.ts index 2920c6c..0389408 100644 --- a/tests/gptscript.test.ts +++ b/tests/gptscript.test.ts @@ -1,5 +1,5 @@ import * as gptscript from "../src/gptscript" -import {ArgumentSchemaType, PropertyType, RunEventType, ToolType} from "../src/gptscript" +import {ArgumentSchemaType, getEnv, PropertyType, RunEventType, ToolType} from "../src/gptscript" import path from "path" import {fileURLToPath} from "url" @@ -535,4 +535,15 @@ describe("gptscript module", () => { expect(run.err).toEqual("") }) + + test("test get_env default", async () => { + const env = getEnv('TEST_ENV_MISSING', 'foo') + expect(env).toEqual('foo') + }) + + test("test get_env", async () => { + process.env.TEST_ENV = '{"_gz":"H4sIAEosrGYC/ytJLS5RKEvMKU0FACtB3ewKAAAA"}' + const env = getEnv('TEST_ENV', 'missing') + expect(env).toEqual('test value') + }) })