Skip to content

Commit

Permalink
POC service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
garronej committed Apr 16, 2024
1 parent d440dfc commit eef47ab
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ export function viteEnvs(params?: {
/import\.meta\.env(?:\.([A-Za-z0-9$_]+)|\["([^"]+)"\]|(.?))/g,
(match, p1, p2, p3) => {
const out = (() => {
const globalRef = `window.${nameOfTheGlobal}`;
const globalRef = `(typeof window === "undefined" ? self : window).${nameOfTheGlobal}`;

if (p3 !== undefined) {
return `${globalRef}${p3}`;
Expand Down Expand Up @@ -583,6 +583,36 @@ export function viteEnvs(params?: {
});

fs.writeFileSync(indexHtmlFilePath, Buffer.from(processedHtml, "utf8"));

{
const envWithValuesInBase64 = Object.fromEntries(
Object.entries(mergedEnv).map(([key, value]) => [
key,
Buffer.from(`${value}`, "utf8").toString("base64")
])
);

const swEnv = [
`const envWithValuesInBase64 = ${JSON.stringify(
envWithValuesInBase64,
null,
2
)
.replace(/^"/, "")
.replace(/"$/, "")};`,
`const env = {};`,
`Object.keys(envWithValuesInBase64).forEach(function (name) {`,
` env[name] = new TextDecoder().decode(`,
` Uint8Array.from(`,
` atob(envWithValuesInBase64[name]),`,
` c => c.charCodeAt(0))`,
` );`,
`});`,
`self.${nameOfTheGlobal} = env;`
].join("\n");

fs.writeFileSync(pathJoin(distDirPath, "swEnv.js"), Buffer.from(swEnv, "utf8"));
}
})(processedHtml);

const placeholderForViteEnvsScript = `<!-- vite-envs script placeholder xKsPmLs30swKsdIsVx -->`;
Expand Down Expand Up @@ -693,6 +723,21 @@ export function viteEnvs(params?: {
`DIR=$(cd "$(dirname "$0")" && pwd)`,
``,
`echo "$processedHtml" > "$DIR/index.html"`,
``,
`swEnv_script="`,
`const envWithValuesInBase64 = $json;`,
`const env = {};`,
`Object.keys(envWithValuesInBase64).forEach(function (name) {`,
` env[name] = new TextDecoder().decode(`,
` Uint8Array.from(`,
` atob(envWithValuesInBase64[name]),`,
` c => c.charCodeAt(0))`,
` ).slice(0,-1);`,
`});`,
`self.${nameOfTheGlobal} = env;`,
`"`,
``,
`echo "$swEnv_script" > "$DIR/swEnv.js"`,
``
].join("\n");

Expand Down

0 comments on commit eef47ab

Please sign in to comment.