Compare commits
95 Commits
v10.0.0-rc
...
v10.0.0-rc
Author | SHA1 | Date | |
---|---|---|---|
c0ca078b43 | |||
53e94d04f6 | |||
dd198f9f06 | |||
43f455f4d0 | |||
d9132ea5a5 | |||
d5c7e2547b | |||
13b87de06c | |||
83bdbb7a7e | |||
89320b8d51 | |||
5fa9c3879c | |||
c0cd76d40e | |||
01f60f8013 | |||
91ad0712af | |||
2cb1b36725 | |||
67ce66765f | |||
c8cc453942 | |||
3f835f152f | |||
35e8a853e0 | |||
d084a4bf4a | |||
2a6b79e097 | |||
5d786c922f | |||
26bd5dd534 | |||
b4df0ce52c | |||
386a8d7cd7 | |||
5221fb3479 | |||
2871f63f25 | |||
4c282d0559 | |||
4ac14dc074 | |||
fcdbb04ea6 | |||
14f283cf49 | |||
efc459663a | |||
d459aaf943 | |||
921c7d5441 | |||
7d7e648968 | |||
96fc779ec8 | |||
9605e17e96 | |||
111c1675f9 | |||
d547ec3126 | |||
0ce6a7be7f | |||
1e5eae69e9 | |||
89d9208f44 | |||
3e80aaf242 | |||
86c3159ded | |||
230e05abc0 | |||
ff2e6e6432 | |||
dc00be9be6 | |||
77249d8a58 | |||
b9ee0afe7f | |||
db23ab0bc2 | |||
13dc47533c | |||
0091a888bc | |||
724b585004 | |||
c0d127e4f4 | |||
1638577d98 | |||
951c202fd0 | |||
a578b86715 | |||
b6b384854e | |||
dac937060d | |||
c628183773 | |||
eaacaa6966 | |||
9a09e280c9 | |||
70ac07d861 | |||
dabe372360 | |||
d8e3fdeb14 | |||
a147084458 | |||
b25e171412 | |||
60aaa03202 | |||
3392ab8385 | |||
f172b94467 | |||
ca549fe8d8 | |||
0b6f56a774 | |||
e5bcff12cb | |||
2754900f7a | |||
54f43d3331 | |||
4900200c06 | |||
6d82a74db4 | |||
2d7f21b021 | |||
4292c0c642 | |||
9dca515a42 | |||
b577cd9829 | |||
704682cbbe | |||
858f0d77c0 | |||
31ef6063f2 | |||
f3bd81c55b | |||
24bb4902c2 | |||
ca7821cfad | |||
a73b25580e | |||
82e179730e | |||
b5d5002061 | |||
2ab2c9e05e | |||
b1e9ba3ac6 | |||
5822ed0185 | |||
17b295788d | |||
6cd5b958c7 | |||
df92cc5f73 |
.github/workflows
.gitignore.prettierignore.storybook
README.mdpackage.jsonscripts
build-storybook.tsbuild.tscopyKeycloakResourcesToStorybookStaticDir.tsdump-keycloak-realm.tsgenerate-i18n-messages.tslink-in-app.tsstart-storybook.ts
src
PUBLIC_URL.ts
account
KcContext
i18n
pages
bin
add-story.tseject-page.tsmain.ts
initialize-account-theme
copyBoilerplate.tsindex.tsinitialize-account-theme.tsinitializeAccountTheme_multiPage.tsinitializeAccountTheme_singlePage.ts
initialize-email-theme.tssrc
updateAccountThemeImplementationInConfig.tskeycloakify
buildJars
generateFtl
generateResources
bringInAccountV1.tsgenerateMessageProperties.tsgenerateResourcesForMainTheme.tsgenerateResourcesForThemeVariant.tsreadExtraPageNames.ts
keycloakify.tsreplacers
shared
buildContext.tsconstants.tscopyKeycloakResourcesToPublic.tsdownloadKeycloakDefaultTheme.tsdownloadKeycloakStaticResources.tsgenerateKcGenTs.tsgetLatestsSemVersionedTag.tspromptKeycloakVersion.ts
start-keycloak
appBuild.tskeycloakifyBuild.tsmyrealm-realm-18.jsonmyrealm-realm-19.jsonmyrealm-realm-20.jsonmyrealm-realm-21.jsonmyrealm-realm-23.jsonmyrealm-realm-24.jsonmyrealm-realm-25.jsonstart-keycloak.ts
tools
tsconfig.jsonlib
login
tools
vite-plugin
stories
test
yarn.lock
2
.github/workflows/ci.yaml
vendored
2
.github/workflows/ci.yaml
vendored
@ -37,7 +37,7 @@ jobs:
|
|||||||
|
|
||||||
storybook:
|
storybook:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
#if: github.event_name == 'push'
|
if: github.event_name == 'push'
|
||||||
needs: test
|
needs: test
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
4
.gitignore
vendored
4
.gitignore
vendored
@ -48,8 +48,8 @@ jspm_packages
|
|||||||
|
|
||||||
.idea
|
.idea
|
||||||
|
|
||||||
/src/login/i18n/baseMessages/
|
/src/login/i18n/messages_defaultSet/
|
||||||
/src/account/i18n/baseMessages/
|
/src/account/i18n/messages_defaultSet/
|
||||||
|
|
||||||
# VS Code devcontainers
|
# VS Code devcontainers
|
||||||
.devcontainer
|
.devcontainer
|
||||||
|
@ -6,8 +6,8 @@ node_modules/
|
|||||||
/src/tools/types/
|
/src/tools/types/
|
||||||
/build_keycloak/
|
/build_keycloak/
|
||||||
/.vscode/
|
/.vscode/
|
||||||
/src/login/i18n/baseMessages/
|
/src/login/i18n/messages_defaultSet/
|
||||||
/src/account/i18n/baseMessages/
|
/src/account/i18n/messages_defaultSet/
|
||||||
/dist_test
|
/dist_test
|
||||||
/sample_react_project/
|
/sample_react_project/
|
||||||
/sample_custom_react_project/
|
/sample_custom_react_project/
|
||||||
|
@ -1,70 +0,0 @@
|
|||||||
|
|
||||||
import React from "react";
|
|
||||||
import { DocsContainer as BaseContainer } from "@storybook/addon-docs";
|
|
||||||
import { useDarkMode } from "storybook-dark-mode";
|
|
||||||
import { darkTheme, lightTheme } from "./customTheme";
|
|
||||||
import "./static/fonts/WorkSans/font.css";
|
|
||||||
|
|
||||||
export function DocsContainer({ children, context }) {
|
|
||||||
const isStorybookUiDark = useDarkMode();
|
|
||||||
|
|
||||||
const theme = isStorybookUiDark ? darkTheme : lightTheme;
|
|
||||||
|
|
||||||
const backgroundColor = theme.appBg;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<style>{`
|
|
||||||
body {
|
|
||||||
padding: 0 !important;
|
|
||||||
background-color: ${backgroundColor};
|
|
||||||
}
|
|
||||||
|
|
||||||
.docs-story {
|
|
||||||
background-color: ${backgroundColor};
|
|
||||||
}
|
|
||||||
[id^=story--] .container {
|
|
||||||
border: 1px dashed #e8e8e8;
|
|
||||||
}
|
|
||||||
|
|
||||||
.docblock-argstable-head th:nth-child(3), .docblock-argstable-body tr > td:nth-child(3) {
|
|
||||||
visibility: collapse;
|
|
||||||
}
|
|
||||||
|
|
||||||
.docblock-argstable-head th:nth-child(3), .docblock-argstable-body tr > td:nth-child(2) p {
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
`}</style>
|
|
||||||
<BaseContainer
|
|
||||||
context={{
|
|
||||||
...context,
|
|
||||||
"storyById": id => {
|
|
||||||
const storyContext = context.storyById(id);
|
|
||||||
return {
|
|
||||||
...storyContext,
|
|
||||||
"parameters": {
|
|
||||||
...storyContext?.parameters,
|
|
||||||
"docs": {
|
|
||||||
...storyContext?.parameters?.docs,
|
|
||||||
"theme": isStorybookUiDark ? darkTheme : lightTheme
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</BaseContainer>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CanvasContainer({ children }) {
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{children}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
import { create } from "@storybook/theming";
|
|
||||||
|
|
||||||
const brandImage = "logo.png";
|
|
||||||
const brandTitle = "Keycloakify";
|
|
||||||
const brandUrl = "https://github.com/keycloakify/keycloakify";
|
|
||||||
const fontBase = '"Work Sans", sans-serif';
|
|
||||||
const fontCode = "monospace";
|
|
||||||
|
|
||||||
export const darkTheme = create({
|
|
||||||
"base": "dark",
|
|
||||||
"appBg": "#1E1E1E",
|
|
||||||
"appContentBg": "#161616",
|
|
||||||
"barBg": "#161616",
|
|
||||||
"colorSecondary": "#8585F6",
|
|
||||||
"textColor": "#FFFFFF",
|
|
||||||
brandImage,
|
|
||||||
brandTitle,
|
|
||||||
brandUrl,
|
|
||||||
fontBase,
|
|
||||||
fontCode
|
|
||||||
});
|
|
||||||
|
|
||||||
export const lightTheme = create({
|
|
||||||
"base": "light",
|
|
||||||
"appBg": "#F6F6F6",
|
|
||||||
"appContentBg": "#FFFFFF",
|
|
||||||
"barBg": "#FFFFFF",
|
|
||||||
"colorSecondary": "#000091",
|
|
||||||
"textColor": "#212121",
|
|
||||||
brandImage,
|
|
||||||
brandTitle,
|
|
||||||
brandUrl,
|
|
||||||
fontBase,
|
|
||||||
fontCode
|
|
||||||
});
|
|
33
.storybook/customTheme.ts
Normal file
33
.storybook/customTheme.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
const brandImage = "logo.png";
|
||||||
|
const brandTitle = "Keycloakify";
|
||||||
|
const brandUrl = "https://github.com/keycloakify/keycloakify";
|
||||||
|
const fontBase = '"Work Sans", sans-serif';
|
||||||
|
const fontCode = "monospace";
|
||||||
|
|
||||||
|
export const darkTheme = {
|
||||||
|
base: "dark",
|
||||||
|
appBg: "#1E1E1E",
|
||||||
|
appContentBg: "#161616",
|
||||||
|
barBg: "#161616",
|
||||||
|
colorSecondary: "#8585F6",
|
||||||
|
textColor: "#FFFFFF",
|
||||||
|
brandImage,
|
||||||
|
brandTitle,
|
||||||
|
brandUrl,
|
||||||
|
fontBase,
|
||||||
|
fontCode
|
||||||
|
};
|
||||||
|
|
||||||
|
export const lightTheme: typeof darkTheme = {
|
||||||
|
base: "light",
|
||||||
|
appBg: "#F6F6F6",
|
||||||
|
appContentBg: "#FFFFFF",
|
||||||
|
barBg: "#FFFFFF",
|
||||||
|
colorSecondary: "#000091",
|
||||||
|
textColor: "#212121",
|
||||||
|
brandImage,
|
||||||
|
brandTitle,
|
||||||
|
brandUrl,
|
||||||
|
fontBase,
|
||||||
|
fontCode
|
||||||
|
};
|
@ -1,15 +1,13 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
"stories": [
|
stories: [
|
||||||
"../stories/**/*.stories.@(ts|tsx|mdx)"
|
"../stories/**/*.stories.tsx"
|
||||||
],
|
],
|
||||||
"addons": [
|
addons: [
|
||||||
"@storybook/addon-links",
|
|
||||||
"@storybook/addon-essentials",
|
|
||||||
"storybook-dark-mode",
|
"storybook-dark-mode",
|
||||||
"@storybook/addon-a11y"
|
"@storybook/addon-a11y"
|
||||||
],
|
],
|
||||||
"core": {
|
core: {
|
||||||
"builder": "webpack5"
|
builder: "webpack5"
|
||||||
},
|
},
|
||||||
"staticDirs": ["./static"]
|
staticDirs: ["./static"]
|
||||||
};
|
};
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { addons } from '@storybook/addons';
|
import { addons } from '@storybook/addons';
|
||||||
|
|
||||||
addons.setConfig({
|
addons.setConfig({
|
||||||
"selectedPanel": 'storybook/a11y/panel',
|
selectedPanel: 'storybook/a11y/panel',
|
||||||
"showPanel": false,
|
showPanel: false
|
||||||
});
|
});
|
||||||
|
@ -1,3 +1,9 @@
|
|||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-bold-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-medium-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-regular-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="preload" href="/fonts/WorkSans/worksans-semibold-webfont.woff2" as="font" crossorigin="anonymous">
|
||||||
|
<link rel="stylesheet" type="text/css" href="/fonts/WorkSans/font.css">
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
body.sb-show-main.sb-main-padded {
|
body.sb-show-main.sb-main-padded {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
|
@ -1,116 +1,105 @@
|
|||||||
import { darkTheme, lightTheme } from "./customTheme";
|
import { darkTheme, lightTheme } from "./customTheme";
|
||||||
import { DocsContainer, CanvasContainer } from "./Containers";
|
import { create as createTheme } from "@storybook/theming";
|
||||||
|
|
||||||
export const parameters = {
|
export const parameters = {
|
||||||
"actions": { "argTypesRegex": "^on[A-Z].*" },
|
actions: { argTypesRegex: "^on[A-Z].*" },
|
||||||
"controls": {
|
controls: {
|
||||||
"matchers": {
|
matchers: {
|
||||||
"color": /(background|color)$/i,
|
color: /(background|color)$/i,
|
||||||
"date": /Date$/,
|
date: /Date$/,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"backgrounds": { "disable": true },
|
backgrounds: { disable: true },
|
||||||
"darkMode": {
|
darkMode: {
|
||||||
"light": lightTheme,
|
light: createTheme(lightTheme),
|
||||||
"dark": darkTheme,
|
dark: createTheme(darkTheme),
|
||||||
},
|
},
|
||||||
"docs": {
|
controls: {
|
||||||
"container": DocsContainer
|
disable: true,
|
||||||
},
|
},
|
||||||
"controls": {
|
actions: {
|
||||||
"disable": true,
|
disable: true
|
||||||
},
|
},
|
||||||
"actions": {
|
viewport: {
|
||||||
"disable": true
|
viewports: {
|
||||||
},
|
|
||||||
"viewport": {
|
|
||||||
"viewports": {
|
|
||||||
"1440p": {
|
"1440p": {
|
||||||
"name": "1440p",
|
name: "1440p",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "2560px",
|
width: "2560px",
|
||||||
"height": "1440px",
|
height: "1440px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"fullHD": {
|
fullHD: {
|
||||||
"name": "Full HD",
|
name: "Full HD",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1920px",
|
width: "1920px",
|
||||||
"height": "1080px",
|
height: "1080px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"macBookProBig": {
|
macBookProBig: {
|
||||||
"name": "MacBook Pro Big",
|
name: "MacBook Pro Big",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1024px",
|
width: "1024px",
|
||||||
"height": "640px",
|
height: "640px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"macBookProMedium": {
|
macBookProMedium: {
|
||||||
"name": "MacBook Pro Medium",
|
name: "MacBook Pro Medium",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1440px",
|
width: "1440px",
|
||||||
"height": "900px",
|
height: "900px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"macBookProSmall": {
|
macBookProSmall: {
|
||||||
"name": "MacBook Pro Small",
|
name: "MacBook Pro Small",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1680px",
|
width: "1680px",
|
||||||
"height": "1050px",
|
height: "1050px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"pcAgent": {
|
pcAgent: {
|
||||||
"name": "PC Agent",
|
name: "PC Agent",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "960px",
|
width: "960px",
|
||||||
"height": "540px",
|
height: "540px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"iphone12Pro": {
|
iphone12Pro: {
|
||||||
"name": "Iphone 12 pro",
|
name: "Iphone 12 pro",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "390px",
|
width: "390px",
|
||||||
"height": "844px",
|
height: "844px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"iphone5se": {
|
iphone5se: {
|
||||||
"name": "Iphone 5/SE",
|
name: "Iphone 5/SE",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "320px",
|
width: "320px",
|
||||||
"height": "568px",
|
height: "568px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"ipadPro": {
|
ipadPro: {
|
||||||
"name": "Ipad pro",
|
name: "Ipad pro",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "1240px",
|
width: "1240px",
|
||||||
"height": "1366px",
|
height: "1366px",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"Galaxy s9+": {
|
"Galaxy s9+": {
|
||||||
"name": "Galaxy S9+",
|
name: "Galaxy S9+",
|
||||||
"styles": {
|
styles: {
|
||||||
"width": "320px",
|
width: "320px",
|
||||||
"height": "658px",
|
height: "658px",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"options": {
|
options: {
|
||||||
"storySort": (a, b) =>
|
storySort: (a, b) =>
|
||||||
getHardCodedWeight(b[1].kind) - getHardCodedWeight(a[1].kind),
|
getHardCodedWeight(b[1].kind) - getHardCodedWeight(a[1].kind),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const decorators = [
|
|
||||||
(Story) => (
|
|
||||||
<CanvasContainer>
|
|
||||||
<Story />
|
|
||||||
</CanvasContainer>
|
|
||||||
),
|
|
||||||
];
|
|
||||||
|
|
||||||
const { getHardCodedWeight } = (() => {
|
const { getHardCodedWeight } = (() => {
|
||||||
|
|
||||||
const orderedPagesPrefix = [
|
const orderedPagesPrefix = [
|
||||||
|
269
README.md
269
README.md
@ -2,7 +2,7 @@
|
|||||||
<img src="https://user-images.githubusercontent.com/6702424/109387840-eba11f80-7903-11eb-9050-db1dad883f78.png">
|
<img src="https://user-images.githubusercontent.com/6702424/109387840-eba11f80-7903-11eb-9050-db1dad883f78.png">
|
||||||
</p>
|
</p>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<i>🔏 Create Keycloak themes using React 🔏</i>
|
<i>🔏 Keycloak Theming for the Modern Web 🔏</i>
|
||||||
<br>
|
<br>
|
||||||
<br>
|
<br>
|
||||||
<a href="https://github.com/garronej/keycloakify/actions">
|
<a href="https://github.com/garronej/keycloakify/actions">
|
||||||
@ -38,22 +38,38 @@
|
|||||||
<i>This build tool generates a Keycloak theme <a href="https://www.keycloakify.dev">Learn more</a></i>
|
<i>This build tool generates a Keycloak theme <a href="https://www.keycloakify.dev">Learn more</a></i>
|
||||||
<br/>
|
<br/>
|
||||||
<br/>
|
<br/>
|
||||||
<img width="400" src="https://github.com/keycloakify/keycloakify/assets/6702424/e66d105c-c06f-47d1-8a31-a6ab09da4e80">
|
<img width="400" src="https://github.com/user-attachments/assets/6bf3bef9-00b0-4460-97b9-0d2da8500798">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
Keycloakify is fully compatible with Keycloak 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, [~~22~~](https://github.com/keycloakify/keycloakify/issues/389#issuecomment-1822509763), 23, 24, 25...[and beyond](https://github.com/keycloakify/keycloakify/discussions/346#discussioncomment-5889791)
|
Keycloakify is fully compatible with Keycloak 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, [~~22~~](https://github.com/keycloakify/keycloakify/issues/389#issuecomment-1822509763), 23, 24, 25...[and beyond](https://github.com/keycloakify/keycloakify/discussions/346#discussioncomment-5889791)
|
||||||
|
|
||||||
> NOTE: Keycloakify 10 is still in realase-candidate state. [Follow progress](https://github.com/keycloakify/keycloakify/pull/538).
|
> NOTE: Keycloakify 10 is still in release-candidate state. [Follow progress](https://github.com/keycloakify/keycloakify/pull/538).
|
||||||
|
|
||||||
## Sponsor
|
## Sponsors
|
||||||
|
|
||||||
We are exclusively sponsored by [Cloud IAM](https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github), a French company offering Keycloak as a service.
|
Friends for the project, we trust and recommend their services.
|
||||||
Their dedicated support helps us continue the development and maintenance of this project.
|
|
||||||
|
|
||||||
[Cloud IAM](https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github) provides the following services:
|
<br/>
|
||||||
|
|
||||||
- Simplify and secure your Keycloak Identity and Access Management. Keycloak as a Service.
|
<div align="center">
|
||||||
- Custom theme building for your brand using Keycloakify.
|
|
||||||
|

|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<br/>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.zone2.tech/services/keycloak-consulting">
|
||||||
|
<i><strong>Keycloak Consulting Services</strong> - Your partner in Keycloak deployment, configuration, and extension development for optimized identity management solutions.</i>
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
@ -68,13 +84,11 @@ Their dedicated support helps us continue the development and maintenance of thi
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<i>Checkout <a href="https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github">Cloud-IAM</a> and use promo code <code>keycloakify5</code></i>
|
<a href="https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github"><strong>Managed Keycloak Provider</strong> - With Cloud-IAM powering your Keycloak clusters, you can sleep easy knowing you've got the software and the experts you need for operational excellence. </a>
|
||||||
<br/>
|
<br/>
|
||||||
<i>5% of your annual subscription will be donated to us, and you'll get 5% off too.</i>
|
Use code <code>keycloakify5</code> at checkout for a 5% discount.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
Thank you, [Cloud-IAM](https://cloud-iam.com/?mtm_campaign=keycloakify-deal&mtm_source=keycloakify-github), for your support!
|
|
||||||
|
|
||||||
## Contributors ✨
|
## Contributors ✨
|
||||||
|
|
||||||
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
|
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
|
||||||
@ -125,230 +139,3 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
|||||||
<!-- prettier-ignore-end -->
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||||
|
|
||||||
# Changelog highlights
|
|
||||||
|
|
||||||
## 9.5
|
|
||||||
|
|
||||||
- Post build hook: You can now apply custom transformation to your theme files. [Learn more](https://docs.keycloakify.dev/build-options#postbuild-hook).
|
|
||||||
- You can now specify your option in the Keycloakify's Vite plugin instead in the package.json. [See example](https://docs.keycloakify.dev/build-options#themename).
|
|
||||||
|
|
||||||
## 9.4
|
|
||||||
|
|
||||||
**Vite Support! 🎉**
|
|
||||||
|
|
||||||
- [The starter is now a Vite project](https://github.com/keycloakify/keycloakify-starter).
|
|
||||||
The Webpack based starter is accessible [here](https://github.com/keycloakify/keycloakify-starter-cra).
|
|
||||||
- CRA (Webpack) remains supported for the forseable future.
|
|
||||||
- If you have a CRA Keycloakify theme that you wish to migrate to Vite checkout [this migration guide](https://docs.keycloakify.dev/migration-guides/cra-greater-than-vite).
|
|
||||||
|
|
||||||
## 9.0
|
|
||||||
|
|
||||||
Bring back support for account themes in Keycloak v23 and up! [See issue](https://github.com/keycloakify/keycloakify/issues/389).
|
|
||||||
|
|
||||||
### Breaking changes
|
|
||||||
|
|
||||||
Very few. Check them out [here](https://docs.keycloakify.dev/migration-guides/v8-greater-than-v9).
|
|
||||||
|
|
||||||
## 8.0
|
|
||||||
|
|
||||||
- Much smaller .jar size. 70.2 MB -> 7.8 MB.
|
|
||||||
Keycloakify now detects which of the static resources from the default theme are actually used by your theme and only include those in the .jar.
|
|
||||||
- Build time: The first build is slowed but the subsequent build are faster. [Update your CI so that the cache is persisted across CI build](https://github.com/keycloakify/keycloakify-starter/commit/bc378d5afb67e796f520afbc348185f3e319d9d0).
|
|
||||||
|
|
||||||
### Breaking changes
|
|
||||||
|
|
||||||
There are very few breaking changes in this major version. [Check them out](https://docs.keycloakify.dev/migration-guides/v7-greater-than-v8).
|
|
||||||
|
|
||||||
## 7.15
|
|
||||||
|
|
||||||
- The i18n messages you defines in your theme are now also maid available to Keycloak.
|
|
||||||
In practice this mean that you can now customize the `kcContext.message.summary` that
|
|
||||||
display a general alert and the values returned by `kcContext.messagesPerField.get()` that
|
|
||||||
are used to display specific error on some field of the form.
|
|
||||||
[See video](https://youtu.be/D6tZcemReTI)
|
|
||||||
|
|
||||||
## 7.14
|
|
||||||
|
|
||||||
- Deprecate the `extraPages` build option. Keycloakify is now able to analyze your code to detect extra pages.
|
|
||||||
|
|
||||||
## 7.13
|
|
||||||
|
|
||||||
- Deprecate `customUserAttribute`, Keycloakify now analyze your code to predict field name usage. [See doc](https://docs.keycloakify.dev/build-options#customuserattributes).
|
|
||||||
It's now mandatory to [adopt the new directory structure](https://docs.keycloakify.dev/migration-guides/v6-greater-than-v7).
|
|
||||||
|
|
||||||
## 7.12
|
|
||||||
|
|
||||||
- You can now pack multiple themes variant in a single `.jar` bundle. In vanilla Keycloak themes you have the ability to extend a base theme.
|
|
||||||
There is now an idiomatic way of achieving the same result. [Learn more](https://docs.keycloakify.dev/build-options#keycloakify.themeVariantNames).
|
|
||||||
|
|
||||||
## 7.9
|
|
||||||
|
|
||||||
- Separate script for copying the default theme static assets to the public directory.
|
|
||||||
Theses assets are only needed for testing your theme locally in Storybook or with a `mockPageId`.
|
|
||||||
You are now expected to have a `"prepare": "copy-keycloak-resources-to-public",` in your package.json scripts.
|
|
||||||
This script will create `public/keycloak-assets` when you run `yarn install` (If you are using another package manager
|
|
||||||
like `pnpm` makes sure that `"prepare"` is actually ran.)
|
|
||||||
[See the updated starter](https://github.com/keycloakify/keycloakify-starter/blob/94532fcf10bf8b19e0873be8575fd28a8958a806/package.json#L11). `public/keycloak-assets` shouldn't be tracked by GIT and is automatically ignored.
|
|
||||||
|
|
||||||
## 7.7
|
|
||||||
|
|
||||||
- Better storybook support, see [the starter project](https://github.com/keycloakify/keycloakify-starter).
|
|
||||||
|
|
||||||
## 7.0 🍾
|
|
||||||
|
|
||||||
- Account theme support 🚀
|
|
||||||
- It's much easier to customize pages at the CSS level, you can now see in the browser dev tool the customizable classes.
|
|
||||||
- New interactive CLI tool `npx eject-keycloak-page`, that enables to select the page you want to customize at the component level.
|
|
||||||
- There is [a Storybook](https://storybook.keycloakify.dev)
|
|
||||||
- [Remember me is fixed](https://github.com/keycloakify/keycloakify/pull/272)
|
|
||||||
|
|
||||||
## 6.13
|
|
||||||
|
|
||||||
- Build work behind corporate proxies, [see issue](https://github.com/keycloakify/keycloakify/issues/257).
|
|
||||||
|
|
||||||
## 6.12
|
|
||||||
|
|
||||||
Massive improvement in the developer experience:
|
|
||||||
|
|
||||||
- There is now only one starter repo: https://github.com/codegouvfr/keycloakify-starter
|
|
||||||
- A lot of comments have been added in the code of the starter to make it easier to get started.
|
|
||||||
- The doc has been updated: https://docs.keycloakify.dev
|
|
||||||
- A lot of improvements in the type system.
|
|
||||||
|
|
||||||
## 6.11.4
|
|
||||||
|
|
||||||
- You no longer need to have Maven installed to build the theme. Thanks to @lordvlad, [see PR](https://github.com/keycloakify/keycloakify/pull/239).
|
|
||||||
- Feature new build options: [`bundler`](https://docs.keycloakify.dev/build-options#keycloakify.bundler), [`groupId`](https://docs.keycloakify.dev/build-options#keycloakify.groupid), [`artifactId`](https://docs.keycloakify.dev/build-options#keycloakify.artifactid), [`version`](https://docs.keycloakify.dev/build-options#version).
|
|
||||||
Theses options can be user to customize the output name of the .jar. You can use environnement variables to overrides the values read in the package.json. Thanks to @lordvlad.
|
|
||||||
|
|
||||||
## 6.10.0
|
|
||||||
|
|
||||||
- Widows compat (thanks to @lordvlad, [see PR](https://github.com/keycloakify/keycloakify/pull/226)). WSL is no longer required 🎉
|
|
||||||
|
|
||||||
## 6.8.4
|
|
||||||
|
|
||||||
- `@emotion/react` is no longer a peer dependency of Keycloakify.
|
|
||||||
|
|
||||||
## 6.8.0
|
|
||||||
|
|
||||||
- It is now possible to pass a custom `<Template />` component as a prop to `<KcApp />` and every
|
|
||||||
individual page (`<Login />`, `<RegisterUserProfile />`, ...) it enables to customize only the header and footer for
|
|
||||||
example without having to switch to a full-component level customization. [See issue](https://github.com/keycloakify/keycloakify/issues/191).
|
|
||||||
|
|
||||||
## 6.7.0
|
|
||||||
|
|
||||||
- Add support for `webauthn-authenticate.ftl` thanks to [@mstrodl](https://github.com/Mstrodl)'s hacktoberfest [PR](https://github.com/keycloakify/keycloakify/pull/185).
|
|
||||||
|
|
||||||
## 6.6.0
|
|
||||||
|
|
||||||
- Add support for `login-password.ftl` thanks to [@mstrodl](https://github.com/Mstrodl)'s hacktoberfest [PR](https://github.com/keycloakify/keycloakify/pull/184).
|
|
||||||
|
|
||||||
## 6.5.0
|
|
||||||
|
|
||||||
- Add support for `login-username.ftl` thanks to [@mstrodl](https://github.com/Mstrodl)'s hacktoberfest [PR](https://github.com/keycloakify/keycloakify/pull/183).
|
|
||||||
|
|
||||||
## 6.4.0
|
|
||||||
|
|
||||||
- You can now optionally pass a `doFetchDefaultThemeResources: boolean` prop to every page component and the default `<KcApp />`
|
|
||||||
This enables you to prevent the default CSS and JS that comes with the builtin Keycloak theme to be downloaded.
|
|
||||||
You'll get [a black slate](https://user-images.githubusercontent.com/6702424/192619083-4baa5df4-4a21-4ec7-8e28-d200d1208299.png).
|
|
||||||
|
|
||||||
## 6.0.0
|
|
||||||
|
|
||||||
- Bundle size drastically reduced, locals and component dynamically loaded.
|
|
||||||
- First print much quicker, use of React.lazy() everywhere.
|
|
||||||
- Real i18n API.
|
|
||||||
- Actual documentation for build options.
|
|
||||||
|
|
||||||
Checkout [the migration guide](https://docs.keycloakify.dev/v5-to-v6)
|
|
||||||
|
|
||||||
## 5.8.0
|
|
||||||
|
|
||||||
- [React.lazy()](https://reactjs.org/docs/code-splitting.html#reactlazy) support 🎉. [#141](https://github.com/keycloakify/keycloakify/issues/141)
|
|
||||||
|
|
||||||
## 5.7.0
|
|
||||||
|
|
||||||
- Feat `logout-confirm.ftl`. [PR](https://github.com/keycloakify/keycloakify/pull/120)
|
|
||||||
|
|
||||||
## 5.6.4
|
|
||||||
|
|
||||||
Fix `login-verify-email.ftl` page. [Before](https://user-images.githubusercontent.com/6702424/177436014-0bad22c4-5bfb-45bb-8fc9-dad65143cd0c.png) - [After](https://user-images.githubusercontent.com/6702424/177435797-ec5d7db3-84cf-49cb-8efc-3427a81f744e.png)
|
|
||||||
|
|
||||||
## 5.6.0
|
|
||||||
|
|
||||||
Add support for `login-config-totp.ftl` page [#127](https://github.com/keycloakify/keycloakify/pull/127).
|
|
||||||
|
|
||||||
## 5.3.0
|
|
||||||
|
|
||||||
Rename `keycloak_theme_email` to `keycloak_email`.
|
|
||||||
If you already had a `keycloak_theme_email` you should rename it `keycloak_email`.
|
|
||||||
|
|
||||||
## 5.0.0
|
|
||||||
|
|
||||||
[Migration guide](https://github.com/garronej/keycloakify-demo-app/blob/a5b6a50f24bc25e082931f5ad9ebf47492acd12a/src/index.tsx#L46-L63)
|
|
||||||
New i18n system.
|
|
||||||
Import of terms and services have changed. [See example](https://github.com/garronej/keycloakify-demo-app/blob/a5b6a50f24bc25e082931f5ad9ebf47492acd12a/src/index.tsx#L46-L63).
|
|
||||||
|
|
||||||
## 4.10.0
|
|
||||||
|
|
||||||
Add `login-idp-link-email.ftl` page [See PR](https://github.com/keycloakify/keycloakify/pull/92).
|
|
||||||
|
|
||||||
## 4.8.0
|
|
||||||
|
|
||||||
[Email template customization.](#email-template-customization)
|
|
||||||
|
|
||||||
## 4.7.4
|
|
||||||
|
|
||||||
**M1 Mac** support (for testing locally with a dockerized Keycloak).
|
|
||||||
|
|
||||||
## 4.7.2
|
|
||||||
|
|
||||||
> WARNING: This is broken.
|
|
||||||
> Testing with local Keycloak container working with M1 Mac. Thanks to [@eduardosanzb](https://github.com/keycloakify/keycloakify/issues/43#issuecomment-975699658).
|
|
||||||
> Be aware: When running M1s you are testing with Keycloak v15 else the local container spun will be a Keycloak v16.1.0.
|
|
||||||
|
|
||||||
## 4.7.0
|
|
||||||
|
|
||||||
Register with user profile enabled: Out of the box `options` validator support.
|
|
||||||
[Example](https://user-images.githubusercontent.com/6702424/158911163-81e6bbe8-feb0-4dc8-abff-de199d7a678e.mov)
|
|
||||||
|
|
||||||
## 4.6.0
|
|
||||||
|
|
||||||
`tss-react` and `powerhooks` are no longer peer dependencies of `keycloakify`.
|
|
||||||
After updating Keycloakify you can remove `tss-react` and `powerhooks` from your dependencies if you don't use them explicitly.
|
|
||||||
|
|
||||||
## 4.5.3
|
|
||||||
|
|
||||||
There is a new recommended way to setup highly customized theme. See [here](https://github.com/garronej/keycloakify-demo-app/blob/look_and_feel/src/KcApp/KcApp.tsx).
|
|
||||||
Unlike with [the previous recommended method](https://github.com/garronej/keycloakify-demo-app/blob/a51660578bea15fb3e506b8a2b78e1056c6d68bb/src/KcApp/KcApp.tsx),
|
|
||||||
with this new method your theme wont break on minor Keycloakify update.
|
|
||||||
|
|
||||||
## 4.3.0
|
|
||||||
|
|
||||||
Feature [`login-update-password.ftl`](https://user-images.githubusercontent.com/6702424/147517600-6191cf72-93dd-437b-a35c-47180142063e.png).
|
|
||||||
Every time a page is added it's a breaking change for non CSS-only theme.
|
|
||||||
Change [this](https://github.com/garronej/keycloakify-demo-app/blob/df664c13c77ce3c53ac7df0622d94d04e76d3f9f/src/KcApp/KcApp.tsx#L17) and [this](https://github.com/garronej/keycloakify-demo-app/blob/df664c13c77ce3c53ac7df0622d94d04e76d3f9f/src/KcApp/KcApp.tsx#L37) to update.
|
|
||||||
|
|
||||||
## 4
|
|
||||||
|
|
||||||
- Out of the box [frontend form validation](#user-profile-and-frontend-form-validation) 🥳
|
|
||||||
- Improvements (and breaking changes in `import { useKcMessage } from "keycloakify"`.
|
|
||||||
|
|
||||||
## 3
|
|
||||||
|
|
||||||
No breaking changes except that `@emotion/react`, [`tss-react`](https://www.npmjs.com/package/tss-react) and [`powerhooks`](https://www.npmjs.com/package/powerhooks) are now `peerDependencies` instead of being just dependencies.
|
|
||||||
It's important to avoid problem when using `keycloakify` alongside [`mui`](https://mui.com) and
|
|
||||||
[when passing params from the app to the login page](https://github.com/keycloakify/keycloakify#implement-context-persistence-optional).
|
|
||||||
|
|
||||||
## 2.5
|
|
||||||
|
|
||||||
- Feature [Use advanced message](https://github.com/keycloakify/keycloakify/blob/59f106bf9e210b63b190826da2bf5f75fc8b7644/src/lib/i18n/useKcMessage.tsx#L53-L66)
|
|
||||||
and [`messagesPerFields`](https://github.com/keycloakify/keycloakify/blob/59f106bf9e210b63b190826da2bf5f75fc8b7644/src/lib/getKcContext/KcContextBase.ts#L70-L75) (implementation [here](https://github.com/keycloakify/keycloakify/blob/59f106bf9e210b63b190826da2bf5f75fc8b7644/src/bin/build-keycloak-theme/generateFtl/common.ftl#L130-L189))
|
|
||||||
- Test container now uses Keycloak version `15.0.2`.
|
|
||||||
|
|
||||||
## 2
|
|
||||||
|
|
||||||
- It's now possible to implement custom `.ftl` pages.
|
|
||||||
- Support for Keycloak plugins that introduce non standard ftl values.
|
|
||||||
(Like for example [this plugin](https://github.com/micedre/keycloak-mail-whitelisting) that define `authorizedMailDomains` in `register.ftl`).
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "keycloakify",
|
"name": "keycloakify",
|
||||||
"version": "10.0.0-rc.103",
|
"version": "10.0.0-rc.132",
|
||||||
"description": "Create Keycloak themes using React",
|
"description": "Create Keycloak themes using React",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@ -72,14 +72,10 @@
|
|||||||
"@emotion/react": "^11.11.4",
|
"@emotion/react": "^11.11.4",
|
||||||
"@octokit/rest": "^20.1.1",
|
"@octokit/rest": "^20.1.1",
|
||||||
"@storybook/addon-a11y": "^6.5.16",
|
"@storybook/addon-a11y": "^6.5.16",
|
||||||
"@storybook/addon-actions": "^6.5.13",
|
|
||||||
"@storybook/addon-essentials": "^6.5.13",
|
|
||||||
"@storybook/addon-interactions": "^6.5.13",
|
|
||||||
"@storybook/addon-links": "^6.5.13",
|
|
||||||
"@storybook/builder-webpack5": "^6.5.13",
|
"@storybook/builder-webpack5": "^6.5.13",
|
||||||
"@storybook/manager-webpack5": "^6.5.13",
|
"@storybook/manager-webpack5": "^6.5.13",
|
||||||
"@storybook/react": "^6.5.13",
|
"@storybook/react": "^6.5.13",
|
||||||
"@storybook/testing-library": "^0.0.13",
|
"eslint-plugin-storybook": "^0.6.7",
|
||||||
"@types/babel__generator": "^7.6.4",
|
"@types/babel__generator": "^7.6.4",
|
||||||
"@types/make-fetch-happen": "^10.0.1",
|
"@types/make-fetch-happen": "^10.0.1",
|
||||||
"@types/minimist": "^1.2.2",
|
"@types/minimist": "^1.2.2",
|
||||||
@ -92,7 +88,6 @@
|
|||||||
"cheerio": "^1.0.0-rc.12",
|
"cheerio": "^1.0.0-rc.12",
|
||||||
"chokidar-cli": "^3.0.0",
|
"chokidar-cli": "^3.0.0",
|
||||||
"cli-select": "^1.1.2",
|
"cli-select": "^1.1.2",
|
||||||
"eslint-plugin-storybook": "^0.6.7",
|
|
||||||
"husky": "^4.3.8",
|
"husky": "^4.3.8",
|
||||||
"lint-staged": "^11.0.0",
|
"lint-staged": "^11.0.0",
|
||||||
"magic-string": "^0.30.7",
|
"magic-string": "^0.30.7",
|
||||||
|
@ -1,16 +1,13 @@
|
|||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import { join } from "path";
|
import { copyKeycloakResourcesToStorybookStaticDir } from "./copyKeycloakResourcesToStorybookStaticDir";
|
||||||
|
|
||||||
run("yarn build");
|
(async () => {
|
||||||
|
run("yarn build");
|
||||||
|
|
||||||
run(`node ${join("dist", "bin", "main.js")} copy-keycloak-resources-to-public`, {
|
await copyKeycloakResourcesToStorybookStaticDir();
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
PUBLIC_DIR_PATH: join(".storybook", "static")
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
run("npx build-storybook");
|
run("npx build-storybook");
|
||||||
|
})();
|
||||||
|
|
||||||
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
||||||
console.log(`$ ${command}`);
|
console.log(`$ ${command}`);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { join, relative } from "path";
|
import { join } from "path";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { transformCodebase } from "../src/bin/tools/transformCodebase";
|
import { transformCodebase } from "../src/bin/tools/transformCodebase";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
|
18
scripts/copyKeycloakResourcesToStorybookStaticDir.ts
Normal file
18
scripts/copyKeycloakResourcesToStorybookStaticDir.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import { copyKeycloakResourcesToPublic } from "../src/bin/shared/copyKeycloakResourcesToPublic";
|
||||||
|
import { getProxyFetchOptions } from "../src/bin/tools/fetchProxyOptions";
|
||||||
|
import { LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT } from "../src/bin/shared/constants";
|
||||||
|
|
||||||
|
export async function copyKeycloakResourcesToStorybookStaticDir() {
|
||||||
|
await copyKeycloakResourcesToPublic({
|
||||||
|
buildContext: {
|
||||||
|
cacheDirPath: pathJoin(__dirname, "..", "node_modules", ".cache", "scripts"),
|
||||||
|
fetchOptions: getProxyFetchOptions({
|
||||||
|
npmConfigGetCwd: pathJoin(__dirname, "..")
|
||||||
|
}),
|
||||||
|
loginThemeResourcesFromKeycloakVersion:
|
||||||
|
LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT,
|
||||||
|
publicDirPath: pathJoin(__dirname, "..", ".storybook", "static")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
import { containerName } from "../src/bin/shared/constants";
|
import { CONTAINER_NAME } from "../src/bin/shared/constants";
|
||||||
import child_process from "child_process";
|
import child_process from "child_process";
|
||||||
import { SemVer } from "../src/bin/tools/SemVer";
|
import { SemVer } from "../src/bin/tools/SemVer";
|
||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
@ -14,7 +14,7 @@ import { is } from "tsafe/is";
|
|||||||
const child = child_process.spawn(
|
const child = child_process.spawn(
|
||||||
"docker",
|
"docker",
|
||||||
[
|
[
|
||||||
...["exec", containerName],
|
...["exec", CONTAINER_NAME],
|
||||||
...["/opt/keycloak/bin/kc.sh", "export"],
|
...["/opt/keycloak/bin/kc.sh", "export"],
|
||||||
...["--dir", "/tmp"],
|
...["--dir", "/tmp"],
|
||||||
...["--realm", "myrealm"],
|
...["--realm", "myrealm"],
|
||||||
@ -62,7 +62,7 @@ import { is } from "tsafe/is";
|
|||||||
|
|
||||||
const keycloakMajorVersionNumber = SemVer.parse(
|
const keycloakMajorVersionNumber = SemVer.parse(
|
||||||
child_process
|
child_process
|
||||||
.execSync(`docker inspect --format '{{.Config.Image}}' ${containerName}`)
|
.execSync(`docker inspect --format '{{.Config.Image}}' ${CONTAINER_NAME}`)
|
||||||
.toString("utf8")
|
.toString("utf8")
|
||||||
.trim()
|
.trim()
|
||||||
.split(":")[1]
|
.split(":")[1]
|
||||||
@ -80,7 +80,7 @@ import { is } from "tsafe/is";
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
run(`docker cp ${containerName}:/tmp/myrealm-realm.json ${targetFilePath}`);
|
run(`docker cp ${CONTAINER_NAME}:/tmp/myrealm-realm.json ${targetFilePath}`);
|
||||||
|
|
||||||
console.log(`${chalk.green(`✓ Exported realm to`)} ${chalk.bold(targetFilePath)}`);
|
console.log(`${chalk.green(`✓ Exported realm to`)} ${chalk.bold(targetFilePath)}`);
|
||||||
})();
|
})();
|
||||||
|
@ -12,6 +12,7 @@ import { crawl } from "../src/bin/tools/crawl";
|
|||||||
import { downloadKeycloakDefaultTheme } from "../src/bin/shared/downloadKeycloakDefaultTheme";
|
import { downloadKeycloakDefaultTheme } from "../src/bin/shared/downloadKeycloakDefaultTheme";
|
||||||
import { getThisCodebaseRootDirPath } from "../src/bin/tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "../src/bin/tools/getThisCodebaseRootDirPath";
|
||||||
import { deepAssign } from "../src/tools/deepAssign";
|
import { deepAssign } from "../src/tools/deepAssign";
|
||||||
|
import { getProxyFetchOptions } from "../src/bin/tools/fetchProxyOptions";
|
||||||
|
|
||||||
// NOTE: To run without argument when we want to generate src/i18n/generated_kcMessages files,
|
// NOTE: To run without argument when we want to generate src/i18n/generated_kcMessages files,
|
||||||
// update the version array for generating for newer version.
|
// update the version array for generating for newer version.
|
||||||
@ -33,7 +34,9 @@ async function main() {
|
|||||||
".cache",
|
".cache",
|
||||||
"keycloakify"
|
"keycloakify"
|
||||||
),
|
),
|
||||||
npmWorkspaceRootDirPath: thisCodebaseRootDirPath
|
fetchOptions: getProxyFetchOptions({
|
||||||
|
npmConfigGetCwd: thisCodebaseRootDirPath
|
||||||
|
})
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -107,12 +110,12 @@ async function main() {
|
|||||||
source: keycloakifyExtraMessages
|
source: keycloakifyExtraMessages
|
||||||
});
|
});
|
||||||
|
|
||||||
const baseMessagesDirPath = pathJoin(
|
const messagesDirPath = pathJoin(
|
||||||
thisCodebaseRootDirPath,
|
thisCodebaseRootDirPath,
|
||||||
"src",
|
"src",
|
||||||
themeType,
|
themeType,
|
||||||
"i18n",
|
"i18n",
|
||||||
"baseMessages"
|
"messages_defaultSet"
|
||||||
);
|
);
|
||||||
|
|
||||||
const generatedFileHeader = [
|
const generatedFileHeader = [
|
||||||
@ -124,7 +127,7 @@ async function main() {
|
|||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
languages.forEach(language => {
|
languages.forEach(language => {
|
||||||
const filePath = pathJoin(baseMessagesDirPath, `${language}.ts`);
|
const filePath = pathJoin(messagesDirPath, `${language}.ts`);
|
||||||
|
|
||||||
fs.mkdirSync(pathDirname(filePath), { recursive: true });
|
fs.mkdirSync(pathDirname(filePath), { recursive: true });
|
||||||
|
|
||||||
@ -152,14 +155,14 @@ async function main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
pathJoin(baseMessagesDirPath, "index.ts"),
|
pathJoin(messagesDirPath, "index.ts"),
|
||||||
Buffer.from(
|
Buffer.from(
|
||||||
[
|
[
|
||||||
generatedFileHeader,
|
generatedFileHeader,
|
||||||
`import * as en from "./en";`,
|
`import * as en from "./en";`,
|
||||||
"",
|
"",
|
||||||
"export async function getMessages(currentLanguageTag: string) {",
|
"export async function fetchMessages_defaultSet(currentLanguageTag: string) {",
|
||||||
" const { default: messages } = await (() => {",
|
" const { default: messages_defaultSet } = await (() => {",
|
||||||
" switch (currentLanguageTag) {",
|
" switch (currentLanguageTag) {",
|
||||||
` case "en": return en;`,
|
` case "en": return en;`,
|
||||||
...languages
|
...languages
|
||||||
@ -171,7 +174,7 @@ async function main() {
|
|||||||
' default: return { "default": {} };',
|
' default: return { "default": {} };',
|
||||||
" }",
|
" }",
|
||||||
" })();",
|
" })();",
|
||||||
" return messages;",
|
" return messages_defaultSet;",
|
||||||
"}"
|
"}"
|
||||||
].join("\n"),
|
].join("\n"),
|
||||||
"utf8"
|
"utf8"
|
||||||
|
@ -44,6 +44,12 @@ const commonThirdPartyDeps = [
|
|||||||
.replace(/"!dist\//g, '"!')
|
.replace(/"!dist\//g, '"!')
|
||||||
.replace(/"!\.\/dist\//g, '"!./');
|
.replace(/"!\.\/dist\//g, '"!./');
|
||||||
|
|
||||||
|
modifiedPackageJsonContent = JSON.stringify(
|
||||||
|
{ ...JSON.parse(modifiedPackageJsonContent), version: "0.0.0" },
|
||||||
|
null,
|
||||||
|
4
|
||||||
|
);
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
pathJoin(rootDirPath, "dist", "package.json"),
|
pathJoin(rootDirPath, "dist", "package.json"),
|
||||||
Buffer.from(modifiedPackageJsonContent, "utf8")
|
Buffer.from(modifiedPackageJsonContent, "utf8")
|
||||||
|
@ -1,30 +1,26 @@
|
|||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import * as fs from "fs";
|
|
||||||
import { join } from "path";
|
|
||||||
import { startRebuildOnSrcChange } from "./startRebuildOnSrcChange";
|
import { startRebuildOnSrcChange } from "./startRebuildOnSrcChange";
|
||||||
|
import { copyKeycloakResourcesToStorybookStaticDir } from "./copyKeycloakResourcesToStorybookStaticDir";
|
||||||
|
|
||||||
run("yarn build");
|
(async () => {
|
||||||
|
run("yarn build");
|
||||||
|
|
||||||
run(`node ${join("dist", "bin", "main.js")} copy-keycloak-resources-to-public`, {
|
await copyKeycloakResourcesToStorybookStaticDir();
|
||||||
env: {
|
|
||||||
...process.env,
|
{
|
||||||
PUBLIC_DIR_PATH: join(".storybook", "static")
|
const child = child_process.spawn("npx", ["start-storybook", "-p", "6006"], {
|
||||||
|
shell: true
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stdout.on("data", data => process.stdout.write(data));
|
||||||
|
|
||||||
|
child.stderr.on("data", data => process.stderr.write(data));
|
||||||
|
|
||||||
|
child.on("exit", process.exit.bind(process));
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
{
|
startRebuildOnSrcChange();
|
||||||
const child = child_process.spawn("npx", ["start-storybook", "-p", "6006"], {
|
})();
|
||||||
shell: true
|
|
||||||
});
|
|
||||||
|
|
||||||
child.stdout.on("data", data => process.stdout.write(data));
|
|
||||||
|
|
||||||
child.stderr.on("data", data => process.stderr.write(data));
|
|
||||||
|
|
||||||
child.on("exit", process.exit.bind(process));
|
|
||||||
}
|
|
||||||
|
|
||||||
startRebuildOnSrcChange();
|
|
||||||
|
|
||||||
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
function run(command: string, options?: { env?: NodeJS.ProcessEnv }) {
|
||||||
console.log(`$ ${command}`);
|
console.log(`$ ${command}`);
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { basenameOfTheKeycloakifyResourcesDir } from "keycloakify/bin/shared/constants";
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } from "keycloakify/bin/shared/constants";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -17,5 +17,5 @@ export const PUBLIC_URL = (() => {
|
|||||||
return process.env.PUBLIC_URL;
|
return process.env.PUBLIC_URL;
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${kcContext.url.resourcesPath}/${basenameOfTheKeycloakifyResourcesDir}`;
|
return `${kcContext.url.resourcesPath}/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}`;
|
||||||
})();
|
})();
|
||||||
|
@ -118,7 +118,10 @@ export declare namespace KcContext {
|
|||||||
lastName?: string;
|
lastName?: string;
|
||||||
username?: string;
|
username?: string;
|
||||||
};
|
};
|
||||||
properties: Record<string, string | undefined>;
|
properties: {};
|
||||||
|
"x-keycloakify": {
|
||||||
|
messages: Record<string, string>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Password = Common & {
|
export type Password = Common & {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import "keycloakify/tools/Object.fromEntries";
|
import "keycloakify/tools/Object.fromEntries";
|
||||||
import { resources_common, keycloak_resources } from "keycloakify/bin/shared/constants";
|
import { RESOURCES_COMMON, KEYCLOAK_RESOURCES } from "keycloakify/bin/shared/constants";
|
||||||
import { id } from "tsafe/id";
|
import { id } from "tsafe/id";
|
||||||
import type { KcContext } from "./KcContext";
|
import type { KcContext } from "./KcContext";
|
||||||
import { BASE_URL } from "keycloakify/lib/BASE_URL";
|
import { BASE_URL } from "keycloakify/lib/BASE_URL";
|
||||||
|
|
||||||
const resourcesPath = `${BASE_URL}${keycloak_resources}/account/resources`;
|
const resourcesPath = `${BASE_URL}${KEYCLOAK_RESOURCES}/account/resources`;
|
||||||
|
|
||||||
export const kcContextCommonMock: KcContext.Common = {
|
export const kcContextCommonMock: KcContext.Common = {
|
||||||
themeVersion: "0.0.0",
|
themeVersion: "0.0.0",
|
||||||
@ -13,7 +13,7 @@ export const kcContextCommonMock: KcContext.Common = {
|
|||||||
themeName: "my-theme-name",
|
themeName: "my-theme-name",
|
||||||
url: {
|
url: {
|
||||||
resourcesPath,
|
resourcesPath,
|
||||||
resourcesCommonPath: `${resourcesPath}/${resources_common}`,
|
resourcesCommonPath: `${resourcesPath}/${RESOURCES_COMMON}`,
|
||||||
resourceUrl: "#",
|
resourceUrl: "#",
|
||||||
accountUrl: "#",
|
accountUrl: "#",
|
||||||
applicationsUrl: "#",
|
applicationsUrl: "#",
|
||||||
@ -82,7 +82,10 @@ export const kcContextCommonMock: KcContext.Common = {
|
|||||||
email: "john.doe@code.gouv.fr",
|
email: "john.doe@code.gouv.fr",
|
||||||
username: "doe_j"
|
username: "doe_j"
|
||||||
},
|
},
|
||||||
properties: {}
|
properties: {},
|
||||||
|
"x-keycloakify": {
|
||||||
|
messages: {}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const kcContextMocks: KcContext[] = [
|
export const kcContextMocks: KcContext[] = [
|
||||||
|
6
src/account/i18n/GenericI18n.tsx
Normal file
6
src/account/i18n/GenericI18n.tsx
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import type { GenericI18n_noJsx } from "./i18n";
|
||||||
|
|
||||||
|
export type GenericI18n<MessageKey extends string> = GenericI18n_noJsx<MessageKey> & {
|
||||||
|
msg: (key: MessageKey, ...args: (string | undefined)[]) => JSX.Element;
|
||||||
|
advancedMsg: (key: string, ...args: (string | undefined)[]) => JSX.Element;
|
||||||
|
};
|
@ -1,22 +1,24 @@
|
|||||||
import "keycloakify/tools/Object.fromEntries";
|
import "keycloakify/tools/Object.fromEntries";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import messages_fallbackLanguage from "./baseMessages/en";
|
import messages_defaultSet_fallbackLanguage from "./messages_defaultSet/en";
|
||||||
import { getMessages } from "./baseMessages";
|
import { fetchMessages_defaultSet } from "./messages_defaultSet";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { fallbackLanguageTag } from "keycloakify/bin/shared/constants";
|
import { FALLBACK_LANGUAGE_TAG } from "keycloakify/bin/shared/constants";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
|
||||||
export type KcContextLike = {
|
export type KcContextLike = {
|
||||||
locale?: {
|
locale?: {
|
||||||
currentLanguageTag: string;
|
currentLanguageTag: string;
|
||||||
supported: { languageTag: string; url: string; label: string }[];
|
supported: { languageTag: string; url: string; label: string }[];
|
||||||
};
|
};
|
||||||
|
"x-keycloakify": {
|
||||||
|
messages: Record<string, string>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<KcContext extends KcContextLike ? true : false>();
|
assert<KcContext extends KcContextLike ? true : false>();
|
||||||
|
|
||||||
export type MessageKey = keyof typeof messages_fallbackLanguage;
|
export type GenericI18n_noJsx<MessageKey extends string> = {
|
||||||
|
|
||||||
export type GenericI18n<MessageKey extends string> = {
|
|
||||||
/**
|
/**
|
||||||
* e.g: "en", "fr", "zh-CN"
|
* e.g: "en", "fr", "zh-CN"
|
||||||
*
|
*
|
||||||
@ -36,16 +38,21 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
* */
|
* */
|
||||||
labelBySupportedLanguageTag: Record<string, string>;
|
labelBySupportedLanguageTag: Record<string, string>;
|
||||||
/**
|
/**
|
||||||
* Examples assuming currentLanguageTag === "en"
|
|
||||||
*
|
*
|
||||||
* msg("access-denied") === <span>Access denied</span>
|
* Examples assuming currentLanguageTag === "en"
|
||||||
* msg("impersonateTitleHtml", "Foo") === <span><strong>Foo</strong> Impersonate User</span>
|
* {
|
||||||
*/
|
* en: {
|
||||||
msg: (key: MessageKey, ...args: (string | undefined)[]) => JSX.Element;
|
* "access-denied": "Access denied",
|
||||||
/**
|
* "impersonateTitleHtml": "<strong>{0}</strong> Impersonate User",
|
||||||
* It's the same thing as msg() but instead of returning a JSX.Element it returns a string.
|
* "bar": "Bar {0}"
|
||||||
* It can be more convenient to manipulate strings but if there are HTML tags it wont render.
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* msgStr("access-denied") === "Access denied"
|
||||||
|
* msgStr("not-a-message-key") Throws an error
|
||||||
* msgStr("impersonateTitleHtml", "Foo") === "<strong>Foo</strong> Impersonate User"
|
* msgStr("impersonateTitleHtml", "Foo") === "<strong>Foo</strong> Impersonate User"
|
||||||
|
* msgStr("${bar}", "<strong>c</strong>") === "Bar <strong>XXX</strong>"
|
||||||
|
* The html in the arg is partially escaped for security reasons, it might come from an untrusted source, it's not safe to render it as html.
|
||||||
*/
|
*/
|
||||||
msgStr: (key: MessageKey, ...args: (string | undefined)[]) => string;
|
msgStr: (key: MessageKey, ...args: (string | undefined)[]) => string;
|
||||||
/**
|
/**
|
||||||
@ -56,24 +63,11 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
* {
|
* {
|
||||||
* en: {
|
* en: {
|
||||||
* "access-denied": "Access denied",
|
* "access-denied": "Access denied",
|
||||||
* "foo": "Foo {0} {1}",
|
|
||||||
* "bar": "Bar {0}"
|
|
||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* advancedMsg("${access-denied} foo bar") === <span>{msgStr("access-denied")} foo bar<span> === <span>Access denied foo bar</span>
|
* advancedMsgStr("${access-denied}") === advancedMsgStr("access-denied") === msgStr("access-denied") === "Access denied"
|
||||||
* advancedMsg("${access-denied}") === advancedMsg("access-denied") === msg("access-denied") === <span>Access denied</span>
|
* advancedMsgStr("${not-a-message-key}") === advancedMsgStr("not-a-message-key") === "not-a-message-key"
|
||||||
* advancedMsg("${not-a-message-key}") === advancedMsg(not-a-message-key") === <span>not-a-message-key</span>
|
|
||||||
* advancedMsg("${bar}", "<strong>c</strong>")
|
|
||||||
* === <span>{msgStr("bar", "<strong>XXX</strong>")}<span>
|
|
||||||
* === <span>Bar <strong>XXX</strong></span> (The html in the arg is partially escaped for security reasons, it might be untrusted)
|
|
||||||
* advancedMsg("${foo} xx ${bar}", "a", "b", "c")
|
|
||||||
* === <span>{msgStr("foo", "a", "b")} xx {msgStr("bar")}<span>
|
|
||||||
* === <span>Foo a b xx Bar {0}</span> (The substitution are only applied in the first message)
|
|
||||||
*/
|
|
||||||
advancedMsg: (key: string, ...args: (string | undefined)[]) => JSX.Element;
|
|
||||||
/**
|
|
||||||
* See advancedMsg() but instead of returning a JSX.Element it returns a string.
|
|
||||||
*/
|
*/
|
||||||
advancedMsgStr: (key: string, ...args: (string | undefined)[]) => string;
|
advancedMsgStr: (key: string, ...args: (string | undefined)[]) => string;
|
||||||
|
|
||||||
@ -85,10 +79,12 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
isFetchingTranslations: boolean;
|
isFetchingTranslations: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createGetI18n<ExtraMessageKey extends string = never>(messageBundle: {
|
export type MessageKey_defaultSet = keyof typeof messages_defaultSet_fallbackLanguage;
|
||||||
[languageTag: string]: { [key in ExtraMessageKey]: string };
|
|
||||||
|
export function createGetI18n<MessageKey_themeDefined extends string = never>(messagesByLanguageTag_themeDefined: {
|
||||||
|
[languageTag: string]: { [key in MessageKey_themeDefined]: string };
|
||||||
}) {
|
}) {
|
||||||
type I18n = GenericI18n<MessageKey | ExtraMessageKey>;
|
type I18n = GenericI18n_noJsx<MessageKey_defaultSet | MessageKey_themeDefined>;
|
||||||
|
|
||||||
type Result = { i18n: I18n; prI18n_currentLanguage: Promise<I18n> | undefined };
|
type Result = { i18n: I18n; prI18n_currentLanguage: Promise<I18n> | undefined };
|
||||||
|
|
||||||
@ -108,7 +104,7 @@ export function createGetI18n<ExtraMessageKey extends string = never>(messageBun
|
|||||||
}
|
}
|
||||||
|
|
||||||
const partialI18n: Pick<I18n, "currentLanguageTag" | "getChangeLocaleUrl" | "labelBySupportedLanguageTag"> = {
|
const partialI18n: Pick<I18n, "currentLanguageTag" | "getChangeLocaleUrl" | "labelBySupportedLanguageTag"> = {
|
||||||
currentLanguageTag: kcContext.locale?.currentLanguageTag ?? fallbackLanguageTag,
|
currentLanguageTag: kcContext.locale?.currentLanguageTag ?? FALLBACK_LANGUAGE_TAG,
|
||||||
getChangeLocaleUrl: newLanguageTag => {
|
getChangeLocaleUrl: newLanguageTag => {
|
||||||
const { locale } = kcContext;
|
const { locale } = kcContext;
|
||||||
|
|
||||||
@ -123,30 +119,38 @@ export function createGetI18n<ExtraMessageKey extends string = never>(messageBun
|
|||||||
labelBySupportedLanguageTag: Object.fromEntries((kcContext.locale?.supported ?? []).map(({ languageTag, label }) => [languageTag, label]))
|
labelBySupportedLanguageTag: Object.fromEntries((kcContext.locale?.supported ?? []).map(({ languageTag, label }) => [languageTag, label]))
|
||||||
};
|
};
|
||||||
|
|
||||||
const { createI18nTranslationFunctions } = createI18nTranslationFunctionsFactory<MessageKey, ExtraMessageKey>({
|
const { createI18nTranslationFunctions } = createI18nTranslationFunctionsFactory<MessageKey_themeDefined>({
|
||||||
messages_fallbackLanguage,
|
messages_themeDefined:
|
||||||
messageBundle_fallbackLanguage: messageBundle[fallbackLanguageTag],
|
messagesByLanguageTag_themeDefined[partialI18n.currentLanguageTag] ??
|
||||||
messageBundle_currentLanguage: messageBundle[partialI18n.currentLanguageTag]
|
messagesByLanguageTag_themeDefined[FALLBACK_LANGUAGE_TAG] ??
|
||||||
|
(() => {
|
||||||
|
const firstLanguageTag = Object.keys(messagesByLanguageTag_themeDefined)[0];
|
||||||
|
if (firstLanguageTag === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return messagesByLanguageTag_themeDefined[firstLanguageTag];
|
||||||
|
})(),
|
||||||
|
messages_fromKcServer: kcContext["x-keycloakify"].messages
|
||||||
});
|
});
|
||||||
|
|
||||||
const isCurrentLanguageFallbackLanguage = partialI18n.currentLanguageTag === fallbackLanguageTag;
|
const isCurrentLanguageFallbackLanguage = partialI18n.currentLanguageTag === FALLBACK_LANGUAGE_TAG;
|
||||||
|
|
||||||
const result: Result = {
|
const result: Result = {
|
||||||
i18n: {
|
i18n: {
|
||||||
...partialI18n,
|
...partialI18n,
|
||||||
...createI18nTranslationFunctions({
|
...createI18nTranslationFunctions({
|
||||||
messages_currentLanguage: isCurrentLanguageFallbackLanguage ? messages_fallbackLanguage : undefined
|
messages_defaultSet_currentLanguage: isCurrentLanguageFallbackLanguage ? messages_defaultSet_fallbackLanguage : undefined
|
||||||
}),
|
}),
|
||||||
isFetchingTranslations: !isCurrentLanguageFallbackLanguage
|
isFetchingTranslations: !isCurrentLanguageFallbackLanguage
|
||||||
},
|
},
|
||||||
prI18n_currentLanguage: isCurrentLanguageFallbackLanguage
|
prI18n_currentLanguage: isCurrentLanguageFallbackLanguage
|
||||||
? undefined
|
? undefined
|
||||||
: (async () => {
|
: (async () => {
|
||||||
const messages_currentLanguage = await getMessages(partialI18n.currentLanguageTag);
|
const messages_defaultSet_currentLanguage = await fetchMessages_defaultSet(partialI18n.currentLanguageTag);
|
||||||
|
|
||||||
const i18n_currentLanguage: I18n = {
|
const i18n_currentLanguage: I18n = {
|
||||||
...partialI18n,
|
...partialI18n,
|
||||||
...createI18nTranslationFunctions({ messages_currentLanguage }),
|
...createI18nTranslationFunctions({ messages_defaultSet_currentLanguage }),
|
||||||
isFetchingTranslations: false
|
isFetchingTranslations: false
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -169,118 +173,76 @@ export function createGetI18n<ExtraMessageKey extends string = never>(messageBun
|
|||||||
return { getI18n };
|
return { getI18n };
|
||||||
}
|
}
|
||||||
|
|
||||||
function createI18nTranslationFunctionsFactory<MessageKey extends string, ExtraMessageKey extends string>(params: {
|
function createI18nTranslationFunctionsFactory<MessageKey_themeDefined extends string>(params: {
|
||||||
messages_fallbackLanguage: Record<MessageKey, string>;
|
messages_themeDefined: Record<MessageKey_themeDefined, string> | undefined;
|
||||||
messageBundle_fallbackLanguage: Record<ExtraMessageKey, string> | undefined;
|
messages_fromKcServer: Record<string, string>;
|
||||||
messageBundle_currentLanguage: Partial<Record<ExtraMessageKey, string>> | undefined;
|
|
||||||
}) {
|
}) {
|
||||||
const { messageBundle_currentLanguage } = params;
|
const { messages_themeDefined, messages_fromKcServer } = params;
|
||||||
|
|
||||||
const messages_fallbackLanguage = {
|
|
||||||
...params.messages_fallbackLanguage,
|
|
||||||
...params.messageBundle_fallbackLanguage
|
|
||||||
};
|
|
||||||
|
|
||||||
function createI18nTranslationFunctions(params: {
|
function createI18nTranslationFunctions(params: {
|
||||||
messages_currentLanguage: Partial<Record<MessageKey, string>> | undefined;
|
messages_defaultSet_currentLanguage: Partial<Record<MessageKey_defaultSet, string>> | undefined;
|
||||||
}): Pick<GenericI18n<MessageKey | ExtraMessageKey>, "msg" | "msgStr" | "advancedMsg" | "advancedMsgStr"> {
|
}): Pick<GenericI18n_noJsx<MessageKey_defaultSet | MessageKey_themeDefined>, "msgStr" | "advancedMsgStr"> {
|
||||||
const messages_currentLanguage = {
|
const { messages_defaultSet_currentLanguage } = params;
|
||||||
...params.messages_currentLanguage,
|
|
||||||
...messageBundle_currentLanguage
|
|
||||||
};
|
|
||||||
|
|
||||||
function resolveMsg(props: { key: string; args: (string | undefined)[]; doRenderAsHtml: boolean }): string | JSX.Element | undefined {
|
function resolveMsg(props: { key: string; args: (string | undefined)[] }): string | undefined {
|
||||||
const { key, args, doRenderAsHtml } = props;
|
const { key, args } = props;
|
||||||
|
|
||||||
const messageOrUndefined: string | undefined = (messages_currentLanguage as any)[key] ?? (messages_fallbackLanguage as any)[key];
|
const message =
|
||||||
|
id<Record<string, string | undefined>>(messages_fromKcServer)[key] ??
|
||||||
|
id<Record<string, string | undefined> | undefined>(messages_themeDefined)?.[key] ??
|
||||||
|
id<Record<string, string | undefined> | undefined>(messages_defaultSet_currentLanguage)?.[key] ??
|
||||||
|
id<Record<string, string | undefined>>(messages_defaultSet_fallbackLanguage)[key];
|
||||||
|
|
||||||
if (messageOrUndefined === undefined) {
|
if (message === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = messageOrUndefined;
|
const startIndex = message
|
||||||
|
.match(/{[0-9]+}/g)
|
||||||
|
?.map(g => g.match(/{([0-9]+)}/)![1])
|
||||||
|
.map(indexStr => parseInt(indexStr))
|
||||||
|
.sort((a, b) => a - b)[0];
|
||||||
|
|
||||||
const messageWithArgsInjectedIfAny = (() => {
|
if (startIndex === undefined) {
|
||||||
const startIndex = message
|
// No {0} in message (no arguments expected)
|
||||||
.match(/{[0-9]+}/g)
|
return message;
|
||||||
?.map(g => g.match(/{([0-9]+)}/)![1])
|
|
||||||
.map(indexStr => parseInt(indexStr))
|
|
||||||
.sort((a, b) => a - b)[0];
|
|
||||||
|
|
||||||
if (startIndex === undefined) {
|
|
||||||
// No {0} in message (no arguments expected)
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
let messageWithArgsInjected = message;
|
|
||||||
|
|
||||||
args.forEach((arg, i) => {
|
|
||||||
if (arg === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
messageWithArgsInjected = messageWithArgsInjected.replace(
|
|
||||||
new RegExp(`\\{${i + startIndex}\\}`, "g"),
|
|
||||||
arg.replace(/</g, "<").replace(/>/g, ">")
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
return messageWithArgsInjected;
|
|
||||||
})();
|
|
||||||
|
|
||||||
return doRenderAsHtml ? (
|
|
||||||
<span
|
|
||||||
// NOTE: The message is trusted. The arguments are not but are escaped.
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: messageWithArgsInjectedIfAny
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
messageWithArgsInjectedIfAny
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveMsgAdvanced(props: { key: string; args: (string | undefined)[]; doRenderAsHtml: boolean }): JSX.Element | string {
|
|
||||||
const { key, args, doRenderAsHtml } = props;
|
|
||||||
|
|
||||||
if (!/\$\{[^}]+\}/.test(key)) {
|
|
||||||
const resolvedMessage = resolveMsg({ key, args, doRenderAsHtml });
|
|
||||||
|
|
||||||
if (resolvedMessage === undefined) {
|
|
||||||
return doRenderAsHtml ? <span dangerouslySetInnerHTML={{ __html: key }} /> : key;
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolvedMessage;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let isFirstMatch = true;
|
let messageWithArgsInjected = message;
|
||||||
|
|
||||||
const resolvedComplexMessage = key.replace(/\$\{([^}]+)\}/g, (...[, key_i]) => {
|
args.forEach((arg, i) => {
|
||||||
const replaceBy = resolveMsg({ key: key_i, args: isFirstMatch ? args : [], doRenderAsHtml: false }) ?? key_i;
|
if (arg === undefined) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
isFirstMatch = false;
|
messageWithArgsInjected = messageWithArgsInjected.replace(
|
||||||
|
new RegExp(`\\{${i + startIndex}\\}`, "g"),
|
||||||
return replaceBy;
|
arg.replace(/</g, "<").replace(/>/g, ">")
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
return doRenderAsHtml ? <span dangerouslySetInnerHTML={{ __html: resolvedComplexMessage }} /> : resolvedComplexMessage;
|
return messageWithArgsInjected;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveMsgAdvanced(props: { key: string; args: (string | undefined)[] }): string {
|
||||||
|
const { key, args } = props;
|
||||||
|
|
||||||
|
const match = key.match(/^\$\{(.+)\}$/);
|
||||||
|
|
||||||
|
if (match === null) {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolveMsg({ key: match[1], args }) ?? key;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
msgStr: (key, ...args) => resolveMsg({ key, args, doRenderAsHtml: false }) as string,
|
msgStr: (key, ...args) => {
|
||||||
msg: (key, ...args) => resolveMsg({ key, args, doRenderAsHtml: true }) as JSX.Element,
|
const resolvedMessage = resolveMsg({ key, args });
|
||||||
advancedMsg: (key, ...args) =>
|
assert(resolvedMessage !== undefined, `Message with key "${key}" not found`);
|
||||||
resolveMsgAdvanced({
|
return resolvedMessage;
|
||||||
key,
|
},
|
||||||
args,
|
advancedMsgStr: (key, ...args) => resolveMsgAdvanced({ key, args })
|
||||||
doRenderAsHtml: true
|
|
||||||
}) as JSX.Element,
|
|
||||||
advancedMsgStr: (key, ...args) =>
|
|
||||||
resolveMsgAdvanced({
|
|
||||||
key,
|
|
||||||
args,
|
|
||||||
doRenderAsHtml: false
|
|
||||||
}) as string
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import type { GenericI18n, MessageKey, KcContextLike } from "./i18n";
|
import type { GenericI18n } from "./GenericI18n";
|
||||||
export type { MessageKey, KcContextLike };
|
import type { MessageKey_defaultSet, KcContextLike } from "./i18n";
|
||||||
export type I18n = GenericI18n<MessageKey>;
|
export type { MessageKey_defaultSet, KcContextLike };
|
||||||
|
export type I18n = GenericI18n<MessageKey_defaultSet>;
|
||||||
export { createUseI18n } from "./useI18n";
|
export { createUseI18n } from "./useI18n";
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
import {
|
|
||||||
createGetI18n,
|
|
||||||
type GenericI18n,
|
|
||||||
type MessageKey,
|
|
||||||
type KcContextLike
|
|
||||||
} from "./i18n";
|
|
||||||
import { Reflect } from "tsafe/Reflect";
|
|
||||||
|
|
||||||
export function createUseI18n<ExtraMessageKey extends string = never>(messageBundle: {
|
|
||||||
[languageTag: string]: { [key in ExtraMessageKey]: string };
|
|
||||||
}) {
|
|
||||||
type I18n = GenericI18n<MessageKey | ExtraMessageKey>;
|
|
||||||
|
|
||||||
const { getI18n } = createGetI18n(messageBundle);
|
|
||||||
|
|
||||||
function useI18n(params: { kcContext: KcContextLike }): { i18n: I18n } {
|
|
||||||
const { kcContext } = params;
|
|
||||||
|
|
||||||
const { i18n, prI18n_currentLanguage } = getI18n({ kcContext });
|
|
||||||
|
|
||||||
const [i18n_toReturn, setI18n_toReturn] = useState<I18n>(i18n);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let isActive = true;
|
|
||||||
|
|
||||||
prI18n_currentLanguage?.then(i18n => {
|
|
||||||
if (!isActive) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setI18n_toReturn(i18n);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
isActive = false;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return { i18n: i18n_toReturn };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { useI18n, ofTypeI18n: Reflect<I18n>() };
|
|
||||||
}
|
|
95
src/account/i18n/useI18n.tsx
Normal file
95
src/account/i18n/useI18n.tsx
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { createGetI18n, type GenericI18n_noJsx, type KcContextLike, type MessageKey_defaultSet } from "./i18n";
|
||||||
|
import { GenericI18n } from "./GenericI18n";
|
||||||
|
import { Reflect } from "tsafe/Reflect";
|
||||||
|
|
||||||
|
export function createUseI18n<MessageKey_themeDefined extends string = never>(messagesByLanguageTag: {
|
||||||
|
[languageTag: string]: { [key in MessageKey_themeDefined]: string };
|
||||||
|
}) {
|
||||||
|
type MessageKey = MessageKey_defaultSet | MessageKey_themeDefined;
|
||||||
|
|
||||||
|
type I18n = GenericI18n<MessageKey>;
|
||||||
|
|
||||||
|
const { withJsx } = (() => {
|
||||||
|
const cache = new WeakMap<GenericI18n_noJsx<MessageKey>, GenericI18n<MessageKey>>();
|
||||||
|
|
||||||
|
function renderHtmlString(params: { htmlString: string; msgKey: string }): JSX.Element {
|
||||||
|
const { htmlString, msgKey } = params;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-kc-msg={msgKey}
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: htmlString
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withJsx(i18n_noJsx: GenericI18n_noJsx<MessageKey>): I18n {
|
||||||
|
use_cache: {
|
||||||
|
const i18n = cache.get(i18n_noJsx);
|
||||||
|
|
||||||
|
if (i18n === undefined) {
|
||||||
|
break use_cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
const i18n: I18n = {
|
||||||
|
...i18n_noJsx,
|
||||||
|
msg: (msgKey, ...args) => renderHtmlString({ htmlString: i18n_noJsx.msgStr(msgKey, ...args), msgKey }),
|
||||||
|
advancedMsg: (msgKey, ...args) => renderHtmlString({ htmlString: i18n_noJsx.advancedMsgStr(msgKey, ...args), msgKey })
|
||||||
|
};
|
||||||
|
|
||||||
|
cache.set(i18n_noJsx, i18n);
|
||||||
|
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { withJsx };
|
||||||
|
})();
|
||||||
|
|
||||||
|
add_style: {
|
||||||
|
const attributeName = "data-kc-i18n";
|
||||||
|
|
||||||
|
// Check if already exists in head
|
||||||
|
if (document.querySelector(`style[${attributeName}]`) !== null) {
|
||||||
|
break add_style;
|
||||||
|
}
|
||||||
|
|
||||||
|
const styleElement = document.createElement("style");
|
||||||
|
styleElement.attributes.setNamedItem(document.createAttribute(attributeName));
|
||||||
|
(styleElement.textContent = `[data-kc-msg] { display: inline-block; }`), document.head.prepend(styleElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { getI18n } = createGetI18n(messagesByLanguageTag);
|
||||||
|
|
||||||
|
function useI18n(params: { kcContext: KcContextLike }): { i18n: I18n } {
|
||||||
|
const { kcContext } = params;
|
||||||
|
|
||||||
|
const { i18n, prI18n_currentLanguage } = getI18n({ kcContext });
|
||||||
|
|
||||||
|
const [i18n_toReturn, setI18n_toReturn] = useState<I18n>(withJsx(i18n));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let isActive = true;
|
||||||
|
|
||||||
|
prI18n_currentLanguage?.then(i18n => {
|
||||||
|
if (!isActive) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setI18n_toReturn(withJsx(i18n));
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isActive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { i18n: i18n_toReturn };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { useI18n, ofTypeI18n: Reflect<I18n>() };
|
||||||
|
}
|
@ -8,7 +8,7 @@ export default function FederatedIdentity(props: PageProps<Extract<KcContext, {
|
|||||||
const { url, federatedIdentity, stateChecker } = kcContext;
|
const { url, federatedIdentity, stateChecker } = kcContext;
|
||||||
const { msg } = i18n;
|
const { msg } = i18n;
|
||||||
return (
|
return (
|
||||||
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="federatedIdentity">
|
<Template {...{ kcContext, i18n, doUseDefaultCss, classes }} active="social">
|
||||||
<div className="main-layout social">
|
<div className="main-layout social">
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<div className="col-md-10">
|
<div className="col-md-10">
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
||||||
import cliSelect from "cli-select";
|
import cliSelect from "cli-select";
|
||||||
import {
|
import {
|
||||||
loginThemePageIds,
|
LOGIN_THEME_PAGE_IDS,
|
||||||
accountThemePageIds,
|
ACCOUNT_THEME_PAGE_IDS,
|
||||||
type LoginThemePageId,
|
type LoginThemePageId,
|
||||||
type AccountThemePageId,
|
type AccountThemePageId,
|
||||||
themeTypes,
|
THEME_TYPES,
|
||||||
type ThemeType
|
type ThemeType
|
||||||
} from "./shared/constants";
|
} from "./shared/constants";
|
||||||
import { capitalize } from "tsafe/capitalize";
|
import { capitalize } from "tsafe/capitalize";
|
||||||
@ -26,11 +26,43 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
|
|
||||||
console.log(chalk.cyan("Theme type:"));
|
console.log(chalk.cyan("Theme type:"));
|
||||||
|
|
||||||
const { value: themeType } = await cliSelect<ThemeType>({
|
const themeType = await (async () => {
|
||||||
values: [...themeTypes]
|
const values = THEME_TYPES.filter(themeType => {
|
||||||
}).catch(() => {
|
switch (themeType) {
|
||||||
process.exit(-1);
|
case "account":
|
||||||
});
|
return buildContext.implementedThemeTypes.account.isImplemented;
|
||||||
|
case "login":
|
||||||
|
return buildContext.implementedThemeTypes.login.isImplemented;
|
||||||
|
}
|
||||||
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
assert(values.length > 0, "No theme is implemented in this project");
|
||||||
|
|
||||||
|
if (values.length === 1) {
|
||||||
|
return values[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { value } = await cliSelect<ThemeType>({
|
||||||
|
values
|
||||||
|
}).catch(() => {
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
|
||||||
|
return value;
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (
|
||||||
|
themeType === "account" &&
|
||||||
|
(assert(buildContext.implementedThemeTypes.account.isImplemented),
|
||||||
|
buildContext.implementedThemeTypes.account.type === "Single-Page")
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`${chalk.red("✗")} Sorry, there is no Storybook support for Single-Page Account themes.`
|
||||||
|
);
|
||||||
|
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`→ ${themeType}`);
|
console.log(`→ ${themeType}`);
|
||||||
|
|
||||||
@ -40,9 +72,9 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
values: (() => {
|
values: (() => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "login":
|
case "login":
|
||||||
return [...loginThemePageIds];
|
return [...LOGIN_THEME_PAGE_IDS];
|
||||||
case "account":
|
case "account":
|
||||||
return [...accountThemePageIds];
|
return [...ACCOUNT_THEME_PAGE_IDS];
|
||||||
}
|
}
|
||||||
assert<Equals<typeof themeType, never>>(false);
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
})()
|
})()
|
||||||
|
@ -3,16 +3,21 @@
|
|||||||
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "./tools/getThisCodebaseRootDirPath";
|
||||||
import cliSelect from "cli-select";
|
import cliSelect from "cli-select";
|
||||||
import {
|
import {
|
||||||
loginThemePageIds,
|
LOGIN_THEME_PAGE_IDS,
|
||||||
accountThemePageIds,
|
ACCOUNT_THEME_PAGE_IDS,
|
||||||
type LoginThemePageId,
|
type LoginThemePageId,
|
||||||
type AccountThemePageId,
|
type AccountThemePageId,
|
||||||
themeTypes,
|
THEME_TYPES,
|
||||||
type ThemeType
|
type ThemeType
|
||||||
} from "./shared/constants";
|
} from "./shared/constants";
|
||||||
import { capitalize } from "tsafe/capitalize";
|
import { capitalize } from "tsafe/capitalize";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { join as pathJoin, relative as pathRelative, dirname as pathDirname } from "path";
|
import {
|
||||||
|
join as pathJoin,
|
||||||
|
relative as pathRelative,
|
||||||
|
dirname as pathDirname,
|
||||||
|
basename as pathBasename
|
||||||
|
} from "path";
|
||||||
import { kebabCaseToCamelCase } from "./tools/kebabCaseToSnakeCase";
|
import { kebabCaseToCamelCase } from "./tools/kebabCaseToSnakeCase";
|
||||||
import { assert, Equals } from "tsafe/assert";
|
import { assert, Equals } from "tsafe/assert";
|
||||||
import type { CliCommandOptions } from "./main";
|
import type { CliCommandOptions } from "./main";
|
||||||
@ -28,11 +33,114 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
|
|
||||||
console.log(chalk.cyan("Theme type:"));
|
console.log(chalk.cyan("Theme type:"));
|
||||||
|
|
||||||
const { value: themeType } = await cliSelect<ThemeType>({
|
const themeType = await (async () => {
|
||||||
values: [...themeTypes]
|
const values = THEME_TYPES.filter(themeType => {
|
||||||
}).catch(() => {
|
switch (themeType) {
|
||||||
process.exit(-1);
|
case "account":
|
||||||
});
|
return buildContext.implementedThemeTypes.account.isImplemented;
|
||||||
|
case "login":
|
||||||
|
return buildContext.implementedThemeTypes.login.isImplemented;
|
||||||
|
}
|
||||||
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
assert(values.length > 0, "No theme is implemented in this project");
|
||||||
|
|
||||||
|
if (values.length === 1) {
|
||||||
|
return values[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { value } = await cliSelect<ThemeType>({
|
||||||
|
values
|
||||||
|
}).catch(() => {
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
|
||||||
|
return value;
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (
|
||||||
|
themeType === "account" &&
|
||||||
|
(assert(buildContext.implementedThemeTypes.account.isImplemented),
|
||||||
|
buildContext.implementedThemeTypes.account.type === "Single-Page")
|
||||||
|
) {
|
||||||
|
const srcDirPath = pathJoin(
|
||||||
|
pathDirname(buildContext.packageJsonFilePath),
|
||||||
|
"node_modules",
|
||||||
|
"@keycloakify",
|
||||||
|
"keycloak-account-ui",
|
||||||
|
"src"
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
`There isn't an interactive CLI to eject components of the Single-Page Account theme.`,
|
||||||
|
`You can however copy paste into your codebase the any file or directory from the following source directory:`,
|
||||||
|
``,
|
||||||
|
`${chalk.bold(pathJoin(pathRelative(process.cwd(), srcDirPath)))}`,
|
||||||
|
``
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
eject_entrypoint: {
|
||||||
|
const kcAccountUiTsxFileRelativePath = "KcAccountUi.tsx";
|
||||||
|
|
||||||
|
const accountThemeSrcDirPath = pathJoin(
|
||||||
|
buildContext.themeSrcDirPath,
|
||||||
|
"account"
|
||||||
|
);
|
||||||
|
|
||||||
|
const targetFilePath = pathJoin(
|
||||||
|
accountThemeSrcDirPath,
|
||||||
|
kcAccountUiTsxFileRelativePath
|
||||||
|
);
|
||||||
|
|
||||||
|
if (fs.existsSync(targetFilePath)) {
|
||||||
|
break eject_entrypoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.cpSync(
|
||||||
|
pathJoin(srcDirPath, kcAccountUiTsxFileRelativePath),
|
||||||
|
targetFilePath
|
||||||
|
);
|
||||||
|
|
||||||
|
{
|
||||||
|
const kcPageTsxFilePath = pathJoin(accountThemeSrcDirPath, "KcPage.tsx");
|
||||||
|
|
||||||
|
const kcPageTsxCode = fs.readFileSync(kcPageTsxFilePath).toString("utf8");
|
||||||
|
|
||||||
|
const componentName = pathBasename(
|
||||||
|
kcAccountUiTsxFileRelativePath
|
||||||
|
).replace(/.tsx$/, "");
|
||||||
|
|
||||||
|
const modifiedKcPageTsxCode = kcPageTsxCode.replace(
|
||||||
|
`@keycloakify/keycloak-account-ui/${componentName}`,
|
||||||
|
`./${componentName}`
|
||||||
|
);
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
kcPageTsxFilePath,
|
||||||
|
Buffer.from(modifiedKcPageTsxCode, "utf8")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const routesTsxFilePath = pathRelative(
|
||||||
|
process.cwd(),
|
||||||
|
pathJoin(srcDirPath, "routes.tsx")
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
`To help you get started ${chalk.bold(pathRelative(process.cwd(), targetFilePath))} has been copied into your project.`,
|
||||||
|
`The next step is usually to eject ${chalk.bold(routesTsxFilePath)}`,
|
||||||
|
`with \`cp ${routesTsxFilePath} ${pathRelative(process.cwd(), accountThemeSrcDirPath)}\``,
|
||||||
|
`then update the import of routes in ${kcAccountUiTsxFileRelativePath}.`
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`→ ${themeType}`);
|
console.log(`→ ${themeType}`);
|
||||||
|
|
||||||
@ -54,10 +162,10 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
return [
|
return [
|
||||||
templateValue,
|
templateValue,
|
||||||
userProfileFormFieldsValue,
|
userProfileFormFieldsValue,
|
||||||
...loginThemePageIds
|
...LOGIN_THEME_PAGE_IDS
|
||||||
];
|
];
|
||||||
case "account":
|
case "account":
|
||||||
return [templateValue, ...accountThemePageIds];
|
return [templateValue, ...ACCOUNT_THEME_PAGE_IDS];
|
||||||
}
|
}
|
||||||
assert<Equals<typeof themeType, never>>(false);
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
})()
|
})()
|
||||||
|
32
src/bin/initialize-account-theme/copyBoilerplate.ts
Normal file
32
src/bin/initialize-account-theme/copyBoilerplate.ts
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import * as fs from "fs";
|
||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import { getThisCodebaseRootDirPath } from "../tools/getThisCodebaseRootDirPath";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
|
||||||
|
export function copyBoilerplate(params: {
|
||||||
|
accountThemeType: "Single-Page" | "Multi-Page";
|
||||||
|
accountThemeSrcDirPath: string;
|
||||||
|
}) {
|
||||||
|
const { accountThemeType, accountThemeSrcDirPath } = params;
|
||||||
|
|
||||||
|
fs.cpSync(
|
||||||
|
pathJoin(
|
||||||
|
getThisCodebaseRootDirPath(),
|
||||||
|
"src",
|
||||||
|
"bin",
|
||||||
|
"initialize-account-theme",
|
||||||
|
"src",
|
||||||
|
(() => {
|
||||||
|
switch (accountThemeType) {
|
||||||
|
case "Single-Page":
|
||||||
|
return "single-page";
|
||||||
|
case "Multi-Page":
|
||||||
|
return "multi-page";
|
||||||
|
}
|
||||||
|
assert<Equals<typeof accountThemeType, never>>(false);
|
||||||
|
})()
|
||||||
|
),
|
||||||
|
accountThemeSrcDirPath,
|
||||||
|
{ recursive: true }
|
||||||
|
);
|
||||||
|
}
|
1
src/bin/initialize-account-theme/index.ts
Normal file
1
src/bin/initialize-account-theme/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from "./initialize-account-theme";
|
112
src/bin/initialize-account-theme/initialize-account-theme.ts
Normal file
112
src/bin/initialize-account-theme/initialize-account-theme.ts
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
import { getBuildContext } from "../shared/buildContext";
|
||||||
|
import type { CliCommandOptions } from "../main";
|
||||||
|
import cliSelect from "cli-select";
|
||||||
|
import child_process from "child_process";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { updateAccountThemeImplementationInConfig } from "./updateAccountThemeImplementationInConfig";
|
||||||
|
import { generateKcGenTs } from "../shared/generateKcGenTs";
|
||||||
|
|
||||||
|
export async function command(params: { cliCommandOptions: CliCommandOptions }) {
|
||||||
|
const { cliCommandOptions } = params;
|
||||||
|
|
||||||
|
const buildContext = getBuildContext({ cliCommandOptions });
|
||||||
|
|
||||||
|
const accountThemeSrcDirPath = pathJoin(buildContext.themeSrcDirPath, "account");
|
||||||
|
|
||||||
|
if (
|
||||||
|
fs.existsSync(accountThemeSrcDirPath) &&
|
||||||
|
fs.readdirSync(accountThemeSrcDirPath).length > 0
|
||||||
|
) {
|
||||||
|
console.warn(
|
||||||
|
chalk.red(
|
||||||
|
`There is already a ${pathRelative(
|
||||||
|
process.cwd(),
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
)} directory in your project. Aborting.`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
exit_if_uncommitted_changes: {
|
||||||
|
let hasUncommittedChanges: boolean | undefined = undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
hasUncommittedChanges =
|
||||||
|
child_process
|
||||||
|
.execSync(`git status --porcelain`, {
|
||||||
|
cwd: buildContext.projectDirPath
|
||||||
|
})
|
||||||
|
.toString()
|
||||||
|
.trim() !== "";
|
||||||
|
} catch {
|
||||||
|
// Probably not a git repository
|
||||||
|
break exit_if_uncommitted_changes;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasUncommittedChanges) {
|
||||||
|
break exit_if_uncommitted_changes;
|
||||||
|
}
|
||||||
|
console.warn(
|
||||||
|
[
|
||||||
|
chalk.red(
|
||||||
|
"Please commit or stash your changes before running this command.\n"
|
||||||
|
),
|
||||||
|
"This command will modify your project's files so it's better to have a clean working directory",
|
||||||
|
"so that you can easily see what has been changed and revert if needed."
|
||||||
|
].join(" ")
|
||||||
|
);
|
||||||
|
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { value: accountThemeType } = await cliSelect({
|
||||||
|
values: ["Single-Page" as const, "Multi-Page" as const]
|
||||||
|
}).catch(() => {
|
||||||
|
process.exit(-1);
|
||||||
|
});
|
||||||
|
|
||||||
|
switch (accountThemeType) {
|
||||||
|
case "Multi-Page":
|
||||||
|
{
|
||||||
|
const { initializeAccountTheme_multiPage } = await import(
|
||||||
|
"./initializeAccountTheme_multiPage"
|
||||||
|
);
|
||||||
|
|
||||||
|
await initializeAccountTheme_multiPage({
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "Single-Page":
|
||||||
|
{
|
||||||
|
const { initializeAccountTheme_singlePage } = await import(
|
||||||
|
"./initializeAccountTheme_singlePage"
|
||||||
|
);
|
||||||
|
|
||||||
|
await initializeAccountTheme_singlePage({
|
||||||
|
accountThemeSrcDirPath,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateAccountThemeImplementationInConfig({ buildContext, accountThemeType });
|
||||||
|
|
||||||
|
await generateKcGenTs({
|
||||||
|
buildContext: {
|
||||||
|
...buildContext,
|
||||||
|
implementedThemeTypes: {
|
||||||
|
...buildContext.implementedThemeTypes,
|
||||||
|
account: {
|
||||||
|
isImplemented: true,
|
||||||
|
type: accountThemeType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
import { relative as pathRelative } from "path";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { copyBoilerplate } from "./copyBoilerplate";
|
||||||
|
|
||||||
|
export async function initializeAccountTheme_multiPage(params: {
|
||||||
|
accountThemeSrcDirPath: string;
|
||||||
|
}) {
|
||||||
|
const { accountThemeSrcDirPath } = params;
|
||||||
|
|
||||||
|
copyBoilerplate({
|
||||||
|
accountThemeType: "Multi-Page",
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
chalk.green("The Multi-Page account theme has been initialized."),
|
||||||
|
`Directory created: ${chalk.bold(pathRelative(process.cwd(), accountThemeSrcDirPath))}`
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
}
|
@ -0,0 +1,152 @@
|
|||||||
|
import { join as pathJoin, relative as pathRelative, dirname as pathDirname } from "path";
|
||||||
|
import type { BuildContext } from "../shared/buildContext";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import {
|
||||||
|
getLatestsSemVersionedTag,
|
||||||
|
type BuildContextLike as BuildContextLike_getLatestsSemVersionedTag
|
||||||
|
} from "../shared/getLatestsSemVersionedTag";
|
||||||
|
import fetch from "make-fetch-happen";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import { is } from "tsafe/is";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
import { npmInstall } from "../tools/npmInstall";
|
||||||
|
import { copyBoilerplate } from "./copyBoilerplate";
|
||||||
|
import { getThisCodebaseRootDirPath } from "../tools/getThisCodebaseRootDirPath";
|
||||||
|
|
||||||
|
type BuildContextLike = BuildContextLike_getLatestsSemVersionedTag & {
|
||||||
|
fetchOptions: BuildContext["fetchOptions"];
|
||||||
|
packageJsonFilePath: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export async function initializeAccountTheme_singlePage(params: {
|
||||||
|
accountThemeSrcDirPath: string;
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}) {
|
||||||
|
const { accountThemeSrcDirPath, buildContext } = params;
|
||||||
|
|
||||||
|
const OWNER = "keycloakify";
|
||||||
|
const REPO = "keycloak-account-ui";
|
||||||
|
|
||||||
|
const [semVersionedTag] = await getLatestsSemVersionedTag({
|
||||||
|
owner: OWNER,
|
||||||
|
repo: REPO,
|
||||||
|
count: 1,
|
||||||
|
doIgnoreReleaseCandidates: false,
|
||||||
|
buildContext
|
||||||
|
});
|
||||||
|
|
||||||
|
const dependencies = await fetch(
|
||||||
|
`https://raw.githubusercontent.com/${OWNER}/${REPO}/${semVersionedTag.tag}/dependencies.gen.json`,
|
||||||
|
buildContext.fetchOptions
|
||||||
|
)
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(
|
||||||
|
(() => {
|
||||||
|
type Dependencies = {
|
||||||
|
dependencies: Record<string, string>;
|
||||||
|
devDependencies?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zDependencies = (() => {
|
||||||
|
type TargetType = Dependencies;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
dependencies: z.record(z.string()),
|
||||||
|
devDependencies: z.record(z.string()).optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
return o => zDependencies.parse(o);
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
|
||||||
|
dependencies.dependencies["@keycloakify/keycloak-account-ui"] = semVersionedTag.tag;
|
||||||
|
|
||||||
|
const parsedPackageJson = (() => {
|
||||||
|
type ParsedPackageJson = {
|
||||||
|
dependencies?: Record<string, string>;
|
||||||
|
devDependencies?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zParsedPackageJson = (() => {
|
||||||
|
type TargetType = ParsedPackageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
dependencies: z.record(z.string()).optional(),
|
||||||
|
devDependencies: z.record(z.string()).optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
const parsedPackageJson = JSON.parse(
|
||||||
|
fs.readFileSync(buildContext.packageJsonFilePath).toString("utf8")
|
||||||
|
);
|
||||||
|
|
||||||
|
zParsedPackageJson.parse(parsedPackageJson);
|
||||||
|
|
||||||
|
assert(is<ParsedPackageJson>(parsedPackageJson));
|
||||||
|
|
||||||
|
return parsedPackageJson;
|
||||||
|
})();
|
||||||
|
|
||||||
|
parsedPackageJson.dependencies = {
|
||||||
|
...parsedPackageJson.dependencies,
|
||||||
|
...dependencies.dependencies
|
||||||
|
};
|
||||||
|
|
||||||
|
parsedPackageJson.devDependencies = {
|
||||||
|
...parsedPackageJson.devDependencies,
|
||||||
|
...dependencies.devDependencies
|
||||||
|
};
|
||||||
|
|
||||||
|
if (Object.keys(parsedPackageJson.devDependencies).length === 0) {
|
||||||
|
delete parsedPackageJson.devDependencies;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
buildContext.packageJsonFilePath,
|
||||||
|
JSON.stringify(parsedPackageJson, undefined, 4)
|
||||||
|
);
|
||||||
|
|
||||||
|
run_npm_install: {
|
||||||
|
if (
|
||||||
|
JSON.parse(
|
||||||
|
fs
|
||||||
|
.readFileSync(pathJoin(getThisCodebaseRootDirPath(), "package.json"))
|
||||||
|
.toString("utf8")
|
||||||
|
)["version"] === "0.0.0"
|
||||||
|
) {
|
||||||
|
//NOTE: Linked version
|
||||||
|
break run_npm_install;
|
||||||
|
}
|
||||||
|
|
||||||
|
npmInstall({ packageJsonDirPath: pathDirname(buildContext.packageJsonFilePath) });
|
||||||
|
}
|
||||||
|
|
||||||
|
copyBoilerplate({
|
||||||
|
accountThemeType: "Single-Page",
|
||||||
|
accountThemeSrcDirPath
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
[
|
||||||
|
chalk.green(
|
||||||
|
"The Single-Page account theme has been successfully initialized."
|
||||||
|
),
|
||||||
|
`Using Account UI of Keycloak version: ${chalk.bold(semVersionedTag.tag.split("-")[0])}`,
|
||||||
|
`Directory created: ${chalk.bold(pathRelative(process.cwd(), accountThemeSrcDirPath))}`,
|
||||||
|
`Dependencies added to your project's package.json: `,
|
||||||
|
chalk.bold(JSON.stringify(dependencies, null, 2))
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
}
|
12
src/bin/initialize-account-theme/src/multi-page/KcContext.ts
Normal file
12
src/bin/initialize-account-theme/src/multi-page/KcContext.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/ban-types */
|
||||||
|
import type { ExtendKcContext } from "keycloakify/account";
|
||||||
|
import type { KcEnvName, ThemeName } from "../kc.gen";
|
||||||
|
|
||||||
|
export type KcContextExtension = {
|
||||||
|
themeName: ThemeName;
|
||||||
|
properties: Record<KcEnvName, string> & {};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type KcContextExtensionPerPage = {};
|
||||||
|
|
||||||
|
export type KcContext = ExtendKcContext<KcContextExtension, KcContextExtensionPerPage>;
|
25
src/bin/initialize-account-theme/src/multi-page/KcPage.tsx
Normal file
25
src/bin/initialize-account-theme/src/multi-page/KcPage.tsx
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { Suspense } from "react";
|
||||||
|
import type { ClassKey } from "keycloakify/account";
|
||||||
|
import type { KcContext } from "./KcContext";
|
||||||
|
import { useI18n } from "./i18n";
|
||||||
|
import DefaultPage from "keycloakify/account/DefaultPage";
|
||||||
|
import Template from "keycloakify/account/Template";
|
||||||
|
|
||||||
|
export default function KcPage(props: { kcContext: KcContext }) {
|
||||||
|
const { kcContext } = props;
|
||||||
|
|
||||||
|
const { i18n } = useI18n({ kcContext });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Suspense>
|
||||||
|
{(() => {
|
||||||
|
switch (kcContext.pageId) {
|
||||||
|
default:
|
||||||
|
return <DefaultPage kcContext={kcContext} i18n={i18n} classes={classes} Template={Template} doUseDefaultCss={true} />;
|
||||||
|
}
|
||||||
|
})()}
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const classes = {} satisfies { [key in ClassKey]?: string };
|
@ -0,0 +1,38 @@
|
|||||||
|
import type { DeepPartial } from "keycloakify/tools/DeepPartial";
|
||||||
|
import type { KcContext } from "./KcContext";
|
||||||
|
import { createGetKcContextMock } from "keycloakify/account/KcContext";
|
||||||
|
import type { KcContextExtension, KcContextExtensionPerPage } from "./KcContext";
|
||||||
|
import KcPage from "./KcPage";
|
||||||
|
import { themeNames, kcEnvDefaults } from "../kc.gen";
|
||||||
|
|
||||||
|
const kcContextExtension: KcContextExtension = {
|
||||||
|
themeName: themeNames[0],
|
||||||
|
properties: {
|
||||||
|
...kcEnvDefaults
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const kcContextExtensionPerPage: KcContextExtensionPerPage = {};
|
||||||
|
|
||||||
|
export const { getKcContextMock } = createGetKcContextMock({
|
||||||
|
kcContextExtension,
|
||||||
|
kcContextExtensionPerPage,
|
||||||
|
overrides: {},
|
||||||
|
overridesPerPage: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
export function createKcPageStory<PageId extends KcContext["pageId"]>(params: { pageId: PageId }) {
|
||||||
|
const { pageId } = params;
|
||||||
|
|
||||||
|
function KcPageStory(props: { kcContext?: DeepPartial<Extract<KcContext, { pageId: PageId }>> }) {
|
||||||
|
const { kcContext: overrides } = props;
|
||||||
|
|
||||||
|
const kcContextMock = getKcContextMock({
|
||||||
|
pageId,
|
||||||
|
overrides
|
||||||
|
});
|
||||||
|
|
||||||
|
return <KcPage kcContext={kcContextMock} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { KcPageStory };
|
||||||
|
}
|
5
src/bin/initialize-account-theme/src/multi-page/i18n.ts
Normal file
5
src/bin/initialize-account-theme/src/multi-page/i18n.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { createUseI18n } from "keycloakify/account";
|
||||||
|
|
||||||
|
export const { useI18n, ofTypeI18n } = createUseI18n({});
|
||||||
|
|
||||||
|
export type I18n = typeof ofTypeI18n;
|
@ -0,0 +1,7 @@
|
|||||||
|
import type { KcContextLike } from "@keycloakify/keycloak-account-ui";
|
||||||
|
import type { KcEnvName } from "../kc.gen";
|
||||||
|
|
||||||
|
export type KcContext = KcContextLike & {
|
||||||
|
themeType: "account";
|
||||||
|
properties: Record<KcEnvName, string>;
|
||||||
|
};
|
11
src/bin/initialize-account-theme/src/single-page/KcPage.tsx
Normal file
11
src/bin/initialize-account-theme/src/single-page/KcPage.tsx
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import { lazy } from "react";
|
||||||
|
import { KcAccountUiLoader } from "@keycloakify/keycloak-account-ui";
|
||||||
|
import type { KcContext } from "./KcContext";
|
||||||
|
|
||||||
|
const KcAccountUi = lazy(() => import("@keycloakify/keycloak-account-ui/KcAccountUi"));
|
||||||
|
|
||||||
|
export default function KcPage(props: { kcContext: KcContext }) {
|
||||||
|
const { kcContext } = props;
|
||||||
|
|
||||||
|
return <KcAccountUiLoader kcContext={kcContext} KcAccountUi={KcAccountUi} />;
|
||||||
|
}
|
@ -0,0 +1,92 @@
|
|||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import type { BuildContext } from "../shared/buildContext";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
|
||||||
|
export type BuildContextLike = {
|
||||||
|
bundler: BuildContext["bundler"];
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export function updateAccountThemeImplementationInConfig(params: {
|
||||||
|
buildContext: BuildContext;
|
||||||
|
accountThemeType: "Single-Page" | "Multi-Page";
|
||||||
|
}) {
|
||||||
|
const { buildContext, accountThemeType } = params;
|
||||||
|
|
||||||
|
switch (buildContext.bundler) {
|
||||||
|
case "vite":
|
||||||
|
{
|
||||||
|
const viteConfigPath = pathJoin(
|
||||||
|
buildContext.projectDirPath,
|
||||||
|
"vite.config.ts"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!fs.existsSync(viteConfigPath)) {
|
||||||
|
console.log(
|
||||||
|
chalk.bold(
|
||||||
|
`You must manually set the accountThemeImplementation to "${accountThemeType}" in your vite config`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const viteConfigContent = fs
|
||||||
|
.readFileSync(viteConfigPath)
|
||||||
|
.toString("utf8");
|
||||||
|
|
||||||
|
const modifiedViteConfigContent = viteConfigContent.replace(
|
||||||
|
/accountThemeImplementation\s*:\s*"none"/,
|
||||||
|
`accountThemeImplementation: "${accountThemeType}"`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (modifiedViteConfigContent === viteConfigContent) {
|
||||||
|
console.log(
|
||||||
|
chalk.bold(
|
||||||
|
`You must manually set the accountThemeImplementation to "${accountThemeType}" in your vite.config.ts`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(viteConfigPath, modifiedViteConfigContent);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "webpack":
|
||||||
|
{
|
||||||
|
const parsedPackageJson = (() => {
|
||||||
|
type ParsedPackageJson = {
|
||||||
|
keycloakify: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zParsedPackageJson = (() => {
|
||||||
|
type TargetType = ParsedPackageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
keycloakify: z.record(z.string())
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
return zParsedPackageJson.parse(
|
||||||
|
JSON.parse(
|
||||||
|
fs
|
||||||
|
.readFileSync(buildContext.packageJsonFilePath)
|
||||||
|
.toString("utf8")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
|
||||||
|
parsedPackageJson.keycloakify.accountThemeImplementation =
|
||||||
|
accountThemeType;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
@ -30,7 +30,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
// NOTE: This is arbitrary
|
// NOTE: This is arbitrary
|
||||||
startingFromMajor: 17,
|
startingFromMajor: 17,
|
||||||
excludeMajorVersions: [],
|
excludeMajorVersions: [],
|
||||||
cacheDirPath: buildContext.cacheDirPath
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
||||||
|
@ -7,7 +7,7 @@ import { join as pathJoin, dirname as pathDirname } from "path";
|
|||||||
import { transformCodebase } from "../../tools/transformCodebase";
|
import { transformCodebase } from "../../tools/transformCodebase";
|
||||||
import type { BuildContext } from "../../shared/buildContext";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import * as fs from "fs/promises";
|
import * as fs from "fs/promises";
|
||||||
import { accountV1ThemeName } from "../../shared/constants";
|
import { ACCOUNT_V1_THEME_NAME } from "../../shared/constants";
|
||||||
import {
|
import {
|
||||||
generatePom,
|
generatePom,
|
||||||
BuildContextLike as BuildContextLike_generatePom
|
BuildContextLike as BuildContextLike_generatePom
|
||||||
@ -24,6 +24,7 @@ export type BuildContextLike = BuildContextLike_generatePom & {
|
|||||||
artifactId: string;
|
artifactId: string;
|
||||||
themeVersion: string;
|
themeVersion: string;
|
||||||
cacheDirPath: string;
|
cacheDirPath: string;
|
||||||
|
implementedThemeTypes: BuildContext["implementedThemeTypes"];
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildContext extends BuildContextLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
@ -45,20 +46,21 @@ export async function buildJar(params: {
|
|||||||
buildContext
|
buildContext
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
const keycloakifyBuildTmpDirPath = pathJoin(
|
const keycloakifyBuildCacheDirPath = pathJoin(
|
||||||
buildContext.cacheDirPath,
|
buildContext.cacheDirPath,
|
||||||
|
"maven",
|
||||||
jarFileBasename.replace(".jar", "")
|
jarFileBasename.replace(".jar", "")
|
||||||
);
|
);
|
||||||
|
|
||||||
rmSync(keycloakifyBuildTmpDirPath, { recursive: true, force: true });
|
|
||||||
|
|
||||||
const tmpResourcesDirPath = pathJoin(
|
const tmpResourcesDirPath = pathJoin(
|
||||||
keycloakifyBuildTmpDirPath,
|
keycloakifyBuildCacheDirPath,
|
||||||
"src",
|
"src",
|
||||||
"main",
|
"main",
|
||||||
"resources"
|
"resources"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
rmSync(tmpResourcesDirPath, { recursive: true, force: true });
|
||||||
|
|
||||||
transformCodebase({
|
transformCodebase({
|
||||||
srcDirPath: resourcesDirPath,
|
srcDirPath: resourcesDirPath,
|
||||||
destDirPath: tmpResourcesDirPath,
|
destDirPath: tmpResourcesDirPath,
|
||||||
@ -73,7 +75,7 @@ export async function buildJar(params: {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
isInside({
|
isInside({
|
||||||
dirPath: pathJoin("theme", accountV1ThemeName),
|
dirPath: pathJoin("theme", ACCOUNT_V1_THEME_NAME),
|
||||||
filePath: fileRelativePath
|
filePath: fileRelativePath
|
||||||
})
|
})
|
||||||
) {
|
) {
|
||||||
@ -89,7 +91,7 @@ export async function buildJar(params: {
|
|||||||
sourceCode
|
sourceCode
|
||||||
.toString("utf8")
|
.toString("utf8")
|
||||||
.replace(
|
.replace(
|
||||||
`parent=${accountV1ThemeName}`,
|
`parent=${ACCOUNT_V1_THEME_NAME}`,
|
||||||
"parent=keycloak"
|
"parent=keycloak"
|
||||||
),
|
),
|
||||||
"utf8"
|
"utf8"
|
||||||
@ -124,7 +126,7 @@ export async function buildJar(params: {
|
|||||||
assert(metaInfKeycloakTheme !== undefined);
|
assert(metaInfKeycloakTheme !== undefined);
|
||||||
|
|
||||||
metaInfKeycloakTheme.themes = metaInfKeycloakTheme.themes.filter(
|
metaInfKeycloakTheme.themes = metaInfKeycloakTheme.themes.filter(
|
||||||
({ name }) => name !== accountV1ThemeName
|
({ name }) => name !== ACCOUNT_V1_THEME_NAME
|
||||||
);
|
);
|
||||||
|
|
||||||
return metaInfKeycloakTheme;
|
return metaInfKeycloakTheme;
|
||||||
@ -133,6 +135,10 @@ export async function buildJar(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
route_legacy_pages: {
|
route_legacy_pages: {
|
||||||
|
if (!buildContext.implementedThemeTypes.login.isImplemented) {
|
||||||
|
break route_legacy_pages;
|
||||||
|
}
|
||||||
|
|
||||||
// NOTE: If there's no account theme there is no special target for keycloak 24 and up so we create
|
// NOTE: If there's no account theme there is no special target for keycloak 24 and up so we create
|
||||||
// the pages anyway. If there is an account pages, since we know that account-v1 is only support keycloak
|
// the pages anyway. If there is an account pages, since we know that account-v1 is only support keycloak
|
||||||
// 24 in version 0.4 and up, we can safely break the route for legacy pages.
|
// 24 in version 0.4 and up, we can safely break the route for legacy pages.
|
||||||
@ -155,10 +161,7 @@ export async function buildJar(params: {
|
|||||||
(["register.ftl", "login-update-profile.ftl"] as const).forEach(pageId =>
|
(["register.ftl", "login-update-profile.ftl"] as const).forEach(pageId =>
|
||||||
buildContext.themeNames.map(themeName => {
|
buildContext.themeNames.map(themeName => {
|
||||||
const ftlFilePath = pathJoin(
|
const ftlFilePath = pathJoin(
|
||||||
keycloakifyBuildTmpDirPath,
|
tmpResourcesDirPath,
|
||||||
"src",
|
|
||||||
"main",
|
|
||||||
"resources",
|
|
||||||
"theme",
|
"theme",
|
||||||
themeName,
|
themeName,
|
||||||
"login",
|
"login",
|
||||||
@ -167,7 +170,7 @@ export async function buildJar(params: {
|
|||||||
|
|
||||||
const ftlFileContent = readFileSync(ftlFilePath).toString("utf8");
|
const ftlFileContent = readFileSync(ftlFilePath).toString("utf8");
|
||||||
|
|
||||||
const realPageId = (() => {
|
const ftlFileBasename = (() => {
|
||||||
switch (pageId) {
|
switch (pageId) {
|
||||||
case "register.ftl":
|
case "register.ftl":
|
||||||
return "register-user-profile.ftl";
|
return "register-user-profile.ftl";
|
||||||
@ -178,14 +181,14 @@ export async function buildJar(params: {
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
const modifiedFtlFileContent = ftlFileContent.replace(
|
const modifiedFtlFileContent = ftlFileContent.replace(
|
||||||
`kcContext.pageId = "\${pageId}";`,
|
`"ftlTemplateFileName": "${pageId}"`,
|
||||||
`kcContext.pageId = "${pageId}"; kcContext.realPageId = "${realPageId}";`
|
`"ftlTemplateFileName": "${ftlFileBasename}"`
|
||||||
);
|
);
|
||||||
|
|
||||||
assert(modifiedFtlFileContent !== ftlFileContent);
|
assert(modifiedFtlFileContent !== ftlFileContent);
|
||||||
|
|
||||||
fs.writeFile(
|
fs.writeFile(
|
||||||
pathJoin(pathDirname(ftlFilePath), realPageId),
|
pathJoin(pathDirname(ftlFilePath), ftlFileBasename),
|
||||||
Buffer.from(modifiedFtlFileContent, "utf8")
|
Buffer.from(modifiedFtlFileContent, "utf8")
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@ -200,15 +203,15 @@ export async function buildJar(params: {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await fs.writeFile(
|
await fs.writeFile(
|
||||||
pathJoin(keycloakifyBuildTmpDirPath, "pom.xml"),
|
pathJoin(keycloakifyBuildCacheDirPath, "pom.xml"),
|
||||||
Buffer.from(pomFileCode, "utf8")
|
Buffer.from(pomFileCode, "utf8")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await new Promise<void>((resolve, reject) =>
|
await new Promise<void>((resolve, reject) =>
|
||||||
child_process.exec(
|
child_process.exec(
|
||||||
`mvn clean install -Dmaven.repo.local=${pathJoin(keycloakifyBuildTmpDirPath, ".m2")}`,
|
`mvn install -Dmaven.repo.local="${pathJoin(keycloakifyBuildCacheDirPath, ".m2")}"`,
|
||||||
{ cwd: keycloakifyBuildTmpDirPath },
|
{ cwd: keycloakifyBuildCacheDirPath },
|
||||||
error => {
|
error => {
|
||||||
if (error !== null) {
|
if (error !== null) {
|
||||||
console.error(
|
console.error(
|
||||||
@ -233,12 +236,10 @@ export async function buildJar(params: {
|
|||||||
|
|
||||||
await fs.rename(
|
await fs.rename(
|
||||||
pathJoin(
|
pathJoin(
|
||||||
keycloakifyBuildTmpDirPath,
|
keycloakifyBuildCacheDirPath,
|
||||||
"target",
|
"target",
|
||||||
`${buildContext.artifactId}-${buildContext.themeVersion}.jar`
|
`${buildContext.artifactId}-${buildContext.themeVersion}.jar`
|
||||||
),
|
),
|
||||||
pathJoin(buildContext.keycloakifyBuildDirPath, jarFileBasename)
|
pathJoin(buildContext.keycloakifyBuildDirPath, jarFileBasename)
|
||||||
);
|
);
|
||||||
|
|
||||||
rmSync(keycloakifyBuildTmpDirPath, { recursive: true });
|
|
||||||
}
|
}
|
||||||
|
@ -10,9 +10,8 @@ import type { BuildContext } from "../../shared/buildContext";
|
|||||||
export type BuildContextLike = BuildContextLike_buildJar & {
|
export type BuildContextLike = BuildContextLike_buildJar & {
|
||||||
projectDirPath: string;
|
projectDirPath: string;
|
||||||
keycloakifyBuildDirPath: string;
|
keycloakifyBuildDirPath: string;
|
||||||
recordIsImplementedByThemeType: BuildContext["recordIsImplementedByThemeType"];
|
implementedThemeTypes: BuildContext["implementedThemeTypes"];
|
||||||
jarTargets: BuildContext["jarTargets"];
|
jarTargets: BuildContext["jarTargets"];
|
||||||
doUseAccountV3: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildContext extends BuildContextLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
@ -24,8 +23,8 @@ export async function buildJars(params: {
|
|||||||
const { resourcesDirPath, buildContext } = params;
|
const { resourcesDirPath, buildContext } = params;
|
||||||
|
|
||||||
const doesImplementAccountV1Theme =
|
const doesImplementAccountV1Theme =
|
||||||
buildContext.recordIsImplementedByThemeType.account &&
|
buildContext.implementedThemeTypes.account.isImplemented &&
|
||||||
!buildContext.doUseAccountV3;
|
buildContext.implementedThemeTypes.account.type === "Multi-Page";
|
||||||
|
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
keycloakAccountV1Versions
|
keycloakAccountV1Versions
|
||||||
|
@ -13,8 +13,8 @@ import type { BuildContext } from "../../shared/buildContext";
|
|||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import {
|
import {
|
||||||
type ThemeType,
|
type ThemeType,
|
||||||
basenameOfTheKeycloakifyResourcesDir,
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR,
|
||||||
resources_common
|
RESOURCES_COMMON
|
||||||
} from "../../shared/constants";
|
} from "../../shared/constants";
|
||||||
import { getThisCodebaseRootDirPath } from "../../tools/getThisCodebaseRootDirPath";
|
import { getThisCodebaseRootDirPath } from "../../tools/getThisCodebaseRootDirPath";
|
||||||
|
|
||||||
@ -34,7 +34,6 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
keycloakifyVersion: string;
|
keycloakifyVersion: string;
|
||||||
themeType: ThemeType;
|
themeType: ThemeType;
|
||||||
fieldNames: string[];
|
fieldNames: string[];
|
||||||
isAccountV3: boolean;
|
|
||||||
}) {
|
}) {
|
||||||
const {
|
const {
|
||||||
themeName,
|
themeName,
|
||||||
@ -42,8 +41,7 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
buildContext,
|
buildContext,
|
||||||
keycloakifyVersion,
|
keycloakifyVersion,
|
||||||
themeType,
|
themeType,
|
||||||
fieldNames,
|
fieldNames
|
||||||
isAccountV3
|
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
const $ = cheerio.load(indexHtmlCode);
|
const $ = cheerio.load(indexHtmlCode);
|
||||||
@ -70,8 +68,7 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
const { fixedCssCode } = replaceImportsInCssCode({
|
const { fixedCssCode } = replaceImportsInCssCode({
|
||||||
cssCode,
|
cssCode,
|
||||||
cssFileRelativeDirPath: undefined,
|
cssFileRelativeDirPath: undefined,
|
||||||
buildContext,
|
buildContext
|
||||||
isAccountV3
|
|
||||||
});
|
});
|
||||||
|
|
||||||
$(element).text(fixedCssCode);
|
$(element).text(fixedCssCode);
|
||||||
@ -80,7 +77,8 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
(
|
(
|
||||||
[
|
[
|
||||||
["link", "href"],
|
["link", "href"],
|
||||||
["script", "src"]
|
["script", "src"],
|
||||||
|
["script", "data-src"]
|
||||||
] as const
|
] as const
|
||||||
).forEach(([selector, attrName]) =>
|
).forEach(([selector, attrName]) =>
|
||||||
$(selector).each((...[, element]) => {
|
$(selector).each((...[, element]) => {
|
||||||
@ -96,7 +94,7 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
new RegExp(
|
new RegExp(
|
||||||
`^${(buildContext.urlPathname ?? "/").replace(/\//g, "\\/")}`
|
`^${(buildContext.urlPathname ?? "/").replace(/\//g, "\\/")}`
|
||||||
),
|
),
|
||||||
`\${${!isAccountV3 ? "url.resourcesPath" : "resourceUrl"}}/${basenameOfTheKeycloakifyResourcesDir}/`
|
`\${xKeycloakify.resourcesPath}/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@ -116,19 +114,17 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
.toString("utf8")
|
.toString("utf8")
|
||||||
|
.replace("{{themeType}}", themeType)
|
||||||
|
.replace("{{themeName}}", themeName)
|
||||||
|
.replace("{{keycloakifyVersion}}", keycloakifyVersion)
|
||||||
|
.replace("{{themeVersion}}", buildContext.themeVersion)
|
||||||
|
.replace("{{fieldNames}}", fieldNames.map(name => `"${name}"`).join(", "))
|
||||||
|
.replace("{{RESOURCES_COMMON}}", RESOURCES_COMMON)
|
||||||
.replace(
|
.replace(
|
||||||
"FIELD_NAMES_eKsIY4ZsZ4xeM",
|
"{{userDefinedExclusions}}",
|
||||||
fieldNames.map(name => `"${name}"`).join(", ")
|
|
||||||
)
|
|
||||||
.replace("KEYCLOAKIFY_VERSION_xEdKd3xEdr", keycloakifyVersion)
|
|
||||||
.replace("KEYCLOAKIFY_THEME_VERSION_sIgKd3xEdr3dx", buildContext.themeVersion)
|
|
||||||
.replace("KEYCLOAKIFY_THEME_TYPE_dExKd3xEdr", themeType)
|
|
||||||
.replace("KEYCLOAKIFY_THEME_NAME_cXxKd3xEer", themeName)
|
|
||||||
.replace("RESOURCES_COMMON_cLsLsMrtDkpVv", resources_common)
|
|
||||||
.replace(
|
|
||||||
"USER_DEFINED_EXCLUSIONS_eKsaY4ZsZ4eMr2",
|
|
||||||
buildContext.kcContextExclusionsFtlCode ?? ""
|
buildContext.kcContextExclusionsFtlCode ?? ""
|
||||||
);
|
);
|
||||||
|
|
||||||
const ftlObjectToJsCodeDeclaringAnObjectPlaceholder =
|
const ftlObjectToJsCodeDeclaringAnObjectPlaceholder =
|
||||||
'{ "x": "vIdLqMeOed9sdLdIdOxdK0d" }';
|
'{ "x": "vIdLqMeOed9sdLdIdOxdK0d" }';
|
||||||
|
|
||||||
@ -173,7 +169,8 @@ export function generateFtlFilesCodeFactory(params: {
|
|||||||
Object.entries({
|
Object.entries({
|
||||||
[ftlObjectToJsCodeDeclaringAnObjectPlaceholder]:
|
[ftlObjectToJsCodeDeclaringAnObjectPlaceholder]:
|
||||||
kcContextDeclarationTemplateFtl,
|
kcContextDeclarationTemplateFtl,
|
||||||
PAGE_ID_xIgLsPgGId9D8e: pageId
|
"{{pageId}}": pageId,
|
||||||
|
"{{ftlTemplateFileName}}": pageId
|
||||||
}).map(
|
}).map(
|
||||||
([searchValue, replaceValue]) =>
|
([searchValue, replaceValue]) =>
|
||||||
(ftlCode = ftlCode.replace(searchValue, replaceValue))
|
(ftlCode = ftlCode.replace(searchValue, replaceValue))
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -3,9 +3,9 @@ import { join as pathJoin } from "path";
|
|||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildContext } from "../../shared/buildContext";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import {
|
import {
|
||||||
resources_common,
|
RESOURCES_COMMON,
|
||||||
lastKeycloakVersionWithAccountV1,
|
LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1,
|
||||||
accountV1ThemeName
|
ACCOUNT_V1_THEME_NAME
|
||||||
} from "../../shared/constants";
|
} from "../../shared/constants";
|
||||||
import {
|
import {
|
||||||
downloadKeycloakDefaultTheme,
|
downloadKeycloakDefaultTheme,
|
||||||
@ -24,14 +24,14 @@ export async function bringInAccountV1(params: {
|
|||||||
const { resourcesDirPath, buildContext } = params;
|
const { resourcesDirPath, buildContext } = params;
|
||||||
|
|
||||||
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
const { defaultThemeDirPath } = await downloadKeycloakDefaultTheme({
|
||||||
keycloakVersion: lastKeycloakVersionWithAccountV1,
|
keycloakVersion: LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1,
|
||||||
buildContext
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
const accountV1DirPath = pathJoin(
|
const accountV1DirPath = pathJoin(
|
||||||
resourcesDirPath,
|
resourcesDirPath,
|
||||||
"theme",
|
"theme",
|
||||||
accountV1ThemeName,
|
ACCOUNT_V1_THEME_NAME,
|
||||||
"account"
|
"account"
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -47,7 +47,7 @@ export async function bringInAccountV1(params: {
|
|||||||
|
|
||||||
transformCodebase({
|
transformCodebase({
|
||||||
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
||||||
destDirPath: pathJoin(accountV1DirPath, "resources", resources_common)
|
destDirPath: pathJoin(accountV1DirPath, "resources", RESOURCES_COMMON)
|
||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
@ -69,7 +69,7 @@ export async function bringInAccountV1(params: {
|
|||||||
"patternfly-additions.min.css"
|
"patternfly-additions.min.css"
|
||||||
].map(
|
].map(
|
||||||
fileBasename =>
|
fileBasename =>
|
||||||
`${resources_common}/node_modules/patternfly/dist/css/${fileBasename}`
|
`${RESOURCES_COMMON}/node_modules/patternfly/dist/css/${fileBasename}`
|
||||||
)
|
)
|
||||||
].join(" "),
|
].join(" "),
|
||||||
"",
|
"",
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { type ThemeType, fallbackLanguageTag } from "../../shared/constants";
|
import { type ThemeType, FALLBACK_LANGUAGE_TAG } from "../../shared/constants";
|
||||||
import { crawl } from "../../tools/crawl";
|
import { crawl } from "../../tools/crawl";
|
||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
import { symToStr } from "tsafe/symToStr";
|
import { symToStr } from "tsafe/symToStr";
|
||||||
@ -22,7 +22,7 @@ export function generateMessageProperties(params: {
|
|||||||
"src",
|
"src",
|
||||||
themeType,
|
themeType,
|
||||||
"i18n",
|
"i18n",
|
||||||
"baseMessages"
|
"messages_defaultSet"
|
||||||
);
|
);
|
||||||
|
|
||||||
const baseMessageBundle: { [languageTag: string]: Record<string, string> } =
|
const baseMessageBundle: { [languageTag: string]: Record<string, string> } =
|
||||||
@ -168,7 +168,7 @@ export function generateMessageProperties(params: {
|
|||||||
...(messageBundle === undefined
|
...(messageBundle === undefined
|
||||||
? {}
|
? {}
|
||||||
: messageBundle[languageTag] ??
|
: messageBundle[languageTag] ??
|
||||||
messageBundle[fallbackLanguageTag] ??
|
messageBundle[FALLBACK_LANGUAGE_TAG] ??
|
||||||
messageBundle[Object.keys(messageBundle)[0]] ??
|
messageBundle[Object.keys(messageBundle)[0]] ??
|
||||||
{})
|
{})
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,8 @@ import {
|
|||||||
join as pathJoin,
|
join as pathJoin,
|
||||||
resolve as pathResolve,
|
resolve as pathResolve,
|
||||||
relative as pathRelative,
|
relative as pathRelative,
|
||||||
dirname as pathDirname
|
dirname as pathDirname,
|
||||||
|
basename as pathBasename
|
||||||
} from "path";
|
} from "path";
|
||||||
import { replaceImportsInJsCode } from "../replacers/replaceImportsInJsCode";
|
import { replaceImportsInJsCode } from "../replacers/replaceImportsInJsCode";
|
||||||
import { replaceImportsInCssCode } from "../replacers/replaceImportsInCssCode";
|
import { replaceImportsInCssCode } from "../replacers/replaceImportsInCssCode";
|
||||||
@ -14,12 +15,12 @@ import {
|
|||||||
} from "../generateFtl";
|
} from "../generateFtl";
|
||||||
import {
|
import {
|
||||||
type ThemeType,
|
type ThemeType,
|
||||||
lastKeycloakVersionWithAccountV1,
|
LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1,
|
||||||
keycloak_resources,
|
KEYCLOAK_RESOURCES,
|
||||||
accountV1ThemeName,
|
ACCOUNT_V1_THEME_NAME,
|
||||||
basenameOfTheKeycloakifyResourcesDir,
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR,
|
||||||
loginThemePageIds,
|
LOGIN_THEME_PAGE_IDS,
|
||||||
accountThemePageIds
|
ACCOUNT_THEME_PAGE_IDS
|
||||||
} from "../../shared/constants";
|
} from "../../shared/constants";
|
||||||
import type { BuildContext } from "../../shared/buildContext";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import { assert, type Equals } from "tsafe/assert";
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
@ -42,6 +43,7 @@ import {
|
|||||||
} from "../../shared/metaInfKeycloakThemes";
|
} from "../../shared/metaInfKeycloakThemes";
|
||||||
import { objectEntries } from "tsafe/objectEntries";
|
import { objectEntries } from "tsafe/objectEntries";
|
||||||
import { escapeStringForPropertiesFile } from "../../tools/escapeStringForPropertiesFile";
|
import { escapeStringForPropertiesFile } from "../../tools/escapeStringForPropertiesFile";
|
||||||
|
import { downloadAndExtractArchive } from "../../tools/downloadAndExtractArchive";
|
||||||
|
|
||||||
export type BuildContextLike = BuildContextLike_kcContextExclusionsFtlCode &
|
export type BuildContextLike = BuildContextLike_kcContextExclusionsFtlCode &
|
||||||
BuildContextLike_downloadKeycloakStaticResources &
|
BuildContextLike_downloadKeycloakStaticResources &
|
||||||
@ -51,10 +53,9 @@ export type BuildContextLike = BuildContextLike_kcContextExclusionsFtlCode &
|
|||||||
projectDirPath: string;
|
projectDirPath: string;
|
||||||
projectBuildDirPath: string;
|
projectBuildDirPath: string;
|
||||||
environmentVariables: { name: string; default: string }[];
|
environmentVariables: { name: string; default: string }[];
|
||||||
recordIsImplementedByThemeType: BuildContext["recordIsImplementedByThemeType"];
|
implementedThemeTypes: BuildContext["implementedThemeTypes"];
|
||||||
themeSrcDirPath: string;
|
themeSrcDirPath: string;
|
||||||
bundler: { type: "vite" } | { type: "webpack" };
|
bundler: "vite" | "webpack";
|
||||||
doUseAccountV3: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildContext extends BuildContextLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
@ -72,18 +73,22 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
for (const themeType of ["login", "account"] as const) {
|
for (const themeType of ["login", "account"] as const) {
|
||||||
const isAccountV3 = themeType === "account" && buildContext.doUseAccountV3;
|
if (!buildContext.implementedThemeTypes[themeType].isImplemented) {
|
||||||
if (!buildContext.recordIsImplementedByThemeType[themeType]) {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isForAccountSpa =
|
||||||
|
themeType === "account" &&
|
||||||
|
(assert(buildContext.implementedThemeTypes.account.isImplemented),
|
||||||
|
buildContext.implementedThemeTypes.account.type === "Single-Page");
|
||||||
|
|
||||||
const themeTypeDirPath = getThemeTypeDirPath({ themeType });
|
const themeTypeDirPath = getThemeTypeDirPath({ themeType });
|
||||||
|
|
||||||
apply_replacers_and_move_to_theme_resources: {
|
apply_replacers_and_move_to_theme_resources: {
|
||||||
const destDirPath = pathJoin(
|
const destDirPath = pathJoin(
|
||||||
themeTypeDirPath,
|
themeTypeDirPath,
|
||||||
"resources",
|
"resources",
|
||||||
basenameOfTheKeycloakifyResourcesDir
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR
|
||||||
);
|
);
|
||||||
|
|
||||||
// NOTE: Prevent accumulation of files in the assets dir, as names are hashed they pile up.
|
// NOTE: Prevent accumulation of files in the assets dir, as names are hashed they pile up.
|
||||||
@ -91,7 +96,7 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
themeType === "account" &&
|
themeType === "account" &&
|
||||||
buildContext.recordIsImplementedByThemeType.login
|
buildContext.implementedThemeTypes.login.isImplemented
|
||||||
) {
|
) {
|
||||||
// NOTE: We prevent doing it twice, it has been done for the login theme.
|
// NOTE: We prevent doing it twice, it has been done for the login theme.
|
||||||
|
|
||||||
@ -101,7 +106,7 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
themeType: "login"
|
themeType: "login"
|
||||||
}),
|
}),
|
||||||
"resources",
|
"resources",
|
||||||
basenameOfTheKeycloakifyResourcesDir
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR
|
||||||
),
|
),
|
||||||
destDirPath
|
destDirPath
|
||||||
});
|
});
|
||||||
@ -112,15 +117,15 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
{
|
{
|
||||||
const dirPath = pathJoin(
|
const dirPath = pathJoin(
|
||||||
buildContext.projectBuildDirPath,
|
buildContext.projectBuildDirPath,
|
||||||
keycloak_resources
|
KEYCLOAK_RESOURCES
|
||||||
);
|
);
|
||||||
|
|
||||||
if (fs.existsSync(dirPath)) {
|
if (fs.existsSync(dirPath)) {
|
||||||
assert(buildContext.bundler.type === "webpack");
|
assert(buildContext.bundler === "webpack");
|
||||||
|
|
||||||
throw new Error(
|
throw new Error(
|
||||||
[
|
[
|
||||||
`Keycloakify build error: The ${keycloak_resources} directory shouldn't exist in your build directory.`,
|
`Keycloakify build error: The ${KEYCLOAK_RESOURCES} directory shouldn't exist in your build directory.`,
|
||||||
`(${pathRelative(process.cwd(), dirPath)}).\n`,
|
`(${pathRelative(process.cwd(), dirPath)}).\n`,
|
||||||
`Theses assets are only required for local development with Storybook.",
|
`Theses assets are only required for local development with Storybook.",
|
||||||
"Please remove this directory as an additional step of your command.\n`,
|
"Please remove this directory as an additional step of your command.\n`,
|
||||||
@ -138,8 +143,7 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
const { fixedCssCode } = replaceImportsInCssCode({
|
const { fixedCssCode } = replaceImportsInCssCode({
|
||||||
cssCode: sourceCode.toString("utf8"),
|
cssCode: sourceCode.toString("utf8"),
|
||||||
cssFileRelativeDirPath: pathDirname(fileRelativePath),
|
cssFileRelativeDirPath: pathDirname(fileRelativePath),
|
||||||
buildContext,
|
buildContext
|
||||||
isAccountV3
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -174,20 +178,19 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
fieldNames: readFieldNameUsage({
|
fieldNames: readFieldNameUsage({
|
||||||
themeSrcDirPath: buildContext.themeSrcDirPath,
|
themeSrcDirPath: buildContext.themeSrcDirPath,
|
||||||
themeType
|
themeType
|
||||||
}),
|
})
|
||||||
isAccountV3
|
|
||||||
});
|
});
|
||||||
|
|
||||||
[
|
[
|
||||||
...(() => {
|
...(() => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "login":
|
case "login":
|
||||||
return loginThemePageIds;
|
return LOGIN_THEME_PAGE_IDS;
|
||||||
case "account":
|
case "account":
|
||||||
return isAccountV3 ? ["index.ftl"] : accountThemePageIds;
|
return isForAccountSpa ? ["index.ftl"] : ACCOUNT_THEME_PAGE_IDS;
|
||||||
}
|
}
|
||||||
})(),
|
})(),
|
||||||
...(isAccountV3
|
...(isForAccountSpa
|
||||||
? []
|
? []
|
||||||
: readExtraPagesNames({
|
: readExtraPagesNames({
|
||||||
themeType,
|
themeType,
|
||||||
@ -203,7 +206,7 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
});
|
});
|
||||||
|
|
||||||
i18n_messages_generation: {
|
i18n_messages_generation: {
|
||||||
if (isAccountV3) {
|
if (isForAccountSpa) {
|
||||||
break i18n_messages_generation;
|
break i18n_messages_generation;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -230,7 +233,7 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
keycloak_static_resources: {
|
keycloak_static_resources: {
|
||||||
if (isAccountV3) {
|
if (isForAccountSpa) {
|
||||||
break keycloak_static_resources;
|
break keycloak_static_resources;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -238,7 +241,7 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
keycloakVersion: (() => {
|
keycloakVersion: (() => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "account":
|
case "account":
|
||||||
return lastKeycloakVersionWithAccountV1;
|
return LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1;
|
||||||
case "login":
|
case "login":
|
||||||
return buildContext.loginThemeResourcesFromKeycloakVersion;
|
return buildContext.loginThemeResourcesFromKeycloakVersion;
|
||||||
}
|
}
|
||||||
@ -256,13 +259,13 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
`parent=${(() => {
|
`parent=${(() => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "account":
|
case "account":
|
||||||
return isAccountV3 ? "base" : accountV1ThemeName;
|
return isForAccountSpa ? "base" : ACCOUNT_V1_THEME_NAME;
|
||||||
case "login":
|
case "login":
|
||||||
return "keycloak";
|
return "keycloak";
|
||||||
}
|
}
|
||||||
assert<Equals<typeof themeType, never>>(false);
|
assert<Equals<typeof themeType, never>>(false);
|
||||||
})()}`,
|
})()}`,
|
||||||
...(isAccountV3 ? ["deprecatedMode=false"] : []),
|
...(isForAccountSpa ? ["deprecatedMode=false"] : []),
|
||||||
...(buildContext.extraThemeProperties ?? []),
|
...(buildContext.extraThemeProperties ?? []),
|
||||||
...buildContext.environmentVariables.map(
|
...buildContext.environmentVariables.map(
|
||||||
({ name, default: defaultValue }) =>
|
({ name, default: defaultValue }) =>
|
||||||
@ -275,7 +278,7 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
email: {
|
email: {
|
||||||
if (!buildContext.recordIsImplementedByThemeType.email) {
|
if (!buildContext.implementedThemeTypes.email.isImplemented) {
|
||||||
break email;
|
break email;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -288,11 +291,11 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bring_in_account_v1: {
|
bring_in_account_v1: {
|
||||||
if (buildContext.doUseAccountV3) {
|
if (!buildContext.implementedThemeTypes.account.isImplemented) {
|
||||||
break bring_in_account_v1;
|
break bring_in_account_v1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!buildContext.recordIsImplementedByThemeType.account) {
|
if (buildContext.implementedThemeTypes.account.type !== "Multi-Page") {
|
||||||
break bring_in_account_v1;
|
break bring_in_account_v1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -302,19 +305,55 @@ export async function generateResourcesForMainTheme(params: {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bring_in_account_v3_i18n_messages: {
|
||||||
|
if (!buildContext.implementedThemeTypes.account.isImplemented) {
|
||||||
|
break bring_in_account_v3_i18n_messages;
|
||||||
|
}
|
||||||
|
if (buildContext.implementedThemeTypes.account.type !== "Single-Page") {
|
||||||
|
break bring_in_account_v3_i18n_messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { extractedDirPath } = await downloadAndExtractArchive({
|
||||||
|
url: "https://repo1.maven.org/maven2/org/keycloak/keycloak-account-ui/25.0.1/keycloak-account-ui-25.0.1.jar",
|
||||||
|
cacheDirPath: buildContext.cacheDirPath,
|
||||||
|
fetchOptions: buildContext.fetchOptions,
|
||||||
|
uniqueIdOfOnArchiveFile: "bring_in_account_v3_i18n_messages",
|
||||||
|
onArchiveFile: async ({ fileRelativePath, writeFile }) => {
|
||||||
|
if (
|
||||||
|
!fileRelativePath.startsWith(
|
||||||
|
pathJoin("theme", "keycloak.v3", "account", "messages")
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await writeFile({
|
||||||
|
fileRelativePath: pathBasename(fileRelativePath)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
transformCodebase({
|
||||||
|
srcDirPath: extractedDirPath,
|
||||||
|
destDirPath: pathJoin(
|
||||||
|
getThemeTypeDirPath({ themeType: "account" }),
|
||||||
|
"messages"
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
const metaInfKeycloakThemes: MetaInfKeycloakTheme = { themes: [] };
|
const metaInfKeycloakThemes: MetaInfKeycloakTheme = { themes: [] };
|
||||||
|
|
||||||
metaInfKeycloakThemes.themes.push({
|
metaInfKeycloakThemes.themes.push({
|
||||||
name: themeName,
|
name: themeName,
|
||||||
types: objectEntries(buildContext.recordIsImplementedByThemeType)
|
types: objectEntries(buildContext.implementedThemeTypes)
|
||||||
.filter(([, isImplemented]) => isImplemented)
|
.filter(([, { isImplemented }]) => isImplemented)
|
||||||
.map(([themeType]) => themeType)
|
.map(([themeType]) => themeType)
|
||||||
});
|
});
|
||||||
|
|
||||||
if (buildContext.recordIsImplementedByThemeType.account) {
|
if (buildContext.implementedThemeTypes.account.isImplemented) {
|
||||||
metaInfKeycloakThemes.themes.push({
|
metaInfKeycloakThemes.themes.push({
|
||||||
name: accountV1ThemeName,
|
name: ACCOUNT_V1_THEME_NAME,
|
||||||
types: ["account"]
|
types: ["account"]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -31,8 +31,8 @@ export function generateResourcesForThemeVariant(params: {
|
|||||||
Buffer.from(sourceCode)
|
Buffer.from(sourceCode)
|
||||||
.toString("utf-8")
|
.toString("utf-8")
|
||||||
.replace(
|
.replace(
|
||||||
`kcContext.themeName = "${themeName}";`,
|
`"themeName": "${themeName}"`,
|
||||||
`kcContext.themeName = "${themeVariantName}";`
|
`"themeName": "${themeVariantName}"`
|
||||||
),
|
),
|
||||||
"utf8"
|
"utf8"
|
||||||
);
|
);
|
||||||
|
@ -5,8 +5,8 @@ import * as fs from "fs";
|
|||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
import {
|
import {
|
||||||
type ThemeType,
|
type ThemeType,
|
||||||
accountThemePageIds,
|
ACCOUNT_THEME_PAGE_IDS,
|
||||||
loginThemePageIds
|
LOGIN_THEME_PAGE_IDS
|
||||||
} from "../../shared/constants";
|
} from "../../shared/constants";
|
||||||
|
|
||||||
export function readExtraPagesNames(params: {
|
export function readExtraPagesNames(params: {
|
||||||
@ -41,9 +41,9 @@ export function readExtraPagesNames(params: {
|
|||||||
return extraPages.reduce(...removeDuplicates<string>()).filter(pageId => {
|
return extraPages.reduce(...removeDuplicates<string>()).filter(pageId => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "account":
|
case "account":
|
||||||
return !id<readonly string[]>(accountThemePageIds).includes(pageId);
|
return !id<readonly string[]>(ACCOUNT_THEME_PAGE_IDS).includes(pageId);
|
||||||
case "login":
|
case "login":
|
||||||
return !id<readonly string[]>(loginThemePageIds).includes(pageId);
|
return !id<readonly string[]>(LOGIN_THEME_PAGE_IDS).includes(pageId);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,7 @@ import { join as pathJoin, relative as pathRelative, sep as pathSep } from "path
|
|||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import { getBuildContext } from "../shared/buildContext";
|
import { getBuildContext } from "../shared/buildContext";
|
||||||
import { vitePluginSubScriptEnvNames } from "../shared/constants";
|
import { VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES } from "../shared/constants";
|
||||||
import { buildJars } from "./buildJars";
|
import { buildJars } from "./buildJars";
|
||||||
import type { CliCommandOptions } from "../main";
|
import type { CliCommandOptions } from "../main";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
@ -85,7 +85,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
});
|
});
|
||||||
|
|
||||||
run_post_build_script: {
|
run_post_build_script: {
|
||||||
if (buildContext.bundler.type !== "vite") {
|
if (buildContext.bundler !== "vite") {
|
||||||
break run_post_build_script;
|
break run_post_build_script;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -93,10 +93,12 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
cwd: buildContext.projectDirPath,
|
cwd: buildContext.projectDirPath,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
[vitePluginSubScriptEnvNames.runPostBuildScript]: JSON.stringify({
|
[VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RUN_POST_BUILD_SCRIPT]: JSON.stringify(
|
||||||
resourcesDirPath,
|
{
|
||||||
buildContext
|
resourcesDirPath,
|
||||||
})
|
buildContext
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import type { BuildContext } from "../../shared/buildContext";
|
import type { BuildContext } from "../../shared/buildContext";
|
||||||
import { basenameOfTheKeycloakifyResourcesDir } from "../../shared/constants";
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } from "../../shared/constants";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { posix } from "path";
|
import { posix } from "path";
|
||||||
|
|
||||||
@ -12,42 +12,55 @@ assert<BuildContext extends BuildContextLike ? true : false>();
|
|||||||
export function replaceImportsInCssCode(params: {
|
export function replaceImportsInCssCode(params: {
|
||||||
cssCode: string;
|
cssCode: string;
|
||||||
cssFileRelativeDirPath: string | undefined;
|
cssFileRelativeDirPath: string | undefined;
|
||||||
isAccountV3: boolean;
|
|
||||||
buildContext: BuildContextLike;
|
buildContext: BuildContextLike;
|
||||||
}): {
|
}): {
|
||||||
fixedCssCode: string;
|
fixedCssCode: string;
|
||||||
} {
|
} {
|
||||||
const { cssCode, cssFileRelativeDirPath, buildContext, isAccountV3 } = params;
|
const { cssCode, cssFileRelativeDirPath, buildContext } = params;
|
||||||
|
|
||||||
const fixedCssCode = cssCode.replace(
|
let fixedCssCode = cssCode;
|
||||||
/url\(["']?(\/[^/][^)"']+)["']?\)/g,
|
|
||||||
(match, assetFileAbsoluteUrlPathname) => {
|
[
|
||||||
if (buildContext.urlPathname !== undefined) {
|
/url\("(\/[^/][^"]+)"\)/g,
|
||||||
if (!assetFileAbsoluteUrlPathname.startsWith(buildContext.urlPathname)) {
|
/url\('(\/[^/][^']+)'\)/g,
|
||||||
// NOTE: Should never happen
|
/url\((\/[^/][^)]+)\)/g
|
||||||
return match;
|
].forEach(
|
||||||
|
regex =>
|
||||||
|
(fixedCssCode = fixedCssCode.replace(
|
||||||
|
regex,
|
||||||
|
(match, assetFileAbsoluteUrlPathname) => {
|
||||||
|
if (buildContext.urlPathname !== undefined) {
|
||||||
|
if (
|
||||||
|
!assetFileAbsoluteUrlPathname.startsWith(
|
||||||
|
buildContext.urlPathname
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
// NOTE: Should never happen
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
assetFileAbsoluteUrlPathname =
|
||||||
|
assetFileAbsoluteUrlPathname.replace(
|
||||||
|
buildContext.urlPathname,
|
||||||
|
"/"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline_style_in_html: {
|
||||||
|
if (cssFileRelativeDirPath !== undefined) {
|
||||||
|
break inline_style_in_html;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `url("\${xKeycloakify.resourcesPath}/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}${assetFileAbsoluteUrlPathname}")`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const assetFileRelativeUrlPathname = posix.relative(
|
||||||
|
cssFileRelativeDirPath.replace(/\\/g, "/"),
|
||||||
|
assetFileAbsoluteUrlPathname.replace(/^\//, "")
|
||||||
|
);
|
||||||
|
|
||||||
|
return `url("${assetFileRelativeUrlPathname}")`;
|
||||||
}
|
}
|
||||||
assetFileAbsoluteUrlPathname = assetFileAbsoluteUrlPathname.replace(
|
))
|
||||||
buildContext.urlPathname,
|
|
||||||
"/"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline_style_in_html: {
|
|
||||||
if (cssFileRelativeDirPath !== undefined) {
|
|
||||||
break inline_style_in_html;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `url(\${${!isAccountV3 ? "url.resourcesPath" : "resourceUrl"}}/${basenameOfTheKeycloakifyResourcesDir}${assetFileAbsoluteUrlPathname})`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const assetFileRelativeUrlPathname = posix.relative(
|
|
||||||
cssFileRelativeDirPath.replace(/\\/g, "/"),
|
|
||||||
assetFileAbsoluteUrlPathname.replace(/^\//, "")
|
|
||||||
);
|
|
||||||
|
|
||||||
return `url(${assetFileRelativeUrlPathname})`;
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return { fixedCssCode };
|
return { fixedCssCode };
|
||||||
|
@ -8,7 +8,7 @@ export type BuildContextLike = {
|
|||||||
projectBuildDirPath: string;
|
projectBuildDirPath: string;
|
||||||
assetsDirPath: string;
|
assetsDirPath: string;
|
||||||
urlPathname: string | undefined;
|
urlPathname: string | undefined;
|
||||||
bundler: { type: "vite" } | { type: "webpack" };
|
bundler: "vite" | "webpack";
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildContext extends BuildContextLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
@ -20,7 +20,7 @@ export function replaceImportsInJsCode(params: {
|
|||||||
const { jsCode, buildContext } = params;
|
const { jsCode, buildContext } = params;
|
||||||
|
|
||||||
const { fixedJsCode } = (() => {
|
const { fixedJsCode } = (() => {
|
||||||
switch (buildContext.bundler.type) {
|
switch (buildContext.bundler) {
|
||||||
case "vite":
|
case "vite":
|
||||||
return replaceImportsInJsCode_vite({
|
return replaceImportsInJsCode_vite({
|
||||||
jsCode,
|
jsCode,
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { basenameOfTheKeycloakifyResourcesDir } from "../../../shared/constants";
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } from "../../../shared/constants";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildContext } from "../../../shared/buildContext";
|
import type { BuildContext } from "../../../shared/buildContext";
|
||||||
import * as nodePath from "path";
|
import * as nodePath from "path";
|
||||||
@ -31,13 +31,13 @@ export function replaceImportsInJsCode_vite(params: {
|
|||||||
|
|
||||||
let fixedJsCode = jsCode;
|
let fixedJsCode = jsCode;
|
||||||
|
|
||||||
replace_base_javacript_import: {
|
replace_base_js_import: {
|
||||||
if (buildContext.urlPathname === undefined) {
|
if (buildContext.urlPathname === undefined) {
|
||||||
break replace_base_javacript_import;
|
break replace_base_js_import;
|
||||||
}
|
}
|
||||||
// Optimization
|
// Optimization
|
||||||
if (!jsCode.includes(buildContext.urlPathname)) {
|
if (!jsCode.includes(buildContext.urlPathname)) {
|
||||||
break replace_base_javacript_import;
|
break replace_base_js_import;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace `Hv=function(e){return"/abcde12345/"+e}` by `Hv=function(e){return"/"+e}`
|
// Replace `Hv=function(e){return"/abcde12345/"+e}` by `Hv=function(e){return"/"+e}`
|
||||||
@ -85,13 +85,13 @@ export function replaceImportsInJsCode_vite(params: {
|
|||||||
fixedJsCode = replaceAll(
|
fixedJsCode = replaceAll(
|
||||||
fixedJsCode,
|
fixedJsCode,
|
||||||
`"${relativePathOfAssetFile}"`,
|
`"${relativePathOfAssetFile}"`,
|
||||||
`(window.kcContext.url.resourcesPath.substring(1) + "/${basenameOfTheKeycloakifyResourcesDir}/${relativePathOfAssetFile}")`
|
`(window.kcContext["x-keycloakify"].resourcesPath.substring(1) + "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${relativePathOfAssetFile}")`
|
||||||
);
|
);
|
||||||
|
|
||||||
fixedJsCode = replaceAll(
|
fixedJsCode = replaceAll(
|
||||||
fixedJsCode,
|
fixedJsCode,
|
||||||
`"${buildContext.urlPathname ?? "/"}${relativePathOfAssetFile}"`,
|
`"${buildContext.urlPathname ?? "/"}${relativePathOfAssetFile}"`,
|
||||||
`(window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/${relativePathOfAssetFile}")`
|
`(window.kcContext["x-keycloakify"].resourcesPath + "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${relativePathOfAssetFile}")`
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { basenameOfTheKeycloakifyResourcesDir } from "../../../shared/constants";
|
import { BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR } from "../../../shared/constants";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { BuildContext } from "../../../shared/buildContext";
|
import type { BuildContext } from "../../../shared/buildContext";
|
||||||
import * as nodePath from "path";
|
import * as nodePath from "path";
|
||||||
@ -83,14 +83,14 @@ export function replaceImportsInJsCode_webpack(params: {
|
|||||||
var pd = Object.getOwnPropertyDescriptor(${n}, "p");
|
var pd = Object.getOwnPropertyDescriptor(${n}, "p");
|
||||||
if( pd === undefined || pd.configurable ){
|
if( pd === undefined || pd.configurable ){
|
||||||
Object.defineProperty(${n}, "p", {
|
Object.defineProperty(${n}, "p", {
|
||||||
get: function() { return window.kcContext.url.resourcesPath; },
|
get: function() { return window.kcContext["x-keycloakify"].resourcesPath; },
|
||||||
set: function() {}
|
set: function() {}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return "${u}";
|
return "${u}";
|
||||||
})()] = ${
|
})()] = ${
|
||||||
isArrowFunction ? `${e} =>` : `function(${e}) { return `
|
isArrowFunction ? `${e} =>` : `function(${e}) { return `
|
||||||
} "/${basenameOfTheKeycloakifyResourcesDir}/${staticDir}${language}/"`
|
} "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${staticDir}${language}/"`
|
||||||
.replace(/\s+/g, " ")
|
.replace(/\s+/g, " ")
|
||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
@ -104,7 +104,7 @@ export function replaceImportsInJsCode_webpack(params: {
|
|||||||
`[a-zA-Z]+\\.[a-zA-Z]+\\+"${staticDir.replace(/\//g, "\\/")}`,
|
`[a-zA-Z]+\\.[a-zA-Z]+\\+"${staticDir.replace(/\//g, "\\/")}`,
|
||||||
"g"
|
"g"
|
||||||
),
|
),
|
||||||
`window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/${staticDir}`
|
`window.kcContext["x-keycloakify"].resourcesPath + "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/${staticDir}`
|
||||||
);
|
);
|
||||||
|
|
||||||
return { fixedJsCode };
|
return { fixedJsCode };
|
||||||
|
@ -179,6 +179,20 @@ program
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
program
|
||||||
|
.command({
|
||||||
|
name: "initialize-account-theme",
|
||||||
|
description: "Initialize the account theme."
|
||||||
|
})
|
||||||
|
.task({
|
||||||
|
skip,
|
||||||
|
handler: async cliCommandOptions => {
|
||||||
|
const { command } = await import("./initialize-account-theme");
|
||||||
|
|
||||||
|
await command({ cliCommandOptions });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
program
|
program
|
||||||
.command({
|
.command({
|
||||||
name: "copy-keycloak-resources-to-public",
|
name: "copy-keycloak-resources-to-public",
|
||||||
|
@ -13,18 +13,17 @@ import * as fs from "fs";
|
|||||||
import { assert, type Equals } from "tsafe/assert";
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import {
|
import {
|
||||||
vitePluginSubScriptEnvNames,
|
VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES,
|
||||||
buildForKeycloakMajorVersionEnvName
|
BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME,
|
||||||
|
LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT
|
||||||
} from "./constants";
|
} from "./constants";
|
||||||
import type { KeycloakVersionRange } from "./KeycloakVersionRange";
|
import type { KeycloakVersionRange } from "./KeycloakVersionRange";
|
||||||
import { exclude } from "tsafe";
|
import { exclude } from "tsafe";
|
||||||
import { crawl } from "../tools/crawl";
|
import { crawl } from "../tools/crawl";
|
||||||
import { themeTypes } from "./constants";
|
import { THEME_TYPES } from "./constants";
|
||||||
import { objectFromEntries } from "tsafe/objectFromEntries";
|
|
||||||
import { objectEntries } from "tsafe/objectEntries";
|
import { objectEntries } from "tsafe/objectEntries";
|
||||||
import { type ThemeType } from "./constants";
|
import { type ThemeType } from "./constants";
|
||||||
import { id } from "tsafe/id";
|
import { id } from "tsafe/id";
|
||||||
import { symToStr } from "tsafe/symToStr";
|
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
import { getProxyFetchOptions, type ProxyFetchOptions } from "../tools/fetchProxyOptions";
|
import { getProxyFetchOptions, type ProxyFetchOptions } from "../tools/fetchProxyOptions";
|
||||||
|
|
||||||
@ -49,23 +48,23 @@ export type BuildContext = {
|
|||||||
kcContextExclusionsFtlCode: string | undefined;
|
kcContextExclusionsFtlCode: string | undefined;
|
||||||
environmentVariables: { name: string; default: string }[];
|
environmentVariables: { name: string; default: string }[];
|
||||||
themeSrcDirPath: string;
|
themeSrcDirPath: string;
|
||||||
recordIsImplementedByThemeType: Readonly<Record<ThemeType | "email", boolean>>;
|
implementedThemeTypes: {
|
||||||
|
login: { isImplemented: boolean };
|
||||||
|
email: { isImplemented: boolean };
|
||||||
|
account:
|
||||||
|
| { isImplemented: false }
|
||||||
|
| { isImplemented: true; type: "Single-Page" | "Multi-Page" };
|
||||||
|
};
|
||||||
|
packageJsonFilePath: string;
|
||||||
|
bundler: "vite" | "webpack";
|
||||||
jarTargets: {
|
jarTargets: {
|
||||||
keycloakVersionRange: KeycloakVersionRange;
|
keycloakVersionRange: KeycloakVersionRange;
|
||||||
jarFileBasename: string;
|
jarFileBasename: string;
|
||||||
}[];
|
}[];
|
||||||
bundler:
|
|
||||||
| {
|
|
||||||
type: "vite";
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
type: "webpack";
|
|
||||||
packageJsonDirPath: string;
|
|
||||||
packageJsonScripts: Record<string, string>;
|
|
||||||
};
|
|
||||||
doUseAccountV3: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
assert<Equals<keyof BuildContext["implementedThemeTypes"], ThemeType | "email">>();
|
||||||
|
|
||||||
export type BuildOptions = {
|
export type BuildOptions = {
|
||||||
themeName?: string | string[];
|
themeName?: string | string[];
|
||||||
themeVersion?: string;
|
themeVersion?: string;
|
||||||
@ -76,21 +75,30 @@ export type BuildOptions = {
|
|||||||
loginThemeResourcesFromKeycloakVersion?: string;
|
loginThemeResourcesFromKeycloakVersion?: string;
|
||||||
keycloakifyBuildDirPath?: string;
|
keycloakifyBuildDirPath?: string;
|
||||||
kcContextExclusionsFtl?: string;
|
kcContextExclusionsFtl?: string;
|
||||||
/** https://docs.keycloakify.dev/v/v10/targetting-specific-keycloak-versions */
|
} & BuildOptions.AccountThemeImplAndKeycloakVersionTargets;
|
||||||
keycloakVersionTargets?: BuildOptions.KeycloakVersionTargets;
|
|
||||||
doUseAccountV3?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export namespace BuildOptions {
|
export namespace BuildOptions {
|
||||||
export type KeycloakVersionTargets =
|
export type AccountThemeImplAndKeycloakVersionTargets =
|
||||||
| ({ hasAccountTheme: true } & Record<
|
| AccountThemeImplAndKeycloakVersionTargets.MultiPageApp
|
||||||
KeycloakVersionRange.WithAccountV1Theme,
|
| AccountThemeImplAndKeycloakVersionTargets.SinglePageAppOrNone;
|
||||||
string | boolean
|
|
||||||
>)
|
export namespace AccountThemeImplAndKeycloakVersionTargets {
|
||||||
| ({ hasAccountTheme: false } & Record<
|
export type MultiPageApp = {
|
||||||
KeycloakVersionRange.WithoutAccountV1Theme,
|
accountThemeImplementation: "Multi-Page";
|
||||||
string | boolean
|
keycloakVersionTargets?: Record<
|
||||||
>);
|
KeycloakVersionRange.WithAccountV1Theme,
|
||||||
|
string | boolean
|
||||||
|
>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SinglePageAppOrNone = {
|
||||||
|
accountThemeImplementation: "Single-Page" | "none";
|
||||||
|
keycloakVersionTargets?: Record<
|
||||||
|
KeycloakVersionRange.WithoutAccountV1Theme,
|
||||||
|
string | boolean
|
||||||
|
>;
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ResolvedViteConfig = {
|
export type ResolvedViteConfig = {
|
||||||
@ -136,7 +144,7 @@ export function getBuildContext(params: {
|
|||||||
return { themeSrcDirPath };
|
return { themeSrcDirPath };
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const themeType of [...themeTypes, "email"]) {
|
for (const themeType of [...THEME_TYPES, "email"]) {
|
||||||
if (!fs.existsSync(pathJoin(srcDirPath, themeType))) {
|
if (!fs.existsSync(pathJoin(srcDirPath, themeType))) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -171,18 +179,18 @@ export function getBuildContext(params: {
|
|||||||
cwd: projectDirPath,
|
cwd: projectDirPath,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
[vitePluginSubScriptEnvNames.resolveViteConfig]: "true"
|
[VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG]: "true"
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.toString("utf8");
|
.toString("utf8");
|
||||||
|
|
||||||
assert(
|
assert(
|
||||||
output.includes(vitePluginSubScriptEnvNames.resolveViteConfig),
|
output.includes(VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG),
|
||||||
"Seems like the Keycloakify's Vite plugin is not installed."
|
"Seems like the Keycloakify's Vite plugin is not installed."
|
||||||
);
|
);
|
||||||
|
|
||||||
const resolvedViteConfigStr = output
|
const resolvedViteConfigStr = output
|
||||||
.split(vitePluginSubScriptEnvNames.resolveViteConfig)
|
.split(VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG)
|
||||||
.reverse()[0];
|
.reverse()[0];
|
||||||
|
|
||||||
const resolvedViteConfig: ResolvedViteConfig = JSON.parse(resolvedViteConfigStr);
|
const resolvedViteConfig: ResolvedViteConfig = JSON.parse(resolvedViteConfigStr);
|
||||||
@ -231,7 +239,6 @@ export function getBuildContext(params: {
|
|||||||
projectBuildDirPath?: string;
|
projectBuildDirPath?: string;
|
||||||
staticDirPathInProjectBuildDirPath?: string;
|
staticDirPathInProjectBuildDirPath?: string;
|
||||||
publicDirPath?: string;
|
publicDirPath?: string;
|
||||||
doUseAccountV3?: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type ParsedPackageJson = {
|
type ParsedPackageJson = {
|
||||||
@ -241,85 +248,120 @@ export function getBuildContext(params: {
|
|||||||
keycloakify?: BuildOptions_packageJson;
|
keycloakify?: BuildOptions_packageJson;
|
||||||
};
|
};
|
||||||
|
|
||||||
const zParsedPackageJson = z.object({
|
const zMultiPageApp = (() => {
|
||||||
name: z.string().optional(),
|
type TargetType =
|
||||||
version: z.string().optional(),
|
BuildOptions.AccountThemeImplAndKeycloakVersionTargets.MultiPageApp;
|
||||||
homepage: z.string().optional(),
|
|
||||||
keycloakify: id<z.ZodType<BuildOptions_packageJson>>(
|
|
||||||
(() => {
|
|
||||||
const zBuildOptions_packageJson = z.object({
|
|
||||||
extraThemeProperties: z.array(z.string()).optional(),
|
|
||||||
artifactId: z.string().optional(),
|
|
||||||
groupId: z.string().optional(),
|
|
||||||
loginThemeResourcesFromKeycloakVersion: z.string().optional(),
|
|
||||||
projectBuildDirPath: z.string().optional(),
|
|
||||||
keycloakifyBuildDirPath: z.string().optional(),
|
|
||||||
kcContextExclusionsFtl: z.string().optional(),
|
|
||||||
environmentVariables: z
|
|
||||||
.array(
|
|
||||||
z.object({
|
|
||||||
name: z.string(),
|
|
||||||
default: z.string()
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.optional(),
|
|
||||||
themeName: z.union([z.string(), z.array(z.string())]).optional(),
|
|
||||||
themeVersion: z.string().optional(),
|
|
||||||
staticDirPathInProjectBuildDirPath: z.string().optional(),
|
|
||||||
publicDirPath: z.string().optional(),
|
|
||||||
keycloakVersionTargets: id<
|
|
||||||
z.ZodType<BuildOptions.KeycloakVersionTargets>
|
|
||||||
>(
|
|
||||||
(() => {
|
|
||||||
const zKeycloakVersionTargets = z.union([
|
|
||||||
z.object({
|
|
||||||
hasAccountTheme: z.literal(true),
|
|
||||||
"21-and-below": z.union([
|
|
||||||
z.boolean(),
|
|
||||||
z.string()
|
|
||||||
]),
|
|
||||||
"23": z.union([z.boolean(), z.string()]),
|
|
||||||
"24": z.union([z.boolean(), z.string()]),
|
|
||||||
"25-and-above": z.union([z.boolean(), z.string()])
|
|
||||||
}),
|
|
||||||
z.object({
|
|
||||||
hasAccountTheme: z.literal(false),
|
|
||||||
"21-and-below": z.union([
|
|
||||||
z.boolean(),
|
|
||||||
z.string()
|
|
||||||
]),
|
|
||||||
"22-and-above": z.union([z.boolean(), z.string()])
|
|
||||||
})
|
|
||||||
]);
|
|
||||||
|
|
||||||
{
|
const zTargetType = z.object({
|
||||||
type Got = z.infer<typeof zKeycloakVersionTargets>;
|
accountThemeImplementation: z.literal("Multi-Page"),
|
||||||
type Expected = BuildOptions.KeycloakVersionTargets;
|
keycloakVersionTargets: z
|
||||||
assert<Equals<Got, Expected>>();
|
.object({
|
||||||
}
|
"21-and-below": z.union([z.boolean(), z.string()]),
|
||||||
|
"23": z.union([z.boolean(), z.string()]),
|
||||||
|
"24": z.union([z.boolean(), z.string()]),
|
||||||
|
"25-and-above": z.union([z.boolean(), z.string()])
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
});
|
||||||
|
|
||||||
return zKeycloakVersionTargets;
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
})()
|
|
||||||
).optional(),
|
|
||||||
doUseAccountV3: z.boolean().optional()
|
|
||||||
});
|
|
||||||
|
|
||||||
{
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
type Got = z.infer<typeof zBuildOptions_packageJson>;
|
})();
|
||||||
type Expected = BuildOptions_packageJson;
|
|
||||||
assert<Equals<Got, Expected>>();
|
|
||||||
}
|
|
||||||
|
|
||||||
return zBuildOptions_packageJson;
|
const zSinglePageApp = (() => {
|
||||||
})()
|
type TargetType =
|
||||||
).optional()
|
BuildOptions.AccountThemeImplAndKeycloakVersionTargets.SinglePageAppOrNone;
|
||||||
});
|
|
||||||
|
|
||||||
{
|
const zTargetType = z.object({
|
||||||
type Got = z.infer<typeof zParsedPackageJson>;
|
accountThemeImplementation: z.union([
|
||||||
type Expected = ParsedPackageJson;
|
z.literal("Single-Page"),
|
||||||
assert<Equals<Got, Expected>>();
|
z.literal("none")
|
||||||
}
|
]),
|
||||||
|
keycloakVersionTargets: z
|
||||||
|
.object({
|
||||||
|
"21-and-below": z.union([z.boolean(), z.string()]),
|
||||||
|
"22-and-above": z.union([z.boolean(), z.string()])
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zAccountThemeImplAndKeycloakVersionTargets = (() => {
|
||||||
|
type TargetType = BuildOptions.AccountThemeImplAndKeycloakVersionTargets;
|
||||||
|
|
||||||
|
const zTargetType = z.union([zMultiPageApp, zSinglePageApp]);
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zBuildOptions = (() => {
|
||||||
|
type TargetType = BuildOptions;
|
||||||
|
|
||||||
|
const zTargetType = z.intersection(
|
||||||
|
z.object({
|
||||||
|
themeName: z.union([z.string(), z.array(z.string())]).optional(),
|
||||||
|
themeVersion: z.string().optional(),
|
||||||
|
environmentVariables: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
name: z.string(),
|
||||||
|
default: z.string()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
extraThemeProperties: z.array(z.string()).optional(),
|
||||||
|
artifactId: z.string().optional(),
|
||||||
|
groupId: z.string().optional(),
|
||||||
|
loginThemeResourcesFromKeycloakVersion: z.string().optional(),
|
||||||
|
keycloakifyBuildDirPath: z.string().optional(),
|
||||||
|
kcContextExclusionsFtl: z.string().optional()
|
||||||
|
}),
|
||||||
|
zAccountThemeImplAndKeycloakVersionTargets
|
||||||
|
);
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zBuildOptions_packageJson = (() => {
|
||||||
|
type TargetType = BuildOptions_packageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.intersection(
|
||||||
|
zBuildOptions,
|
||||||
|
z.object({
|
||||||
|
projectBuildDirPath: z.string().optional(),
|
||||||
|
staticDirPathInProjectBuildDirPath: z.string().optional(),
|
||||||
|
publicDirPath: z.string().optional()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zParsedPackageJson = (() => {
|
||||||
|
type TargetType = ParsedPackageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
name: z.string().optional(),
|
||||||
|
version: z.string().optional(),
|
||||||
|
homepage: z.string().optional(),
|
||||||
|
keycloakify: zBuildOptions_packageJson.optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
const configurationPackageJsonFilePath = (() => {
|
const configurationPackageJsonFilePath = (() => {
|
||||||
const rootPackageJsonFilePath = pathJoin(projectDirPath, "package.json");
|
const rootPackageJsonFilePath = pathJoin(projectDirPath, "package.json");
|
||||||
@ -334,17 +376,63 @@ export function getBuildContext(params: {
|
|||||||
);
|
);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const buildOptions = {
|
const bundler = resolvedViteConfig !== undefined ? "vite" : "webpack";
|
||||||
...parsedPackageJson.keycloakify,
|
|
||||||
...resolvedViteConfig?.buildOptions
|
if (bundler === "vite" && parsedPackageJson.keycloakify !== undefined) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(
|
||||||
|
`In vite projects, provide your Keycloakify options in vite.config.ts, not in package.json`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildOptions: BuildOptions = (() => {
|
||||||
|
switch (bundler) {
|
||||||
|
case "vite":
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
return resolvedViteConfig.buildOptions;
|
||||||
|
case "webpack":
|
||||||
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
return parsedPackageJson.keycloakify;
|
||||||
|
}
|
||||||
|
assert<Equals<typeof bundler, never>>(false);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const implementedThemeTypes: BuildContext["implementedThemeTypes"] = {
|
||||||
|
login: {
|
||||||
|
isImplemented: fs.existsSync(pathJoin(themeSrcDirPath, "login"))
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
isImplemented: fs.existsSync(pathJoin(themeSrcDirPath, "email"))
|
||||||
|
},
|
||||||
|
account: (() => {
|
||||||
|
if (buildOptions.accountThemeImplementation === "none") {
|
||||||
|
return { isImplemented: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
isImplemented: true,
|
||||||
|
type: buildOptions.accountThemeImplementation
|
||||||
|
};
|
||||||
|
})()
|
||||||
};
|
};
|
||||||
|
|
||||||
const recordIsImplementedByThemeType = objectFromEntries(
|
if (
|
||||||
(["login", "account", "email"] as const).map(themeType => [
|
implementedThemeTypes.account.isImplemented &&
|
||||||
themeType,
|
!fs.existsSync(pathJoin(themeSrcDirPath, "account"))
|
||||||
fs.existsSync(pathJoin(themeSrcDirPath, themeType))
|
) {
|
||||||
])
|
console.error(
|
||||||
);
|
chalk.red(
|
||||||
|
[
|
||||||
|
`You have set 'accountThemeImplementation' to '${implementedThemeTypes.account.type}'`,
|
||||||
|
`but the 'account' directory is missing in your theme source directory`,
|
||||||
|
"Use the `npx keycloakify initialize-account-theme` command to create it"
|
||||||
|
].join(" ")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(-1);
|
||||||
|
}
|
||||||
|
|
||||||
const themeNames = ((): [string, ...string[]] => {
|
const themeNames = ((): [string, ...string[]] => {
|
||||||
if (buildOptions.themeName === undefined) {
|
if (buildOptions.themeName === undefined) {
|
||||||
@ -371,13 +459,15 @@ export function getBuildContext(params: {
|
|||||||
|
|
||||||
const projectBuildDirPath = (() => {
|
const projectBuildDirPath = (() => {
|
||||||
webpack: {
|
webpack: {
|
||||||
if (resolvedViteConfig !== undefined) {
|
if (bundler !== "webpack") {
|
||||||
break webpack;
|
break webpack;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buildOptions.projectBuildDirPath !== undefined) {
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
|
||||||
|
if (parsedPackageJson.keycloakify.projectBuildDirPath !== undefined) {
|
||||||
return getAbsoluteAndInOsFormatPath({
|
return getAbsoluteAndInOsFormatPath({
|
||||||
pathIsh: buildOptions.projectBuildDirPath,
|
pathIsh: parsedPackageJson.keycloakify.projectBuildDirPath,
|
||||||
cwd: projectDirPath
|
cwd: projectDirPath
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -385,34 +475,15 @@ export function getBuildContext(params: {
|
|||||||
return pathJoin(projectDirPath, "build");
|
return pathJoin(projectDirPath, "build");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
return pathJoin(projectDirPath, resolvedViteConfig.buildDir);
|
return pathJoin(projectDirPath, resolvedViteConfig.buildDir);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const bundler = resolvedViteConfig !== undefined ? "vite" : "webpack";
|
|
||||||
|
|
||||||
const doUseAccountV3 = buildOptions.doUseAccountV3 ?? false;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
bundler:
|
bundler,
|
||||||
resolvedViteConfig !== undefined
|
packageJsonFilePath,
|
||||||
? { type: "vite" }
|
|
||||||
: (() => {
|
|
||||||
const { scripts } = z
|
|
||||||
.object({
|
|
||||||
scripts: z.record(z.string()).optional()
|
|
||||||
})
|
|
||||||
.parse(
|
|
||||||
JSON.parse(
|
|
||||||
fs.readFileSync(packageJsonFilePath).toString("utf8")
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: "webpack",
|
|
||||||
packageJsonDirPath: pathDirname(packageJsonFilePath),
|
|
||||||
packageJsonScripts: scripts ?? {}
|
|
||||||
};
|
|
||||||
})(),
|
|
||||||
themeVersion: buildOptions.themeVersion ?? parsedPackageJson.version ?? "0.0.0",
|
themeVersion: buildOptions.themeVersion ?? parsedPackageJson.version ?? "0.0.0",
|
||||||
themeNames,
|
themeNames,
|
||||||
extraThemeProperties: buildOptions.extraThemeProperties,
|
extraThemeProperties: buildOptions.extraThemeProperties,
|
||||||
@ -436,7 +507,8 @@ export function getBuildContext(params: {
|
|||||||
buildOptions.artifactId ??
|
buildOptions.artifactId ??
|
||||||
`${themeNames[0]}-keycloak-theme`,
|
`${themeNames[0]}-keycloak-theme`,
|
||||||
loginThemeResourcesFromKeycloakVersion:
|
loginThemeResourcesFromKeycloakVersion:
|
||||||
buildOptions.loginThemeResourcesFromKeycloakVersion ?? "24.0.4",
|
buildOptions.loginThemeResourcesFromKeycloakVersion ??
|
||||||
|
LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT,
|
||||||
projectDirPath,
|
projectDirPath,
|
||||||
projectBuildDirPath,
|
projectBuildDirPath,
|
||||||
keycloakifyBuildDirPath: (() => {
|
keycloakifyBuildDirPath: (() => {
|
||||||
@ -463,13 +535,15 @@ export function getBuildContext(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
webpack: {
|
webpack: {
|
||||||
if (resolvedViteConfig !== undefined) {
|
if (bundler !== "webpack") {
|
||||||
break webpack;
|
break webpack;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buildOptions.publicDirPath !== undefined) {
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
|
||||||
|
if (parsedPackageJson.keycloakify.publicDirPath !== undefined) {
|
||||||
return getAbsoluteAndInOsFormatPath({
|
return getAbsoluteAndInOsFormatPath({
|
||||||
pathIsh: buildOptions.publicDirPath,
|
pathIsh: parsedPackageJson.keycloakify.publicDirPath,
|
||||||
cwd: projectDirPath
|
cwd: projectDirPath
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -477,32 +551,31 @@ export function getBuildContext(params: {
|
|||||||
return pathJoin(projectDirPath, "public");
|
return pathJoin(projectDirPath, "public");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
return pathJoin(projectDirPath, resolvedViteConfig.publicDir);
|
return pathJoin(projectDirPath, resolvedViteConfig.publicDir);
|
||||||
})(),
|
})(),
|
||||||
cacheDirPath: (() => {
|
cacheDirPath: pathJoin(
|
||||||
const cacheDirPath = pathJoin(
|
(() => {
|
||||||
(() => {
|
if (process.env.XDG_CACHE_HOME !== undefined) {
|
||||||
if (process.env.XDG_CACHE_HOME !== undefined) {
|
return getAbsoluteAndInOsFormatPath({
|
||||||
return getAbsoluteAndInOsFormatPath({
|
pathIsh: process.env.XDG_CACHE_HOME,
|
||||||
pathIsh: process.env.XDG_CACHE_HOME,
|
cwd: process.cwd()
|
||||||
cwd: process.cwd()
|
});
|
||||||
});
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return pathJoin(
|
return pathJoin(
|
||||||
pathDirname(packageJsonFilePath),
|
pathDirname(packageJsonFilePath),
|
||||||
"node_modules",
|
"node_modules",
|
||||||
".cache"
|
".cache"
|
||||||
);
|
);
|
||||||
})(),
|
})(),
|
||||||
"keycloakify"
|
"keycloakify"
|
||||||
);
|
),
|
||||||
|
|
||||||
return cacheDirPath;
|
|
||||||
})(),
|
|
||||||
urlPathname: (() => {
|
urlPathname: (() => {
|
||||||
webpack: {
|
webpack: {
|
||||||
if (resolvedViteConfig !== undefined) {
|
if (bundler !== "webpack") {
|
||||||
break webpack;
|
break webpack;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -522,23 +595,35 @@ export function getBuildContext(params: {
|
|||||||
return out === "/" ? undefined : out;
|
return out === "/" ? undefined : out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
return resolvedViteConfig.urlPathname;
|
return resolvedViteConfig.urlPathname;
|
||||||
})(),
|
})(),
|
||||||
assetsDirPath: (() => {
|
assetsDirPath: (() => {
|
||||||
webpack: {
|
webpack: {
|
||||||
if (resolvedViteConfig !== undefined) {
|
if (bundler !== "webpack") {
|
||||||
break webpack;
|
break webpack;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buildOptions.staticDirPathInProjectBuildDirPath !== undefined) {
|
assert(parsedPackageJson.keycloakify !== undefined);
|
||||||
|
|
||||||
|
if (
|
||||||
|
parsedPackageJson.keycloakify.staticDirPathInProjectBuildDirPath !==
|
||||||
|
undefined
|
||||||
|
) {
|
||||||
getAbsoluteAndInOsFormatPath({
|
getAbsoluteAndInOsFormatPath({
|
||||||
pathIsh: buildOptions.staticDirPathInProjectBuildDirPath,
|
pathIsh:
|
||||||
|
parsedPackageJson.keycloakify
|
||||||
|
.staticDirPathInProjectBuildDirPath,
|
||||||
cwd: projectBuildDirPath
|
cwd: projectBuildDirPath
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return pathJoin(projectBuildDirPath, "static");
|
return pathJoin(projectBuildDirPath, "static");
|
||||||
}
|
}
|
||||||
|
assert(bundler === "vite");
|
||||||
|
assert(resolvedViteConfig !== undefined);
|
||||||
|
|
||||||
return pathJoin(projectBuildDirPath, resolvedViteConfig.assetsDir);
|
return pathJoin(projectBuildDirPath, resolvedViteConfig.assetsDir);
|
||||||
})(),
|
})(),
|
||||||
@ -559,7 +644,7 @@ export function getBuildContext(params: {
|
|||||||
return buildOptions.kcContextExclusionsFtl;
|
return buildOptions.kcContextExclusionsFtl;
|
||||||
})(),
|
})(),
|
||||||
environmentVariables: buildOptions.environmentVariables ?? [],
|
environmentVariables: buildOptions.environmentVariables ?? [],
|
||||||
recordIsImplementedByThemeType,
|
implementedThemeTypes,
|
||||||
themeSrcDirPath,
|
themeSrcDirPath,
|
||||||
fetchOptions: getProxyFetchOptions({
|
fetchOptions: getProxyFetchOptions({
|
||||||
npmConfigGetCwd: (function callee(upCount: number): string {
|
npmConfigGetCwd: (function callee(upCount: number): string {
|
||||||
@ -575,7 +660,7 @@ export function getBuildContext(params: {
|
|||||||
try {
|
try {
|
||||||
child_process.execSync("npm config get", {
|
child_process.execSync("npm config get", {
|
||||||
cwd: dirPath,
|
cwd: dirPath,
|
||||||
stdio: "ignore"
|
stdio: "pipe"
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (String(error).includes("ENOWORKSPACES")) {
|
if (String(error).includes("ENOWORKSPACES")) {
|
||||||
@ -594,7 +679,8 @@ export function getBuildContext(params: {
|
|||||||
|
|
||||||
build_for_specific_keycloak_major_version: {
|
build_for_specific_keycloak_major_version: {
|
||||||
const buildForKeycloakMajorVersionNumber = (() => {
|
const buildForKeycloakMajorVersionNumber = (() => {
|
||||||
const envValue = process.env[buildForKeycloakMajorVersionEnvName];
|
const envValue =
|
||||||
|
process.env[BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME];
|
||||||
|
|
||||||
if (envValue === undefined) {
|
if (envValue === undefined) {
|
||||||
return undefined;
|
return undefined;
|
||||||
@ -612,10 +698,10 @@ export function getBuildContext(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const keycloakVersionRange: KeycloakVersionRange = (() => {
|
const keycloakVersionRange: KeycloakVersionRange = (() => {
|
||||||
const doesImplementAccountV1Theme =
|
if (
|
||||||
!doUseAccountV3 && recordIsImplementedByThemeType.account;
|
implementedThemeTypes.account.isImplemented &&
|
||||||
|
implementedThemeTypes.account.type === "Multi-Page"
|
||||||
if (doesImplementAccountV1Theme) {
|
) {
|
||||||
const keycloakVersionRange = (() => {
|
const keycloakVersionRange = (() => {
|
||||||
if (buildForKeycloakMajorVersionNumber <= 21) {
|
if (buildForKeycloakMajorVersionNumber <= 21) {
|
||||||
return "21-and-below" as const;
|
return "21-and-below" as const;
|
||||||
@ -702,7 +788,10 @@ export function getBuildContext(params: {
|
|||||||
const jarTargets_default = (() => {
|
const jarTargets_default = (() => {
|
||||||
const jarTargets: BuildContext["jarTargets"] = [];
|
const jarTargets: BuildContext["jarTargets"] = [];
|
||||||
|
|
||||||
if (!doUseAccountV3 && recordIsImplementedByThemeType.account) {
|
if (
|
||||||
|
implementedThemeTypes.account.isImplemented &&
|
||||||
|
implementedThemeTypes.account.type === "Multi-Page"
|
||||||
|
) {
|
||||||
for (const keycloakVersionRange of [
|
for (const keycloakVersionRange of [
|
||||||
"21-and-below",
|
"21-and-below",
|
||||||
"23",
|
"23",
|
||||||
@ -747,79 +836,11 @@ export function getBuildContext(params: {
|
|||||||
return jarTargets_default;
|
return jarTargets_default;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
|
||||||
buildOptions.keycloakVersionTargets.hasAccountTheme !== doUseAccountV3
|
|
||||||
? false
|
|
||||||
: recordIsImplementedByThemeType.account
|
|
||||||
) {
|
|
||||||
console.log(
|
|
||||||
chalk.red(
|
|
||||||
(() => {
|
|
||||||
const { keycloakVersionTargets } = buildOptions;
|
|
||||||
|
|
||||||
let message = `Bad ${symToStr({ keycloakVersionTargets })} configuration.\n`;
|
|
||||||
|
|
||||||
if (keycloakVersionTargets.hasAccountTheme) {
|
|
||||||
message +=
|
|
||||||
"Your codebase does not seem to implement an account theme ";
|
|
||||||
} else {
|
|
||||||
message += "Your codebase implements an account theme ";
|
|
||||||
}
|
|
||||||
|
|
||||||
const { hasAccountTheme } = keycloakVersionTargets;
|
|
||||||
|
|
||||||
message += `but you have set ${symToStr({ keycloakVersionTargets })}.${symToStr({ hasAccountTheme })}`;
|
|
||||||
message += ` to ${hasAccountTheme} in your `;
|
|
||||||
message += (() => {
|
|
||||||
switch (bundler) {
|
|
||||||
case "vite":
|
|
||||||
return "vite.config.ts";
|
|
||||||
case "webpack":
|
|
||||||
return "package.json";
|
|
||||||
}
|
|
||||||
assert<Equals<typeof bundler, never>>(false);
|
|
||||||
})();
|
|
||||||
message += `. Please set it to ${!hasAccountTheme} `;
|
|
||||||
message +=
|
|
||||||
"and fill up the relevant keycloak version ranges.\n";
|
|
||||||
message += "Example:\n";
|
|
||||||
message += JSON.stringify(
|
|
||||||
id<Pick<BuildOptions, "keycloakVersionTargets">>({
|
|
||||||
keycloakVersionTargets: {
|
|
||||||
hasAccountTheme:
|
|
||||||
recordIsImplementedByThemeType.account,
|
|
||||||
...objectFromEntries(
|
|
||||||
jarTargets_default.map(
|
|
||||||
({
|
|
||||||
keycloakVersionRange,
|
|
||||||
jarFileBasename
|
|
||||||
}) => [
|
|
||||||
keycloakVersionRange,
|
|
||||||
jarFileBasename
|
|
||||||
]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
null,
|
|
||||||
2
|
|
||||||
);
|
|
||||||
message +=
|
|
||||||
"\nSee: https://docs.keycloakify.dev/v/v10/targetting-specific-keycloak-versions";
|
|
||||||
|
|
||||||
return message;
|
|
||||||
})()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const jarTargets: BuildContext["jarTargets"] = [];
|
const jarTargets: BuildContext["jarTargets"] = [];
|
||||||
|
|
||||||
const { hasAccountTheme, ...rest } = buildOptions.keycloakVersionTargets;
|
for (const [keycloakVersionRange, jarNameOrBoolean] of objectEntries(
|
||||||
|
buildOptions.keycloakVersionTargets
|
||||||
for (const [keycloakVersionRange, jarNameOrBoolean] of objectEntries(rest)) {
|
)) {
|
||||||
if (jarNameOrBoolean === false) {
|
if (jarNameOrBoolean === false) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -870,7 +891,6 @@ export function getBuildContext(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return jarTargets;
|
return jarTargets;
|
||||||
})(),
|
})()
|
||||||
doUseAccountV3
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,22 @@
|
|||||||
export const keycloak_resources = "keycloak-resources";
|
export const KEYCLOAK_RESOURCES = "keycloak-resources";
|
||||||
export const resources_common = "resources-common";
|
export const RESOURCES_COMMON = "resources-common";
|
||||||
export const lastKeycloakVersionWithAccountV1 = "21.1.2";
|
export const LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1 = "21.1.2";
|
||||||
export const basenameOfTheKeycloakifyResourcesDir = "dist";
|
export const BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR = "dist";
|
||||||
|
|
||||||
export const themeTypes = ["login", "account"] as const;
|
export const THEME_TYPES = ["login", "account"] as const;
|
||||||
export const accountV1ThemeName = "account-v1";
|
export const ACCOUNT_V1_THEME_NAME = "account-v1";
|
||||||
|
|
||||||
export type ThemeType = (typeof themeTypes)[number];
|
export type ThemeType = (typeof THEME_TYPES)[number];
|
||||||
|
|
||||||
export const vitePluginSubScriptEnvNames = {
|
export const VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES = {
|
||||||
runPostBuildScript: "KEYCLOAKIFY_RUN_POST_BUILD_SCRIPT",
|
RUN_POST_BUILD_SCRIPT: "KEYCLOAKIFY_RUN_POST_BUILD_SCRIPT",
|
||||||
resolveViteConfig: "KEYCLOAKIFY_RESOLVE_VITE_CONFIG"
|
RESOLVE_VITE_CONFIG: "KEYCLOAKIFY_RESOLVE_VITE_CONFIG"
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export const buildForKeycloakMajorVersionEnvName =
|
export const BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME =
|
||||||
"KEYCLOAKIFY_BUILD_FOR_KEYCLOAK_MAJOR_VERSION";
|
"KEYCLOAKIFY_BUILD_FOR_KEYCLOAK_MAJOR_VERSION";
|
||||||
|
|
||||||
export const loginThemePageIds = [
|
export const LOGIN_THEME_PAGE_IDS = [
|
||||||
"login.ftl",
|
"login.ftl",
|
||||||
"login-username.ftl",
|
"login-username.ftl",
|
||||||
"login-password.ftl",
|
"login-password.ftl",
|
||||||
@ -53,7 +53,7 @@ export const loginThemePageIds = [
|
|||||||
"webauthn-error.ftl"
|
"webauthn-error.ftl"
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const accountThemePageIds = [
|
export const ACCOUNT_THEME_PAGE_IDS = [
|
||||||
"password.ftl",
|
"password.ftl",
|
||||||
"account.ftl",
|
"account.ftl",
|
||||||
"sessions.ftl",
|
"sessions.ftl",
|
||||||
@ -63,9 +63,11 @@ export const accountThemePageIds = [
|
|||||||
"federatedIdentity.ftl"
|
"federatedIdentity.ftl"
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type LoginThemePageId = (typeof loginThemePageIds)[number];
|
export type LoginThemePageId = (typeof LOGIN_THEME_PAGE_IDS)[number];
|
||||||
export type AccountThemePageId = (typeof accountThemePageIds)[number];
|
export type AccountThemePageId = (typeof ACCOUNT_THEME_PAGE_IDS)[number];
|
||||||
|
|
||||||
export const containerName = "keycloak-keycloakify";
|
export const CONTAINER_NAME = "keycloak-keycloakify";
|
||||||
|
|
||||||
export const fallbackLanguageTag = "en";
|
export const FALLBACK_LANGUAGE_TAG = "en";
|
||||||
|
|
||||||
|
export const LOGIN_THEME_RESOURCES_FROMkEYCLOAK_VERSION_DEFAULT = "24.0.4";
|
||||||
|
@ -4,9 +4,9 @@ import {
|
|||||||
} from "./downloadKeycloakStaticResources";
|
} from "./downloadKeycloakStaticResources";
|
||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
import {
|
import {
|
||||||
themeTypes,
|
THEME_TYPES,
|
||||||
keycloak_resources,
|
KEYCLOAK_RESOURCES,
|
||||||
lastKeycloakVersionWithAccountV1
|
LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1
|
||||||
} from "../shared/constants";
|
} from "../shared/constants";
|
||||||
import { readThisNpmPackageVersion } from "../tools/readThisNpmPackageVersion";
|
import { readThisNpmPackageVersion } from "../tools/readThisNpmPackageVersion";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
@ -26,7 +26,7 @@ export async function copyKeycloakResourcesToPublic(params: {
|
|||||||
}) {
|
}) {
|
||||||
const { buildContext } = params;
|
const { buildContext } = params;
|
||||||
|
|
||||||
const destDirPath = pathJoin(buildContext.publicDirPath, keycloak_resources);
|
const destDirPath = pathJoin(buildContext.publicDirPath, KEYCLOAK_RESOURCES);
|
||||||
|
|
||||||
const keycloakifyBuildinfoFilePath = pathJoin(destDirPath, "keycloakify.buildinfo");
|
const keycloakifyBuildinfoFilePath = pathJoin(destDirPath, "keycloakify.buildinfo");
|
||||||
|
|
||||||
@ -66,14 +66,14 @@ export async function copyKeycloakResourcesToPublic(params: {
|
|||||||
|
|
||||||
fs.writeFileSync(pathJoin(destDirPath, ".gitignore"), Buffer.from("*", "utf8"));
|
fs.writeFileSync(pathJoin(destDirPath, ".gitignore"), Buffer.from("*", "utf8"));
|
||||||
|
|
||||||
for (const themeType of themeTypes) {
|
for (const themeType of THEME_TYPES) {
|
||||||
await downloadKeycloakStaticResources({
|
await downloadKeycloakStaticResources({
|
||||||
keycloakVersion: (() => {
|
keycloakVersion: (() => {
|
||||||
switch (themeType) {
|
switch (themeType) {
|
||||||
case "login":
|
case "login":
|
||||||
return buildContext.loginThemeResourcesFromKeycloakVersion;
|
return buildContext.loginThemeResourcesFromKeycloakVersion;
|
||||||
case "account":
|
case "account":
|
||||||
return lastKeycloakVersionWithAccountV1;
|
return LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1;
|
||||||
}
|
}
|
||||||
})(),
|
})(),
|
||||||
themeType,
|
themeType,
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { join as pathJoin, relative as pathRelative } from "path";
|
import { join as pathJoin, relative as pathRelative } from "path";
|
||||||
import { type BuildContext } from "./buildContext";
|
import { type BuildContext } from "./buildContext";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { lastKeycloakVersionWithAccountV1 } from "./constants";
|
import { LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1 } from "./constants";
|
||||||
import { downloadAndExtractArchive } from "../tools/downloadAndExtractArchive";
|
import { downloadAndExtractArchive } from "../tools/downloadAndExtractArchive";
|
||||||
|
|
||||||
export type BuildContextLike = {
|
export type BuildContextLike = {
|
||||||
@ -17,14 +17,14 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
}): Promise<{ defaultThemeDirPath: string }> {
|
}): Promise<{ defaultThemeDirPath: string }> {
|
||||||
const { keycloakVersion, buildContext } = params;
|
const { keycloakVersion, buildContext } = params;
|
||||||
|
|
||||||
let kcNodeModulesKeepFilePaths: string[] | undefined = undefined;
|
let kcNodeModulesKeepFilePaths: Set<string> | undefined = undefined;
|
||||||
let kcNodeModulesKeepFilePaths_lastAccountV1: string[] | undefined = undefined;
|
let kcNodeModulesKeepFilePaths_lastAccountV1: Set<string> | undefined = undefined;
|
||||||
|
|
||||||
const { extractedDirPath } = await downloadAndExtractArchive({
|
const { extractedDirPath } = await downloadAndExtractArchive({
|
||||||
url: `https://repo1.maven.org/maven2/org/keycloak/keycloak-themes/${keycloakVersion}/keycloak-themes-${keycloakVersion}.jar`,
|
url: `https://repo1.maven.org/maven2/org/keycloak/keycloak-themes/${keycloakVersion}/keycloak-themes-${keycloakVersion}.jar`,
|
||||||
cacheDirPath: buildContext.cacheDirPath,
|
cacheDirPath: buildContext.cacheDirPath,
|
||||||
fetchOptions: buildContext.fetchOptions,
|
fetchOptions: buildContext.fetchOptions,
|
||||||
uniqueIdOfOnOnArchiveFile: "downloadKeycloakDefaultTheme",
|
uniqueIdOfOnArchiveFile: "downloadKeycloakDefaultTheme",
|
||||||
onArchiveFile: async params => {
|
onArchiveFile: async params => {
|
||||||
const fileRelativePath = pathRelative("theme", params.fileRelativePath);
|
const fileRelativePath = pathRelative("theme", params.fileRelativePath);
|
||||||
|
|
||||||
@ -43,7 +43,7 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
last_account_v1_transformations: {
|
last_account_v1_transformations: {
|
||||||
if (lastKeycloakVersionWithAccountV1 !== keycloakVersion) {
|
if (LAST_KEYCLOAK_VERSION_WITH_ACCOUNT_V1 !== keycloakVersion) {
|
||||||
break last_account_v1_transformations;
|
break last_account_v1_transformations;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,16 +72,19 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
skip_node_modules: {
|
skip_node_modules: {
|
||||||
if (
|
const nodeModulesRelativeDirPath = pathJoin(
|
||||||
!fileRelativePath.startsWith(
|
"keycloak",
|
||||||
pathJoin("keycloak", "common", "resources", "node_modules")
|
"common",
|
||||||
)
|
"resources",
|
||||||
) {
|
"node_modules"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!fileRelativePath.startsWith(nodeModulesRelativeDirPath)) {
|
||||||
break skip_node_modules;
|
break skip_node_modules;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (kcNodeModulesKeepFilePaths_lastAccountV1 === undefined) {
|
if (kcNodeModulesKeepFilePaths_lastAccountV1 === undefined) {
|
||||||
kcNodeModulesKeepFilePaths_lastAccountV1 = [
|
kcNodeModulesKeepFilePaths_lastAccountV1 = new Set([
|
||||||
pathJoin("patternfly", "dist", "css", "patternfly.min.css"),
|
pathJoin("patternfly", "dist", "css", "patternfly.min.css"),
|
||||||
pathJoin(
|
pathJoin(
|
||||||
"patternfly",
|
"patternfly",
|
||||||
@ -125,13 +128,19 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
"fonts",
|
"fonts",
|
||||||
"PatternFlyIcons-webfont.woff"
|
"PatternFlyIcons-webfont.woff"
|
||||||
)
|
)
|
||||||
];
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const keepPath of kcNodeModulesKeepFilePaths_lastAccountV1) {
|
const fileRelativeToNodeModulesPath = fileRelativePath.substring(
|
||||||
if (fileRelativePath.endsWith(keepPath)) {
|
nodeModulesRelativeDirPath.length + 1
|
||||||
break skip_node_modules;
|
);
|
||||||
}
|
|
||||||
|
if (
|
||||||
|
kcNodeModulesKeepFilePaths_lastAccountV1.has(
|
||||||
|
fileRelativeToNodeModulesPath
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
break skip_node_modules;
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
@ -165,16 +174,19 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
skip_node_modules: {
|
skip_node_modules: {
|
||||||
if (
|
const nodeModulesRelativeDirPath = pathJoin(
|
||||||
!fileRelativePath.startsWith(
|
"keycloak",
|
||||||
pathJoin("keycloak", "common", "resources", "node_modules")
|
"common",
|
||||||
)
|
"resources",
|
||||||
) {
|
"node_modules"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!fileRelativePath.startsWith(nodeModulesRelativeDirPath)) {
|
||||||
break skip_node_modules;
|
break skip_node_modules;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (kcNodeModulesKeepFilePaths === undefined) {
|
if (kcNodeModulesKeepFilePaths === undefined) {
|
||||||
kcNodeModulesKeepFilePaths = [
|
kcNodeModulesKeepFilePaths = new Set([
|
||||||
pathJoin("@patternfly", "patternfly", "patternfly.min.css"),
|
pathJoin("@patternfly", "patternfly", "patternfly.min.css"),
|
||||||
pathJoin("patternfly", "dist", "css", "patternfly.min.css"),
|
pathJoin("patternfly", "dist", "css", "patternfly.min.css"),
|
||||||
pathJoin(
|
pathJoin(
|
||||||
@ -231,15 +243,23 @@ export async function downloadKeycloakDefaultTheme(params: {
|
|||||||
"fonts",
|
"fonts",
|
||||||
"PatternFlyIcons-webfont.woff"
|
"PatternFlyIcons-webfont.woff"
|
||||||
),
|
),
|
||||||
|
pathJoin(
|
||||||
|
"patternfly",
|
||||||
|
"dist",
|
||||||
|
"fonts",
|
||||||
|
"OpenSans-Semibold-webfont.woff2"
|
||||||
|
),
|
||||||
pathJoin("patternfly", "dist", "img", "bg-login.jpg"),
|
pathJoin("patternfly", "dist", "img", "bg-login.jpg"),
|
||||||
pathJoin("jquery", "dist", "jquery.min.js")
|
pathJoin("jquery", "dist", "jquery.min.js")
|
||||||
];
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const keepPath of kcNodeModulesKeepFilePaths) {
|
const fileRelativeToNodeModulesPath = fileRelativePath.substring(
|
||||||
if (fileRelativePath.endsWith(keepPath)) {
|
nodeModulesRelativeDirPath.length + 1
|
||||||
break skip_node_modules;
|
);
|
||||||
}
|
|
||||||
|
if (kcNodeModulesKeepFilePaths.has(fileRelativeToNodeModulesPath)) {
|
||||||
|
break skip_node_modules;
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
@ -4,7 +4,7 @@ import {
|
|||||||
downloadKeycloakDefaultTheme,
|
downloadKeycloakDefaultTheme,
|
||||||
type BuildContextLike as BuildContextLike_downloadKeycloakDefaultTheme
|
type BuildContextLike as BuildContextLike_downloadKeycloakDefaultTheme
|
||||||
} from "./downloadKeycloakDefaultTheme";
|
} from "./downloadKeycloakDefaultTheme";
|
||||||
import { resources_common, type ThemeType } from "./constants";
|
import { RESOURCES_COMMON, type ThemeType } from "./constants";
|
||||||
import type { BuildContext } from "./buildContext";
|
import type { BuildContext } from "./buildContext";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import { existsAsync } from "../tools/fs.existsAsync";
|
import { existsAsync } from "../tools/fs.existsAsync";
|
||||||
@ -48,6 +48,6 @@ export async function downloadKeycloakStaticResources(params: {
|
|||||||
|
|
||||||
transformCodebase({
|
transformCodebase({
|
||||||
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
srcDirPath: pathJoin(defaultThemeDirPath, "keycloak", "common", "resources"),
|
||||||
destDirPath: pathJoin(resourcesDirPath, resources_common)
|
destDirPath: pathJoin(resourcesDirPath, RESOURCES_COMMON)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,21 @@
|
|||||||
import { assert } from "tsafe/assert";
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
import type { BuildContext } from "./buildContext";
|
import type { BuildContext } from "./buildContext";
|
||||||
import * as fs from "fs/promises";
|
import * as fs from "fs/promises";
|
||||||
import { join as pathJoin } from "path";
|
import { join as pathJoin } from "path";
|
||||||
import { existsAsync } from "../tools/fs.existsAsync";
|
import { existsAsync } from "../tools/fs.existsAsync";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
export type BuildContextLike = {
|
export type BuildContextLike = {
|
||||||
projectDirPath: string;
|
projectDirPath: string;
|
||||||
themeNames: string[];
|
themeNames: string[];
|
||||||
environmentVariables: { name: string; default: string }[];
|
environmentVariables: { name: string; default: string }[];
|
||||||
themeSrcDirPath: string;
|
themeSrcDirPath: string;
|
||||||
|
implementedThemeTypes: Pick<
|
||||||
|
BuildContext["implementedThemeTypes"],
|
||||||
|
"login" | "account"
|
||||||
|
>;
|
||||||
|
packageJsonFilePath: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildContext extends BuildContextLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
@ -18,12 +25,53 @@ export async function generateKcGenTs(params: {
|
|||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const { buildContext } = params;
|
const { buildContext } = params;
|
||||||
|
|
||||||
const filePath = pathJoin(buildContext.themeSrcDirPath, "kc.gen.ts");
|
const isReactProject: boolean = await (async () => {
|
||||||
|
const parsedPackageJson = await (async () => {
|
||||||
|
type ParsedPackageJson = {
|
||||||
|
dependencies?: Record<string, string>;
|
||||||
|
devDependencies?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zParsedPackageJson = (() => {
|
||||||
|
type TargetType = ParsedPackageJson;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
dependencies: z.record(z.string()).optional(),
|
||||||
|
devDependencies: z.record(z.string()).optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
return zParsedPackageJson.parse(
|
||||||
|
JSON.parse(
|
||||||
|
(await fs.readFile(buildContext.packageJsonFilePath)).toString("utf8")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
...parsedPackageJson.dependencies,
|
||||||
|
...parsedPackageJson.devDependencies
|
||||||
|
}.react !== undefined
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const filePath = pathJoin(
|
||||||
|
buildContext.themeSrcDirPath,
|
||||||
|
`kc.gen.ts${isReactProject ? "x" : ""}`
|
||||||
|
);
|
||||||
|
|
||||||
const currentContent = (await existsAsync(filePath))
|
const currentContent = (await existsAsync(filePath))
|
||||||
? await fs.readFile(filePath)
|
? await fs.readFile(filePath)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
|
const hasLoginTheme = buildContext.implementedThemeTypes.login.isImplemented;
|
||||||
|
const hasAccountTheme = buildContext.implementedThemeTypes.account.isImplemented;
|
||||||
|
|
||||||
const newContent = Buffer.from(
|
const newContent = Buffer.from(
|
||||||
[
|
[
|
||||||
`/* prettier-ignore-start */`,
|
`/* prettier-ignore-start */`,
|
||||||
@ -36,6 +84,8 @@ export async function generateKcGenTs(params: {
|
|||||||
``,
|
``,
|
||||||
`// This file is auto-generated by Keycloakify`,
|
`// This file is auto-generated by Keycloakify`,
|
||||||
``,
|
``,
|
||||||
|
isReactProject && `import { lazy, Suspense, type ReactNode } from "react";`,
|
||||||
|
``,
|
||||||
`export type ThemeName = ${buildContext.themeNames.map(themeName => `"${themeName}"`).join(" | ")};`,
|
`export type ThemeName = ${buildContext.themeNames.map(themeName => `"${themeName}"`).join(" | ")};`,
|
||||||
``,
|
``,
|
||||||
`export const themeNames: ThemeName[] = [${buildContext.themeNames.map(themeName => `"${themeName}"`).join(", ")}];`,
|
`export const themeNames: ThemeName[] = [${buildContext.themeNames.map(themeName => `"${themeName}"`).join(", ")}];`,
|
||||||
@ -54,9 +104,52 @@ export async function generateKcGenTs(params: {
|
|||||||
2
|
2
|
||||||
)};`,
|
)};`,
|
||||||
``,
|
``,
|
||||||
|
`export type KcContext =`,
|
||||||
|
hasLoginTheme && ` | import("./login/KcContext").KcContext`,
|
||||||
|
hasAccountTheme && ` | import("./account/KcContext").KcContext`,
|
||||||
|
` ;`,
|
||||||
|
``,
|
||||||
|
`declare global {`,
|
||||||
|
` interface Window {`,
|
||||||
|
` kcContext?: KcContext;`,
|
||||||
|
` }`,
|
||||||
|
`}`,
|
||||||
|
``,
|
||||||
|
...(!isReactProject
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
hasLoginTheme &&
|
||||||
|
`export const KcLoginPage = lazy(() => import("./login/KcPage"));`,
|
||||||
|
hasAccountTheme &&
|
||||||
|
`export const KcAccountPage = lazy(() => import("./account/KcPage"));`,
|
||||||
|
``,
|
||||||
|
`export function KcPage(`,
|
||||||
|
` props: {`,
|
||||||
|
` kcContext: KcContext;`,
|
||||||
|
` fallback?: ReactNode;`,
|
||||||
|
` }`,
|
||||||
|
`) {`,
|
||||||
|
` const { kcContext, fallback } = props;`,
|
||||||
|
` return (`,
|
||||||
|
` <Suspense fallback={fallback}>`,
|
||||||
|
` {(() => {`,
|
||||||
|
` switch (kcContext.themeType) {`,
|
||||||
|
hasLoginTheme &&
|
||||||
|
` case "login": return <KcLoginPage kcContext={kcContext} />;`,
|
||||||
|
hasAccountTheme &&
|
||||||
|
` case "account": return <KcAccountPage kcContext={kcContext} />;`,
|
||||||
|
` }`,
|
||||||
|
` })()}`,
|
||||||
|
` </Suspense>`,
|
||||||
|
` );`,
|
||||||
|
`}`
|
||||||
|
]),
|
||||||
|
``,
|
||||||
`/* prettier-ignore-end */`,
|
`/* prettier-ignore-end */`,
|
||||||
``
|
``
|
||||||
].join("\n"),
|
]
|
||||||
|
.filter(item => typeof item === "string")
|
||||||
|
.join("\n"),
|
||||||
"utf8"
|
"utf8"
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -65,4 +158,18 @@ export async function generateKcGenTs(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await fs.writeFile(filePath, newContent);
|
await fs.writeFile(filePath, newContent);
|
||||||
|
|
||||||
|
delete_legacy_file: {
|
||||||
|
if (!isReactProject) {
|
||||||
|
break delete_legacy_file;
|
||||||
|
}
|
||||||
|
|
||||||
|
const legacyFilePath = filePath.replace(/tsx$/, "ts");
|
||||||
|
|
||||||
|
if (!(await existsAsync(legacyFilePath))) {
|
||||||
|
break delete_legacy_file;
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.unlink(legacyFilePath);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
194
src/bin/shared/getLatestsSemVersionedTag.ts
Normal file
194
src/bin/shared/getLatestsSemVersionedTag.ts
Normal file
@ -0,0 +1,194 @@
|
|||||||
|
import { getLatestsSemVersionedTagFactory } from "../tools/octokit-addons/getLatestsSemVersionedTag";
|
||||||
|
import { Octokit } from "@octokit/rest";
|
||||||
|
import type { ReturnType } from "tsafe";
|
||||||
|
import type { Param0 } from "tsafe";
|
||||||
|
import { join as pathJoin, dirname as pathDirname } from "path";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { assert, type Equals } from "tsafe/assert";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
import type { SemVer } from "../tools/SemVer";
|
||||||
|
import { same } from "evt/tools/inDepth/same";
|
||||||
|
import type { BuildContext } from "./buildContext";
|
||||||
|
|
||||||
|
type GetLatestsSemVersionedTag = ReturnType<
|
||||||
|
typeof getLatestsSemVersionedTagFactory
|
||||||
|
>["getLatestsSemVersionedTag"];
|
||||||
|
|
||||||
|
type Params = Param0<GetLatestsSemVersionedTag>;
|
||||||
|
type R = ReturnType<GetLatestsSemVersionedTag>;
|
||||||
|
|
||||||
|
let getLatestsSemVersionedTag_stateless: GetLatestsSemVersionedTag | undefined =
|
||||||
|
undefined;
|
||||||
|
|
||||||
|
const CACHE_VERSION = 1;
|
||||||
|
|
||||||
|
type Cache = {
|
||||||
|
version: typeof CACHE_VERSION;
|
||||||
|
entries: {
|
||||||
|
time: number;
|
||||||
|
params: Params;
|
||||||
|
result: R;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BuildContextLike = {
|
||||||
|
cacheDirPath: string;
|
||||||
|
fetchOptions: BuildContext["fetchOptions"];
|
||||||
|
};
|
||||||
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
|
export async function getLatestsSemVersionedTag({
|
||||||
|
buildContext,
|
||||||
|
...params
|
||||||
|
}: Params & {
|
||||||
|
buildContext: BuildContextLike;
|
||||||
|
}): Promise<R> {
|
||||||
|
const cacheFilePath = pathJoin(
|
||||||
|
buildContext.cacheDirPath,
|
||||||
|
"latest-sem-versioned-tags.json"
|
||||||
|
);
|
||||||
|
|
||||||
|
const cacheLookupResult = (() => {
|
||||||
|
const getResult_currentCache = (currentCacheEntries: Cache["entries"]) => ({
|
||||||
|
hasCachedResult: false as const,
|
||||||
|
currentCache: {
|
||||||
|
version: CACHE_VERSION,
|
||||||
|
entries: currentCacheEntries
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!fs.existsSync(cacheFilePath)) {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache_json;
|
||||||
|
|
||||||
|
try {
|
||||||
|
cache_json = fs.readFileSync(cacheFilePath).toString("utf8");
|
||||||
|
} catch {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache_json_parsed: unknown;
|
||||||
|
|
||||||
|
try {
|
||||||
|
cache_json_parsed = JSON.parse(cache_json);
|
||||||
|
} catch {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const zSemVer = (() => {
|
||||||
|
type TargetType = SemVer;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
major: z.number(),
|
||||||
|
minor: z.number(),
|
||||||
|
patch: z.number(),
|
||||||
|
rc: z.number().optional(),
|
||||||
|
parsedFrom: z.string()
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const zCache = (() => {
|
||||||
|
type TargetType = Cache;
|
||||||
|
|
||||||
|
const zTargetType = z.object({
|
||||||
|
version: z.literal(CACHE_VERSION),
|
||||||
|
entries: z.array(
|
||||||
|
z.object({
|
||||||
|
time: z.number(),
|
||||||
|
params: z.object({
|
||||||
|
owner: z.string(),
|
||||||
|
repo: z.string(),
|
||||||
|
count: z.number(),
|
||||||
|
doIgnoreReleaseCandidates: z.boolean()
|
||||||
|
}),
|
||||||
|
result: z.array(
|
||||||
|
z.object({
|
||||||
|
tag: z.string(),
|
||||||
|
version: zSemVer
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
assert<Equals<z.infer<typeof zTargetType>, TargetType>>();
|
||||||
|
|
||||||
|
return id<z.ZodType<TargetType>>(zTargetType);
|
||||||
|
})();
|
||||||
|
|
||||||
|
let cache: Cache;
|
||||||
|
|
||||||
|
try {
|
||||||
|
cache = zCache.parse(cache_json_parsed);
|
||||||
|
} catch {
|
||||||
|
return getResult_currentCache([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheEntry = cache.entries.find(e => same(e.params, params));
|
||||||
|
|
||||||
|
if (cacheEntry === undefined) {
|
||||||
|
return getResult_currentCache(cache.entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Date.now() - cacheEntry.time > 3_600_000) {
|
||||||
|
return getResult_currentCache(cache.entries.filter(e => e !== cacheEntry));
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
hasCachedResult: true as const,
|
||||||
|
cachedResult: cacheEntry.result
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (cacheLookupResult.hasCachedResult) {
|
||||||
|
return cacheLookupResult.cachedResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { currentCache } = cacheLookupResult;
|
||||||
|
|
||||||
|
getLatestsSemVersionedTag_stateless ??= (() => {
|
||||||
|
const octokit = (() => {
|
||||||
|
const githubToken = process.env.GITHUB_TOKEN;
|
||||||
|
|
||||||
|
const octokit = new Octokit({
|
||||||
|
...(githubToken === undefined ? {} : { auth: githubToken }),
|
||||||
|
request: buildContext.fetchOptions
|
||||||
|
});
|
||||||
|
|
||||||
|
return octokit;
|
||||||
|
})();
|
||||||
|
|
||||||
|
const { getLatestsSemVersionedTag } = getLatestsSemVersionedTagFactory({
|
||||||
|
octokit
|
||||||
|
});
|
||||||
|
|
||||||
|
return getLatestsSemVersionedTag;
|
||||||
|
})();
|
||||||
|
|
||||||
|
const result = await getLatestsSemVersionedTag_stateless(params);
|
||||||
|
|
||||||
|
currentCache.entries.push({
|
||||||
|
time: Date.now(),
|
||||||
|
params,
|
||||||
|
result
|
||||||
|
});
|
||||||
|
|
||||||
|
{
|
||||||
|
const dirPath = pathDirname(cacheFilePath);
|
||||||
|
|
||||||
|
if (!fs.existsSync(dirPath)) {
|
||||||
|
fs.mkdirSync(dirPath, { recursive: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(cacheFilePath, JSON.stringify(currentCache, null, 2));
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
@ -1,92 +1,32 @@
|
|||||||
import { getLatestsSemVersionedTagFactory } from "../tools/octokit-addons/getLatestsSemVersionedTag";
|
import {
|
||||||
import { Octokit } from "@octokit/rest";
|
getLatestsSemVersionedTag,
|
||||||
|
type BuildContextLike as BuildContextLike_getLatestsSemVersionedTag
|
||||||
|
} from "./getLatestsSemVersionedTag";
|
||||||
import cliSelect from "cli-select";
|
import cliSelect from "cli-select";
|
||||||
|
import { assert } from "tsafe/assert";
|
||||||
import { SemVer } from "../tools/SemVer";
|
import { SemVer } from "../tools/SemVer";
|
||||||
import { join as pathJoin, dirname as pathDirname } from "path";
|
import type { BuildContext } from "./buildContext";
|
||||||
import * as fs from "fs";
|
|
||||||
import type { ReturnType } from "tsafe";
|
export type BuildContextLike = BuildContextLike_getLatestsSemVersionedTag & {};
|
||||||
import { id } from "tsafe/id";
|
|
||||||
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
|
|
||||||
export async function promptKeycloakVersion(params: {
|
export async function promptKeycloakVersion(params: {
|
||||||
startingFromMajor: number | undefined;
|
startingFromMajor: number | undefined;
|
||||||
excludeMajorVersions: number[];
|
excludeMajorVersions: number[];
|
||||||
cacheDirPath: string;
|
buildContext: BuildContextLike;
|
||||||
}) {
|
}) {
|
||||||
const { startingFromMajor, excludeMajorVersions, cacheDirPath } = params;
|
const { startingFromMajor, excludeMajorVersions, buildContext } = params;
|
||||||
|
|
||||||
const { getLatestsSemVersionedTag } = (() => {
|
|
||||||
const { octokit } = (() => {
|
|
||||||
const githubToken = process.env.GITHUB_TOKEN;
|
|
||||||
|
|
||||||
const octokit = new Octokit(
|
|
||||||
githubToken === undefined ? undefined : { auth: githubToken }
|
|
||||||
);
|
|
||||||
|
|
||||||
return { octokit };
|
|
||||||
})();
|
|
||||||
|
|
||||||
const { getLatestsSemVersionedTag } = getLatestsSemVersionedTagFactory({
|
|
||||||
octokit
|
|
||||||
});
|
|
||||||
|
|
||||||
return { getLatestsSemVersionedTag };
|
|
||||||
})();
|
|
||||||
|
|
||||||
const semVersionedTagByMajor = new Map<number, { tag: string; version: SemVer }>();
|
const semVersionedTagByMajor = new Map<number, { tag: string; version: SemVer }>();
|
||||||
|
|
||||||
const semVersionedTags = await (async () => {
|
const semVersionedTags = await getLatestsSemVersionedTag({
|
||||||
const cacheFilePath = pathJoin(cacheDirPath, "keycloak-versions.json");
|
count: 50,
|
||||||
|
owner: "keycloak",
|
||||||
type Cache = {
|
repo: "keycloak",
|
||||||
time: number;
|
doIgnoreReleaseCandidates: true,
|
||||||
semVersionedTags: ReturnType<typeof getLatestsSemVersionedTag>;
|
buildContext
|
||||||
};
|
});
|
||||||
|
|
||||||
use_cache: {
|
|
||||||
if (!fs.existsSync(cacheFilePath)) {
|
|
||||||
break use_cache;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cache: Cache = JSON.parse(
|
|
||||||
fs.readFileSync(cacheFilePath).toString("utf8")
|
|
||||||
);
|
|
||||||
|
|
||||||
if (Date.now() - cache.time > 3_600_000) {
|
|
||||||
fs.unlinkSync(cacheFilePath);
|
|
||||||
break use_cache;
|
|
||||||
}
|
|
||||||
|
|
||||||
return cache.semVersionedTags;
|
|
||||||
}
|
|
||||||
|
|
||||||
const semVersionedTags = await getLatestsSemVersionedTag({
|
|
||||||
count: 50,
|
|
||||||
owner: "keycloak",
|
|
||||||
repo: "keycloak"
|
|
||||||
});
|
|
||||||
|
|
||||||
{
|
|
||||||
const dirPath = pathDirname(cacheFilePath);
|
|
||||||
|
|
||||||
if (!fs.existsSync(dirPath)) {
|
|
||||||
fs.mkdirSync(dirPath, { recursive: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.writeFileSync(
|
|
||||||
cacheFilePath,
|
|
||||||
JSON.stringify(
|
|
||||||
id<Cache>({
|
|
||||||
time: Date.now(),
|
|
||||||
semVersionedTags
|
|
||||||
}),
|
|
||||||
null,
|
|
||||||
2
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
return semVersionedTags;
|
|
||||||
})();
|
|
||||||
|
|
||||||
semVersionedTags.forEach(semVersionedTag => {
|
semVersionedTags.forEach(semVersionedTag => {
|
||||||
if (
|
if (
|
||||||
|
@ -5,12 +5,15 @@ import type { BuildContext } from "../shared/buildContext";
|
|||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
import { sep as pathSep, join as pathJoin } from "path";
|
import { sep as pathSep, join as pathJoin } from "path";
|
||||||
import { getAbsoluteAndInOsFormatPath } from "../tools/getAbsoluteAndInOsFormatPath";
|
import { getAbsoluteAndInOsFormatPath } from "../tools/getAbsoluteAndInOsFormatPath";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { dirname as pathDirname, relative as pathRelative } from "path";
|
||||||
|
|
||||||
export type BuildContextLike = {
|
export type BuildContextLike = {
|
||||||
projectDirPath: string;
|
projectDirPath: string;
|
||||||
keycloakifyBuildDirPath: string;
|
keycloakifyBuildDirPath: string;
|
||||||
bundler: BuildContext["bundler"];
|
bundler: BuildContext["bundler"];
|
||||||
projectBuildDirPath: string;
|
projectBuildDirPath: string;
|
||||||
|
packageJsonFilePath: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<BuildContext extends BuildContextLike ? true : false>();
|
assert<BuildContext extends BuildContextLike ? true : false>();
|
||||||
@ -20,7 +23,7 @@ export async function appBuild(params: {
|
|||||||
}): Promise<{ isAppBuildSuccess: boolean }> {
|
}): Promise<{ isAppBuildSuccess: boolean }> {
|
||||||
const { buildContext } = params;
|
const { buildContext } = params;
|
||||||
|
|
||||||
switch (buildContext.bundler.type) {
|
switch (buildContext.bundler) {
|
||||||
case "vite":
|
case "vite":
|
||||||
return appBuild_vite({ buildContext });
|
return appBuild_vite({ buildContext });
|
||||||
case "webpack":
|
case "webpack":
|
||||||
@ -33,7 +36,7 @@ async function appBuild_vite(params: {
|
|||||||
}): Promise<{ isAppBuildSuccess: boolean }> {
|
}): Promise<{ isAppBuildSuccess: boolean }> {
|
||||||
const { buildContext } = params;
|
const { buildContext } = params;
|
||||||
|
|
||||||
assert(buildContext.bundler.type === "vite");
|
assert(buildContext.bundler === "vite");
|
||||||
|
|
||||||
const dIsSuccess = new Deferred<boolean>();
|
const dIsSuccess = new Deferred<boolean>();
|
||||||
|
|
||||||
@ -66,17 +69,18 @@ async function appBuild_webpack(params: {
|
|||||||
}): Promise<{ isAppBuildSuccess: boolean }> {
|
}): Promise<{ isAppBuildSuccess: boolean }> {
|
||||||
const { buildContext } = params;
|
const { buildContext } = params;
|
||||||
|
|
||||||
assert(buildContext.bundler.type === "webpack");
|
assert(buildContext.bundler === "webpack");
|
||||||
|
|
||||||
const entries = Object.entries(buildContext.bundler.packageJsonScripts).filter(
|
const entries = Object.entries(
|
||||||
([, scriptCommand]) => scriptCommand.includes("keycloakify build")
|
(JSON.parse(fs.readFileSync(buildContext.packageJsonFilePath).toString("utf8"))
|
||||||
);
|
.scripts ?? {}) as Record<string, string>
|
||||||
|
).filter(([, scriptCommand]) => scriptCommand.includes("keycloakify build"));
|
||||||
|
|
||||||
if (entries.length === 0) {
|
if (entries.length === 0) {
|
||||||
console.log(
|
console.log(
|
||||||
chalk.red(
|
chalk.red(
|
||||||
[
|
[
|
||||||
`You should have a script in your package.json at ${buildContext.bundler.packageJsonDirPath}`,
|
`You should have a script in your package.json at ${pathRelative(process.cwd(), pathDirname(buildContext.packageJsonFilePath))}`,
|
||||||
`that includes the 'keycloakify build' command`
|
`that includes the 'keycloakify build' command`
|
||||||
].join(" ")
|
].join(" ")
|
||||||
)
|
)
|
||||||
@ -123,7 +127,7 @@ async function appBuild_webpack(params: {
|
|||||||
process.exit(-1);
|
process.exit(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
let commandCwd = buildContext.bundler.packageJsonDirPath;
|
let commandCwd = pathDirname(buildContext.packageJsonFilePath);
|
||||||
|
|
||||||
for (const subCommand of appBuildSubCommands) {
|
for (const subCommand of appBuildSubCommands) {
|
||||||
const dIsSuccess = new Deferred<boolean>();
|
const dIsSuccess = new Deferred<boolean>();
|
||||||
@ -152,7 +156,7 @@ async function appBuild_webpack(params: {
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
pathJoin(
|
pathJoin(
|
||||||
buildContext.bundler.packageJsonDirPath,
|
pathDirname(buildContext.packageJsonFilePath),
|
||||||
"node_modules",
|
"node_modules",
|
||||||
".bin"
|
".bin"
|
||||||
),
|
),
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { buildForKeycloakMajorVersionEnvName } from "../shared/constants";
|
import { BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME } from "../shared/constants";
|
||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import { Deferred } from "evt/tools/Deferred";
|
import { Deferred } from "evt/tools/Deferred";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
@ -26,7 +26,7 @@ export async function keycloakifyBuild(params: {
|
|||||||
cwd: buildContext.projectDirPath,
|
cwd: buildContext.projectDirPath,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
[buildForKeycloakMajorVersionEnvName]: `${buildForKeycloakMajorVersionNumber}`
|
[BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME]: `${buildForKeycloakMajorVersionNumber}`
|
||||||
},
|
},
|
||||||
shell: true
|
shell: true
|
||||||
});
|
});
|
||||||
|
@ -73,7 +73,7 @@
|
|||||||
"composites": {
|
"composites": {
|
||||||
"realm": ["offline_access", "uma_authorization"],
|
"realm": ["offline_access", "uma_authorization"],
|
||||||
"client": {
|
"client": {
|
||||||
"account": ["view-profile", "manage-account"]
|
"account": ["delete-account", "view-profile", "manage-account"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"clientRole": false,
|
"clientRole": false,
|
||||||
@ -611,8 +611,8 @@
|
|||||||
"name": "",
|
"name": "",
|
||||||
"description": "",
|
"description": "",
|
||||||
"rootUrl": "https://my-theme.keycloakify.dev",
|
"rootUrl": "https://my-theme.keycloakify.dev",
|
||||||
"adminUrl": "",
|
"adminUrl": "https://my-theme.keycloakify.dev",
|
||||||
"baseUrl": "",
|
"baseUrl": "https://my-theme.keycloakify.dev",
|
||||||
"surrogateAuthRequired": false,
|
"surrogateAuthRequired": false,
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"alwaysDisplayInConsole": false,
|
"alwaysDisplayInConsole": false,
|
||||||
@ -2099,7 +2099,7 @@
|
|||||||
"alias": "delete_account",
|
"alias": "delete_account",
|
||||||
"name": "Delete Account",
|
"name": "Delete Account",
|
||||||
"providerId": "delete_account",
|
"providerId": "delete_account",
|
||||||
"enabled": false,
|
"enabled": true,
|
||||||
"defaultAction": false,
|
"defaultAction": false,
|
||||||
"priority": 60,
|
"priority": 60,
|
||||||
"config": {}
|
"config": {}
|
||||||
|
@ -73,7 +73,7 @@
|
|||||||
"composites": {
|
"composites": {
|
||||||
"realm": ["offline_access", "uma_authorization"],
|
"realm": ["offline_access", "uma_authorization"],
|
||||||
"client": {
|
"client": {
|
||||||
"account": ["view-profile", "manage-account"]
|
"account": ["delete-account", "view-profile", "manage-account"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"clientRole": false,
|
"clientRole": false,
|
||||||
@ -618,8 +618,8 @@
|
|||||||
"name": "",
|
"name": "",
|
||||||
"description": "",
|
"description": "",
|
||||||
"rootUrl": "https://my-theme.keycloakify.dev",
|
"rootUrl": "https://my-theme.keycloakify.dev",
|
||||||
"adminUrl": "",
|
"adminUrl": "https://my-theme.keycloakify.dev",
|
||||||
"baseUrl": "",
|
"baseUrl": "https://my-theme.keycloakify.dev",
|
||||||
"surrogateAuthRequired": false,
|
"surrogateAuthRequired": false,
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"alwaysDisplayInConsole": false,
|
"alwaysDisplayInConsole": false,
|
||||||
@ -2130,7 +2130,7 @@
|
|||||||
"alias": "delete_account",
|
"alias": "delete_account",
|
||||||
"name": "Delete Account",
|
"name": "Delete Account",
|
||||||
"providerId": "delete_account",
|
"providerId": "delete_account",
|
||||||
"enabled": false,
|
"enabled": true,
|
||||||
"defaultAction": false,
|
"defaultAction": false,
|
||||||
"priority": 60,
|
"priority": 60,
|
||||||
"config": {}
|
"config": {}
|
||||||
|
@ -73,7 +73,7 @@
|
|||||||
"composites": {
|
"composites": {
|
||||||
"realm": ["offline_access", "uma_authorization"],
|
"realm": ["offline_access", "uma_authorization"],
|
||||||
"client": {
|
"client": {
|
||||||
"account": ["view-profile", "manage-account"]
|
"account": ["delete-account", "view-profile", "manage-account"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"clientRole": false,
|
"clientRole": false,
|
||||||
@ -628,8 +628,8 @@
|
|||||||
"name": "",
|
"name": "",
|
||||||
"description": "",
|
"description": "",
|
||||||
"rootUrl": "https://my-theme.keycloakify.dev",
|
"rootUrl": "https://my-theme.keycloakify.dev",
|
||||||
"adminUrl": "",
|
"adminUrl": "https://my-theme.keycloakify.dev",
|
||||||
"baseUrl": "",
|
"baseUrl": "https://my-theme.keycloakify.dev",
|
||||||
"surrogateAuthRequired": false,
|
"surrogateAuthRequired": false,
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"alwaysDisplayInConsole": false,
|
"alwaysDisplayInConsole": false,
|
||||||
@ -2140,7 +2140,7 @@
|
|||||||
"alias": "delete_account",
|
"alias": "delete_account",
|
||||||
"name": "Delete Account",
|
"name": "Delete Account",
|
||||||
"providerId": "delete_account",
|
"providerId": "delete_account",
|
||||||
"enabled": false,
|
"enabled": true,
|
||||||
"defaultAction": false,
|
"defaultAction": false,
|
||||||
"priority": 60,
|
"priority": 60,
|
||||||
"config": {}
|
"config": {}
|
||||||
|
@ -73,7 +73,7 @@
|
|||||||
"composites": {
|
"composites": {
|
||||||
"realm": ["offline_access", "uma_authorization"],
|
"realm": ["offline_access", "uma_authorization"],
|
||||||
"client": {
|
"client": {
|
||||||
"account": ["view-profile", "manage-account"]
|
"account": ["delete-account", "view-profile", "manage-account"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"clientRole": false,
|
"clientRole": false,
|
||||||
@ -632,8 +632,8 @@
|
|||||||
"name": "",
|
"name": "",
|
||||||
"description": "",
|
"description": "",
|
||||||
"rootUrl": "https://my-theme.keycloakify.dev",
|
"rootUrl": "https://my-theme.keycloakify.dev",
|
||||||
"adminUrl": "",
|
"adminUrl": "https://my-theme.keycloakify.dev",
|
||||||
"baseUrl": "",
|
"baseUrl": "https://my-theme.keycloakify.dev",
|
||||||
"surrogateAuthRequired": false,
|
"surrogateAuthRequired": false,
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"alwaysDisplayInConsole": false,
|
"alwaysDisplayInConsole": false,
|
||||||
@ -2144,7 +2144,7 @@
|
|||||||
"alias": "delete_account",
|
"alias": "delete_account",
|
||||||
"name": "Delete Account",
|
"name": "Delete Account",
|
||||||
"providerId": "delete_account",
|
"providerId": "delete_account",
|
||||||
"enabled": false,
|
"enabled": true,
|
||||||
"defaultAction": false,
|
"defaultAction": false,
|
||||||
"priority": 60,
|
"priority": 60,
|
||||||
"config": {}
|
"config": {}
|
||||||
|
@ -55,7 +55,7 @@
|
|||||||
"composites": {
|
"composites": {
|
||||||
"realm": ["offline_access", "uma_authorization"],
|
"realm": ["offline_access", "uma_authorization"],
|
||||||
"client": {
|
"client": {
|
||||||
"account": ["view-profile", "manage-account"]
|
"account": ["delete-account", "view-profile", "manage-account"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"clientRole": false,
|
"clientRole": false,
|
||||||
@ -644,7 +644,7 @@
|
|||||||
"description": "",
|
"description": "",
|
||||||
"rootUrl": "https://my-theme.keycloakify.dev",
|
"rootUrl": "https://my-theme.keycloakify.dev",
|
||||||
"adminUrl": "https://my-theme.keycloakify.dev",
|
"adminUrl": "https://my-theme.keycloakify.dev",
|
||||||
"baseUrl": "",
|
"baseUrl": "https://my-theme.keycloakify.dev",
|
||||||
"surrogateAuthRequired": false,
|
"surrogateAuthRequired": false,
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"alwaysDisplayInConsole": false,
|
"alwaysDisplayInConsole": false,
|
||||||
@ -2088,7 +2088,7 @@
|
|||||||
"alias": "delete_account",
|
"alias": "delete_account",
|
||||||
"name": "Delete Account",
|
"name": "Delete Account",
|
||||||
"providerId": "delete_account",
|
"providerId": "delete_account",
|
||||||
"enabled": false,
|
"enabled": true,
|
||||||
"defaultAction": false,
|
"defaultAction": false,
|
||||||
"priority": 60,
|
"priority": 60,
|
||||||
"config": {}
|
"config": {}
|
||||||
|
@ -63,7 +63,7 @@
|
|||||||
"composites": {
|
"composites": {
|
||||||
"realm": ["offline_access", "uma_authorization"],
|
"realm": ["offline_access", "uma_authorization"],
|
||||||
"client": {
|
"client": {
|
||||||
"account": ["manage-account", "view-profile"]
|
"account": ["delete-account", "manage-account", "view-profile"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"clientRole": false,
|
"clientRole": false,
|
||||||
@ -449,7 +449,7 @@
|
|||||||
"gender": ["prefer_not_to_say"],
|
"gender": ["prefer_not_to_say"],
|
||||||
"bio": ["Hello I'm Test User and I do not exist."],
|
"bio": ["Hello I'm Test User and I do not exist."],
|
||||||
"phone_number": ["1111111111"],
|
"phone_number": ["1111111111"],
|
||||||
"locale": ["fr"],
|
"locale": ["en"],
|
||||||
"favorite_media": ["movies", "series"]
|
"favorite_media": ["movies", "series"]
|
||||||
},
|
},
|
||||||
"createdTimestamp": 1716183898408,
|
"createdTimestamp": 1716183898408,
|
||||||
@ -653,7 +653,7 @@
|
|||||||
"description": "",
|
"description": "",
|
||||||
"rootUrl": "https://my-theme.keycloakify.dev",
|
"rootUrl": "https://my-theme.keycloakify.dev",
|
||||||
"adminUrl": "https://my-theme.keycloakify.dev",
|
"adminUrl": "https://my-theme.keycloakify.dev",
|
||||||
"baseUrl": "",
|
"baseUrl": "https://my-theme.keycloakify.dev",
|
||||||
"surrogateAuthRequired": false,
|
"surrogateAuthRequired": false,
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"alwaysDisplayInConsole": false,
|
"alwaysDisplayInConsole": false,
|
||||||
@ -2235,7 +2235,7 @@
|
|||||||
"alias": "delete_account",
|
"alias": "delete_account",
|
||||||
"name": "Delete Account",
|
"name": "Delete Account",
|
||||||
"providerId": "delete_account",
|
"providerId": "delete_account",
|
||||||
"enabled": false,
|
"enabled": true,
|
||||||
"defaultAction": false,
|
"defaultAction": false,
|
||||||
"priority": 60,
|
"priority": 60,
|
||||||
"config": {}
|
"config": {}
|
||||||
|
@ -63,7 +63,7 @@
|
|||||||
"composites": {
|
"composites": {
|
||||||
"realm": ["offline_access", "uma_authorization"],
|
"realm": ["offline_access", "uma_authorization"],
|
||||||
"client": {
|
"client": {
|
||||||
"account": ["manage-account", "view-profile"]
|
"account": ["delete-account", "manage-account", "view-profile"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"clientRole": false,
|
"clientRole": false,
|
||||||
@ -543,7 +543,7 @@
|
|||||||
"favourite_pet": ["cat"],
|
"favourite_pet": ["cat"],
|
||||||
"bio": ["Hello I'm Test User and I do not exist."],
|
"bio": ["Hello I'm Test User and I do not exist."],
|
||||||
"phone_number": ["1111111111"],
|
"phone_number": ["1111111111"],
|
||||||
"locale": ["fr"],
|
"locale": ["en"],
|
||||||
"favorite_media": ["movies", "series"]
|
"favorite_media": ["movies", "series"]
|
||||||
},
|
},
|
||||||
"createdTimestamp": 1716183898408,
|
"createdTimestamp": 1716183898408,
|
||||||
@ -767,7 +767,7 @@
|
|||||||
"description": "",
|
"description": "",
|
||||||
"rootUrl": "https://my-theme.keycloakify.dev",
|
"rootUrl": "https://my-theme.keycloakify.dev",
|
||||||
"adminUrl": "https://my-theme.keycloakify.dev",
|
"adminUrl": "https://my-theme.keycloakify.dev",
|
||||||
"baseUrl": "",
|
"baseUrl": "https://my-theme.keycloakify.dev",
|
||||||
"surrogateAuthRequired": false,
|
"surrogateAuthRequired": false,
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"alwaysDisplayInConsole": false,
|
"alwaysDisplayInConsole": false,
|
||||||
@ -2315,7 +2315,7 @@
|
|||||||
"alias": "delete_account",
|
"alias": "delete_account",
|
||||||
"name": "Delete Account",
|
"name": "Delete Account",
|
||||||
"providerId": "delete_account",
|
"providerId": "delete_account",
|
||||||
"enabled": false,
|
"enabled": true,
|
||||||
"defaultAction": false,
|
"defaultAction": false,
|
||||||
"priority": 60,
|
"priority": 60,
|
||||||
"config": {}
|
"config": {}
|
||||||
|
@ -2,7 +2,7 @@ import { getBuildContext } from "../shared/buildContext";
|
|||||||
import { exclude } from "tsafe/exclude";
|
import { exclude } from "tsafe/exclude";
|
||||||
import type { CliCommandOptions as CliCommandOptions_common } from "../main";
|
import type { CliCommandOptions as CliCommandOptions_common } from "../main";
|
||||||
import { promptKeycloakVersion } from "../shared/promptKeycloakVersion";
|
import { promptKeycloakVersion } from "../shared/promptKeycloakVersion";
|
||||||
import { accountV1ThemeName, containerName } from "../shared/constants";
|
import { ACCOUNT_V1_THEME_NAME, CONTAINER_NAME } from "../shared/constants";
|
||||||
import { SemVer } from "../tools/SemVer";
|
import { SemVer } from "../tools/SemVer";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
@ -97,13 +97,20 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
chalk.cyan("On which version of Keycloak do you want to test your theme?")
|
[
|
||||||
|
chalk.cyan(
|
||||||
|
"On which version of Keycloak do you want to test your theme?"
|
||||||
|
),
|
||||||
|
chalk.gray(
|
||||||
|
"You can also explicitly provide the version with `npx keycloakify start-keycloak --keycloak-version 25.0.2` (or any other version)"
|
||||||
|
)
|
||||||
|
].join("\n")
|
||||||
);
|
);
|
||||||
|
|
||||||
const { keycloakVersion } = await promptKeycloakVersion({
|
const { keycloakVersion } = await promptKeycloakVersion({
|
||||||
startingFromMajor: 18,
|
startingFromMajor: 18,
|
||||||
excludeMajorVersions: [22],
|
excludeMajorVersions: [22],
|
||||||
cacheDirPath: buildContext.cacheDirPath
|
buildContext
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`→ ${keycloakVersion}`);
|
console.log(`→ ${keycloakVersion}`);
|
||||||
@ -269,7 +276,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
fs.copyFileSync(jarFilePath, jarFilePath_cacheDir);
|
fs.copyFileSync(jarFilePath, jarFilePath_cacheDir);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
child_process.execSync(`docker rm --force ${containerName}`, {
|
child_process.execSync(`docker rm --force ${CONTAINER_NAME}`, {
|
||||||
stdio: "ignore"
|
stdio: "ignore"
|
||||||
});
|
});
|
||||||
} catch {}
|
} catch {}
|
||||||
@ -279,18 +286,18 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
[
|
[
|
||||||
"run",
|
"run",
|
||||||
...["-p", `${cliCommandOptions.port}:8080`],
|
...["-p", `${cliCommandOptions.port}:8080`],
|
||||||
...["--name", containerName],
|
...["--name", CONTAINER_NAME],
|
||||||
...["-e", "KEYCLOAK_ADMIN=admin"],
|
...["-e", "KEYCLOAK_ADMIN=admin"],
|
||||||
...["-e", "KEYCLOAK_ADMIN_PASSWORD=admin"],
|
...["-e", "KEYCLOAK_ADMIN_PASSWORD=admin"],
|
||||||
...(realmJsonFilePath === undefined
|
...(realmJsonFilePath === undefined
|
||||||
? []
|
? []
|
||||||
: [
|
: [
|
||||||
"-v",
|
"-v",
|
||||||
`${realmJsonFilePath}:/opt/keycloak/data/import/myrealm-realm.json`
|
`"${realmJsonFilePath}":/opt/keycloak/data/import/myrealm-realm.json`
|
||||||
]),
|
]),
|
||||||
...[
|
...[
|
||||||
"-v",
|
"-v",
|
||||||
`${jarFilePath_cacheDir}:/opt/keycloak/providers/keycloak-theme.jar`
|
`"${jarFilePath_cacheDir}":/opt/keycloak/providers/keycloak-theme.jar`
|
||||||
],
|
],
|
||||||
...(keycloakMajorVersionNumber <= 20
|
...(keycloakMajorVersionNumber <= 20
|
||||||
? ["-e", "JAVA_OPTS=-Dkeycloak.profile=preview"]
|
? ["-e", "JAVA_OPTS=-Dkeycloak.profile=preview"]
|
||||||
@ -301,10 +308,10 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
pathJoin(
|
pathJoin(
|
||||||
buildContext.keycloakifyBuildDirPath,
|
buildContext.keycloakifyBuildDirPath,
|
||||||
"theme",
|
"theme",
|
||||||
accountV1ThemeName
|
ACCOUNT_V1_THEME_NAME
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
? [accountV1ThemeName]
|
? [ACCOUNT_V1_THEME_NAME]
|
||||||
: [])
|
: [])
|
||||||
]
|
]
|
||||||
.map(themeName => ({
|
.map(themeName => ({
|
||||||
@ -317,7 +324,7 @@ export async function command(params: { cliCommandOptions: CliCommandOptions })
|
|||||||
}))
|
}))
|
||||||
.map(({ localDirPath, containerDirPath }) => [
|
.map(({ localDirPath, containerDirPath }) => [
|
||||||
"-v",
|
"-v",
|
||||||
`${localDirPath}:${containerDirPath}:rw`
|
`"${localDirPath}":${containerDirPath}:rw`
|
||||||
])
|
])
|
||||||
.flat(),
|
.flat(),
|
||||||
...buildContext.environmentVariables
|
...buildContext.environmentVariables
|
||||||
|
@ -5,9 +5,11 @@ export function assertNoPnpmDlx() {
|
|||||||
if (__dirname.includes(`${pathSep}pnpm${pathSep}dlx${pathSep}`)) {
|
if (__dirname.includes(`${pathSep}pnpm${pathSep}dlx${pathSep}`)) {
|
||||||
console.log(
|
console.log(
|
||||||
[
|
[
|
||||||
chalk.red("Please don't use `pnpm dlx keycloakify`"),
|
chalk.red(
|
||||||
|
"Please don't use `pnpm dlx keycloakify` (download and execute)"
|
||||||
|
),
|
||||||
"\nUse `npx keycloakify` or `pnpm exec keycloakify` instead since you want to use the keycloakify",
|
"\nUse `npx keycloakify` or `pnpm exec keycloakify` instead since you want to use the keycloakify",
|
||||||
"version that is installed in your project and not the latest version on NPM."
|
"version that is installed in your project and not download and run the latest NPM version of keycloakify."
|
||||||
].join(" ")
|
].join(" ")
|
||||||
);
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
@ -10,7 +10,7 @@ import { rm } from "./fs.rm";
|
|||||||
|
|
||||||
export async function downloadAndExtractArchive(params: {
|
export async function downloadAndExtractArchive(params: {
|
||||||
url: string;
|
url: string;
|
||||||
uniqueIdOfOnOnArchiveFile: string;
|
uniqueIdOfOnArchiveFile: string;
|
||||||
onArchiveFile: (params: {
|
onArchiveFile: (params: {
|
||||||
fileRelativePath: string;
|
fileRelativePath: string;
|
||||||
readFile: () => Promise<Buffer>;
|
readFile: () => Promise<Buffer>;
|
||||||
@ -22,7 +22,7 @@ export async function downloadAndExtractArchive(params: {
|
|||||||
cacheDirPath: string;
|
cacheDirPath: string;
|
||||||
fetchOptions: FetchOptions | undefined;
|
fetchOptions: FetchOptions | undefined;
|
||||||
}): Promise<{ extractedDirPath: string }> {
|
}): Promise<{ extractedDirPath: string }> {
|
||||||
const { url, uniqueIdOfOnOnArchiveFile, onArchiveFile, cacheDirPath, fetchOptions } =
|
const { url, uniqueIdOfOnArchiveFile, onArchiveFile, cacheDirPath, fetchOptions } =
|
||||||
params;
|
params;
|
||||||
|
|
||||||
const archiveFileBasename = url.split("?")[0].split("/").reverse()[0];
|
const archiveFileBasename = url.split("?")[0].split("/").reverse()[0];
|
||||||
@ -63,7 +63,7 @@ export async function downloadAndExtractArchive(params: {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const extractDirBasename = `${archiveFileBasename.split(".")[0]}_${uniqueIdOfOnOnArchiveFile}_${crypto
|
const extractDirBasename = `${archiveFileBasename.replace(/\.([^.]+)$/, (...[, ext]) => `_${ext}`)}_${uniqueIdOfOnArchiveFile}_${crypto
|
||||||
.createHash("sha256")
|
.createHash("sha256")
|
||||||
.update(onArchiveFile.toString())
|
.update(onArchiveFile.toString())
|
||||||
.digest("hex")
|
.digest("hex")
|
||||||
@ -85,7 +85,9 @@ export async function downloadAndExtractArchive(params: {
|
|||||||
})()
|
})()
|
||||||
)
|
)
|
||||||
.map(async extractDirBasename => {
|
.map(async extractDirBasename => {
|
||||||
await rm(pathJoin(cacheDirPath, extractDirBasename), { recursive: true });
|
await rm(pathJoin(cacheDirPath, extractDirBasename), {
|
||||||
|
recursive: true
|
||||||
|
});
|
||||||
await SuccessTracker.removeFromExtracted({
|
await SuccessTracker.removeFromExtracted({
|
||||||
cacheDirPath,
|
cacheDirPath,
|
||||||
extractDirBasename
|
extractDirBasename
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import { type FetchOptions } from "make-fetch-happen";
|
import { type FetchOptions } from "make-fetch-happen";
|
||||||
import * as child_process from "child_process";
|
import * as child_process from "child_process";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
|
import { exclude } from "tsafe/exclude";
|
||||||
|
|
||||||
export type ProxyFetchOptions = Pick<
|
export type ProxyFetchOptions = Pick<
|
||||||
FetchOptions,
|
FetchOptions,
|
||||||
@ -23,12 +24,32 @@ export function getProxyFetchOptions(params: {
|
|||||||
.split("\n")
|
.split("\n")
|
||||||
.filter(line => !line.startsWith(";"))
|
.filter(line => !line.startsWith(";"))
|
||||||
.map(line => line.trim())
|
.map(line => line.trim())
|
||||||
.map(line => line.split("=", 2) as [string, string])
|
.map(line => {
|
||||||
|
const [key, value] = line.split("=");
|
||||||
|
if (key === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (value === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return [key.trim(), value.trim()] as const;
|
||||||
|
})
|
||||||
|
.filter(exclude(undefined))
|
||||||
|
.filter(([key]) => key !== "")
|
||||||
|
.map(([key, value]) => {
|
||||||
|
if (value.startsWith('"') && value.endsWith('"')) {
|
||||||
|
return [key, value.slice(1, -1)] as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value === "true" || value === "false") {
|
||||||
|
return [key, value] as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
})
|
||||||
|
.filter(exclude(undefined))
|
||||||
.reduce(
|
.reduce(
|
||||||
(
|
(cfg: Record<string, string | string[]>, [key, value]) =>
|
||||||
cfg: Record<string, string | string[]>,
|
|
||||||
[key, value]: [string, string]
|
|
||||||
) =>
|
|
||||||
key in cfg
|
key in cfg
|
||||||
? { ...cfg, [key]: [...ensureArray(cfg[key]), value] }
|
? { ...cfg, [key]: [...ensureArray(cfg[key]), value] }
|
||||||
: { ...cfg, [key]: value },
|
: { ...cfg, [key]: value },
|
||||||
@ -37,18 +58,18 @@ export function getProxyFetchOptions(params: {
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
const proxy = ensureSingleOrNone(cfg["https-proxy"] ?? cfg["proxy"]);
|
const proxy = ensureSingleOrNone(cfg["https-proxy"] ?? cfg["proxy"]);
|
||||||
|
|
||||||
const noProxy = cfg["noproxy"] ?? cfg["no-proxy"];
|
const noProxy = cfg["noproxy"] ?? cfg["no-proxy"];
|
||||||
|
|
||||||
function maybeBoolean(arg0: string | undefined) {
|
const strictSSL = ensureSingleOrNone(cfg["strict-ssl"]) === "true";
|
||||||
return typeof arg0 === "undefined" ? undefined : Boolean(arg0);
|
|
||||||
}
|
|
||||||
|
|
||||||
const strictSSL = maybeBoolean(ensureSingleOrNone(cfg["strict-ssl"]));
|
|
||||||
const cert = cfg["cert"];
|
const cert = cfg["cert"];
|
||||||
|
|
||||||
const ca = ensureArray(cfg["ca"] ?? cfg["ca[]"]);
|
const ca = ensureArray(cfg["ca"] ?? cfg["ca[]"]);
|
||||||
|
|
||||||
const cafile = ensureSingleOrNone(cfg["cafile"]);
|
const cafile = ensureSingleOrNone(cfg["cafile"]);
|
||||||
|
|
||||||
if (typeof cafile !== "undefined" && cafile !== "null") {
|
if (cafile !== undefined) {
|
||||||
ca.push(
|
ca.push(
|
||||||
...(() => {
|
...(() => {
|
||||||
const cafileContent = fs.readFileSync(cafile).toString("utf8");
|
const cafileContent = fs.readFileSync(cafile).toString("utf8");
|
||||||
@ -82,7 +103,7 @@ export function getProxyFetchOptions(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ensureArray<T>(arg0: T | T[]) {
|
function ensureArray<T>(arg0: T | T[]) {
|
||||||
return Array.isArray(arg0) ? arg0 : typeof arg0 === "undefined" ? [] : [arg0];
|
return Array.isArray(arg0) ? arg0 : arg0 === undefined ? [] : [arg0];
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensureSingleOrNone<T>(arg0: T | T[]) {
|
function ensureSingleOrNone<T>(arg0: T | T[]) {
|
||||||
|
63
src/bin/tools/npmInstall.ts
Normal file
63
src/bin/tools/npmInstall.ts
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
import * as fs from "fs";
|
||||||
|
import { join as pathJoin } from "path";
|
||||||
|
import * as child_process from "child_process";
|
||||||
|
import chalk from "chalk";
|
||||||
|
|
||||||
|
export function npmInstall(params: { packageJsonDirPath: string }) {
|
||||||
|
const { packageJsonDirPath } = params;
|
||||||
|
|
||||||
|
const packageManagerBinName = (() => {
|
||||||
|
const packageMangers = [
|
||||||
|
{
|
||||||
|
binName: "yarn",
|
||||||
|
lockFileBasename: "yarn.lock"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
binName: "npm",
|
||||||
|
lockFileBasename: "package-lock.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
binName: "pnpm",
|
||||||
|
lockFileBasename: "pnpm-lock.yaml"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
binName: "bun",
|
||||||
|
lockFileBasename: "bun.lockdb"
|
||||||
|
}
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
for (const packageManager of packageMangers) {
|
||||||
|
if (
|
||||||
|
fs.existsSync(
|
||||||
|
pathJoin(packageJsonDirPath, packageManager.lockFileBasename)
|
||||||
|
) ||
|
||||||
|
fs.existsSync(pathJoin(process.cwd(), packageManager.lockFileBasename))
|
||||||
|
) {
|
||||||
|
return packageManager.binName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
})();
|
||||||
|
|
||||||
|
install_dependencies: {
|
||||||
|
if (packageManagerBinName === undefined) {
|
||||||
|
break install_dependencies;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Installing the new dependencies...`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
child_process.execSync(`${packageManagerBinName} install`, {
|
||||||
|
cwd: packageJsonDirPath,
|
||||||
|
stdio: "inherit"
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(
|
||||||
|
`\`${packageManagerBinName} install\` failed, continuing anyway...`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -9,13 +9,14 @@ export function getLatestsSemVersionedTagFactory(params: { octokit: Octokit }) {
|
|||||||
owner: string;
|
owner: string;
|
||||||
repo: string;
|
repo: string;
|
||||||
count: number;
|
count: number;
|
||||||
|
doIgnoreReleaseCandidates: boolean;
|
||||||
}): Promise<
|
}): Promise<
|
||||||
{
|
{
|
||||||
tag: string;
|
tag: string;
|
||||||
version: SemVer;
|
version: SemVer;
|
||||||
}[]
|
}[]
|
||||||
> {
|
> {
|
||||||
const { owner, repo, count } = params;
|
const { owner, repo, count, doIgnoreReleaseCandidates } = params;
|
||||||
|
|
||||||
const semVersionedTags: { tag: string; version: SemVer }[] = [];
|
const semVersionedTags: { tag: string; version: SemVer }[] = [];
|
||||||
|
|
||||||
@ -30,7 +31,7 @@ export function getLatestsSemVersionedTagFactory(params: { octokit: Octokit }) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (version.rc !== undefined) {
|
if (doIgnoreReleaseCandidates && version.rc !== undefined) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,5 +8,7 @@
|
|||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"outDir": "../../dist/bin",
|
"outDir": "../../dist/bin",
|
||||||
"rootDir": "."
|
"rootDir": "."
|
||||||
}
|
},
|
||||||
|
"include": ["**/*.ts", "**/*.tsx"],
|
||||||
|
"exclude": ["initialize-account-theme/src"]
|
||||||
}
|
}
|
||||||
|
@ -73,8 +73,8 @@ export function createGetKcClsx<ClassKey extends string>(params: {
|
|||||||
|
|
||||||
return clsx(
|
return clsx(
|
||||||
classKey,
|
classKey,
|
||||||
doUseDefaultCss ? defaultClasses[classKey] : undefined,
|
classes?.[classKey] ??
|
||||||
classes?.[classKey]
|
(doUseDefaultCss ? defaultClasses[classKey] : undefined)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
import type { ThemeType, LoginThemePageId } from "keycloakify/bin/shared/constants";
|
import type { ThemeType, LoginThemePageId } from "keycloakify/bin/shared/constants";
|
||||||
import type { ExtractAfterStartingWith } from "keycloakify/tools/ExtractAfterStartingWith";
|
|
||||||
import type { ValueOf } from "keycloakify/tools/ValueOf";
|
import type { ValueOf } from "keycloakify/tools/ValueOf";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import type { Equals } from "tsafe";
|
import type { Equals } from "tsafe";
|
||||||
import type { MessageKey } from "../i18n/i18n";
|
import type { ClassKey } from "keycloakify/login/TemplateProps";
|
||||||
|
|
||||||
export type ExtendKcContext<
|
export type ExtendKcContext<
|
||||||
KcContextExtension extends { properties?: Record<string, string | undefined> },
|
KcContextExtension extends { properties?: Record<string, string | undefined> },
|
||||||
@ -155,8 +154,7 @@ export declare namespace KcContext {
|
|||||||
};
|
};
|
||||||
properties: {};
|
properties: {};
|
||||||
"x-keycloakify": {
|
"x-keycloakify": {
|
||||||
realmMessageBundleUserProfile: Record<string, string> | undefined;
|
messages: Record<string, string>;
|
||||||
realmMessageBundleTermsText: string | undefined;
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -221,7 +219,7 @@ export declare namespace KcContext {
|
|||||||
export type Info = Common & {
|
export type Info = Common & {
|
||||||
pageId: "info.ftl";
|
pageId: "info.ftl";
|
||||||
messageHeader?: string;
|
messageHeader?: string;
|
||||||
requiredActions?: ExtractAfterStartingWith<"requiredAction.", MessageKey>[];
|
requiredActions?: string[];
|
||||||
skipLink: boolean;
|
skipLink: boolean;
|
||||||
pageRedirectUri?: string;
|
pageRedirectUri?: string;
|
||||||
actionUri?: string;
|
actionUri?: string;
|
||||||
@ -384,7 +382,7 @@ export declare namespace KcContext {
|
|||||||
credentialId: string;
|
credentialId: string;
|
||||||
transports: {
|
transports: {
|
||||||
iconClass: string;
|
iconClass: string;
|
||||||
displayNameProperties?: MessageKey[];
|
displayNameProperties?: string[];
|
||||||
};
|
};
|
||||||
label: string;
|
label: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
@ -501,26 +499,9 @@ export declare namespace KcContext {
|
|||||||
export namespace SelectAuthenticator {
|
export namespace SelectAuthenticator {
|
||||||
export type AuthenticationSelection = {
|
export type AuthenticationSelection = {
|
||||||
authExecId: string;
|
authExecId: string;
|
||||||
displayName:
|
displayName: string;
|
||||||
| "otp-display-name"
|
helpText: string;
|
||||||
| "password-display-name"
|
iconCssClass?: ClassKey;
|
||||||
| "auth-username-form-display-name"
|
|
||||||
| "auth-username-password-form-display-name"
|
|
||||||
| "webauthn-display-name"
|
|
||||||
| "webauthn-passwordless-display-name";
|
|
||||||
helpText:
|
|
||||||
| "otp-help-text"
|
|
||||||
| "password-help-text"
|
|
||||||
| "auth-username-form-help-text"
|
|
||||||
| "auth-username-password-form-help-text"
|
|
||||||
| "webauthn-help-text"
|
|
||||||
| "webauthn-passwordless-help-text";
|
|
||||||
iconCssClass?:
|
|
||||||
| "kcAuthenticatorDefaultClass"
|
|
||||||
| "kcAuthenticatorPasswordClass"
|
|
||||||
| "kcAuthenticatorOTPClass"
|
|
||||||
| "kcAuthenticatorWebAuthnClass"
|
|
||||||
| "kcAuthenticatorWebAuthnPasswordlessClass";
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -610,6 +591,7 @@ export type Attribute = {
|
|||||||
value?: string;
|
value?: string;
|
||||||
values?: string[];
|
values?: string[];
|
||||||
group?: {
|
group?: {
|
||||||
|
annotations: Record<string, string>;
|
||||||
html5DataAnnotations: Record<string, string>;
|
html5DataAnnotations: Record<string, string>;
|
||||||
displayHeader?: string;
|
displayHeader?: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import "keycloakify/tools/Object.fromEntries";
|
import "keycloakify/tools/Object.fromEntries";
|
||||||
import type { KcContext, Attribute } from "./KcContext";
|
import type { KcContext, Attribute } from "./KcContext";
|
||||||
import {
|
import {
|
||||||
resources_common,
|
RESOURCES_COMMON,
|
||||||
keycloak_resources,
|
KEYCLOAK_RESOURCES,
|
||||||
type LoginThemePageId
|
type LoginThemePageId
|
||||||
} from "keycloakify/bin/shared/constants";
|
} from "keycloakify/bin/shared/constants";
|
||||||
import { id } from "tsafe/id";
|
import { id } from "tsafe/id";
|
||||||
@ -76,7 +76,7 @@ const attributesByName = Object.fromEntries(
|
|||||||
]).map(attribute => [attribute.name, attribute])
|
]).map(attribute => [attribute.name, attribute])
|
||||||
);
|
);
|
||||||
|
|
||||||
const resourcesPath = `${BASE_URL}${keycloak_resources}/login/resources`;
|
const resourcesPath = `${BASE_URL}${KEYCLOAK_RESOURCES}/login/resources`;
|
||||||
|
|
||||||
export const kcContextCommonMock: KcContext.Common = {
|
export const kcContextCommonMock: KcContext.Common = {
|
||||||
themeVersion: "0.0.0",
|
themeVersion: "0.0.0",
|
||||||
@ -86,7 +86,7 @@ export const kcContextCommonMock: KcContext.Common = {
|
|||||||
url: {
|
url: {
|
||||||
loginAction: "#",
|
loginAction: "#",
|
||||||
resourcesPath,
|
resourcesPath,
|
||||||
resourcesCommonPath: `${resourcesPath}/${resources_common}`,
|
resourcesCommonPath: `${resourcesPath}/${RESOURCES_COMMON}`,
|
||||||
loginRestartFlowUrl: "#",
|
loginRestartFlowUrl: "#",
|
||||||
loginUrl: "#",
|
loginUrl: "#",
|
||||||
ssoLoginInOtherTabsUrl: "#"
|
ssoLoginInOtherTabsUrl: "#"
|
||||||
@ -162,8 +162,7 @@ export const kcContextCommonMock: KcContext.Common = {
|
|||||||
isAppInitiatedAction: false,
|
isAppInitiatedAction: false,
|
||||||
properties: {},
|
properties: {},
|
||||||
"x-keycloakify": {
|
"x-keycloakify": {
|
||||||
realmMessageBundleUserProfile: undefined,
|
messages: {}
|
||||||
realmMessageBundleTermsText: undefined
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useReducer, Fragment } from "react";
|
import { useEffect, useReducer, Fragment } from "react";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "keycloakify/tools/assert";
|
||||||
import type { KcClsx } from "keycloakify/login/lib/kcClsx";
|
import type { KcClsx } from "keycloakify/login/lib/kcClsx";
|
||||||
import {
|
import {
|
||||||
useUserProfileForm,
|
useUserProfileForm,
|
||||||
@ -70,7 +70,7 @@ export default function UserProfileFormFields(props: UserProfileFormFieldsProps<
|
|||||||
{advancedMsg(attribute.annotations.inputHelperTextBefore)}
|
{advancedMsg(attribute.annotations.inputHelperTextBefore)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<InputFiledByType
|
<InputFieldByType
|
||||||
attribute={attribute}
|
attribute={attribute}
|
||||||
valueOrValues={valueOrValues}
|
valueOrValues={valueOrValues}
|
||||||
displayableErrors={displayableErrors}
|
displayableErrors={displayableErrors}
|
||||||
@ -196,7 +196,7 @@ function FieldErrors(props: { attribute: Attribute; displayableErrors: FormField
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type InputFiledByTypeProps = {
|
type InputFieldByTypeProps = {
|
||||||
attribute: Attribute;
|
attribute: Attribute;
|
||||||
valueOrValues: string | string[];
|
valueOrValues: string | string[];
|
||||||
displayableErrors: FormFieldError[];
|
displayableErrors: FormFieldError[];
|
||||||
@ -205,7 +205,7 @@ type InputFiledByTypeProps = {
|
|||||||
kcClsx: KcClsx;
|
kcClsx: KcClsx;
|
||||||
};
|
};
|
||||||
|
|
||||||
function InputFiledByType(props: InputFiledByTypeProps) {
|
function InputFieldByType(props: InputFieldByTypeProps) {
|
||||||
const { attribute, valueOrValues } = props;
|
const { attribute, valueOrValues } = props;
|
||||||
|
|
||||||
switch (attribute.annotations.inputType) {
|
switch (attribute.annotations.inputType) {
|
||||||
@ -274,9 +274,11 @@ function PasswordWrapper(props: { kcClsx: KcClsx; i18n: I18n; passwordInputId: s
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function InputTag(props: InputFiledByTypeProps & { fieldIndex: number | undefined }) {
|
function InputTag(props: InputFieldByTypeProps & { fieldIndex: number | undefined }) {
|
||||||
const { attribute, fieldIndex, kcClsx, dispatchFormAction, valueOrValues, i18n, displayableErrors } = props;
|
const { attribute, fieldIndex, kcClsx, dispatchFormAction, valueOrValues, i18n, displayableErrors } = props;
|
||||||
|
|
||||||
|
const { advancedMsgStr } = i18n;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<input
|
<input
|
||||||
@ -305,7 +307,9 @@ function InputTag(props: InputFiledByTypeProps & { fieldIndex: number | undefine
|
|||||||
aria-invalid={displayableErrors.find(error => error.fieldIndex === fieldIndex) !== undefined}
|
aria-invalid={displayableErrors.find(error => error.fieldIndex === fieldIndex) !== undefined}
|
||||||
disabled={attribute.readOnly}
|
disabled={attribute.readOnly}
|
||||||
autoComplete={attribute.autocomplete}
|
autoComplete={attribute.autocomplete}
|
||||||
placeholder={attribute.annotations.inputTypePlaceholder}
|
placeholder={
|
||||||
|
attribute.annotations.inputTypePlaceholder === undefined ? undefined : advancedMsgStr(attribute.annotations.inputTypePlaceholder)
|
||||||
|
}
|
||||||
pattern={attribute.annotations.inputTypePattern}
|
pattern={attribute.annotations.inputTypePattern}
|
||||||
size={attribute.annotations.inputTypeSize === undefined ? undefined : parseInt(`${attribute.annotations.inputTypeSize}`)}
|
size={attribute.annotations.inputTypeSize === undefined ? undefined : parseInt(`${attribute.annotations.inputTypeSize}`)}
|
||||||
maxLength={
|
maxLength={
|
||||||
@ -429,7 +433,7 @@ function AddRemoveButtonsMultiValuedAttribute(props: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function InputTagSelects(props: InputFiledByTypeProps) {
|
function InputTagSelects(props: InputFieldByTypeProps) {
|
||||||
const { attribute, dispatchFormAction, kcClsx, valueOrValues } = props;
|
const { attribute, dispatchFormAction, kcClsx, valueOrValues } = props;
|
||||||
|
|
||||||
const { advancedMsg } = props.i18n;
|
const { advancedMsg } = props.i18n;
|
||||||
@ -537,7 +541,7 @@ function InputTagSelects(props: InputFiledByTypeProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TextareaTag(props: InputFiledByTypeProps) {
|
function TextareaTag(props: InputFieldByTypeProps) {
|
||||||
const { attribute, dispatchFormAction, kcClsx, displayableErrors, valueOrValues } = props;
|
const { attribute, dispatchFormAction, kcClsx, displayableErrors, valueOrValues } = props;
|
||||||
|
|
||||||
assert(typeof valueOrValues === "string");
|
assert(typeof valueOrValues === "string");
|
||||||
@ -573,7 +577,7 @@ function TextareaTag(props: InputFiledByTypeProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectTag(props: InputFiledByTypeProps) {
|
function SelectTag(props: InputFieldByTypeProps) {
|
||||||
const { attribute, dispatchFormAction, kcClsx, displayableErrors, i18n, valueOrValues } = props;
|
const { attribute, dispatchFormAction, kcClsx, displayableErrors, i18n, valueOrValues } = props;
|
||||||
|
|
||||||
const { advancedMsg } = i18n;
|
const { advancedMsg } = i18n;
|
||||||
|
6
src/login/i18n/GenericI18n.tsx
Normal file
6
src/login/i18n/GenericI18n.tsx
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import type { GenericI18n_noJsx } from "./i18n";
|
||||||
|
|
||||||
|
export type GenericI18n<MessageKey extends string> = GenericI18n_noJsx<MessageKey> & {
|
||||||
|
msg: (key: MessageKey, ...args: (string | undefined)[]) => JSX.Element;
|
||||||
|
advancedMsg: (key: string, ...args: (string | undefined)[]) => JSX.Element;
|
||||||
|
};
|
@ -1,9 +1,10 @@
|
|||||||
import "keycloakify/tools/Object.fromEntries";
|
import "keycloakify/tools/Object.fromEntries";
|
||||||
import { assert } from "tsafe/assert";
|
import { assert } from "tsafe/assert";
|
||||||
import messages_fallbackLanguage from "./baseMessages/en";
|
import messages_defaultSet_fallbackLanguage from "./messages_defaultSet/en";
|
||||||
import { getMessages } from "./baseMessages";
|
import { fetchMessages_defaultSet } from "./messages_defaultSet";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import { fallbackLanguageTag } from "keycloakify/bin/shared/constants";
|
import { FALLBACK_LANGUAGE_TAG } from "keycloakify/bin/shared/constants";
|
||||||
|
import { id } from "tsafe/id";
|
||||||
|
|
||||||
export type KcContextLike = {
|
export type KcContextLike = {
|
||||||
locale?: {
|
locale?: {
|
||||||
@ -11,16 +12,13 @@ export type KcContextLike = {
|
|||||||
supported: { languageTag: string; url: string; label: string }[];
|
supported: { languageTag: string; url: string; label: string }[];
|
||||||
};
|
};
|
||||||
"x-keycloakify": {
|
"x-keycloakify": {
|
||||||
realmMessageBundleUserProfile: Record<string, string> | undefined;
|
messages: Record<string, string>;
|
||||||
realmMessageBundleTermsText: string | undefined;
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
assert<KcContext extends KcContextLike ? true : false>();
|
assert<KcContext extends KcContextLike ? true : false>();
|
||||||
|
|
||||||
export type MessageKey = keyof typeof messages_fallbackLanguage;
|
export type GenericI18n_noJsx<MessageKey extends string> = {
|
||||||
|
|
||||||
export type GenericI18n<MessageKey extends string> = {
|
|
||||||
/**
|
/**
|
||||||
* e.g: "en", "fr", "zh-CN"
|
* e.g: "en", "fr", "zh-CN"
|
||||||
*
|
*
|
||||||
@ -40,16 +38,21 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
* */
|
* */
|
||||||
labelBySupportedLanguageTag: Record<string, string>;
|
labelBySupportedLanguageTag: Record<string, string>;
|
||||||
/**
|
/**
|
||||||
* Examples assuming currentLanguageTag === "en"
|
|
||||||
*
|
*
|
||||||
* msg("access-denied") === <span>Access denied</span>
|
* Examples assuming currentLanguageTag === "en"
|
||||||
* msg("impersonateTitleHtml", "Foo") === <span><strong>Foo</strong> Impersonate User</span>
|
* {
|
||||||
*/
|
* en: {
|
||||||
msg: (key: MessageKey, ...args: (string | undefined)[]) => JSX.Element;
|
* "access-denied": "Access denied",
|
||||||
/**
|
* "impersonateTitleHtml": "<strong>{0}</strong> Impersonate User",
|
||||||
* It's the same thing as msg() but instead of returning a JSX.Element it returns a string.
|
* "bar": "Bar {0}"
|
||||||
* It can be more convenient to manipulate strings but if there are HTML tags it wont render.
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* msgStr("access-denied") === "Access denied"
|
||||||
|
* msgStr("not-a-message-key") Throws an error
|
||||||
* msgStr("impersonateTitleHtml", "Foo") === "<strong>Foo</strong> Impersonate User"
|
* msgStr("impersonateTitleHtml", "Foo") === "<strong>Foo</strong> Impersonate User"
|
||||||
|
* msgStr("${bar}", "<strong>c</strong>") === "Bar <strong>XXX</strong>"
|
||||||
|
* The html in the arg is partially escaped for security reasons, it might come from an untrusted source, it's not safe to render it as html.
|
||||||
*/
|
*/
|
||||||
msgStr: (key: MessageKey, ...args: (string | undefined)[]) => string;
|
msgStr: (key: MessageKey, ...args: (string | undefined)[]) => string;
|
||||||
/**
|
/**
|
||||||
@ -60,24 +63,11 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
* {
|
* {
|
||||||
* en: {
|
* en: {
|
||||||
* "access-denied": "Access denied",
|
* "access-denied": "Access denied",
|
||||||
* "foo": "Foo {0} {1}",
|
|
||||||
* "bar": "Bar {0}"
|
|
||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* advancedMsg("${access-denied} foo bar") === <span>{msgStr("access-denied")} foo bar<span> === <span>Access denied foo bar</span>
|
* advancedMsgStr("${access-denied}") === advancedMsgStr("access-denied") === msgStr("access-denied") === "Access denied"
|
||||||
* advancedMsg("${access-denied}") === advancedMsg("access-denied") === msg("access-denied") === <span>Access denied</span>
|
* advancedMsgStr("${not-a-message-key}") === advancedMsgStr("not-a-message-key") === "not-a-message-key"
|
||||||
* advancedMsg("${not-a-message-key}") === advancedMsg(not-a-message-key") === <span>not-a-message-key</span>
|
|
||||||
* advancedMsg("${bar}", "<strong>c</strong>")
|
|
||||||
* === <span>{msgStr("bar", "<strong>XXX</strong>")}<span>
|
|
||||||
* === <span>Bar <strong>XXX</strong></span> (The html in the arg is partially escaped for security reasons, it might be untrusted)
|
|
||||||
* advancedMsg("${foo} xx ${bar}", "a", "b", "c")
|
|
||||||
* === <span>{msgStr("foo", "a", "b")} xx {msgStr("bar")}<span>
|
|
||||||
* === <span>Foo a b xx Bar {0}</span> (The substitution are only applied in the first message)
|
|
||||||
*/
|
|
||||||
advancedMsg: (key: string, ...args: (string | undefined)[]) => JSX.Element;
|
|
||||||
/**
|
|
||||||
* See advancedMsg() but instead of returning a JSX.Element it returns a string.
|
|
||||||
*/
|
*/
|
||||||
advancedMsgStr: (key: string, ...args: (string | undefined)[]) => string;
|
advancedMsgStr: (key: string, ...args: (string | undefined)[]) => string;
|
||||||
|
|
||||||
@ -89,10 +79,12 @@ export type GenericI18n<MessageKey extends string> = {
|
|||||||
isFetchingTranslations: boolean;
|
isFetchingTranslations: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createGetI18n<ExtraMessageKey extends string = never>(messageBundle: {
|
export type MessageKey_defaultSet = keyof typeof messages_defaultSet_fallbackLanguage;
|
||||||
[languageTag: string]: { [key in ExtraMessageKey]: string };
|
|
||||||
|
export function createGetI18n<MessageKey_themeDefined extends string = never>(messagesByLanguageTag_themeDefined: {
|
||||||
|
[languageTag: string]: { [key in MessageKey_themeDefined]: string };
|
||||||
}) {
|
}) {
|
||||||
type I18n = GenericI18n<MessageKey | ExtraMessageKey>;
|
type I18n = GenericI18n_noJsx<MessageKey_defaultSet | MessageKey_themeDefined>;
|
||||||
|
|
||||||
type Result = { i18n: I18n; prI18n_currentLanguage: Promise<I18n> | undefined };
|
type Result = { i18n: I18n; prI18n_currentLanguage: Promise<I18n> | undefined };
|
||||||
|
|
||||||
@ -112,7 +104,7 @@ export function createGetI18n<ExtraMessageKey extends string = never>(messageBun
|
|||||||
}
|
}
|
||||||
|
|
||||||
const partialI18n: Pick<I18n, "currentLanguageTag" | "getChangeLocaleUrl" | "labelBySupportedLanguageTag"> = {
|
const partialI18n: Pick<I18n, "currentLanguageTag" | "getChangeLocaleUrl" | "labelBySupportedLanguageTag"> = {
|
||||||
currentLanguageTag: kcContext.locale?.currentLanguageTag ?? fallbackLanguageTag,
|
currentLanguageTag: kcContext.locale?.currentLanguageTag ?? FALLBACK_LANGUAGE_TAG,
|
||||||
getChangeLocaleUrl: newLanguageTag => {
|
getChangeLocaleUrl: newLanguageTag => {
|
||||||
const { locale } = kcContext;
|
const { locale } = kcContext;
|
||||||
|
|
||||||
@ -127,32 +119,38 @@ export function createGetI18n<ExtraMessageKey extends string = never>(messageBun
|
|||||||
labelBySupportedLanguageTag: Object.fromEntries((kcContext.locale?.supported ?? []).map(({ languageTag, label }) => [languageTag, label]))
|
labelBySupportedLanguageTag: Object.fromEntries((kcContext.locale?.supported ?? []).map(({ languageTag, label }) => [languageTag, label]))
|
||||||
};
|
};
|
||||||
|
|
||||||
const { createI18nTranslationFunctions } = createI18nTranslationFunctionsFactory<MessageKey, ExtraMessageKey>({
|
const { createI18nTranslationFunctions } = createI18nTranslationFunctionsFactory<MessageKey_themeDefined>({
|
||||||
messages_fallbackLanguage,
|
messages_themeDefined:
|
||||||
messageBundle_fallbackLanguage: messageBundle[fallbackLanguageTag],
|
messagesByLanguageTag_themeDefined[partialI18n.currentLanguageTag] ??
|
||||||
messageBundle_currentLanguage: messageBundle[partialI18n.currentLanguageTag],
|
messagesByLanguageTag_themeDefined[FALLBACK_LANGUAGE_TAG] ??
|
||||||
realmMessageBundleUserProfile: kcContext["x-keycloakify"].realmMessageBundleUserProfile,
|
(() => {
|
||||||
realmMessageBundleTermsText: kcContext["x-keycloakify"].realmMessageBundleTermsText
|
const firstLanguageTag = Object.keys(messagesByLanguageTag_themeDefined)[0];
|
||||||
|
if (firstLanguageTag === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return messagesByLanguageTag_themeDefined[firstLanguageTag];
|
||||||
|
})(),
|
||||||
|
messages_fromKcServer: kcContext["x-keycloakify"].messages
|
||||||
});
|
});
|
||||||
|
|
||||||
const isCurrentLanguageFallbackLanguage = partialI18n.currentLanguageTag === fallbackLanguageTag;
|
const isCurrentLanguageFallbackLanguage = partialI18n.currentLanguageTag === FALLBACK_LANGUAGE_TAG;
|
||||||
|
|
||||||
const result: Result = {
|
const result: Result = {
|
||||||
i18n: {
|
i18n: {
|
||||||
...partialI18n,
|
...partialI18n,
|
||||||
...createI18nTranslationFunctions({
|
...createI18nTranslationFunctions({
|
||||||
messages_currentLanguage: isCurrentLanguageFallbackLanguage ? messages_fallbackLanguage : undefined
|
messages_defaultSet_currentLanguage: isCurrentLanguageFallbackLanguage ? messages_defaultSet_fallbackLanguage : undefined
|
||||||
}),
|
}),
|
||||||
isFetchingTranslations: !isCurrentLanguageFallbackLanguage
|
isFetchingTranslations: !isCurrentLanguageFallbackLanguage
|
||||||
},
|
},
|
||||||
prI18n_currentLanguage: isCurrentLanguageFallbackLanguage
|
prI18n_currentLanguage: isCurrentLanguageFallbackLanguage
|
||||||
? undefined
|
? undefined
|
||||||
: (async () => {
|
: (async () => {
|
||||||
const messages_currentLanguage = await getMessages(partialI18n.currentLanguageTag);
|
const messages_defaultSet_currentLanguage = await fetchMessages_defaultSet(partialI18n.currentLanguageTag);
|
||||||
|
|
||||||
const i18n_currentLanguage: I18n = {
|
const i18n_currentLanguage: I18n = {
|
||||||
...partialI18n,
|
...partialI18n,
|
||||||
...createI18nTranslationFunctions({ messages_currentLanguage }),
|
...createI18nTranslationFunctions({ messages_defaultSet_currentLanguage }),
|
||||||
isFetchingTranslations: false
|
isFetchingTranslations: false
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -175,151 +173,72 @@ export function createGetI18n<ExtraMessageKey extends string = never>(messageBun
|
|||||||
return { getI18n };
|
return { getI18n };
|
||||||
}
|
}
|
||||||
|
|
||||||
function createI18nTranslationFunctionsFactory<MessageKey extends string, ExtraMessageKey extends string>(params: {
|
function createI18nTranslationFunctionsFactory<MessageKey_themeDefined extends string>(params: {
|
||||||
messages_fallbackLanguage: Record<MessageKey, string>;
|
messages_themeDefined: Record<MessageKey_themeDefined, string> | undefined;
|
||||||
messageBundle_fallbackLanguage: Record<ExtraMessageKey, string> | undefined;
|
messages_fromKcServer: Record<string, string>;
|
||||||
messageBundle_currentLanguage: Partial<Record<ExtraMessageKey, string>> | undefined;
|
|
||||||
realmMessageBundleUserProfile: Record<string, string> | undefined;
|
|
||||||
realmMessageBundleTermsText: string | undefined;
|
|
||||||
}) {
|
}) {
|
||||||
const { messageBundle_currentLanguage, realmMessageBundleUserProfile, realmMessageBundleTermsText } = params;
|
const { messages_themeDefined, messages_fromKcServer } = params;
|
||||||
|
|
||||||
const messages_fallbackLanguage = {
|
|
||||||
...params.messages_fallbackLanguage,
|
|
||||||
...params.messageBundle_fallbackLanguage
|
|
||||||
};
|
|
||||||
|
|
||||||
function createI18nTranslationFunctions(params: {
|
function createI18nTranslationFunctions(params: {
|
||||||
messages_currentLanguage: Partial<Record<MessageKey, string>> | undefined;
|
messages_defaultSet_currentLanguage: Partial<Record<MessageKey_defaultSet, string>> | undefined;
|
||||||
}): Pick<GenericI18n<MessageKey | ExtraMessageKey>, "msg" | "msgStr" | "advancedMsg" | "advancedMsgStr"> {
|
}): Pick<GenericI18n_noJsx<MessageKey_defaultSet | MessageKey_themeDefined>, "msgStr" | "advancedMsgStr"> {
|
||||||
const messages_currentLanguage = {
|
const { messages_defaultSet_currentLanguage } = params;
|
||||||
...params.messages_currentLanguage,
|
|
||||||
...messageBundle_currentLanguage
|
|
||||||
};
|
|
||||||
|
|
||||||
function resolveMsg(props: { key: string; args: (string | undefined)[]; doRenderAsHtml: boolean }): string | JSX.Element | undefined {
|
function resolveMsg(props: { key: string; args: (string | undefined)[] }): string | undefined {
|
||||||
const { key, args, doRenderAsHtml } = props;
|
const { key, args } = props;
|
||||||
|
|
||||||
const messageOrUndefined: string | undefined = (() => {
|
const message =
|
||||||
const messageOrUndefined = (messages_currentLanguage as any)[key] ?? (messages_fallbackLanguage as any)[key];
|
id<Record<string, string | undefined>>(messages_fromKcServer)[key] ??
|
||||||
|
id<Record<string, string | undefined> | undefined>(messages_themeDefined)?.[key] ??
|
||||||
|
id<Record<string, string | undefined> | undefined>(messages_defaultSet_currentLanguage)?.[key] ??
|
||||||
|
id<Record<string, string | undefined>>(messages_defaultSet_fallbackLanguage)[key];
|
||||||
|
|
||||||
if (key === "termsText" && realmMessageBundleTermsText !== undefined) {
|
if (message === undefined) {
|
||||||
return realmMessageBundleTermsText;
|
|
||||||
}
|
|
||||||
|
|
||||||
return messageOrUndefined;
|
|
||||||
})();
|
|
||||||
|
|
||||||
if (messageOrUndefined === undefined) {
|
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = messageOrUndefined;
|
const startIndex = message
|
||||||
|
.match(/{[0-9]+}/g)
|
||||||
|
?.map(g => g.match(/{([0-9]+)}/)![1])
|
||||||
|
.map(indexStr => parseInt(indexStr))
|
||||||
|
.sort((a, b) => a - b)[0];
|
||||||
|
|
||||||
const messageWithArgsInjectedIfAny = (() => {
|
if (startIndex === undefined) {
|
||||||
const startIndex = message
|
// No {0} in message (no arguments expected)
|
||||||
.match(/{[0-9]+}/g)
|
return message;
|
||||||
?.map(g => g.match(/{([0-9]+)}/)![1])
|
}
|
||||||
.map(indexStr => parseInt(indexStr))
|
|
||||||
.sort((a, b) => a - b)[0];
|
|
||||||
|
|
||||||
if (startIndex === undefined) {
|
let messageWithArgsInjected = message;
|
||||||
// No {0} in message (no arguments expected)
|
|
||||||
return message;
|
args.forEach((arg, i) => {
|
||||||
|
if (arg === undefined) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let messageWithArgsInjected = message;
|
messageWithArgsInjected = messageWithArgsInjected.replace(
|
||||||
|
new RegExp(`\\{${i + startIndex}\\}`, "g"),
|
||||||
args.forEach((arg, i) => {
|
arg.replace(/</g, "<").replace(/>/g, ">")
|
||||||
if (arg === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
messageWithArgsInjected = messageWithArgsInjected.replace(
|
|
||||||
new RegExp(`\\{${i + startIndex}\\}`, "g"),
|
|
||||||
arg.replace(/</g, "<").replace(/>/g, ">")
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
return messageWithArgsInjected;
|
|
||||||
})();
|
|
||||||
|
|
||||||
return doRenderAsHtml ? (
|
|
||||||
<span
|
|
||||||
// NOTE: The message is trusted. The arguments are not but are escaped.
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: messageWithArgsInjectedIfAny
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
messageWithArgsInjectedIfAny
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveMsgAdvanced(props: { key: string; args: (string | undefined)[]; doRenderAsHtml: boolean }): JSX.Element | string {
|
|
||||||
const { key, args, doRenderAsHtml } = props;
|
|
||||||
|
|
||||||
user_profile: {
|
|
||||||
if (realmMessageBundleUserProfile === undefined) {
|
|
||||||
break user_profile;
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolvedMessage = realmMessageBundleUserProfile[key] ?? realmMessageBundleUserProfile["${" + key + "}"];
|
|
||||||
|
|
||||||
if (resolvedMessage === undefined) {
|
|
||||||
break user_profile;
|
|
||||||
}
|
|
||||||
|
|
||||||
return doRenderAsHtml ? (
|
|
||||||
<span
|
|
||||||
// NOTE: The message is trusted. The arguments are not but are escaped.
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: resolvedMessage
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
resolvedMessage
|
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
if (!/\$\{[^}]+\}/.test(key)) {
|
|
||||||
const resolvedMessage = resolveMsg({ key, args, doRenderAsHtml });
|
|
||||||
|
|
||||||
if (resolvedMessage === undefined) {
|
|
||||||
return doRenderAsHtml ? <span dangerouslySetInnerHTML={{ __html: key }} /> : key;
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolvedMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
let isFirstMatch = true;
|
|
||||||
|
|
||||||
const resolvedComplexMessage = key.replace(/\$\{([^}]+)\}/g, (...[, key_i]) => {
|
|
||||||
const replaceBy = resolveMsg({ key: key_i, args: isFirstMatch ? args : [], doRenderAsHtml: false }) ?? key_i;
|
|
||||||
|
|
||||||
isFirstMatch = false;
|
|
||||||
|
|
||||||
return replaceBy;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return doRenderAsHtml ? <span dangerouslySetInnerHTML={{ __html: resolvedComplexMessage }} /> : resolvedComplexMessage;
|
return messageWithArgsInjected;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveMsgAdvanced(props: { key: string; args: (string | undefined)[] }): string {
|
||||||
|
const { key, args } = props;
|
||||||
|
|
||||||
|
const match = key.match(/^\$\{(.+)\}$/);
|
||||||
|
|
||||||
|
return resolveMsg({ key: match !== null ? match[1] : key, args }) ?? key;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
msgStr: (key, ...args) => resolveMsg({ key, args, doRenderAsHtml: false }) as string,
|
msgStr: (key, ...args) => {
|
||||||
msg: (key, ...args) => resolveMsg({ key, args, doRenderAsHtml: true }) as JSX.Element,
|
const resolvedMessage = resolveMsg({ key, args });
|
||||||
advancedMsg: (key, ...args) =>
|
assert(resolvedMessage !== undefined, `Message with key "${key}" not found`);
|
||||||
resolveMsgAdvanced({
|
return resolvedMessage;
|
||||||
key,
|
},
|
||||||
args,
|
advancedMsgStr: (key, ...args) => resolveMsgAdvanced({ key, args })
|
||||||
doRenderAsHtml: true
|
|
||||||
}) as JSX.Element,
|
|
||||||
advancedMsgStr: (key, ...args) =>
|
|
||||||
resolveMsgAdvanced({
|
|
||||||
key,
|
|
||||||
args,
|
|
||||||
doRenderAsHtml: false
|
|
||||||
}) as string
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import type { GenericI18n, MessageKey, KcContextLike } from "./i18n";
|
import type { GenericI18n } from "./GenericI18n";
|
||||||
export type { MessageKey, KcContextLike };
|
import type { MessageKey_defaultSet, KcContextLike } from "./i18n";
|
||||||
export type I18n = GenericI18n<MessageKey>;
|
export type { MessageKey_defaultSet, KcContextLike };
|
||||||
|
export type I18n = GenericI18n<MessageKey_defaultSet>;
|
||||||
export { createUseI18n } from "./useI18n";
|
export { createUseI18n } from "./useI18n";
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
import {
|
|
||||||
createGetI18n,
|
|
||||||
type GenericI18n,
|
|
||||||
type MessageKey,
|
|
||||||
type KcContextLike
|
|
||||||
} from "./i18n";
|
|
||||||
import { Reflect } from "tsafe/Reflect";
|
|
||||||
|
|
||||||
export function createUseI18n<ExtraMessageKey extends string = never>(messageBundle: {
|
|
||||||
[languageTag: string]: { [key in ExtraMessageKey]: string };
|
|
||||||
}) {
|
|
||||||
type I18n = GenericI18n<MessageKey | ExtraMessageKey>;
|
|
||||||
|
|
||||||
const { getI18n } = createGetI18n(messageBundle);
|
|
||||||
|
|
||||||
function useI18n(params: { kcContext: KcContextLike }): { i18n: I18n } {
|
|
||||||
const { kcContext } = params;
|
|
||||||
|
|
||||||
const { i18n, prI18n_currentLanguage } = getI18n({ kcContext });
|
|
||||||
|
|
||||||
const [i18n_toReturn, setI18n_toReturn] = useState<I18n>(i18n);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let isActive = true;
|
|
||||||
|
|
||||||
prI18n_currentLanguage?.then(i18n => {
|
|
||||||
if (!isActive) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setI18n_toReturn(i18n);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
isActive = false;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return { i18n: i18n_toReturn };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { useI18n, ofTypeI18n: Reflect<I18n>() };
|
|
||||||
}
|
|
95
src/login/i18n/useI18n.tsx
Normal file
95
src/login/i18n/useI18n.tsx
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { createGetI18n, type GenericI18n_noJsx, type KcContextLike, type MessageKey_defaultSet } from "./i18n";
|
||||||
|
import { GenericI18n } from "./GenericI18n";
|
||||||
|
import { Reflect } from "tsafe/Reflect";
|
||||||
|
|
||||||
|
export function createUseI18n<MessageKey_themeDefined extends string = never>(messagesByLanguageTag: {
|
||||||
|
[languageTag: string]: { [key in MessageKey_themeDefined]: string };
|
||||||
|
}) {
|
||||||
|
type MessageKey = MessageKey_defaultSet | MessageKey_themeDefined;
|
||||||
|
|
||||||
|
type I18n = GenericI18n<MessageKey>;
|
||||||
|
|
||||||
|
const { withJsx } = (() => {
|
||||||
|
const cache = new WeakMap<GenericI18n_noJsx<MessageKey>, GenericI18n<MessageKey>>();
|
||||||
|
|
||||||
|
function renderHtmlString(params: { htmlString: string; msgKey: string }): JSX.Element {
|
||||||
|
const { htmlString, msgKey } = params;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-kc-msg={msgKey}
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: htmlString
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withJsx(i18n_noJsx: GenericI18n_noJsx<MessageKey>): I18n {
|
||||||
|
use_cache: {
|
||||||
|
const i18n = cache.get(i18n_noJsx);
|
||||||
|
|
||||||
|
if (i18n === undefined) {
|
||||||
|
break use_cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
const i18n: I18n = {
|
||||||
|
...i18n_noJsx,
|
||||||
|
msg: (msgKey, ...args) => renderHtmlString({ htmlString: i18n_noJsx.msgStr(msgKey, ...args), msgKey }),
|
||||||
|
advancedMsg: (msgKey, ...args) => renderHtmlString({ htmlString: i18n_noJsx.advancedMsgStr(msgKey, ...args), msgKey })
|
||||||
|
};
|
||||||
|
|
||||||
|
cache.set(i18n_noJsx, i18n);
|
||||||
|
|
||||||
|
return i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { withJsx };
|
||||||
|
})();
|
||||||
|
|
||||||
|
add_style: {
|
||||||
|
const attributeName = "data-kc-i18n";
|
||||||
|
|
||||||
|
// Check if already exists in head
|
||||||
|
if (document.querySelector(`style[${attributeName}]`) !== null) {
|
||||||
|
break add_style;
|
||||||
|
}
|
||||||
|
|
||||||
|
const styleElement = document.createElement("style");
|
||||||
|
styleElement.attributes.setNamedItem(document.createAttribute(attributeName));
|
||||||
|
(styleElement.textContent = `[data-kc-msg] { display: inline-block; }`), document.head.prepend(styleElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { getI18n } = createGetI18n(messagesByLanguageTag);
|
||||||
|
|
||||||
|
function useI18n(params: { kcContext: KcContextLike }): { i18n: I18n } {
|
||||||
|
const { kcContext } = params;
|
||||||
|
|
||||||
|
const { i18n, prI18n_currentLanguage } = getI18n({ kcContext });
|
||||||
|
|
||||||
|
const [i18n_toReturn, setI18n_toReturn] = useState<I18n>(withJsx(i18n));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let isActive = true;
|
||||||
|
|
||||||
|
prI18n_currentLanguage?.then(i18n => {
|
||||||
|
if (!isActive) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setI18n_toReturn(withJsx(i18n));
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isActive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { i18n: i18n_toReturn };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { useI18n, ofTypeI18n: Reflect<I18n>() };
|
||||||
|
}
|
@ -9,7 +9,7 @@ import { formatNumber } from "keycloakify/tools/formatNumber";
|
|||||||
import { useInsertScriptTags } from "keycloakify/tools/useInsertScriptTags";
|
import { useInsertScriptTags } from "keycloakify/tools/useInsertScriptTags";
|
||||||
import type { PasswordPolicies, Attribute, Validators } from "keycloakify/login/KcContext";
|
import type { PasswordPolicies, Attribute, Validators } from "keycloakify/login/KcContext";
|
||||||
import type { KcContext } from "../KcContext";
|
import type { KcContext } from "../KcContext";
|
||||||
import type { MessageKey } from "keycloakify/login/i18n";
|
import type { MessageKey_defaultSet } from "keycloakify/login/i18n";
|
||||||
import { KcContextLike as KcContextLike_i18n } from "keycloakify/login/i18n";
|
import { KcContextLike as KcContextLike_i18n } from "keycloakify/login/i18n";
|
||||||
import type { I18n } from "../i18n";
|
import type { I18n } from "../i18n";
|
||||||
|
|
||||||
@ -59,6 +59,8 @@ export type FormAction =
|
|||||||
action: "update";
|
action: "update";
|
||||||
name: string;
|
name: string;
|
||||||
valueOrValues: string | string[];
|
valueOrValues: string | string[];
|
||||||
|
/** Default false */
|
||||||
|
displayErrorsImmediately?: boolean;
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
action: "focus lost";
|
action: "focus lost";
|
||||||
@ -148,7 +150,7 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
.map(name =>
|
.map(name =>
|
||||||
id<Attribute>({
|
id<Attribute>({
|
||||||
name: name,
|
name: name,
|
||||||
displayName: id<`\${${MessageKey}}`>(`\${${name}}`),
|
displayName: id<`\${${MessageKey_defaultSet}}`>(`\${${name}}`),
|
||||||
required: true,
|
required: true,
|
||||||
value: (kcContext.register as any).formData[name] ?? "",
|
value: (kcContext.register as any).formData[name] ?? "",
|
||||||
html5DataAnnotations: {},
|
html5DataAnnotations: {},
|
||||||
@ -176,7 +178,7 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
.map(name =>
|
.map(name =>
|
||||||
id<Attribute>({
|
id<Attribute>({
|
||||||
name: name,
|
name: name,
|
||||||
displayName: id<`\${${MessageKey}}`>(`\${${name}}`),
|
displayName: id<`\${${MessageKey_defaultSet}}`>(`\${${name}}`),
|
||||||
required: true,
|
required: true,
|
||||||
value: (kcContext as any).user[name] ?? "",
|
value: (kcContext as any).user[name] ?? "",
|
||||||
html5DataAnnotations: {},
|
html5DataAnnotations: {},
|
||||||
@ -202,7 +204,7 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
return [
|
return [
|
||||||
id<Attribute>({
|
id<Attribute>({
|
||||||
name: "email",
|
name: "email",
|
||||||
displayName: id<`\${${MessageKey}}`>(`\${email}`),
|
displayName: id<`\${${MessageKey_defaultSet}}`>(`\${email}`),
|
||||||
required: true,
|
required: true,
|
||||||
value: (kcContext.email as any).value ?? "",
|
value: (kcContext.email as any).value ?? "",
|
||||||
html5DataAnnotations: {},
|
html5DataAnnotations: {},
|
||||||
@ -227,7 +229,7 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
break patch_legacy_group;
|
break patch_legacy_group;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { group, groupDisplayHeader, groupDisplayDescription /*, groupAnnotations*/ } = attribute as Attribute & {
|
const { group, groupDisplayHeader, groupDisplayDescription, groupAnnotations } = attribute as Attribute & {
|
||||||
group: string;
|
group: string;
|
||||||
groupDisplayHeader?: string;
|
groupDisplayHeader?: string;
|
||||||
groupDisplayDescription?: string;
|
groupDisplayDescription?: string;
|
||||||
@ -250,6 +252,7 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
name: group,
|
name: group,
|
||||||
displayHeader: groupDisplayHeader,
|
displayHeader: groupDisplayHeader,
|
||||||
displayDescription: groupDisplayDescription,
|
displayDescription: groupDisplayDescription,
|
||||||
|
annotations: groupAnnotations,
|
||||||
html5DataAnnotations: {}
|
html5DataAnnotations: {}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -292,7 +295,7 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
0,
|
0,
|
||||||
{
|
{
|
||||||
name: "password",
|
name: "password",
|
||||||
displayName: id<`\${${MessageKey}}`>("${password}"),
|
displayName: id<`\${${MessageKey_defaultSet}}`>("${password}"),
|
||||||
required: true,
|
required: true,
|
||||||
readOnly: false,
|
readOnly: false,
|
||||||
validators: {},
|
validators: {},
|
||||||
@ -302,7 +305,7 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "password-confirm",
|
name: "password-confirm",
|
||||||
displayName: id<`\${${MessageKey}}`>("${passwordConfirm}"),
|
displayName: id<`\${${MessageKey_defaultSet}}`>("${passwordConfirm}"),
|
||||||
required: true,
|
required: true,
|
||||||
readOnly: false,
|
readOnly: false,
|
||||||
validators: {},
|
validators: {},
|
||||||
@ -412,6 +415,24 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
formFieldStates: state.formFieldStates
|
formFieldStates: state.formFieldStates
|
||||||
});
|
});
|
||||||
|
|
||||||
|
simulate_focus_lost: {
|
||||||
|
const { displayErrorsImmediately = false } = formAction;
|
||||||
|
|
||||||
|
if (!displayErrorsImmediately) {
|
||||||
|
break simulate_focus_lost;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const fieldIndex of formAction.valueOrValues instanceof Array
|
||||||
|
? formAction.valueOrValues.map((...[, index]) => index)
|
||||||
|
: [undefined]) {
|
||||||
|
state = reducer(state, {
|
||||||
|
action: "focus lost",
|
||||||
|
name: formAction.name,
|
||||||
|
fieldIndex
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
update_password_confirm: {
|
update_password_confirm: {
|
||||||
if (doMakeUserConfirmPassword) {
|
if (doMakeUserConfirmPassword) {
|
||||||
break update_password_confirm;
|
break update_password_confirm;
|
||||||
@ -424,7 +445,31 @@ export function useUserProfileForm(params: UseUserProfileFormParams): ReturnType
|
|||||||
state = reducer(state, {
|
state = reducer(state, {
|
||||||
action: "update",
|
action: "update",
|
||||||
name: "password-confirm",
|
name: "password-confirm",
|
||||||
valueOrValues: formAction.valueOrValues
|
valueOrValues: formAction.valueOrValues,
|
||||||
|
displayErrorsImmediately: formAction.displayErrorsImmediately
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
trigger_password_confirm_validation_on_password_change: {
|
||||||
|
if (!doMakeUserConfirmPassword) {
|
||||||
|
break trigger_password_confirm_validation_on_password_change;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formAction.name !== "password") {
|
||||||
|
break trigger_password_confirm_validation_on_password_change;
|
||||||
|
}
|
||||||
|
|
||||||
|
state = reducer(state, {
|
||||||
|
action: "update",
|
||||||
|
name: "password-confirm",
|
||||||
|
valueOrValues: (() => {
|
||||||
|
const formFieldState = state.formFieldStates.find(({ attribute }) => attribute.name === "password-confirm");
|
||||||
|
|
||||||
|
assert(formFieldState !== undefined);
|
||||||
|
|
||||||
|
return formFieldState.valueOrValues;
|
||||||
|
})(),
|
||||||
|
displayErrorsImmediately: formAction.displayErrorsImmediately
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1133,7 +1178,7 @@ function useGetErrors(params: { kcContext: KcContextLike_useGetErrors; i18n: I18
|
|||||||
break validator_x;
|
break validator_x;
|
||||||
}
|
}
|
||||||
|
|
||||||
const msgArgs = [errorMessageKey ?? id<MessageKey>("shouldMatchPattern"), pattern] as const;
|
const msgArgs = [errorMessageKey ?? id<MessageKey_defaultSet>("shouldMatchPattern"), pattern] as const;
|
||||||
|
|
||||||
errors.push({
|
errors.push({
|
||||||
errorMessage: <Fragment key={`${attributeName}-${errors.length}`}>{advancedMsg(...msgArgs)}</Fragment>,
|
errorMessage: <Fragment key={`${attributeName}-${errors.length}`}>{advancedMsg(...msgArgs)}</Fragment>,
|
||||||
@ -1172,7 +1217,7 @@ function useGetErrors(params: { kcContext: KcContextLike_useGetErrors; i18n: I18
|
|||||||
break validator_x;
|
break validator_x;
|
||||||
}
|
}
|
||||||
|
|
||||||
const msgArgs = [id<MessageKey>("invalidEmailMessage")] as const;
|
const msgArgs = [id<MessageKey_defaultSet>("invalidEmailMessage")] as const;
|
||||||
|
|
||||||
errors.push({
|
errors.push({
|
||||||
errorMessage: <Fragment key={`${attributeName}-${errors.length}`}>{msg(...msgArgs)}</Fragment>,
|
errorMessage: <Fragment key={`${attributeName}-${errors.length}`}>{msg(...msgArgs)}</Fragment>,
|
||||||
@ -1264,11 +1309,11 @@ function useGetErrors(params: { kcContext: KcContextLike_useGetErrors; i18n: I18
|
|||||||
break validator_x;
|
break validator_x;
|
||||||
}
|
}
|
||||||
|
|
||||||
const msgArgs = [id<MessageKey>("notAValidOption")] as const;
|
const msgArgs = [id<MessageKey_defaultSet>("notAValidOption")] as const;
|
||||||
|
|
||||||
errors.push({
|
errors.push({
|
||||||
errorMessage: <Fragment key={`${attributeName}-${errors.length}`}>{advancedMsg(...msgArgs)}</Fragment>,
|
errorMessage: <Fragment key={`${attributeName}-${errors.length}`}>{msg(...msgArgs)}</Fragment>,
|
||||||
errorMessageStr: advancedMsgStr(...msgArgs),
|
errorMessageStr: msgStr(...msgArgs),
|
||||||
fieldIndex: undefined,
|
fieldIndex: undefined,
|
||||||
source: {
|
source: {
|
||||||
type: "validator",
|
type: "validator",
|
||||||
|
@ -5,7 +5,7 @@ import type { I18n } from "../i18n";
|
|||||||
export default function Info(props: PageProps<Extract<KcContext, { pageId: "info.ftl" }>, I18n>) {
|
export default function Info(props: PageProps<Extract<KcContext, { pageId: "info.ftl" }>, I18n>) {
|
||||||
const { kcContext, i18n, doUseDefaultCss, Template, classes } = props;
|
const { kcContext, i18n, doUseDefaultCss, Template, classes } = props;
|
||||||
|
|
||||||
const { msgStr, msg } = i18n;
|
const { advancedMsgStr, msg } = i18n;
|
||||||
|
|
||||||
const { messageHeader, message, requiredActions, skipLink, pageRedirectUri, actionUri, client } = kcContext;
|
const { messageHeader, message, requiredActions, skipLink, pageRedirectUri, actionUri, client } = kcContext;
|
||||||
|
|
||||||
@ -34,7 +34,7 @@ export default function Info(props: PageProps<Extract<KcContext, { pageId: "info
|
|||||||
if (requiredActions) {
|
if (requiredActions) {
|
||||||
html += "<b>";
|
html += "<b>";
|
||||||
|
|
||||||
html += requiredActions.map(requiredAction => msgStr(`requiredAction.${requiredAction}` as const)).join(",");
|
html += requiredActions.map(requiredAction => advancedMsgStr(`requiredAction.${requiredAction}`)).join(", ");
|
||||||
|
|
||||||
html += "</b>";
|
html += "</b>";
|
||||||
}
|
}
|
||||||
|
@ -32,30 +32,30 @@ export default function LoginUpdatePassword(props: PageProps<Extract<KcContext,
|
|||||||
<label htmlFor="password-new" className={kcClsx("kcLabelClass")}>
|
<label htmlFor="password-new" className={kcClsx("kcLabelClass")}>
|
||||||
{msg("passwordNew")}
|
{msg("passwordNew")}
|
||||||
</label>
|
</label>
|
||||||
<div className={kcClsx("kcInputWrapperClass")}>
|
</div>
|
||||||
<PasswordWrapper kcClsx={kcClsx} i18n={i18n} passwordInputId="password-new">
|
<div className={kcClsx("kcInputWrapperClass")}>
|
||||||
<input
|
<PasswordWrapper kcClsx={kcClsx} i18n={i18n} passwordInputId="password-new">
|
||||||
type="password"
|
<input
|
||||||
id="password-new"
|
type="password"
|
||||||
name="password-new"
|
id="password-new"
|
||||||
className={kcClsx("kcInputClass")}
|
name="password-new"
|
||||||
autoFocus
|
className={kcClsx("kcInputClass")}
|
||||||
autoComplete="new-password"
|
autoFocus
|
||||||
aria-invalid={messagesPerField.existsError("password", "password-confirm")}
|
autoComplete="new-password"
|
||||||
/>
|
aria-invalid={messagesPerField.existsError("password", "password-confirm")}
|
||||||
</PasswordWrapper>
|
/>
|
||||||
|
</PasswordWrapper>
|
||||||
|
|
||||||
{messagesPerField.existsError("password") && (
|
{messagesPerField.existsError("password") && (
|
||||||
<span
|
<span
|
||||||
id="input-error-password"
|
id="input-error-password"
|
||||||
className={kcClsx("kcInputErrorMessageClass")}
|
className={kcClsx("kcInputErrorMessageClass")}
|
||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
dangerouslySetInnerHTML={{
|
dangerouslySetInnerHTML={{
|
||||||
__html: messagesPerField.get("password")
|
__html: messagesPerField.get("password")
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -89,32 +89,30 @@ export default function LoginUpdatePassword(props: PageProps<Extract<KcContext,
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
<div className={kcClsx("kcFormGroupClass")}>
|
<div className={kcClsx("kcFormGroupClass")}>
|
||||||
<LogoutOtherSessions kcClsx={kcClsx} i18n={i18n} />
|
<LogoutOtherSessions kcClsx={kcClsx} i18n={i18n} />
|
||||||
|
<div id="kc-form-buttons" className={kcClsx("kcFormButtonsClass")}>
|
||||||
<div id="kc-form-buttons" className={kcClsx("kcFormButtonsClass")}>
|
<input
|
||||||
<input
|
className={kcClsx(
|
||||||
className={kcClsx(
|
"kcButtonClass",
|
||||||
"kcButtonClass",
|
"kcButtonPrimaryClass",
|
||||||
"kcButtonPrimaryClass",
|
!isAppInitiatedAction && "kcButtonBlockClass",
|
||||||
isAppInitiatedAction && "kcButtonBlockClass",
|
"kcButtonLargeClass"
|
||||||
"kcButtonLargeClass"
|
|
||||||
)}
|
|
||||||
type="submit"
|
|
||||||
value={msgStr("doSubmit")}
|
|
||||||
/>
|
|
||||||
{isAppInitiatedAction && (
|
|
||||||
<button
|
|
||||||
className={kcClsx("kcButtonClass", "kcButtonDefaultClass", "kcButtonLargeClass")}
|
|
||||||
type="submit"
|
|
||||||
name="cancel-aia"
|
|
||||||
value="true"
|
|
||||||
>
|
|
||||||
{msg("doCancel")}
|
|
||||||
</button>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
type="submit"
|
||||||
|
value={msgStr("doSubmit")}
|
||||||
|
/>
|
||||||
|
{isAppInitiatedAction && (
|
||||||
|
<button
|
||||||
|
className={kcClsx("kcButtonClass", "kcButtonDefaultClass", "kcButtonLargeClass")}
|
||||||
|
type="submit"
|
||||||
|
name="cancel-aia"
|
||||||
|
value="true"
|
||||||
|
>
|
||||||
|
{msg("doCancel")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
@ -8,7 +8,7 @@ export default function SelectAuthenticator(props: PageProps<Extract<KcContext,
|
|||||||
const { url, auth } = kcContext;
|
const { url, auth } = kcContext;
|
||||||
|
|
||||||
const { kcClsx } = getKcClsx({ doUseDefaultCss, classes });
|
const { kcClsx } = getKcClsx({ doUseDefaultCss, classes });
|
||||||
const { msg } = i18n;
|
const { msg, advancedMsg } = i18n;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Template
|
<Template
|
||||||
@ -30,11 +30,11 @@ export default function SelectAuthenticator(props: PageProps<Extract<KcContext,
|
|||||||
value={authenticationSelection.authExecId}
|
value={authenticationSelection.authExecId}
|
||||||
>
|
>
|
||||||
<div className={kcClsx("kcSelectAuthListItemIconClass")}>
|
<div className={kcClsx("kcSelectAuthListItemIconClass")}>
|
||||||
<i className={kcClsx(authenticationSelection.iconCssClass, "kcSelectAuthListItemIconPropertyClass")} />
|
<i className={kcClsx("kcSelectAuthListItemIconPropertyClass", authenticationSelection.iconCssClass)} />
|
||||||
</div>
|
</div>
|
||||||
<div className={kcClsx("kcSelectAuthListItemBodyClass")}>
|
<div className={kcClsx("kcSelectAuthListItemBodyClass")}>
|
||||||
<div className={kcClsx("kcSelectAuthListItemHeadingClass")}>{msg(authenticationSelection.displayName)}</div>
|
<div className={kcClsx("kcSelectAuthListItemHeadingClass")}>{advancedMsg(authenticationSelection.displayName)}</div>
|
||||||
<div className={kcClsx("kcSelectAuthListItemDescriptionClass")}>{msg(authenticationSelection.helpText)}</div>
|
<div className={kcClsx("kcSelectAuthListItemDescriptionClass")}>{advancedMsg(authenticationSelection.helpText)}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={kcClsx("kcSelectAuthListItemFillClass")} />
|
<div className={kcClsx("kcSelectAuthListItemFillClass")} />
|
||||||
<div className={kcClsx("kcSelectAuthListItemArrowClass")}>
|
<div className={kcClsx("kcSelectAuthListItemArrowClass")}>
|
||||||
|
@ -204,13 +204,13 @@ export default function WebauthnAuthenticate(props: PageProps<Extract<KcContext,
|
|||||||
className={kcClsx("kcSelectAuthListItemDescriptionClass")}
|
className={kcClsx("kcSelectAuthListItemDescriptionClass")}
|
||||||
>
|
>
|
||||||
{authenticator.transports.displayNameProperties
|
{authenticator.transports.displayNameProperties
|
||||||
.map((nameProperty, i, arr) => ({
|
.map((displayNameProperty, i, arr) => ({
|
||||||
nameProperty,
|
displayNameProperty,
|
||||||
hasNext: i !== arr.length - 1
|
hasNext: i !== arr.length - 1
|
||||||
}))
|
}))
|
||||||
.map(({ nameProperty, hasNext }) => (
|
.map(({ displayNameProperty, hasNext }) => (
|
||||||
<Fragment key={nameProperty}>
|
<Fragment key={displayNameProperty}>
|
||||||
<span>{msg(nameProperty)}</span>
|
{advancedMsg(displayNameProperty)}
|
||||||
{hasNext && <span>, </span>}
|
{hasNext && <span>, </span>}
|
||||||
</Fragment>
|
</Fragment>
|
||||||
))}
|
))}
|
||||||
|
@ -1,4 +0,0 @@
|
|||||||
export type ExtractAfterStartingWith<
|
|
||||||
Prefix extends string,
|
|
||||||
StrEnum
|
|
||||||
> = StrEnum extends `${Prefix}${infer U}` ? U : never;
|
|
@ -22,7 +22,15 @@ export function useInsertLinkTags(params: {
|
|||||||
alreadyMountedComponentOrHookNames.has(componentOrHookName);
|
alreadyMountedComponentOrHookNames.has(componentOrHookName);
|
||||||
|
|
||||||
if (isAlreadyMounted) {
|
if (isAlreadyMounted) {
|
||||||
window.location.reload();
|
reload: {
|
||||||
|
if (
|
||||||
|
new URL(window.location.href).searchParams.get("viewMode") === "docs"
|
||||||
|
) {
|
||||||
|
// NOTE: Special case for Storybook, we want to avoid infinite reload loop.
|
||||||
|
break reload;
|
||||||
|
}
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -40,7 +40,15 @@ export function useInsertScriptTags(params: {
|
|||||||
alreadyMountedComponentOrHookNames.has(componentOrHookName);
|
alreadyMountedComponentOrHookNames.has(componentOrHookName);
|
||||||
|
|
||||||
if (isAlreadyMounted) {
|
if (isAlreadyMounted) {
|
||||||
window.location.reload();
|
reload: {
|
||||||
|
if (
|
||||||
|
new URL(window.location.href).searchParams.get("viewMode") === "docs"
|
||||||
|
) {
|
||||||
|
// NOTE: Special case for Storybook, we want to avoid infinite reload loop.
|
||||||
|
break reload;
|
||||||
|
}
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
import { join as pathJoin, relative as pathRelative, sep as pathSep } from "path";
|
import { join as pathJoin, relative as pathRelative, sep as pathSep } from "path";
|
||||||
import type { Plugin } from "vite";
|
import type { Plugin } from "vite";
|
||||||
import {
|
import {
|
||||||
basenameOfTheKeycloakifyResourcesDir,
|
BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR,
|
||||||
keycloak_resources,
|
KEYCLOAK_RESOURCES,
|
||||||
vitePluginSubScriptEnvNames
|
VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES
|
||||||
} from "../bin/shared/constants";
|
} from "../bin/shared/constants";
|
||||||
import { id } from "tsafe/id";
|
import { id } from "tsafe/id";
|
||||||
import { rm } from "../bin/tools/fs.rm";
|
import { rm } from "../bin/tools/fs.rm";
|
||||||
@ -18,12 +18,14 @@ import {
|
|||||||
import MagicString from "magic-string";
|
import MagicString from "magic-string";
|
||||||
import { generateKcGenTs } from "../bin/shared/generateKcGenTs";
|
import { generateKcGenTs } from "../bin/shared/generateKcGenTs";
|
||||||
|
|
||||||
export type Params = BuildOptions & {
|
export namespace keycloakify {
|
||||||
postBuild?: (buildContext: Omit<BuildContext, "bundler">) => Promise<void>;
|
export type Params = BuildOptions & {
|
||||||
};
|
postBuild?: (buildContext: Omit<BuildContext, "bundler">) => Promise<void>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function keycloakify(params?: Params) {
|
export function keycloakify(params: keycloakify.Params) {
|
||||||
const { postBuild, ...buildOptions } = params ?? {};
|
const { postBuild, ...buildOptions } = params;
|
||||||
|
|
||||||
let projectDirPath: string | undefined = undefined;
|
let projectDirPath: string | undefined = undefined;
|
||||||
let urlPathname: string | undefined = undefined;
|
let urlPathname: string | undefined = undefined;
|
||||||
@ -38,7 +40,7 @@ export function keycloakify(params?: Params) {
|
|||||||
|
|
||||||
run_post_build_script_case: {
|
run_post_build_script_case: {
|
||||||
const envValue =
|
const envValue =
|
||||||
process.env[vitePluginSubScriptEnvNames.runPostBuildScript];
|
process.env[VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RUN_POST_BUILD_SCRIPT];
|
||||||
|
|
||||||
if (envValue === undefined) {
|
if (envValue === undefined) {
|
||||||
break run_post_build_script_case;
|
break run_post_build_script_case;
|
||||||
@ -94,13 +96,13 @@ export function keycloakify(params?: Params) {
|
|||||||
|
|
||||||
resolve_vite_config_case: {
|
resolve_vite_config_case: {
|
||||||
const envValue =
|
const envValue =
|
||||||
process.env[vitePluginSubScriptEnvNames.resolveViteConfig];
|
process.env[VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG];
|
||||||
|
|
||||||
if (envValue === undefined) {
|
if (envValue === undefined) {
|
||||||
break resolve_vite_config_case;
|
break resolve_vite_config_case;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(vitePluginSubScriptEnvNames.resolveViteConfig);
|
console.log(VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.RESOLVE_VITE_CONFIG);
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
JSON.stringify(
|
JSON.stringify(
|
||||||
@ -172,7 +174,7 @@ export function keycloakify(params?: Params) {
|
|||||||
`(`,
|
`(`,
|
||||||
`(window.kcContext === undefined || import.meta.env.MODE === "development")?`,
|
`(window.kcContext === undefined || import.meta.env.MODE === "development")?`,
|
||||||
`"${urlPathname ?? "/"}":`,
|
`"${urlPathname ?? "/"}":`,
|
||||||
`(window.kcContext.url.resourcesPath + "/${basenameOfTheKeycloakifyResourcesDir}/")`,
|
`(window.kcContext["x-keycloakify"].resourcesPath + "/${BASENAME_OF_KEYCLOAKIFY_RESOURCES_DIR}/")`,
|
||||||
`)`
|
`)`
|
||||||
].join("")
|
].join("")
|
||||||
);
|
);
|
||||||
@ -205,7 +207,7 @@ export function keycloakify(params?: Params) {
|
|||||||
|
|
||||||
assert(buildDirPath !== undefined);
|
assert(buildDirPath !== undefined);
|
||||||
|
|
||||||
await rm(pathJoin(buildDirPath, keycloak_resources), {
|
await rm(pathJoin(buildDirPath, KEYCLOAK_RESOURCES), {
|
||||||
recursive: true,
|
recursive: true,
|
||||||
force: true
|
force: true
|
||||||
});
|
});
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user