Skip to content

Commit

Permalink
feat: production mode (#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
do4ng committed Feb 24, 2024
1 parent a35b51a commit 5ac1878
Show file tree
Hide file tree
Showing 11 changed files with 117 additions and 17 deletions.
5 changes: 5 additions & 0 deletions packages/zely-js-cli/commands/start.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { dev } from './dev';

export async function start() {
await dev();
}
11 changes: 11 additions & 0 deletions packages/zely-js-cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import animaux from 'animaux';

import { info } from '@zely-js/logger';
import pkg from '../package.json';
import { dev } from '../commands/dev';
import { build } from '../commands/build';
import { init } from '../commands/init';
import { start } from '../commands/start';

const app = animaux('zely-js');

Expand All @@ -27,12 +29,21 @@ app.command('build').action(async () => {
await build();
});

app.command('start').action(async () => {
// production mode
process.env.NODE_ENV = 'production';
process.env.ZELY_WORKING_FRAMEWORK = 'zely-cli';

await start();
});

app
.command('init')
.option('--dir, -d', 'Provide output directory.')
.option('--template, -t', 'Template (typescript/javascript)', 'typescript')
.action(async (options) => {
// console.log(options);
info(`cloning template: ${options.template || 'typescript'}`);
await init(options.dir || '.', options.template || 'typescript');
});

Expand Down
45 changes: 36 additions & 9 deletions packages/zely-js-core/src/controller/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,26 +125,53 @@ export class PageCache {
constructor(page: Page[], config: UserConfig) {
const loader = createLoader(config);

if (existsSync(join(config.cwd || process.cwd(), config.dist || '.zely'))) {
rmSync(join(config.cwd || process.cwd(), config.dist || '.zely'), {
if (config.keepDist !== true) {
if (existsSync(join(config.cwd || process.cwd(), config.dist || '.zely'))) {
rmSync(join(config.cwd || process.cwd(), config.dist || '.zely'), {
recursive: true,
});
}

mkdirSync(join(config.cwd || process.cwd(), config.dist || '.zely'), {
recursive: true,
});
} else if (!existsSync(join(config.cwd || process.cwd(), config.dist || '.zely'))) {
mkdirSync(join(config.cwd || process.cwd(), config.dist || '.zely'), {
recursive: true,
});
}

mkdirSync(join(config.cwd || process.cwd(), config.dist || '.zely'), {
recursive: true,
});
mkdirSync(join(config.cwd || process.cwd(), config.dist || '.zely', '_pages'), {
recursive: true,
});

writeFileSync(HASH_DIRECTORY(config), '{}');

this.#modules = page;
this.loader = loader;
this.config = config;
}

async productionBuild() {
const base = join(this.config.cwd || process.cwd(), 'pages');

if (process.env.NODE_ENV === 'production') {
for await (const page of this.#modules) {
const output = await this.loader(join(base, page.filename), {
type: 'page',
buildOptions: {},
});

page.module.data = getValue(output.module);
page.module.builtPath = output.filename;
page.module.builtMapPath = output.map;
page.module.type = isExportDefault(output.module) ? 'export-default' : 'export';
page.module.isLoaded = true;
page.id = performance.now();

this.writeIdMap({ ...this.readIdMap(), [page.filename]: page.id });
}
} else {
throw new Error('production build is only available in production mode.');
}
}

// id map
writeIdMap(data: any) {
writeFileSync(HASH_DIRECTORY(this.config), JSON.stringify(data));
Expand Down
1 change: 1 addition & 0 deletions packages/zely-js-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export { createZelyServer } from './server';
export { controll } from './controller';
export { methods } from './controller/methods';
export * from './methods';
export * from './production';
54 changes: 54 additions & 0 deletions packages/zely-js-core/src/production.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { error } from '@zely-js/logger';
import { pathToRegexp } from '@zept/path-regexp';

import { performance } from 'node:perf_hooks';
import { join, relative } from 'node:path';

import { readDirectory } from '~/zely-js-core/lib/read-directory';
import type { UserConfig } from '~/zely-js-core';
import { transformFilename } from '~/zely-js-core/lib/file-to-path';
import { removeExtension } from '~/zely-js-core/lib/ext';

import { PageCache } from './controller';
import { filenameToRoute } from './server';

export async function productionBuild(options: UserConfig) {
// exit early if no options provided
if (!options) {
error(new Error('config must be provided'));
process.exit(1);
}

const files = readDirectory(join(options.cwd || process.cwd(), 'pages'));
const pages = new PageCache(
filenameToRoute(
files.map((file) => {
const relativePath = relative(join(options.cwd || process.cwd(), 'pages'), file);
const path = transformFilename(removeExtension(relativePath), true);

return {
filename: relativePath.replace(/\\/g, '/'),
regex: null,
params: null,
path,
id: performance.now(),
module: {
type: 'unknown',
isLoaded: false,
},
};
})
).map((file) => {
const outregex = pathToRegexp(file.path);

return {
...file,
regex: outregex.pattern,
params: outregex.params,
};
}),
options
);

await pages.productionBuild();
}
4 changes: 4 additions & 0 deletions packages/zely-js-core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ export async function createZelyServer(options: UserConfig) {
options
);

if (process.env.NODE_ENV === 'production') {
await pages.productionBuild();
}

const applyZelyMiddlewares = (serverInstance: ZeptServer) => {
// Request/Response => ZelyRequest/Response
serverInstance.use(kitMiddleware);
Expand Down
2 changes: 2 additions & 0 deletions packages/zely-js-core/types/config.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,6 @@ export interface UserConfig {
* @default true
*/
enableReporter?: boolean;

keepDist?: boolean;
}
5 changes: 2 additions & 3 deletions packages/zely-js-core/types/functions.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { ZeptServer } from '@zept/http';
import { UserConfig } from './config';

export function createZelyServer(
options: UserConfig
): Promise<{
export function createZelyServer(options: UserConfig): Promise<{
server: ZeptServer;
applyZelyMiddlewares: (serverInstance: ZeptServer) => void;
}>;
export function productionBuild(options: UserConfig): Promise<void>;
2 changes: 1 addition & 1 deletion packages/zely-reporter/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { dirname, join, relative } = require('path');
const errorHandler = async (e) => {
if (!e) return;
if (process.env.NODE_ENV === 'production') {
throw new Error(e);
console.error(e);
}

const stacks = parseError(e);
Expand Down
1 change: 1 addition & 0 deletions playground/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"zely-cli": "workspace:*"
},
"scripts": {
"start": "zely-cli start",
"dev": "zely-cli dev"
}
}
4 changes: 0 additions & 4 deletions playground/typescript/zely.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ import { defineConfig } from '@zely-js/zely';

export default defineConfig({
allowAutoMiddlewares: true,
onError(err) {
console.log('ERROR' + err);
},
enableReporter: false,
plugins: [
{
name: 'error',
Expand Down

0 comments on commit 5ac1878

Please sign in to comment.