1- import { Buffer } from 'node:buffer'
2- import { env } from 'node:process'
1+ import { base64Decode , base64Encode } from './util.ts'
2+
3+ interface EnvironmentVariables {
4+ delete : ( key : string ) => void
5+ get : ( key : string ) => string | undefined
6+ has : ( key : string ) => boolean
7+ set : ( key : string , value : string ) => void
8+ toObject : ( ) => Record < string , string >
9+ }
10+
11+ interface Globals {
12+ Deno ?: {
13+ env : EnvironmentVariables
14+ }
15+ Netlify ?: {
16+ env : EnvironmentVariables
17+ }
18+ process ?: {
19+ env : Record < string , string >
20+ }
21+ }
22+
23+ /**
24+ * Returns a cross-runtime interface for handling environment variables. It
25+ * uses the `Netlify.env` global if available, otherwise looks for `Deno.env`
26+ * and `process.env`.
27+ */
28+ export const getEnvironment = ( ) : EnvironmentVariables => {
29+ const { Deno, Netlify, process } = globalThis as Globals
30+
31+ return (
32+ Netlify ?. env ??
33+ Deno ?. env ?? {
34+ delete : ( key : string ) => delete process ?. env [ key ] ,
35+ get : ( key : string ) => process ?. env [ key ] ,
36+ has : ( key : string ) => Boolean ( process ?. env [ key ] ) ,
37+ set : ( key : string , value : string ) => {
38+ if ( process ?. env ) {
39+ process . env [ key ] = value
40+ }
41+ } ,
42+ toObject : ( ) => process ?. env ?? { } ,
43+ }
44+ )
45+ }
346
447declare global {
548 // Using `var` so that the declaration is hoisted in such a way that we can
@@ -21,13 +64,13 @@ export interface EnvironmentContext {
2164}
2265
2366export const getEnvironmentContext = ( ) : EnvironmentContext => {
24- const context = globalThis . netlifyBlobsContext || env . NETLIFY_BLOBS_CONTEXT
67+ const context = globalThis . netlifyBlobsContext || getEnvironment ( ) . get ( ' NETLIFY_BLOBS_CONTEXT' )
2568
2669 if ( typeof context !== 'string' || ! context ) {
2770 return { }
2871 }
2972
30- const data = Buffer . from ( context , 'base64' ) . toString ( )
73+ const data = base64Decode ( context )
3174
3275 try {
3376 return JSON . parse ( data ) as EnvironmentContext
@@ -39,9 +82,9 @@ export const getEnvironmentContext = (): EnvironmentContext => {
3982}
4083
4184export const setEnvironmentContext = ( context : EnvironmentContext ) => {
42- const encodedContext = Buffer . from ( JSON . stringify ( context ) ) . toString ( 'base64' )
85+ const encodedContext = base64Encode ( JSON . stringify ( context ) )
4386
44- env . NETLIFY_BLOBS_CONTEXT = encodedContext
87+ getEnvironment ( ) . set ( ' NETLIFY_BLOBS_CONTEXT' , encodedContext )
4588}
4689
4790export class MissingBlobsEnvironmentError extends Error {
0 commit comments