Skip to content

Commit

Permalink
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
Browse files Browse the repository at this point in the history
…ct-deployment
  • Loading branch information
leomendoza123 committed Jan 4, 2025
1 parent 66643f8 commit 8a08f2e
Show file tree
Hide file tree
Showing 112 changed files with 531 additions and 463 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,5 @@ cypress/plugins/token.json

# Packages ignore package-lock to depend only on yarn
package-lock.json
src/assets/dev-runtime-environment-setter.js

52 changes: 2 additions & 50 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -243,48 +243,6 @@
}
]
},
"qa": {
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.qa.ts"
}
]
},
"sandbox": {
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.sandbox.ts"
}
]
},
"int": {
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.int.ts"
}
]
},
"en": {
"localize": ["en"]
},
Expand Down Expand Up @@ -370,23 +328,17 @@
},
"local-sandbox": {
"browserTarget": "ng-orcid:build:local-with-proxy",
"proxyConfig": "src/proxy.conf.sandbox..mjs"
"proxyConfig": "src/proxy.conf.sandbox.mjs"
},
"local": {
"browserTarget": "ng-orcid:build:local"
},
"local-tomcat": {
"browserTarget": "ng-orcid:build:local-tomcat"
},
"production": {
"browserTarget": "ng-orcid:build:production"
},
"sandbox": {
"browserTarget": "ng-orcid:build:sandbox"
},
"qa": {
"browserTarget": "ng-orcid:build:qa"
},

"en": {
"browserTarget": "ng-orcid:build:en"
},
Expand Down
34 changes: 17 additions & 17 deletions documentation.json

Large diffs are not rendered by default.

