Compare commits

...

5 Commits

Author SHA1 Message Date
nite-knite
af97364ffb feat: skip env validation on build 2024-05-09 18:42:47 +08:00
nite-knite
2e1766e040 feat: update env validation 2024-05-09 18:00:21 +08:00
TinsFox
ea3f54f28f
feat: update env script 2024-05-08 10:41:03 +08:00
TinsFox
e108617182
feat: generate default env file 2024-05-06 16:13:50 +08:00
TinsFox
50e4ac33ef
feat: verify environment variables 2024-05-06 15:32:49 +08:00
17 changed files with 2706 additions and 2645 deletions

View File

@ -4,12 +4,15 @@ NEXT_PUBLIC_DEPLOY_ENV=DEVELOPMENT
NEXT_PUBLIC_EDITION=SELF_HOSTED
# The base URL of console application, refers to the Console base URL of WEB service if console domain is
# different from api or web app domain.
# example: http://cloud.dify.ai/console/api
NEXT_PUBLIC_API_PREFIX=http://localhost:5001/console/api
# example: http://cloud.dify.ai/console/api or http://localhost:5001/console/api
NEXT_PUBLIC_API_PREFIX=
# The URL for Web APP, refers to the Web App base URL of WEB service if web app domain is different from
# console or api domain.
# example: http://udify.app/api
NEXT_PUBLIC_PUBLIC_API_PREFIX=http://localhost:5001/api
# SENTRY
# example: http://udify.app/api or http://localhost:5001/api
NEXT_PUBLIC_PUBLIC_API_PREFIX=
# Sentry
NEXT_PUBLIC_SENTRY_DSN=
# Pass 'TRUE' to show maintenance notice
NEXT_PUBLIC_MAINTENANCE_NOTICE=
# Pass 'TRUE' to hide cloud service release info and running status
NEXT_PUBLIC_HIDE_ABOUT_INFO=

View File

