Skip to content
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

9562 implement dynamic environment variable loading for single artifact deployment #2439

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
8a08f2e
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
leomendoza123 Jan 4, 2025
70f10d1
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
leomendoza123 Jan 4, 2025
4ee1360
Merge branch 'main' into 9562-implement-dynamic-environment-variable-…
leomendoza123 Jan 4, 2025
02e0749
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
leomendoza123 Jan 8, 2025
794cc1e
Merge branch '9562-implement-dynamic-environment-variable-loading-for…
leomendoza123 Jan 8, 2025
2061f02
Merge branch 'main' into 9562-implement-dynamic-environment-variable-…
leomendoza123 Jan 8, 2025
4eef490
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
leomendoza123 Jan 8, 2025
c678353
Merge branch '9562-implement-dynamic-environment-variable-loading-for…
leomendoza123 Jan 8, 2025
bc4ccda
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
leomendoza123 Jan 8, 2025
c24c396
Merge branch 'main' into 9562-implement-dynamic-environment-variable-…
leomendoza123 Jan 8, 2025
3e7b7d3
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
leomendoza123 Jan 8, 2025
daf21f3
:wMerge branch '9562-implement-dynamic-environment-variable-loading-f…
leomendoza123 Jan 8, 2025
638a100
9562-implement-dynamic-environment-variable-loading-for-single-artifa…
leomendoza123 Jan 8, 2025
2dc5d4a
Merge branch 'main' into 9562-implement-dynamic-environment-variable-…
leomendoza123 Jan 8, 2025
cf97710
Merge branch 'main' into 9562-implement-dynamic-environment-variable-…
leomendoza123 Jan 8, 2025
3de555c
format-fix
leomendoza123 Jan 9, 2025
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,4 @@ cypress/plugins/token.json

# Packages ignore package-lock to depend only on yarn
package-lock.json

src/assets/local-dev-environment.js
57 changes: 4 additions & 53 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,16 @@
},
"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"
},
"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 Expand Up @@ -460,7 +411,7 @@
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": [],
"scripts": ["src/assets/local-dev-environment.js"],
"assets": ["src/favicon.ico", "src/assets", "src/manifest.json"],
"sourceMap": true
}
Expand Down
34 changes: 17 additions & 17 deletions documentation.json

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,30 @@
"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": "npm run build-runtime-env && ng serve --disable-host-check --host 0.0.0.0",
"start": "npm run build-runtime-env && 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",
"start:fr": "ng serve --configuration=local-qa-fr --disable-host-check",
"start:xx": "ng serve --configuration=local-qa-xx --disable-host-check",
"test": "ng test",
"test-headless": "ng test --watch=false --browsers=ChromeHeadless",
"test": "npm run build-runtime-env && ng test",
"test-headless": "npm run build-runtime-env && ng test --watch=false --browsers=ChromeHeadless",
"build-runtime-env": "ts-node -P scripts/tsconfig.json scripts/runtime-environment-setter.dev-runtime.ts",
"lint": "echo 'temporally disable Angular linter to until eslint update'",
"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
}
85 changes: 72 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,72 @@ 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;
} else if (domain.includes('localhost')) { // fallback to dev (e.g. karma testig)
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
Loading
Loading