Skip to content
Closed
10 changes: 10 additions & 0 deletions .mocharc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"loader": "ts-node/esm",
"extensions": ["ts", "tsx"],
"spec": [
"test/**/*.test.mjs"
],
"watch-files": [
"src"
]
}
26 changes: 25 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import playcanvasConfig from '@playcanvas/eslint-config';
import globals from 'globals';
import typescriptParser from '@typescript-eslint/parser';

// Extract or preserve existing JSDoc tags
const jsdocRule = playcanvasConfig.find(
Expand All @@ -10,7 +11,7 @@ const existingTags = jsdocRule?.rules['jsdoc/check-tag-names'][1]?.definedTags |
export default [
...playcanvasConfig,
{
files: ['**/*.js', '**/*.mjs'],
files: ['**/*.js', '**/*.mjs', '**/*.ts'],
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
Expand All @@ -36,6 +37,29 @@ export default [
definedTags: [...new Set([...existingTags, 'range', 'step', 'precision'])]
}
]
},
settings: {
'import/resolver': {
typescript: {
// This allows .js imports to resolve to .ts files
project: './tsconfig.json'
}
}
}
},
{
files: ['**/*.ts'],
languageOptions: {
parser: typescriptParser,
parserOptions: {
project: './tsconfig.json'
}
},
rules: {
// TypeScript provides its own type information, so we don't need JSDoc types
'jsdoc/require-param-type': 'off',
'jsdoc/require-returns-type': 'off',
'jsdoc/require-property-type': 'off'
}
},
{
Expand Down
10 changes: 8 additions & 2 deletions examples/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"clean": "node ./scripts/clean.mjs",
"develop": "cross-env NODE_ENV=development concurrently --kill-others \"npm run watch\" \"npm run serve\"",
"lint": "eslint .",
"serve": "serve dist -l 5555 --no-request-logging --config ../serve.json",
"serve": "PORT=5555 node scripts/serve.js",
"watch": "npm run -s build:metadata && cross-env NODE_ENV=development rollup -c -w"
},
"devDependencies": {
Expand Down
206 changes: 206 additions & 0 deletions examples/scripts/serve.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
#!/usr/bin/env node

import { promises as fs } from 'fs';
import http from 'http';
import path from 'path';
import { parse as parseUrl } from 'url';

import { transformSync } from '@swc/core';
import serveHandler from 'serve-handler';

// Cache for transpiled TypeScript files
const cache = new Map();

// SWC configuration matching the project's existing setup
const swcOptions = {
jsc: {
parser: {
syntax: 'typescript',
tsx: false,
decorators: false,
dynamicImport: true
},
target: 'es2022',
loose: false,
externalHelpers: false
},
module: {
type: 'es6',
strict: false,
strictMode: true,
lazy: false,
noInterop: false
},
sourceMaps: 'inline',
inlineSourcesContent: true
};

/**
* Check if a file exists
* @param {string} filePath - The path to the file
* @returns {Promise<boolean>} Whether the file exists
*/
async function fileExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}

/**
* Get file modification time
* @param {string} filePath - The path to the file
* @returns {Promise<number | null>} The file modification time
*/
async function getMtime(filePath) {
try {
const stats = await fs.stat(filePath);
return stats.mtime.getTime();
} catch {
return null;
}
}

/**
* Transpile TypeScript file to JavaScript
* @param {string} tsPath - The path to the TypeScript file
* @param {string} jsPath - The path to the JavaScript file
* @returns {Promise<string>} The transpiled JavaScript code
*/
async function transpileTypeScript(tsPath, jsPath) {
// Check cache
const cacheKey = tsPath;
const mtime = await getMtime(tsPath);

if (cache.has(cacheKey)) {
const cached = cache.get(cacheKey);
if (cached.mtime === mtime) {
console.log(`[Serve] Cache hit: ${path.relative(process.cwd(), tsPath)}`);
return cached.content;
}
}

console.log(`[Serve] Transpiling: ${path.relative(process.cwd(), tsPath)}`);

try {
const tsContent = await fs.readFile(tsPath, 'utf8');
// @ts-ignore
const result = transformSync(tsContent, {
...swcOptions,
filename: tsPath
});

// Cache the result
cache.set(cacheKey, {
content: result.code,
mtime: mtime
});

return result.code;
} catch (error) {
console.error(`[Serve] Error transpiling ${tsPath}:`, error.message);
throw error;
}
}

