Skip to content

App Hosting JS SDK autoinit #8483

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/tame-parrots-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@firebase/util': minor
'firebase': minor
---

Add support for the `FIREBASE_WEBAPP_CONFIG` environment variable at install time.
12 changes: 10 additions & 2 deletions packages/util/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,16 @@
},
"default": "./dist/index.esm2017.js"
},
"./autoinit_env": {
"require": "./dist/autoinit_env.js",
"import": "./dist/autoinit_env.mjs",
"default": "./dist/autoinit_env.mjs"
},
"./package.json": "./package.json"
},
"files": [
"dist"
"dist",
"postinstall.js"
],
"scripts": {
"lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'",
Expand All @@ -38,13 +44,15 @@
"test:node": "TS_NODE_CACHE=NO TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' nyc --reporter lcovonly -- mocha test/**/*.test.* --config ../../config/mocharc.node.js",
"trusted-type-check": "tsec -p tsconfig.json --noEmit",
"api-report": "api-extractor run --local --verbose",
"typings:public": "node ../../scripts/build/use_typings.js ./dist/util-public.d.ts"
"typings:public": "node ../../scripts/build/use_typings.js ./dist/util-public.d.ts",
"postinstall": "node ./postinstall.js"
},
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.1.0"
},
"devDependencies": {
"@rollup/plugin-replace": "6.0.2",
"rollup": "2.79.2",
"rollup-plugin-typescript2": "0.36.0",
"typescript": "5.5.4"
Expand Down
149 changes: 149 additions & 0 deletions packages/util/postinstall.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* @license
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

const { writeFile, readFile } = require('node:fs/promises');
const { pathToFileURL } = require('node:url');
const { isAbsolute, join } = require('node:path');

async function getPartialConfig() {
if (!process.env.FIREBASE_WEBAPP_CONFIG) {
return undefined;
}

// Like FIREBASE_CONFIG (admin autoinit) FIREBASE_WEBAPP_CONFIG can be
// either a JSON representation of FirebaseOptions or the path to a filename
if (process.env.FIREBASE_WEBAPP_CONFIG.startsWith('{"')) {
try {
return JSON.parse(process.env.FIREBASE_WEBAPP_CONFIG);
} catch (e) {
console.warn(
'FIREBASE_WEBAPP_CONFIG could not be parsed, ignoring.\n',
e
);
return undefined;
}
}

const fileName = process.env.FIREBASE_WEBAPP_CONFIG;
const fileURL = pathToFileURL(
isAbsolute(fileName) ? fileName : join(process.cwd(), fileName)
);

try {
const fileContents = await readFile(fileURL, 'utf-8');
return JSON.parse(fileContents);
} catch (e) {
console.warn(
`Contents of "${fileName}" could not be parsed, ignoring FIREBASE_WEBAPP_CONFIG.\n`,
e
);
return undefined;
}
}

async function getFullConfig(partialConfig) {
if (!partialConfig) {
return undefined;
}
// In Firebase App Hosting the config provided to the environment variable is up-to-date and
// "complete" we should not reach out to the webConfig endpoint to freshen it
if (process.env.X_GOOGLE_TARGET_PLATFORM === 'fah') {
return partialConfig;
}
const projectId = partialConfig.projectId || '-';
// If the projectId starts with demo- this is an demo project from the firebase emulators
// treat the config as whole
if (projectId.startsWith('demo-')) {
return partialConfig;
}
const appId = partialConfig.appId;
const apiKey = partialConfig.apiKey;
if (!appId || !apiKey) {
console.warn(
`Unable to fetch Firebase config, appId and apiKey are required, ignoring FIREBASE_WEBAPP_CONFIG.`
);
return undefined;
}

const url = `https://firebase.googleapis.com/v1alpha/projects/${projectId}/apps/${appId}/webConfig`;

try {
const response = await fetch(url, {
headers: { 'x-goog-api-key': apiKey }
});
if (!response.ok) {
console.warn(
`Unable to fetch Firebase config, ignoring FIREBASE_WEBAPP_CONFIG.`
);
console.warn(
`${url} returned ${response.statusText} (${response.status})`
);
try {
console.warn((await response.json()).error.message);
} catch (e) {}
return undefined;
}
const json = await response.json();
return { ...json, apiKey };
} catch (e) {
console.warn(
`Unable to fetch Firebase config, ignoring FIREBASE_WEBAPP_CONFIG.\n`,
e
);
return undefined;
}
}

function handleUnexpectedError(e) {
console.warn(
'Unexpected error encountered in @firebase/util postinstall script, ignoring FIREBASE_WEBAPP_CONFIG.'
);
console.warn(e);
process.exit(0);
}

getPartialConfig()
.catch(handleUnexpectedError)
.then(getFullConfig)
.catch(handleUnexpectedError)
.then(async config => {
const emulatorHosts = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clarification: does this execute if partialConfig is undefined (and subsequently fullConfig)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does, the idea is to wipe out any hardcoded config from prior runs. The Firebase CLI will trip this script during either a Hosting deploy or emulator start.

firestore: process.env.FIRESTORE_EMULATOR_HOST,
database: process.env.FIREBASE_DATABASE_EMULATOR_HOST,
storage: process.env.FIREBASE_STORAGE_EMULATOR_HOST,
auth: process.env.FIREBASE_AUTH_EMULATOR_HOST
};

const defaults = config && { config, emulatorHosts };

await Promise.all([
writeFile(
join(__dirname, 'dist', 'autoinit_env.js'),
`'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.postinstallDefaults = ${JSON.stringify(defaults)};`
),
writeFile(
join(__dirname, 'dist', 'autoinit_env.mjs'),
`const postinstallDefaults = ${JSON.stringify(defaults)};
export { postinstallDefaults };`
)
]);

process.exit(0);
})
.catch(handleUnexpectedError);
38 changes: 33 additions & 5 deletions packages/util/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,24 @@
*/

