Problem: multiple api runtime in single npm module
I developed a very simple no CORS proxy for Azure and Cloudflare serverless environments.
obviously some code is shared between the two environments and obviously some code is different !
Thinking DRY I decided to create a mono repo with a maximum of sharing.
My first idea was to create a single npm module but I did not found an elegant solution for having the same module with two different runtime api.
In an ideal world index.ts should look like:
//Ignore import while in Cloudflare
import { proxyAzureRequest as _proxyAzureRequest } from "./Azure/index.js";
//Ignore import while in Azure
import { proxyPagesRequest as _proxyPagesRequest } from "./Pages/index.js";
export const proxyAzureRequest = _proxyAzureRequest;
export const proxyPagesRequest = _proxyPagesRequest;
In the real world it throws many issues because for example Cloudflare runtime does not support node streams.
Actual solution
Today I produce two modules one with:
import { proxyPagesRequest as _proxyPagesRequest } from "./Pages/index.js";
export const proxyPagesRequest = _proxyPagesRequest;
the other with:
import { proxyAzureRequest as _proxyAzureRequest } from "./Azure/index.js";
export const proxyAzureRequest = _proxyAzureRequest;
It uses a ugly script and two workflows in Github
which produces two modules:
https://www.npmjs.com/package/@sctg/nocors-azure
https://www.npmjs.com/package/@sctg/nocors-pages
But I do not like this/my solution
What I tried.
I tried to dynamically import with a try/catch closure but it fails. .
I also tried to detect presence of a Cloudflare specific variable (Websocket) and a if/else block but it also fails.
Is there an elegant solution to share a single module for multiple runtimes ?