13 changes: 6 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"name": "ng-orcid",
"version": "0.0.0",
"scripts": {
"start-local": "ng serve --disable-host-check --host 0.0.0.0",
"start": "ng serve --configuration=local-qa --host 0.0.0.0",
"start-local": "ts-node -P scripts/tsconfig.json scripts/runtime-environment-setter.dev-runtime.ts && ng serve --disable-host-check --host 0.0.0.0",
"start": "ts-node -P scripts/tsconfig.json scripts/runtime-environment-setter.dev-runtime.ts && ng serve --configuration=local-qa --host 0.0.0.0",
"start-sandbox": "ng serve --configuration=local-sandbox --host 0.0.0.0",
"start:en": "ng serve --configuration=local-qa-en --disable-host-check",
"start:ar": "ng serve --configuration=local-qa-ar --disable-host-check",
Expand All @@ -15,17 +15,16 @@
"e2e": "ng e2e",
"prebuild": "rimraf dist && yarn build:i18n && yarn build:browserslist",
"build": "ng build --configuration production --localize",
"postbuild": "ts-node -P scripts/tsconfig.json scripts/postbuild.ts --env production",
"postbuild": "ts-node -P scripts/tsconfig.json scripts/postbuild.ts",
"build:i18n:clone": "ts-node -P scripts/tsconfig.json scripts/properties-clone.postbuild.ts",
"build:i18n:generate-testing": "ts-node -P scripts/tsconfig.json scripts/properties-test-generator.postbuild.ts",
"build:i18n:extract": "ng extract-i18n --format=xlf2 --output-path src/locale",
"build:i18n:generate": "ts-node -P scripts/tsconfig.json scripts/translate-file-generator.prebuild.ts",
"build:i18n": "yarn build:i18n:extract && yarn build:i18n:generate",
"build:prod": "yarn build",
"build:sandbox": "yarn prebuild && ng build --configuration=sandbox --localize && yarn postbuild --env sandbox",
"build:qa": "yarn prebuild && ng build --configuration=qa --localize && yarn postbuild --env qa",
"build:int": "yarn prebuild && ng build --configuration=int --localize && yarn postbuild --env int",
"build:local-tomcat": "yarn prebuild && ng build --configuration=local-tomcat --localize && ng run ng-orcid:build:local-tomcat-source",
"build:sandbox": "yarn build",
"build:qa": "yarn build",
"build:int": "yarn build",
"build:local": "yarn run prebuild && ng build --localize",
"format": "npm run lint && prettier --write .",
"build:report": "webpack-bundle-analyzer dist/en/stats.json",
Expand Down
15 changes: 7 additions & 8 deletions scripts/postbuild.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,30 @@
// This file contains some updates made right after Angular Cli

import { uniqueLength } from './unique-length.postbuild'
import { buildInfo } from './build-info.postbuild'
import {
addLanguageCodeToHashesOnToHTMLFiles,
addLanguageCodeToHashesOnJSFiles,
} from './uniqueLanguageFilesNames'
import { getOptionsObjet, save } from './utils'
import { renameSync, readFileSync } from 'fs'
import { zendeskPlugin } from './zend-desk.postbuild'
import { createShareAssetsFolder } from './moveToShareFolder.postbuild'
import { robotsMetadata } from './robots-metada.postbuild'
import { newRelic } from './new-relic.postbuild'
import { replaceEnvPlaceholder } from './runtime-environment-setter.postbuild'

const glob = require('glob')
// Run updates on index.html files across languages
glob
.sync('./dist/*/index.html', { ignore: './dist/storybook/*' })
.forEach((file) => {
const options = getOptionsObjet(file)
let data = readFileSync(file, 'utf8')
data = uniqueLength(data, options)
data = replaceEnvPlaceholder(data)
// data = uniqueLength(data, options) DISABLED unique leght for now, as migth not be required anymore
data = buildInfo(data, options)
data = newRelic(data, options)
data = zendeskPlugin(data, options)
// data = newRelic(data, options) TEMPORALLY DISABLE NEW RELIC

// Replace all the `*.js` references to match updated JS file names with the language code.
data = addLanguageCodeToHashesOnToHTMLFiles(data, options)
data = robotsMetadata(data, options)
// data = robotsMetadata(data, options) DISABLE robots headers, as those will be handle via nginx
save(data, options)
})

Expand Down
24 changes: 24 additions & 0 deletions scripts/runtime-environment-setter.dev-runtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as fs from 'fs'
import * as path from 'path'
import { runtimeEnvironmentScript } from './utils'

function main() {
// Create the script content
const scriptContent = `//DO NOT MODIFY THIS environment file directly, to updat this file.
//To update environments please update the files under "/Users/l.mendoza/code/orcid-angular/src/environments"
${runtimeEnvironmentScript()}`

// Write the file. For example, dist/local-dev-environment.js
const outputPath = path.resolve(
__dirname,
'../src/assets/local-dev-environment.js'
)

fs.writeFileSync(outputPath, scriptContent, { encoding: 'utf8' })

console.log(`Generated: ${outputPath}`)
}
console.log('runtime-environment-setter.dev-runtime.ts')
if (require.main === module) {
main()
}
22 changes: 22 additions & 0 deletions scripts/runtime-environment-setter.postbuild.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { runtimeEnvironmentScript } from "./utils";

/**
* Receives an HTML string, replaces the [ENVIRONMENT_VARAIBLES_PLACEHOLDER]
* with a <script> that sets window.environment at runtime,
* and returns the modified HTML string.
*/
export function replaceEnvPlaceholder(htmlContent: string): string {
// 1. Build the script that runs in the browser


// 2. Wrap the content in a <script> tag
const scriptTag = `<script>${runtimeEnvironmentScript()}</script>`;

// 3. Replace the placeholder in the HTML
const placeholderBlockRegex = /<!-- ENV_SCRIPT_PLACEHOLDER -->([\s\S]*?)<!-- \/ENV_SCRIPT_PLACEHOLDER -->/;

const updatedHtml = htmlContent.replace(placeholderBlockRegex, scriptTag);

// 4. Return the updated HTML
return updatedHtml;
}
79 changes: 66 additions & 13 deletions scripts/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { writeFileSync } from 'fs'
import * as environmentProduction from '../src/environments/environment.production'
import * as environmentQa from '../src/environments/environment.qa'
import * as environmentSandbox from '../src/environments/environment.sandbox'
import { writeFileSync } from 'fs'
import * as environment4200 from '../src/environments/environment.local-with-proxy'
import * as environmentDev from '../src/environments/environment.local'

export function save(data, options) {
writeFileSync(options.file, data, 'utf8')
Expand All @@ -11,23 +13,11 @@ export function getOptionsObjet(file) {
const environment = getEnvironmentVar()
const languageCode = getLanguageCode(file)
const folder = getFolderName(file)
let environmentVariables

if (environment === 'production') {
environmentVariables = environmentProduction.environment
} else if (environment === 'qa') {
environmentVariables = environmentQa.environment
} else if (environment === 'sandbox') {
environmentVariables = environmentSandbox.environment
} else {
console.warn('the environment variable is invalid')
}

return {
languageCode,
environment,
file,
environmentVariables,
folder,
}
}
Expand All @@ -51,3 +41,66 @@ function getFolderName(file) {
folderPathSegments.pop()
return folderPathSegments.join('/')
}

export function runtimeEnvironmentScript() {
return `
(function() {
// The raw environment objects
var environmentProduction = ${JSON.stringify(environmentProduction.environment)};
var environmentQa = ${JSON.stringify(environmentQa.environment)};
var environmentSandbox = ${JSON.stringify(environmentSandbox.environment)};
var environment4200 = ${JSON.stringify(environment4200.environment)};
var environmentDev = ${JSON.stringify(environmentDev.environment)};
function getCurrentLeanDomain() {
var port = window.location.port ? ':' + window.location.port : '';
// e.g. "qa.myorg.com" -> ["qa", "myorg", "com"]
// .slice(-2) -> ["myorg", "com"]
return window.location.hostname.split('.').slice(-2).join('.') + port;
}
function getSubDomain() {
// e.g. "qa.myorg.com" -> ["qa", "myorg", "com"]
// .slice(0, -2) -> ["qa"]
var subdomain = window.location.hostname.split('.').slice(0, -2).join('.');
return subdomain ? subdomain + '.' : '';
}
function replaceEnvironmentVars(env) {
if (!env) return;
if (env.API_WEB) {
env.API_WEB = env.API_WEB
.replace('<SUBDOMAIN>', getSubDomain())
.replace('<DOMAIN>', getCurrentLeanDomain());
}
if (env.BASE_URL) {
env.BASE_URL = env.BASE_URL
.replace('<SUBDOMAIN>', getSubDomain())
.replace('<DOMAIN>', getCurrentLeanDomain());
}
if (env.API_PUB) {
env.API_PUB = env.API_PUB
.replace('<SUBDOMAIN>', getSubDomain())
.replace('<DOMAIN>', getCurrentLeanDomain());
}
}
var domain = window.location.hostname + window.location.pathname;
var chosenEnv = environmentProduction; // default to production
if (domain.includes('qa.orcid.org')) {
chosenEnv = environmentQa;
} else if (domain.includes('sandbox.orcid.org')) {
chosenEnv = environmentSandbox;
} else if (domain.includes('localhost:4200')) {
chosenEnv = environment4200;
} else if (domain.includes('dev.orcid.org')) {
chosenEnv = environmentDev;
}
replaceEnvironmentVars(chosenEnv);
window.runtimeEnvironment = chosenEnv;
})();
`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { environment } from 'src/environments/environment'
preserveWhitespaces: true,
})
export class DialogActionsDuplicatedMergedConfirmedComponent implements OnInit {
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL

constructor(
private matRef: MatDialogRef<DialogActionsDuplicatedMergedConfirmedComponent>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { environment } from 'src/environments/environment'
})
export class DialogActionsDuplicatedComponent implements OnInit {
isMobile: boolean
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL
constructor(
private matRef: MatDialogRef<DialogActionsDuplicatedComponent>,
@Inject(MAT_DIALOG_DATA) public data: DuplicateRemoveEndpoint,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class SettingsDefaultsLanguageComponent implements OnInit, OnDestroy {
private _language: LanguageService,
private _fb: UntypedFormBuilder
) {
this.languageMenuOptions = environment.LANGUAGE_MENU_OPTIONS
this.languageMenuOptions = runtimeEnvironment.LANGUAGE_MENU_OPTIONS
}

ngOnInit() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { environment } from 'src/environments/environment'
export class SettingsSharingHtmlCodeComponent implements OnInit {
@Output() loading = new EventEmitter<boolean>()
userSession: UserSession
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL

constructor(private _user: UserService) {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { environment } from 'src/environments/environment'
})
export class DialogAddTrustedIndividualsComponent implements OnInit {
isMobile: boolean
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL
addByEmailOrOrcid: string
constructor(
private matRef: MatDialogRef<DialogAddTrustedIndividualsComponent>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { environment } from 'src/environments/environment'
})
export class DialogRevokeTrustedIndividualsComponent implements OnInit {
isMobile: boolean
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL
constructor(
private matRef: MatDialogRef<DialogRevokeTrustedIndividualsComponent>,
@Inject(MAT_DIALOG_DATA) public data: AccountTrustedIndividual,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class SettingsTrustedIndividualsSearchComponent
pageSize: number
ariaLabelPaginator = $localize`:@@search.paginator:paginator`
loading: boolean
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL
userSession: UserSession
searchPlaceHolder = $localize`:@@account.searchIndividualsPlaceHolder:ORCID iD, email address, or names`
trustedIndividuals: AccountTrustedIndividual[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class SettingsTrustedIndividualsComponent implements OnInit, OnDestroy {
displayedColumns = ['trustedIndividuals', 'orcid', 'granted', 'actions']
platformSubs = new Subject<void>()
isMobile: boolean
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL
trustedPartiesUrl = '/trusted-parties'
constructor(
private _trustedIndividualsService: AccountTrustedIndividualsService,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class SettingsUsersThatThrustYouComponent implements OnInit {
displayedColumns = ['trustedIndividuals', 'orcid', 'granted']
platformSubs = new Subject<void>()
isMobile: boolean
baseUrl = environment.BASE_URL
baseUrl = runtimeEnvironment.BASE_URL
constructor(
private _trustedIndividualsService: TrustedIndividualsService,
private dialog: MatDialog,
Expand Down
Loading

0 comments on commit 8a08f2e

Please sign in to comment.