/**
* Custom request handler that intercepts .js requests
* @param {import('http').IncomingMessage} request - The incoming request
* @param {import('http').ServerResponse} response - The outgoing response
* @param {object} serveConfig - The serve configuration
* @param {string} rootDir - The root directory to serve
* @returns {Promise<void>}
*/
async function handleRequest(request, response, serveConfig, rootDir) {
const parsedUrl = parseUrl(request.url ?? '');
const requestPath = parsedUrl.pathname;

// Only intercept .js file requests
if (requestPath?.endsWith('.js')) {
const absolutePath = path.join(rootDir, requestPath);
const jsExists = await fileExists(absolutePath);

// If .js file doesn't exist, check for .ts file
if (!jsExists) {
const tsPath = absolutePath.replace(/\.js$/, '.ts');
const tsExists = await fileExists(tsPath);

if (tsExists) {
try {
const transpiledCode = await transpileTypeScript(tsPath, absolutePath);

// Send the transpiled JavaScript
response.setHeader('Content-Type', 'application/javascript; charset=utf-8');
response.setHeader('Cache-Control', 'no-cache');
response.statusCode = 200;
response.end(transpiledCode);
return;
} catch (error) {
// Send error response
response.setHeader('Content-Type', 'text/plain; charset=utf-8');
response.statusCode = 500;
response.end(`Error transpiling TypeScript file: ${error.message}`);
return;
}
}
}
}
Comment on lines +116 to +149
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally we would not want any custom code to auto-convert the typescript files to JS - The serve NPM script would serve the final built version of the engine which would already be in JS so this conversion would not be needed at this stage

Copy link
Contributor Author

@liamdon liamdon Jun 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I generally agree - but then we have this use-case described in the README where you can use the engine source directly:

ENGINE_PATH=../src/index.js npm run develop

I figured this might be a common use-case for engine developers who are working on features and want to preview them live. And this feels like the kind of thing Maksims is concerned about, being able to quickly edit and preview the live engine code.

However, what we should probably do is serve the built version normally with no transformation unless they have specified the raw source ENGINE_PATH, in which case the above could still apply. We could basically check ENGINE_PATH in the handler above and early exit with the serve unless it's ../src/. We are still using serve, it's just the library version rather than the CLI.

This development case is where people often reach for Vite as an extension to Rollup, the dev server will do all the transformation for you. But there is already a heavy investment in Rollup plugins and we don't need most Vite features, so that felt like too large a change.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea thats the only place thats its used directly - It would be better to use tsc watch to chain from the source directly instead of transformation during serving. It would be just as fast it just needs to be setup correctly.

Yea I want to use vite ngl but its the fact that we have multiple sources and outputs thats makes it difficult to migrate but vite has some nice caching and hot reloading so its something I have considered.


// Pass through to serve-handler for all other requests
return serveHandler(request, response, {
...serveConfig,
public: rootDir
});
}

/**
* Start the server
*/
async function startServer() {
const port = process.env.PORT || 3000;
// Get directory to serve from command line args or environment variable
const args = process.argv.slice(2);
let rootDir = args[0] || process.env.SERVE_DIR || 'dist';

// Resolve to absolute path
rootDir = path.resolve(process.cwd(), rootDir);

// Check if directory exists
if (!await fileExists(rootDir)) {
console.error(`[Serve] Error: Directory '${rootDir}' does not exist`);
process.exit(1);
}

// Load serve configuration
let serveConfig = {};
try {
const configPath = path.join(process.cwd(), 'serve.json');
const configContent = await fs.readFile(configPath, 'utf8');
serveConfig = JSON.parse(configContent);
} catch {
// No serve.json found, use defaults
}

const server = http.createServer((request, response) => {
handleRequest(request, response, serveConfig, rootDir).catch((error) => {
console.error('[Serve] Server error:', error);
response.statusCode = 500;
response.end('Internal Server Error');
});
});

server.listen(port, () => {
console.log(`[Serve] TS-enabled server running at http://localhost:${port}`);
console.log(`[Serve] Serving directory: ${rootDir}`);
});
}

// Start the server
startServer().catch((error) => {
console.error('[Serve] Failed to start server:', error);
process.exit(1);
});

export { handleRequest, transpileTypeScript };
Loading