enso/app/ide-desktop/lib/content/esbuild-config.ts
somebody1234 400cdbe893
Cloud/desktop mode switcher (#6308)
* fixmes

* fixmes

* fixmes

* fixmes

* fixmes

* fixes for e-hern's comments

* use abortcontroller

* add docs

* fixes

* revert craco, fix windows build

* remove from gitignore

* remove unnecessary check

* tmp

* augment window

* tmptmp

* split errors back up

* tmp

* tmp

* prettier

* fix

* Fix lints

* Prepare for addition for `as T` lint

* Add lint for early returns

* Address review issues

* Fix lints

* remove withrouter

* fix file length

* fixes

* fixes

* remove dashboard

* fix

* use switch

* prettier

* fixes

* prettier

* fixes

* run prettier

* run prettier

* run prettier

* fix main page url

* allow node.js debugging

* fix lints

* change not equal

* prettier

* Remove references to withRouter; fix lints

* Run prettier

* Add cloud endpoints

* Add JSON-RPC endpoints

* Add dashboard skeleton

* Add components and edit dashboard

* Run prettier

* (WIP) Add cloud endpoints

* Add rpc endpoints

* Address review issues

* Formatting and minor fixes for `newtype.ts`

* Address review issues

* Rename `Brand` to `NewtypeVariant`

* Rename `Brand` to `NewtypeVariant`

* Fix formatting in `newtype.ts`

* Switch dashboard to esbuild

* Minor fixes; move Tailwind generation into esbuild-config

* Fix watching `content/` and `client/`

* Bump esbuild binary versions; minor dependency list fixes

* Add dashboard skeleton

* Run prettier

* Fixes; rename "npm run dev" to "npm run watch-dashboard"

* Avoid writing esbuild outputs to disk for `dashboard/`

* Convert watch-dashboard to be fully in-memory; rebuild css files on change

* Remove obsolete FIXME

* Remove unused constants

* Run prettier

* add missing styles

* Fixes

* Fix the fixes

* Run prettier

* Fixes; use nesting plugin to wrap tailwind preflight

* Remove testing flag from client/watch

* Minor fixes

* Run prettier

* Export newtypes

* Make css rebuild when tailwind config changes

* Fix endpoints

* Finish copying changes over

* Remove duplicate type definitions

* Feat: top-bar styles and changePassword feature

* Fix: remove eslint disable comments

* Fix bundling for dashboard

* Fix dashboard/bundle.ts erroring when build directory does not exist

* Move CSS to Tailwind config

* Run prettier

* Copy changes from old branch

* Update endpoints

* Fix esbuild binary package names

* Remove redundant "npx" prefix from build scripts

* Remove unused dependency

* workaround for mac freeze

* Fix bug

* add missing sections

* Fix: bug

* Address review issue

* Fix prettier config; run prettier

* Fix live-reload of `npm run watch-dashboard`

* Fix service worker for client-side routing

* Remove workaround for backend bug when listing directories

* Fix sizing

* Fix spacing, add fixed paths

* Address review issues; minor fixes

* Fix authentication on desktop IDE

* Run prettier

* Allow unused locals and parameters in tsconfig.json

* Run prettier

* Fix TypeScript errors

* Run prettier

* Fix eslint errors, restructure code

* Minor fixes and other changes

* Revert incorrect change to `cognito/changePassword`

* Remove unused file

* Run prettier

* Merge with top bar; implement switching between IDE and dashboard

* Animate project switcher (WIP)

* Fix IDE and project switcher animation

* Fix eslint errors

* Change `#dashboard` to `.dashboard` for Tailwind

* Split `-authentication` option into `-cloud.authentication` and `-cloud.dashboard`

* Address review issues

* Add description for cloud option group

* Extract custom CSS values into Tailwind config; use ModalProvider

* Hide topbar in IDE view

* Add project manager backend service

* Begin fixing IDE open

* (WIP)

* Clean up unused code

* Minor fixes

* Fix

* Fix local backend's usage of project manager (WIP)

* WIP

* Minor fixes

* Fix scrollbar showing because of margins

* Expose `runProject` instead of `main`

* Keep persistent websocket to Project Manager

* Fix spinner state bug

* Fix race condition when switching between backends

* Fix loading local projects

* Make switching local projects work

* Fix opening cloud projects

* Add shortcut to switch back to dashboard

* Fix templates for desktop; other fixes

* Fix status check polling in `ProjectActionButton` not being stopped

* Run prettier

* Retry reconnecting to Project Manager

* fix back to dashboard shortcut on macOS

* Fixes

* More fixes

* Rename `backendModule` to `cloudService`

---------

Co-authored-by: Nikita Pekin <nikita@frecency.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Paweł Buchowski <pawel.buchowski@enso.org>
Co-authored-by: Nctdtman <137032445@qq.com>
2023-04-26 16:59:39 +02:00

171 lines
6.7 KiB
TypeScript

/**
* @file Configuration for the esbuild bundler and build/watch commands.
*
* The bundler processes each entry point into a single file, each with no external dependencies and
* minified. This primarily involves resolving all imports, along with some other transformations
* (like TypeScript compilation).
*
* See the bundlers documentation for more information:
* https://esbuild.github.io/getting-started/#bundling-for-node.
*/
import * as childProcess from 'node:child_process'
import * as fs from 'node:fs/promises'
import * as fsSync from 'node:fs'
import * as pathModule from 'node:path'
import * as url from 'node:url'
import * as esbuild from 'esbuild'
import * as esbuildPluginNodeGlobals from '@esbuild-plugins/node-globals-polyfill'
import * as esbuildPluginNodeModules from '@esbuild-plugins/node-modules-polyfill'
import esbuildPluginAlias from 'esbuild-plugin-alias'
import esbuildPluginCopyDirectories from 'esbuild-plugin-copy-directories'
import esbuildPluginTime from 'esbuild-plugin-time'
import esbuildPluginYaml from 'esbuild-plugin-yaml'
import * as utils from '../../utils'
import BUILD_INFO from '../../build.json' assert { type: 'json' }
export const THIS_PATH = pathModule.resolve(pathModule.dirname(url.fileURLToPath(import.meta.url)))
// =============================
// === Environment variables ===
// =============================
export interface Arguments {
/** List of files to be copied from WASM artifacts. */
wasmArtifacts: string
/** Directory with assets. Its contents are to be copied. */
assetsPath: string
/** Path where bundled files are output. */
outputPath: string
/** The main JS bundle to load WASM and JS wasm-pack bundles. */
ensoglAppPath: string
/** `true` if in development mode (live-reload), `false` if in production mode. */
devMode: boolean
}
/**
* Get arguments from the environment.
*/
export function argumentsFromEnv(): Arguments {
const wasmArtifacts = utils.requireEnv('ENSO_BUILD_GUI_WASM_ARTIFACTS')
const assetsPath = utils.requireEnv('ENSO_BUILD_GUI_ASSETS')
const outputPath = pathModule.resolve(utils.requireEnv('ENSO_BUILD_GUI'), 'assets')
const ensoglAppPath = utils.requireEnv('ENSO_BUILD_GUI_ENSOGL_APP')
return { wasmArtifacts, assetsPath, outputPath, ensoglAppPath, devMode: false }
}
// ===================
// === Git process ===
// ===================
/**
* Get output of a git command.
* @param command - Command line following the `git` program.
* @returns Output of the command.
*/
function git(command: string): string {
// TODO [mwu] Eventually this should be removed, data should be provided by the build script through `BUILD_INFO`.
// The bundler configuration should not invoke git, it is not its responsibility.
return childProcess.execSync(`git ${command}`, { encoding: 'utf8' }).trim()
}
// ================
// === Bundling ===
// ================
/**
* Generate the builder options.
*/
export function bundlerOptions(args: Arguments) {
const { outputPath, ensoglAppPath, wasmArtifacts, assetsPath, devMode } = args
const buildOptions = {
// Disabling naming convention because these are third-party options.
/* eslint-disable @typescript-eslint/naming-convention */
absWorkingDir: THIS_PATH,
bundle: true,
loader: {
'.html': 'copy',
'.css': 'copy',
'.wasm': 'copy',
'.svg': 'copy',
'.png': 'copy',
'.ttf': 'copy',
},
entryPoints: [
pathModule.resolve(THIS_PATH, 'src', 'index.ts'),
pathModule.resolve(THIS_PATH, 'src', 'index.html'),
pathModule.resolve(THIS_PATH, 'src', 'style.css'),
pathModule.resolve(THIS_PATH, 'src', 'docsStyle.css'),
...wasmArtifacts.split(pathModule.delimiter),
...fsSync
.readdirSync(assetsPath)
.map(fileName => pathModule.resolve(assetsPath, fileName)),
].map(path => ({ in: path, out: pathModule.basename(path, pathModule.extname(path)) })),
outdir: outputPath,
outbase: 'src',
plugins: [
{
// This file MUST be in CommonJS format because it is loaded using `Function()`
// in `ensogl/pack/js/src/runner/index.ts`.
// All other files are ESM because of `"type": "module"` in `package.json`.
name: 'pkg-js-is-cjs',
setup: build => {
build.onLoad({ filter: /[/\\]pkg.js$/ }, async ({ path }) => ({
contents: await fs.readFile(path),
loader: 'copy',
}))
},
},
esbuildPluginCopyDirectories(),
esbuildPluginYaml.yamlPlugin({}),
esbuildPluginNodeModules.NodeModulesPolyfillPlugin(),
esbuildPluginNodeGlobals.NodeGlobalsPolyfillPlugin({ buffer: true, process: true }),
esbuildPluginAlias({ ensogl_app: ensoglAppPath }),
esbuildPluginTime(),
],
define: {
GIT_HASH: JSON.stringify(git('rev-parse HEAD')),
GIT_STATUS: JSON.stringify(git('status --short --porcelain')),
BUILD_INFO: JSON.stringify(BUILD_INFO),
IS_DEV_MODE: JSON.stringify(devMode),
},
sourcemap: true,
minify: true,
metafile: true,
format: 'esm',
platform: 'browser',
color: true,
logOverride: {
// Happens in Emscripten-generated MSDF (msdfgen_wasm.js):
// 1 │ ...typeof module!=="undefined"){module["exports"]=Module}process["o...
'commonjs-variable-in-esm': 'silent',
// Happens in Emscripten-generated MSDF (msdfgen_wasm.js):
// 1 │ ...y{table.grow(1)}catch(err){if(!err instanceof RangeError){throw ...
'suspicious-boolean-not': 'silent',
},
/* eslint-enable @typescript-eslint/naming-convention */
} satisfies esbuild.BuildOptions
// The narrower type is required to avoid non-null assertions elsewhere.
// The intersection with `esbuild.BuildOptions` is required to allow mutation.
const correctlyTypedBuildOptions: esbuild.BuildOptions & typeof buildOptions = buildOptions
return correctlyTypedBuildOptions
}
/** The basic, common settings for the bundler, based on the environment variables.
*
* Note that they should be further customized as per the needs of the specific workflow (e.g. watch vs. build).
*/
export function bundlerOptionsFromEnv() {
return bundlerOptions(argumentsFromEnv())
}
/** ESBuild options for bundling (one-off build) the package.
*
* Relies on the environment variables to be set.
*/
export function bundleOptions() {
return bundlerOptionsFromEnv()
}