@ -1,3 +1,4 @@
@@ -1,71 +1,73 @@
# Dify Frontend
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
@ -21,15 +22,18 @@ NEXT_PUBLIC_DEPLOY_ENV=DEVELOPMENT
NEXT_PUBLIC_EDITION=SELF_HOSTED
# The base URL of console application, refers to the Console base URL of WEB service if console domain is
# different from api or web app domain.
# example: http://cloud.dify.ai/console/api
NEXT_PUBLIC_API_PREFIX=http://localhost:5001/console/api
# example: http://cloud.dify.ai/console/api or http://localhost:5001/console/api
NEXT_PUBLIC_API_PREFIX=
# The URL for Web APP, refers to the Web App base URL of WEB service if web app domain is different from
# console or api domain.
# example: http://udify.app/api
NEXT_PUBLIC_PUBLIC_API_PREFIX=http://localhost:5001/api
# SENTRY
# example: http://udify.app/api or http://localhost:5001/api
NEXT_PUBLIC_PUBLIC_API_PREFIX=
# Sentry
NEXT_PUBLIC_SENTRY_DSN=
# Pass 'TRUE' to show maintenance notice
NEXT_PUBLIC_MAINTENANCE_NOTICE=
# Pass 'TRUE' to hide release info and service status
NEXT_PUBLIC_HIDE_ABOUT_INFO=
```
Finally, run the development server:

View File

@ -17,6 +17,8 @@ import { ArrowUpRight, ChevronDown } from '@/app/components/base/icons/src/vende
import { LogOut01 } from '@/app/components/base/icons/src/vender/line/general'
import { useModalContext } from '@/context/modal-context'
import { LanguagesSupported } from '@/i18n/language'
import { env } from '@/env'
export type IAppSelecotr = {
isMobile: boolean
}
@ -134,7 +136,7 @@ export default function AppSelector({ isMobile }: IAppSelecotr) {
</Link>
</Menu.Item>
{
document?.body?.getAttribute('data-public-site-about') !== 'hide' && (
env.NEXT_PUBLIC_HIDE_ABOUT_INFO !== 'TRUE' && (
<Menu.Item>
<div className={classNames(itemClassName, 'justify-between')} onClick={() => setAboutVisible(true)}>
<div>{t('common.userProfile.about')}</div>

View File

@ -2,6 +2,7 @@
import React, { useEffect, useState } from 'react'
import { Github } from '@/app/components/base/icons/src/public/common'
import type { GithubRepo } from '@/models/common'
import { env } from '@/env'
const getStar = async () => {
const res = await fetch('https://api.github.com/repos/langgenius/dify')
@ -18,10 +19,10 @@ const GithubStar = () => {
useEffect(() => {
(async () => {
try {
if (process.env.NODE_ENV === 'development')
if (env.NODE_ENV?.toUpperCase() === 'DEVELOPMENT')
return
await setGithubRepo(await getStar())
setGithubRepo(await getStar())
setIsFetched(true)
}
catch (e) {

View File

@ -2,14 +2,15 @@
import { useEffect } from 'react'
import * as Sentry from '@sentry/react'
import { env } from '@/env'
const isDevelopment = process.env.NODE_ENV === 'development'
const isDevelopment = env.NEXT_PUBLIC_NODE_ENV === 'DEVELOPMENT'
const SentryInit = ({
children,
}: { children: React.ReactElement }) => {
useEffect(() => {
const SENTRY_DSN = document?.body?.getAttribute('data-public-sentry-dsn')
const SENTRY_DSN = env.NEXT_PUBLIC_SENTRY_DSN
if (!isDevelopment && SENTRY_DSN) {
Sentry.init({
dsn: SENTRY_DSN,

View File

@ -34,16 +34,8 @@ const LocaleLayout = ({
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
</head>
<body
className="h-full select-auto"
data-api-prefix={process.env.NEXT_PUBLIC_API_PREFIX}
data-pubic-api-prefix={process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX}
data-public-edition={process.env.NEXT_PUBLIC_EDITION}
data-public-sentry-dsn={process.env.NEXT_PUBLIC_SENTRY_DSN}
data-public-maintenance-notice={process.env.NEXT_PUBLIC_MAINTENANCE_NOTICE}
data-public-site-about={process.env.NEXT_PUBLIC_SITE_ABOUT}
>
<Topbar/>
<body className="h-full select-auto">
<Topbar />
<BrowerInitor>
<SentryInitor>
{/* @ts-expect-error Async Server Component */}

View File

@ -5,13 +5,11 @@ import { useRouter } from 'next/navigation'
import classNames from 'classnames'
import useSWR from 'swr'
import Link from 'next/link'
import { useContext } from 'use-context-selector'
import Toast from '../components/base/toast'
import style from './page.module.css'
import { IS_CE_EDITION, apiPrefix } from '@/config'
import { API_PREFIX, IS_CE_EDITION } from '@/config'
import Button from '@/app/components/base/button'
import { login, oauth } from '@/service/common'
import I18n from '@/context/i18n'
import { getPurifyHref } from '@/utils'
const validEmailReg = /^[\w\.-]+@([\w-]+\.)+[\w-]{2,}$/
@ -65,7 +63,6 @@ function reducer(state: IState, action: IAction) {
const NormalForm = () => {
const { t } = useTranslation()
const router = useRouter()
const { locale } = useContext(I18n)
const [state, dispatch] = useReducer(reducer, {
formValid: false,
@ -157,7 +154,7 @@ const NormalForm = () => {
{!IS_CE_EDITION && (
<div className="flex flex-col gap-3 mt-6">
<div className='w-full'>
<a href={getPurifyHref(`${apiPrefix}/oauth/login/github`)}>
<a href={getPurifyHref(`${API_PREFIX}/oauth/login/github`)}>
<Button
type='default'
disabled={isLoading}
@ -176,7 +173,7 @@ const NormalForm = () => {
</a>
</div>
<div className='w-full'>
<a href={getPurifyHref(`${apiPrefix}/oauth/login/google`)}>
<a href={getPurifyHref(`${API_PREFIX}/oauth/login/google`)}>
<Button
type='default'
disabled={isLoading}

View File

@ -1,37 +1,14 @@
/* eslint-disable import/no-mutable-exports */
import { InputVarType } from '@/app/components/workflow/types'
import { AgentStrategy } from '@/types/app'
import { PromptRole } from '@/models/debug'
import { env } from '@/env'
export let apiPrefix = ''
export let publicApiPrefix = ''
// NEXT_PUBLIC_API_PREFIX=/console/api NEXT_PUBLIC_PUBLIC_API_PREFIX=/api yarn run start
// NEXT_PUBLIC_API_PREFIX=/console/api NEXT_PUBLIC_PUBLIC_API_PREFIX=/api npm run start
if (process.env.NEXT_PUBLIC_API_PREFIX && process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX) {
apiPrefix = process.env.NEXT_PUBLIC_API_PREFIX
publicApiPrefix = process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX
}
else if (
globalThis.document?.body?.getAttribute('data-api-prefix')
&& globalThis.document?.body?.getAttribute('data-pubic-api-prefix')
) {
// Not bulild can not get env from process.env.NEXT_PUBLIC_ in browser https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser
apiPrefix = globalThis.document.body.getAttribute('data-api-prefix') as string
publicApiPrefix = globalThis.document.body.getAttribute('data-pubic-api-prefix') as string
}
else {
// const domainParts = globalThis.location?.host?.split('.');
// in production env, the host is dify.app . In other env, the host is [dev].dify.app
// const env = domainParts.length === 2 ? 'ai' : domainParts?.[0];
apiPrefix = 'http://localhost:5001/console/api'
publicApiPrefix = 'http://localhost:5001/api' // avoid browser private mode api cross origin
}
export const API_PREFIX: string = env.NEXT_PUBLIC_API_PREFIX
export const PUBLIC_API_PREFIX: string = env.NEXT_PUBLIC_PUBLIC_API_PREFIX
export const API_PREFIX: string = apiPrefix
export const PUBLIC_API_PREFIX: string = publicApiPrefix
const EDITION = process.env.NEXT_PUBLIC_EDITION || globalThis.document?.body?.getAttribute('data-public-edition') || 'SELF_HOSTED'
export const IS_CE_EDITION = EDITION === 'SELF_HOSTED'
export const IS_CE_EDITION = env.NEXT_PUBLIC_EDITION === 'SELF_HOSTED'
export const TONE_LIST = [
{
@ -156,28 +133,28 @@ export const DEFAULT_AGENT_SETTING = {
}
export const DEFAULT_AGENT_PROMPT = {
chat: `Respond to the human as helpfully and accurately as possible.
chat: `Respond to the human as helpfully and accurately as possible.
{{instruction}}
You have access to the following tools:
{{tools}}
Use a json blob to specify a tool by providing an {{TOOL_NAME_KEY}} key (tool name) and an {{ACTION_INPUT_KEY}} key (tool input).
Valid "{{TOOL_NAME_KEY}}" values: "Final Answer" or {{tool_names}}
Provide only ONE action per $JSON_BLOB, as shown:
\`\`\`
{
"{{TOOL_NAME_KEY}}": $TOOL_NAME,
"{{ACTION_INPUT_KEY}}": $ACTION_INPUT
}
\`\`\`
Follow this format:
Question: input question to answer
Thought: consider previous and subsequent steps
Action:
@ -194,10 +171,10 @@ export const DEFAULT_AGENT_PROMPT = {
"{{ACTION_INPUT_KEY}}": "Final response to human"
}
\`\`\`
Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:\`\`\`$JSON_BLOB\`\`\`then Observation:.`,
completion: `
Respond to the human as helpfully and accurately as possible.
Respond to the human as helpfully and accurately as possible.
{{instruction}}

View File

@ -10,6 +10,7 @@ import { fetchCurrentWorkspace, fetchLanggeniusVersion, fetchUserProfile } from
import type { App } from '@/types/app'
import type { ICurrentWorkspace, LangGeniusVersionResponse, UserProfileResponse } from '@/models/common'
import MaintenanceNotice from '@/app/components/header/maintenance-notice'
import { env } from '@/env'
export type AppContextValue = {
apps: App[]
@ -91,7 +92,7 @@ export const AppContextProvider: FC<AppContextProviderProps> = ({ children }) =>
const result = await userProfileResponse.json()
setUserProfile(result)
const current_version = userProfileResponse.headers.get('x-version')
const current_env = process.env.NODE_ENV === 'development' ? 'DEVELOPMENT' : userProfileResponse.headers.get('x-env')
const current_env = env.NODE_ENV?.toUpperCase() === 'DEVELOPMENT' ? 'DEVELOPMENT' : userProfileResponse.headers.get('x-env')
const versionData = await fetchLanggeniusVersion({ url: '/version', params: { current_version } })
setLangeniusVersionInfo({ ...versionData, current_version, latest_version: versionData.version, current_env })
}
@ -124,7 +125,7 @@ export const AppContextProvider: FC<AppContextProviderProps> = ({ children }) =>
mutateCurrentWorkspace,
}}>
<div className='flex flex-col h-full overflow-y-auto'>
{globalThis.document?.body?.getAttribute('data-public-maintenance-notice') && <MaintenanceNotice />}
{env.NEXT_PUBLIC_MAINTENANCE_NOTICE && <MaintenanceNotice />}
<div ref={pageContainerRef} className='grow relative flex flex-col overflow-y-auto overflow-x-hidden bg-gray-100'>
{children}
</div>

View File

@ -18,6 +18,6 @@ export NEXT_PUBLIC_API_PREFIX=${CONSOLE_API_URL}/console/api
export NEXT_PUBLIC_PUBLIC_API_PREFIX=${APP_API_URL}/api
export NEXT_PUBLIC_SENTRY_DSN=${SENTRY_DSN}
export NEXT_PUBLIC_SITE_ABOUT=${SITE_ABOUT}
export NEXT_PUBLIC_HIDE_ABOUT_INFO=${HIDE_ABOUT_INFO}
pm2 start ./pm2.json --no-daemon

64
web/env.ts Normal file
View File

@ -0,0 +1,64 @@
import { createEnv } from '@t3-oss/env-nextjs'
import { z } from 'zod'
import { upperCase } from 'lodash-es'
export const env = createEnv({
/**
* Specify your server-side environment variables schema here. This way you can ensure the app
* isn't built with invalid env vars.
*/
server: {
NODE_ENV: z
.enum(['DEVELOPMENT', 'PRODUCTION'])
.default('DEVELOPMENT'),
},
/**
* Specify your client-side environment variables schema here. This way you can ensure the app
* isn't built with invalid env vars. To expose them to the client, prefix them with
* `NEXT_PUBLIC_`.
*/
client: {
NEXT_PUBLIC_DEPLOY_ENV: z
.enum(['DEVELOPMENT', 'PRODUCTION']),
NEXT_PUBLIC_EDITION: z
.enum(['SELF_HOSTED', 'CLOUD']),
NEXT_PUBLIC_API_PREFIX: z.string().optional().default('http://localhost:5001/console/api'),
NEXT_PUBLIC_PUBLIC_API_PREFIX: z.string().default('http://localhost:5001/api'),
NEXT_PUBLIC_SENTRY_DSN: z.string().optional(),
NEXT_PUBLIC_NODE_ENV: z
.enum(['DEVELOPMENT', 'PRODUCTION'])
.default('DEVELOPMENT'),
NEXT_PUBLIC_MAINTENANCE_NOTICE: z.enum(['TRUE']).optional(),
NEXT_PUBLIC_HIDE_ABOUT_INFO: z.enum(['TRUE']).optional(),
},
/**
* You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
* middlewares) or client-side so we need to destruct manually.
*/
runtimeEnv: {
NODE_ENV: upperCase(process.env.NODE_ENV),
NEXT_PUBLIC_NODE_ENV: upperCase(process.env.NODE_ENV),
NEXT_PUBLIC_DEPLOY_ENV: process.env.NEXT_PUBLIC_DEPLOY_ENV,
NEXT_PUBLIC_EDITION: process.env.NEXT_PUBLIC_EDITION,
NEXT_PUBLIC_API_PREFIX: process.env.NEXT_PUBLIC_API_PREFIX,
NEXT_PUBLIC_PUBLIC_API_PREFIX: process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX,
NEXT_PUBLIC_SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN,
NEXT_PUBLIC_MAINTENANCE_NOTICE: process.env.NEXT_PUBLIC_MAINTENANCE_NOTICE,
// forward compatibility with the old env var
NEXT_PUBLIC_HIDE_ABOUT_INFO: process.env.NEXT_PUBLIC_SITE_ABOUT?.toUpperCase() === 'HIDE'
? 'TRUE'
: process.env.NEXT_PUBLIC_HIDE_ABOUT_INFO,
},
/**
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
* useful for Docker builds.
*/
skipValidation: !!process.env.SKIP_ENV_VALIDATION,
/**
* Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and
* `SOME_VAR=''` will throw an error.
*/
emptyStringAsUndefined: true,
})

View File

@ -1,5 +1,15 @@
const { codeInspectorPlugin } = require('code-inspector-plugin')
const withMDX = require('@next/mdx')({
/**
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful
* for Docker builds.
*/
import { fileURLToPath } from 'node:url'
import { codeInspectorPlugin } from 'code-inspector-plugin'
import mdx from '@next/mdx'
import createJiti from 'jiti'
const jiti = createJiti(fileURLToPath(import.meta.url))
jiti('./env.ts')
const withMDX = mdx({
extension: /\.mdx?$/,
options: {
// If you use remark-gfm, you'll need to use next.config.mjs
@ -46,4 +56,4 @@ const nextConfig = {
output: 'standalone',
}
module.exports = withMDX(nextConfig)
export default withMDX(nextConfig)

View File

@ -4,12 +4,12 @@
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"build": "cross-env SKIP_ENV_VALIDATION=TRUE next build",
"start": "cp -r .next/static .next/standalone/.next/static && cp -r public .next/standalone/public && cross-env PORT=$npm_config_port HOSTNAME=$npm_config_host node .next/standalone/server.js",
"lint": "next lint",
"fix": "next lint --fix",
"eslint-fix": "eslint --fix",
"prepare": "cd ../ && node -e \"if (process.env.NODE_ENV !== 'production'){process.exit(1)} \" || husky install ./web/.husky",
"prepare": "shx test -f .env.local || shx cp .env.example .env.local && cd ../ && node -e \"if (process.env.NODE_ENV !== 'production'){process.exit(1)} \" || husky install ./web/.husky",
"gen-icons": "node ./app/components/base/icons/script.js",
"uglify-embed": "node ./bin/uglify-embed",
"check-i18n": "node ./i18n/script.js"
@ -28,6 +28,7 @@
"@next/mdx": "^14.0.4",
"@sentry/react": "^7.54.0",
"@sentry/utils": "^7.54.0",
"@t3-oss/env-nextjs": "^0.10.1",
"@tailwindcss/line-clamp": "^0.4.4",
"@tailwindcss/typography": "^0.5.9",
"ahooks": "^3.7.5",
@ -84,6 +85,7 @@
"swr": "^2.1.0",
"use-context-selector": "^1.4.1",
"uuid": "^9.0.1",
"zod": "^3.23.6",
"zustand": "^4.5.1"
},
"devDependencies": {
@ -112,11 +114,13 @@
"eslint": "^8.36.0",
"eslint-config-next": "^14.0.4",
"husky": "^8.0.3",
"jiti": "^1.21.0",
"lint-staged": "^13.2.2",
"postcss": "^8.4.31",
"sass": "^1.61.0",
"shx": "^0.3.4",
"tailwindcss": "^3.3.3",
"typescript": "4.9.5",
"typescript": "^5.4.5",
"uglify-js": "^3.17.4"
},
"lint-staged": {

View File

@ -13,7 +13,7 @@
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
@ -33,8 +33,7 @@
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"app/components/develop/Prose.jsx"
".next/types/**/*.ts"
],
"exclude": [
"node_modules"

File diff suppressed because it is too large Load Diff