import typescriptPlugin from 'rollup-plugin-typescript2';
import replacePlugin from '@rollup/plugin-replace';
import typescript from 'typescript';
import pkg from './package.json';
import { emitModulePackageFile } from '../../scripts/build/rollup_emit_module_package_file';

const deps = Object.keys(
Object.assign({}, pkg.peerDependencies, pkg.dependencies)
);
const deps = [
...Object.keys(Object.assign({}, pkg.peerDependencies, pkg.dependencies)),
'./autoinit_env'
];

const buildPlugins = [typescriptPlugin({ typescript })];
const buildPlugins = [
typescriptPlugin({ typescript }),
replacePlugin({
'./src/autoinit_env': '"@firebase/util/autoinit_env"',
delimiters: ["'", "'"],
preventAssignment: true
})
];

const browserBuilds = [
{
Expand Down Expand Up @@ -72,4 +81,23 @@ const nodeBuilds = [
}
];

export default [...browserBuilds, ...nodeBuilds];
const autoinitBuild = [
{
input: './src/autoinit_env.ts',
output: {
file: './dist/autoinit_env.js',
format: 'cjs'
},
plugins: buildPlugins
},
{
input: './src/autoinit_env.ts',
output: {
file: './dist/autoinit_env.mjs',
format: 'es'
},
plugins: buildPlugins
}
];

export default [...browserBuilds, ...nodeBuilds, ...autoinitBuild];
21 changes: 21 additions & 0 deletions packages/util/src/autoinit_env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @license
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { FirebaseDefaults } from './defaults';

// This value is retrieved and hardcoded by the NPM postinstall script
export const postinstallDefaults: FirebaseDefaults | undefined = undefined;
2 changes: 2 additions & 0 deletions packages/util/src/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import { base64Decode } from './crypt';
import { getGlobal } from './global';
import { postinstallDefaults } from './autoinit_env';

/**
* Keys for experimental properties on the `FirebaseDefaults` object.
Expand Down Expand Up @@ -100,6 +101,7 @@ const getDefaultsFromCookie = (): FirebaseDefaults | undefined => {
export const getDefaults = (): FirebaseDefaults | undefined => {
try {
return (
postinstallDefaults ||
getDefaultsFromGlobal() ||
getDefaultsFromEnvVariable() ||
getDefaultsFromCookie()
Expand Down
10 changes: 9 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2633,6 +2633,14 @@
is-module "^1.0.0"
resolve "^1.22.1"

"@rollup/[email protected]":
version "6.0.2"
resolved "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-6.0.2.tgz#2f565d312d681e4570ff376c55c5c08eb6f1908d"
integrity sha512-7QaYCf8bqF04dOy7w/eHmJeNExxTYwvKAmlSAH/EaWWUzbT0h5sbF6bktFoX/0F/0qwng5/dWFMyf3gzaM8DsQ==
dependencies:
"@rollup/pluginutils" "^5.0.1"
magic-string "^0.30.3"

"@rollup/[email protected]":
version "2.1.0"
resolved "https://registry.npmjs.org/@rollup/plugin-strip/-/plugin-strip-2.1.0.tgz#04c2d2ccfb2c6b192bb70447fbf26e336379a333"
Expand Down Expand Up @@ -11233,7 +11241,7 @@ magic-string@^0.25.2, magic-string@^0.25.7:
dependencies:
sourcemap-codec "^1.4.8"

magic-string@^0.30.2, magic-string@~0.30.0:
magic-string@^0.30.2, magic-string@^0.30.3, magic-string@~0.30.0:
version "0.30.17"
resolved "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz#450a449673d2460e5bbcfba9a61916a1714c7453"
integrity sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==
Expand Down
Loading