diff --git a/examples/frost/index.html b/examples/frost/index.html
index e5a5f43..b988e89 100644
--- a/examples/frost/index.html
+++ b/examples/frost/index.html
@@ -1,2 +1,11 @@
-
Iceberg + FrostFrost
+
+
+
+
+ Iceberg + Frost
+
+Frost
+
+
+
diff --git a/examples/frost/src/main.js b/examples/frost/src/main.js
index 9edb987..30b8060 100644
--- a/examples/frost/src/main.js
+++ b/examples/frost/src/main.js
@@ -1,2 +1,3 @@
import '@fretuks/frost';
+
document.querySelector('#app').dataset.built = 'true';
diff --git a/examples/vanilla/src/components/card.css b/examples/vanilla/src/components/card.css
index 50bc23c..f5b7f55 100644
--- a/examples/vanilla/src/components/card.css
+++ b/examples/vanilla/src/components/card.css
@@ -1 +1,3 @@
-.card { padding: 2rem; }
+.card {
+ padding: 2rem;
+}
diff --git a/examples/vanilla/src/main.js b/examples/vanilla/src/main.js
index 01a653c..fc071a3 100644
--- a/examples/vanilla/src/main.js
+++ b/examples/vanilla/src/main.js
@@ -1,3 +1,4 @@
import './style.css';
-import { message } from './utils.js';
+import {message} from './utils.js';
+
document.querySelector('#app').textContent = message;
diff --git a/examples/vanilla/src/style.css b/examples/vanilla/src/style.css
index 5ff6bd3..0d05607 100644
--- a/examples/vanilla/src/style.css
+++ b/examples/vanilla/src/style.css
@@ -1,2 +1,6 @@
@import './components/card.css';
-body { margin: 0; font-family: system-ui, sans-serif; }
+
+body {
+ margin: 0;
+ font-family: system-ui, sans-serif;
+}
diff --git a/src/bundler/index.ts b/src/bundler/index.ts
index 4ae0900..abad69d 100644
--- a/src/bundler/index.ts
+++ b/src/bundler/index.ts
@@ -1,11 +1,55 @@
import path from 'node:path';
-import { mkdir, readdir, rm, writeFile } from 'node:fs/promises';
-import { bundleCss, bundleJavaScript } from './rolldown.js';
-import { loadConfig, type IcebergConfig } from '../core/config.js';
-import { readHtmlEntry, rewriteHtml } from '../core/html.js';
-import { logger } from '../core/logger.js';
-export interface BuildResult { root: string; outDir: string; files: string[]; duration: number; }
-export async function build(inlineConfig?: IcebergConfig): Promise { const started = Date.now(); const config = await loadConfig(process.cwd(), inlineConfig); const outDir = path.resolve(config.root, config.build.outDir); const { html, entry } = await readHtmlEntry(config.root); if (config.build.emptyOutDir) await emptyDirectory(outDir); await mkdir(outDir, { recursive: true }); const jsResult = await bundleJavaScript(config, resolveHtmlPath(config.root, entry.script)); const linkedCssFiles: string[] = []; for (const style of entry.styles) { const result = await bundleCss(resolveHtmlPath(config.root, style), config); const target = path.join(outDir, result.fileName); await mkdir(path.dirname(target), { recursive: true }); await writeFile(target, result.code); linkedCssFiles.push(result.fileName); } await writeFile(path.join(outDir, 'index.html'), rewriteHtml(html, jsResult.jsFile, jsResult.cssFiles, linkedCssFiles, config.base)); const files = await listFiles(outDir); logger.info(`built ${files.length} files in ${Date.now() - started}ms`); return { root: config.root, outDir, files, duration: Date.now() - started }; }
-function resolveHtmlPath(root: string, value: string) { if (value.startsWith('/')) return path.resolve(root, value.slice(1)); if (/^https?:\/\//.test(value)) throw new Error(`Remote asset is not supported: ${value}`); return path.resolve(root, value); }
-async function emptyDirectory(dir: string) { await mkdir(dir, { recursive: true }); for (const item of await readdir(dir)) await rm(path.join(dir, item), { recursive: true, force: true }); }
-async function listFiles(dir: string, prefix = ''): Promise { const result: string[] = []; for (const entry of await readdir(dir, { withFileTypes: true })) { const relative = path.join(prefix, entry.name); if (entry.isDirectory()) result.push(...await listFiles(path.join(dir, entry.name), relative)); else result.push(relative); } return result; }
+import {mkdir, readdir, rm, writeFile} from 'node:fs/promises';
+import {bundleCss, bundleJavaScript} from './rolldown.js';
+import {loadConfig, type IcebergConfig} from '../core/config.js';
+import {readHtmlEntry, rewriteHtml} from '../core/html.js';
+import {logger} from '../core/logger.js';
+
+export interface BuildResult {
+ root: string;
+ outDir: string;
+ files: string[];
+ duration: number;
+}
+
+export async function build(inlineConfig?: IcebergConfig): Promise {
+ const started = Date.now();
+ const config = await loadConfig(process.cwd(), inlineConfig);
+ const outDir = path.resolve(config.root, config.build.outDir);
+ const {html, entry} = await readHtmlEntry(config.root);
+ if (config.build.emptyOutDir) await emptyDirectory(outDir);
+ await mkdir(outDir, {recursive: true});
+ const jsResult = await bundleJavaScript(config, resolveHtmlPath(config.root, entry.script));
+ const linkedCssFiles: string[] = [];
+ for (const style of entry.styles) {
+ const result = await bundleCss(resolveHtmlPath(config.root, style), config);
+ const target = path.join(outDir, result.fileName);
+ await mkdir(path.dirname(target), {recursive: true});
+ await writeFile(target, result.code);
+ linkedCssFiles.push(result.fileName);
+ }
+ await writeFile(path.join(outDir, 'index.html'), rewriteHtml(html, jsResult.jsFile, jsResult.cssFiles, linkedCssFiles, config.base));
+ const files = await listFiles(outDir);
+ logger.info(`built ${files.length} files in ${Date.now() - started}ms`);
+ return {root: config.root, outDir, files, duration: Date.now() - started};
+}
+
+function resolveHtmlPath(root: string, value: string) {
+ if (value.startsWith('/')) return path.resolve(root, value.slice(1));
+ if (/^https?:\/\//.test(value)) throw new Error(`Remote asset is not supported: ${value}`);
+ return path.resolve(root, value);
+}
+
+async function emptyDirectory(dir: string) {
+ await mkdir(dir, {recursive: true});
+ for (const item of await readdir(dir)) await rm(path.join(dir, item), {recursive: true, force: true});
+}
+
+async function listFiles(dir: string, prefix = ''): Promise {
+ const result: string[] = [];
+ for (const entry of await readdir(dir, {withFileTypes: true})) {
+ const relative = path.join(prefix, entry.name);
+ if (entry.isDirectory()) result.push(...await listFiles(path.join(dir, entry.name), relative)); else result.push(relative);
+ }
+ return result;
+}
diff --git a/src/bundler/rolldown.ts b/src/bundler/rolldown.ts
index 2a6cd83..b445c65 100644
--- a/src/bundler/rolldown.ts
+++ b/src/bundler/rolldown.ts
@@ -1,16 +1,84 @@
import path from 'node:path';
-import { readFile } from 'node:fs/promises';
-import { createHash } from 'node:crypto';
-import { rolldown, type Plugin, type RolldownOutput } from 'rolldown';
-import { bundleAsync } from 'lightningcss';
-import type { ResolvedIcebergConfig } from '../core/config.js';
-const cssExtensions = /\.css$/i; const assetExtensions = /\.(png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf|ico)$/i;
-export interface BundleResult { output: RolldownOutput; jsFile: string; cssFiles: string[]; }
-export async function bundleJavaScript(config: ResolvedIcebergConfig, input: string): Promise {
- let css = ''; const cssFiles: string[] = [];
- const virtualFiles = new Map();
- const plugin: Plugin = { name: 'iceberg-css-and-assets', async resolveId(source, importer) { const resolved = importer ? await this.resolve(source, importer, { skipSelf: true }) : null; const file = resolved?.id ?? ((cssExtensions.test(source) || assetExtensions.test(source)) ? path.resolve(config.root, source) : null); if (!file || (!cssExtensions.test(file) && !assetExtensions.test(file))) return null; const kind = cssExtensions.test(file) ? 'css' : 'asset'; const virtual = `\0iceberg-${kind}:${virtualFiles.size}`; virtualFiles.set(virtual, { kind, file }); return virtual; }, async load(id) { const virtual = virtualFiles.get(id); if (!virtual) return null; if (virtual.kind === 'css') { const result = await bundleAsync({ filename: virtual.file, minify: config.build.minify, sourceMap: config.build.sourcemap }); css += Buffer.from(result.code).toString('utf8') + '\n'; return 'export default undefined;'; } const reference = this.emitFile({ type: 'asset', name: path.basename(virtual.file), source: await readFile(virtual.file) }); return `export default import.meta.ROLLUP_FILE_URL_${reference};`; }, generateBundle() { if (css) { const hash = createHash('sha256').update(css).digest('hex').slice(0, 8); const fileName = `assets/index-${hash}.css`; this.emitFile({ type: 'asset', fileName, source: css }); cssFiles.push(fileName); } } };
- const bundle = await rolldown({ input, plugins: [plugin], treeshake: true, moduleTypes: { '.ts': 'ts', '.tsx': 'tsx', '.jsx': 'jsx', '.json': 'json' } });
- try { const output = await bundle.write({ dir: config.build.outDir, format: 'esm', sourcemap: config.build.sourcemap, minify: config.build.minify, entryFileNames: 'assets/[name]-[hash].js', chunkFileNames: 'assets/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' }); const jsChunk = output.output.find(item => item.type === 'chunk' && item.isEntry); if (!jsChunk) throw new Error('Rolldown did not produce an entry chunk.'); return { output, jsFile: jsChunk.fileName, cssFiles }; } finally { await bundle.close(); }
+import {readFile} from 'node:fs/promises';
+import {createHash} from 'node:crypto';
+import {rolldown, type Plugin, type RolldownOutput} from 'rolldown';
+import {bundleAsync} from 'lightningcss';
+import type {ResolvedIcebergConfig} from '../core/config.js';
+
+const cssExtensions = /\.css$/i;
+const assetExtensions = /\.(png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf|ico)$/i;
+
+export interface BundleResult {
+ output: RolldownOutput;
+ jsFile: string;
+ cssFiles: string[];
+}
+
+export async function bundleJavaScript(config: ResolvedIcebergConfig, input: string): Promise {
+ let css = '';
+ const cssFiles: string[] = [];
+ const virtualFiles = new Map();
+ const plugin: Plugin = {
+ name: 'iceberg-css-and-assets', async resolveId(source, importer) {
+ const resolved = importer ? await this.resolve(source, importer, {skipSelf: true}) : null;
+ const file = resolved?.id ?? ((cssExtensions.test(source) || assetExtensions.test(source)) ? path.resolve(config.root, source) : null);
+ if (!file || (!cssExtensions.test(file) && !assetExtensions.test(file))) return null;
+ const kind = cssExtensions.test(file) ? 'css' : 'asset';
+ const virtual = `\0iceberg-${kind}:${virtualFiles.size}`;
+ virtualFiles.set(virtual, {kind, file});
+ return virtual;
+ }, async load(id) {
+ const virtual = virtualFiles.get(id);
+ if (!virtual) return null;
+ if (virtual.kind === 'css') {
+ const result = await bundleAsync({
+ filename: virtual.file,
+ minify: config.build.minify,
+ sourceMap: config.build.sourcemap
+ });
+ css += Buffer.from(result.code).toString('utf8') + '\n';
+ return 'export default undefined;';
+ }
+ const reference = this.emitFile({
+ type: 'asset',
+ name: path.basename(virtual.file),
+ source: await readFile(virtual.file)
+ });
+ return `export default import.meta.ROLLUP_FILE_URL_${reference};`;
+ }, generateBundle() {
+ if (css) {
+ const hash = createHash('sha256').update(css).digest('hex').slice(0, 8);
+ const fileName = `assets/index-${hash}.css`;
+ this.emitFile({type: 'asset', fileName, source: css});
+ cssFiles.push(fileName);
+ }
+ }
+ };
+ const bundle = await rolldown({
+ input,
+ plugins: [plugin],
+ treeshake: true,
+ moduleTypes: {'.ts': 'ts', '.tsx': 'tsx', '.jsx': 'jsx', '.json': 'json'}
+ });
+ try {
+ const output = await bundle.write({
+ dir: config.build.outDir,
+ format: 'esm',
+ sourcemap: config.build.sourcemap,
+ minify: config.build.minify,
+ entryFileNames: 'assets/[name]-[hash].js',
+ chunkFileNames: 'assets/[name]-[hash].js',
+ assetFileNames: 'assets/[name]-[hash][extname]'
+ });
+ const jsChunk = output.output.find(item => item.type === 'chunk' && item.isEntry);
+ if (!jsChunk) throw new Error('Rolldown did not produce an entry chunk.');
+ return {output, jsFile: jsChunk.fileName, cssFiles};
+ } finally {
+ await bundle.close();
+ }
+}
+
+export async function bundleCss(file: string, config: ResolvedIcebergConfig) {
+ const result = await bundleAsync({filename: file, minify: config.build.minify, sourceMap: config.build.sourcemap});
+ return {fileName: `assets/${path.basename(file, '.css')}.css`, code: Buffer.from(result.code).toString('utf8')};
}
-export async function bundleCss(file: string, config: ResolvedIcebergConfig) { const result = await bundleAsync({ filename: file, minify: config.build.minify, sourceMap: config.build.sourcemap }); return { fileName: `assets/${path.basename(file, '.css')}.css`, code: Buffer.from(result.code).toString('utf8') }; }
diff --git a/src/core/config.ts b/src/core/config.ts
index 806155a..8245e1b 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1,25 +1,72 @@
-import { access } from 'node:fs/promises';
+import {access} from 'node:fs/promises';
import path from 'node:path';
-export interface IcebergBuildOptions { outDir?: string; minify?: boolean; sourcemap?: boolean; emptyOutDir?: boolean; }
-export interface IcebergServerOptions { host?: string; port?: number; strictPort?: boolean; open?: boolean; }
-export interface IcebergConfig { root?: string; base?: string; build?: IcebergBuildOptions; server?: IcebergServerOptions; }
-export interface ResolvedIcebergConfig { root: string; base: string; build: Required; server: Required; }
-export function defineConfig(config: IcebergConfig): IcebergConfig { return config; }
-export async function loadConfig(cwd: string, inline?: IcebergConfig): Promise {
- const configPath = path.join(cwd, 'iceberg.config.js'); let fileConfig: IcebergConfig = {};
- try { await access(configPath); const loaded = await import(`${new URL(`file://${configPath.replace(/\\/g, '/')}`).href}?t=${Date.now()}`); fileConfig = loaded.default ?? loaded; }
- catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
- const merged = { ...fileConfig, ...inline, build: { ...fileConfig.build, ...inline?.build } };
- const root = path.resolve(cwd, merged.root ?? '.');
- const build = { outDir: merged.build?.outDir ?? 'dist', minify: merged.build?.minify ?? true, sourcemap: merged.build?.sourcemap ?? false, emptyOutDir: merged.build?.emptyOutDir ?? true };
- const server = { host: merged.server?.host ?? 'localhost', port: merged.server?.port ?? 3000, strictPort: merged.server?.strictPort ?? false, open: merged.server?.open ?? false };
- if (merged.base !== undefined && typeof merged.base !== 'string') throw new Error('Iceberg config: base must be a string.');
- if (typeof build.outDir !== 'string' || !build.outDir) throw new Error('Iceberg config: build.outDir must be a non-empty string.');
- for (const key of ['minify', 'sourcemap', 'emptyOutDir'] as const) if (typeof build[key] !== 'boolean') throw new Error(`Iceberg config: build.${key} must be a boolean.`);
- if (typeof server.host !== 'string' || !server.host) throw new Error('Iceberg config: server.host must be a non-empty string.');
- if (!Number.isInteger(server.port) || server.port < 0 || server.port > 65535) throw new Error('Iceberg config: server.port must be an integer from 0 to 65535.');
- if (typeof server.strictPort !== 'boolean' || typeof server.open !== 'boolean') throw new Error('Iceberg config: server.strictPort and server.open must be booleans.');
- return { root, base: normalizeBase(merged.base ?? '/'), build, server };
+export interface IcebergBuildOptions {
+ outDir?: string;
+ minify?: boolean;
+ sourcemap?: boolean;
+ emptyOutDir?: boolean;
+}
+
+export interface IcebergServerOptions {
+ host?: string;
+ port?: number;
+ strictPort?: boolean;
+ open?: boolean;
+}
+
+export interface IcebergConfig {
+ root?: string;
+ base?: string;
+ build?: IcebergBuildOptions;
+ server?: IcebergServerOptions;
+}
+
+export interface ResolvedIcebergConfig {
+ root: string;
+ base: string;
+ build: Required;
+ server: Required;
+}
+
+export function defineConfig(config: IcebergConfig): IcebergConfig {
+ return config;
+}
+
+export async function loadConfig(cwd: string, inline?: IcebergConfig): Promise {
+ const configPath = path.join(cwd, 'iceberg.config.js');
+ let fileConfig: IcebergConfig = {};
+ try {
+ await access(configPath);
+ const loaded = await import(`${new URL(`file://${configPath.replace(/\\/g, '/')}`).href}?t=${Date.now()}`);
+ fileConfig = loaded.default ?? loaded;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ const merged = {...fileConfig, ...inline, build: {...fileConfig.build, ...inline?.build}};
+ const root = path.resolve(cwd, merged.root ?? '.');
+ const build = {
+ outDir: merged.build?.outDir ?? 'dist',
+ minify: merged.build?.minify ?? true,
+ sourcemap: merged.build?.sourcemap ?? false,
+ emptyOutDir: merged.build?.emptyOutDir ?? true
+ };
+ const server = {
+ host: merged.server?.host ?? 'localhost',
+ port: merged.server?.port ?? 3000,
+ strictPort: merged.server?.strictPort ?? false,
+ open: merged.server?.open ?? false
+ };
+ if (merged.base !== undefined && typeof merged.base !== 'string') throw new Error('Iceberg config: base must be a string.');
+ if (typeof build.outDir !== 'string' || !build.outDir) throw new Error('Iceberg config: build.outDir must be a non-empty string.');
+ for (const key of ['minify', 'sourcemap', 'emptyOutDir'] as const) if (typeof build[key] !== 'boolean') throw new Error(`Iceberg config: build.${key} must be a boolean.`);
+ if (typeof server.host !== 'string' || !server.host) throw new Error('Iceberg config: server.host must be a non-empty string.');
+ if (!Number.isInteger(server.port) || server.port < 0 || server.port > 65535) throw new Error('Iceberg config: server.port must be an integer from 0 to 65535.');
+ if (typeof server.strictPort !== 'boolean' || typeof server.open !== 'boolean') throw new Error('Iceberg config: server.strictPort and server.open must be booleans.');
+ return {root, base: normalizeBase(merged.base ?? '/'), build, server};
+}
+
+function normalizeBase(base: string) {
+ const normalized = base.replace(/\\/g, '/');
+ return `/${normalized.replace(/^\/+|\/+$/g, '')}/`.replace(/^\/\/$/, '/');
}
-function normalizeBase(base: string) { const normalized = base.replace(/\\/g, '/'); return `/${normalized.replace(/^\/+|\/+$/g, '')}/`.replace(/^\/\/$/, '/'); }
diff --git a/src/core/errors.ts b/src/core/errors.ts
index a402fbd..14d5b55 100644
--- a/src/core/errors.ts
+++ b/src/core/errors.ts
@@ -1 +1,6 @@
-export class IcebergError extends Error { constructor(message: string, options?: { cause?: unknown }) { super(message, options); this.name = 'IcebergError'; } }
+export class IcebergError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = 'IcebergError';
+ }
+}
diff --git a/src/core/html.ts b/src/core/html.ts
index cd7ee5f..195770b 100644
--- a/src/core/html.ts
+++ b/src/core/html.ts
@@ -1,27 +1,96 @@
-import { readFile } from 'node:fs/promises';
+import {readFile} from 'node:fs/promises';
import path from 'node:path';
-import { parse, serialize } from 'parse5';
-import { IcebergError } from './errors.js';
-type Node = { nodeName?: string; tagName?: string; attrs?: Array<{ name: string; value: string }>; childNodes?: Node[]; parentNode?: Node };
-export interface HtmlEntry { file: string; script: string; styles: string[]; }
+import {parse, serialize} from 'parse5';
+import {IcebergError} from './errors.js';
+
+type Node = {
+ nodeName?: string;
+ tagName?: string;
+ attrs?: Array<{ name: string; value: string }>;
+ childNodes?: Node[];
+ parentNode?: Node
+};
+
+export interface HtmlEntry {
+ file: string;
+ script: string;
+ styles: string[];
+}
+
export async function readHtmlEntry(root: string): Promise<{ html: string; entry: HtmlEntry }> {
- const htmlFile = path.join(root, 'index.html'); let html: string;
- try { html = await readFile(htmlFile, 'utf8'); } catch { throw new IcebergError(`Could not find HTML entry point: ${htmlFile}`); }
- const document = parse(html) as unknown as Node; const scripts: string[] = []; const styles: string[] = [];
- walk(document, node => { if (node.tagName === 'script') { const type = attr(node, 'type'); const src = attr(node, 'src'); if (src && (!type || type === 'module')) scripts.push(src); else if (src && type !== 'module') throw new IcebergError(`Unsupported script type in ${htmlFile}: ${type}`); } if (node.tagName === 'link' && attr(node, 'rel')?.toLowerCase() === 'stylesheet') { const href = attr(node, 'href'); if (href) styles.push(href); } });
- if (!scripts.length) throw new IcebergError('index.html must contain a module script with a src attribute.');
- if (scripts.length > 1) throw new IcebergError('Phase 1 supports one module script entry in index.html.');
- if (/^https?:\/\//.test(scripts[0]!)) throw new IcebergError('Remote module scripts are not supported.');
- return { html, entry: { file: htmlFile, script: scripts[0]!, styles } };
+ const htmlFile = path.join(root, 'index.html');
+ let html: string;
+ try {
+ html = await readFile(htmlFile, 'utf8');
+ } catch {
+ throw new IcebergError(`Could not find HTML entry point: ${htmlFile}`);
+ }
+ const document = parse(html) as unknown as Node;
+ const scripts: string[] = [];
+ const styles: string[] = [];
+ walk(document, node => {
+ if (node.tagName === 'script') {
+ const type = attr(node, 'type');
+ const src = attr(node, 'src');
+ if (src && (!type || type === 'module')) scripts.push(src); else if (src && type !== 'module') throw new IcebergError(`Unsupported script type in ${htmlFile}: ${type}`);
+ }
+ if (node.tagName === 'link' && attr(node, 'rel')?.toLowerCase() === 'stylesheet') {
+ const href = attr(node, 'href');
+ if (href) styles.push(href);
+ }
+ });
+ if (!scripts.length) throw new IcebergError('index.html must contain a module script with a src attribute.');
+ if (scripts.length > 1) throw new IcebergError('Phase 1 supports one module script entry in index.html.');
+ if (/^https?:\/\//.test(scripts[0]!)) throw new IcebergError('Remote module scripts are not supported.');
+ return {html, entry: {file: htmlFile, script: scripts[0]!, styles}};
}
+
export function rewriteHtml(html: string, jsFile: string, importedCssFiles: string[], linkedCssFiles: string[], base: string): string {
- const document = parse(html) as unknown as Node; let linkedIndex = 0;
- walk(document, node => { if (node.tagName === 'script' && attr(node, 'src')) setAttr(node, 'src', joinBase(base, jsFile)); if (node.tagName === 'link' && attr(node, 'rel')?.toLowerCase() === 'stylesheet') { const replacement = linkedCssFiles[linkedIndex++]; if (replacement) setAttr(node, 'href', joinBase(base, replacement)); } });
- const head = find(document, 'head'); if (head) for (const css of importedCssFiles) head.childNodes!.push({ nodeName: 'link', tagName: 'link', attrs: [{ name: 'rel', value: 'stylesheet' }, { name: 'href', value: joinBase(base, css) }], childNodes: [], parentNode: head });
- return serialize(document as any);
+ const document = parse(html) as unknown as Node;
+ let linkedIndex = 0;
+ walk(document, node => {
+ if (node.tagName === 'script' && attr(node, 'src')) setAttr(node, 'src', joinBase(base, jsFile));
+ if (node.tagName === 'link' && attr(node, 'rel')?.toLowerCase() === 'stylesheet') {
+ const replacement = linkedCssFiles[linkedIndex++];
+ if (replacement) setAttr(node, 'href', joinBase(base, replacement));
+ }
+ });
+ const head = find(document, 'head');
+ if (head) for (const css of importedCssFiles) head.childNodes!.push({
+ nodeName: 'link',
+ tagName: 'link',
+ attrs: [{name: 'rel', value: 'stylesheet'}, {name: 'href', value: joinBase(base, css)}],
+ childNodes: [],
+ parentNode: head
+ });
+ return serialize(document as any);
+}
+
+function walk(node: Node, visit: (node: Node) => void) {
+ visit(node);
+ for (const child of node.childNodes ?? []) {
+ child.parentNode = node;
+ walk(child, visit);
+ }
+}
+
+function find(node: Node, tag: string): Node | undefined {
+ if (node.tagName === tag) return node;
+ for (const child of node.childNodes ?? []) {
+ const found = find(child, tag);
+ if (found) return found;
+ }
+}
+
+function attr(node: Node, name: string) {
+ return node.attrs?.find(item => item.name === name)?.value;
+}
+
+function setAttr(node: Node, name: string, value: string) {
+ const found = node.attrs?.find(item => item.name === name);
+ if (found) found.value = value; else node.attrs?.push({name, value});
+}
+
+function joinBase(base: string, file: string) {
+ return `${base.replace(/\/$/, '')}/${file.replace(/^\//, '')}`;
}
-function walk(node: Node, visit: (node: Node) => void) { visit(node); for (const child of node.childNodes ?? []) { child.parentNode = node; walk(child, visit); } }
-function find(node: Node, tag: string): Node | undefined { if (node.tagName === tag) return node; for (const child of node.childNodes ?? []) { const found = find(child, tag); if (found) return found; } }
-function attr(node: Node, name: string) { return node.attrs?.find(item => item.name === name)?.value; }
-function setAttr(node: Node, name: string, value: string) { const found = node.attrs?.find(item => item.name === name); if (found) found.value = value; else node.attrs?.push({ name, value }); }
-function joinBase(base: string, file: string) { return `${base.replace(/\/$/, '')}/${file.replace(/^\//, '')}`; }
diff --git a/src/core/logger.ts b/src/core/logger.ts
index 71b4e1b..1e951dc 100644
--- a/src/core/logger.ts
+++ b/src/core/logger.ts
@@ -1 +1,4 @@
-export const logger = { info: (message: string) => console.log(`[iceberg] ${message}`), error: (message: string) => console.error(`[iceberg] ${message}`) };
+export const logger = {
+ info: (message: string) => console.log(`[iceberg] ${message}`),
+ error: (message: string) => console.error(`[iceberg] ${message}`)
+};
diff --git a/src/server/index.ts b/src/server/index.ts
index 7c0147f..1a0260f 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -1,2 +1,2 @@
-export { createServer } from './dev-server.js';
-export type { DevServer } from './dev-server.js';
+export {createServer} from './dev-server.js';
+export type {DevServer} from './dev-server.js';
diff --git a/tests/build.test.mjs b/tests/build.test.mjs
index 50d111e..658189c 100644
--- a/tests/build.test.mjs
+++ b/tests/build.test.mjs
@@ -1,12 +1,60 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { mkdtemp, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import {mkdtemp, mkdir, readFile, readdir, writeFile} from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
-import { build } from '../dist/index.js';
+import {build} from '../dist/index.js';
-async function fixture(files) { const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-')); for (const [name, content] of Object.entries(files)) { const file = path.join(root, name); await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, content); } return root; }
-async function inRoot(root, fn) { const previous = process.cwd(); process.chdir(root); try { return await fn(); } finally { process.chdir(previous); } }
-test('builds JavaScript and CSS and rewrites HTML', async () => { const root = await fixture({ 'index.html': 'Keep me', 'src/main.js': "import './style.css'; document.body.dataset.ready = 'yes';", 'src/style.css': '.unused { color: red } body { color: blue; }' }); await inRoot(root, () => build()); const html = await readFile(path.join(root, 'dist/index.html'), 'utf8'); assert.match(html, /Keep me<\/title>/); assert.match(html, /assets\/main-[^"/]+\.js/); assert.match(html, /assets\/index-[^"/]+\.css/); const assets = await readdir(path.join(root, 'dist/assets')); const css = await readFile(path.join(root, 'dist/assets', assets.find(file => file.endsWith('.css'))), 'utf8'); assert.match(css, /body/); });
-test('supports TypeScript and custom output configuration', async () => { const root = await fixture({ 'index.html': '', 'src/main.ts': 'const answer: number = 42; console.log(answer);', 'iceberg.config.js': "export default { build: { outDir: 'build', minify: false, sourcemap: true } };" }); await inRoot(root, () => build()); const files = await readdir(path.join(root, 'build/assets')); assert.ok(files.some(file => file.endsWith('.js'))); assert.ok(files.some(file => file.endsWith('.js.map'))); const js = await readFile(path.join(root, 'build/assets', files.find(file => file.endsWith('.js'))), 'utf8'); assert.match(js, /42/); assert.doesNotMatch(js, /: number/); });
-test('rejects an HTML entry without a module script', async () => { const root = await fixture({ 'index.html': 'No script
' }); await assert.rejects(() => inRoot(root, () => build()), /module script/); });
+async function fixture(files) {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-'));
+ for (const [name, content] of Object.entries(files)) {
+ const file = path.join(root, name);
+ await mkdir(path.dirname(file), {recursive: true});
+ await writeFile(file, content);
+ }
+ return root;
+}
+
+async function inRoot(root, fn) {
+ const previous = process.cwd();
+ process.chdir(root);
+ try {
+ return await fn();
+ } finally {
+ process.chdir(previous);
+ }
+}
+
+test('builds JavaScript and CSS and rewrites HTML', async () => {
+ const root = await fixture({
+ 'index.html': 'Keep me',
+ 'src/main.js': "import './style.css'; document.body.dataset.ready = 'yes';",
+ 'src/style.css': '.unused { color: red } body { color: blue; }'
+ });
+ await inRoot(root, () => build());
+ const html = await readFile(path.join(root, 'dist/index.html'), 'utf8');
+ assert.match(html, /Keep me<\/title>/);
+ assert.match(html, /assets\/main-[^"/]+\.js/);
+ assert.match(html, /assets\/index-[^"/]+\.css/);
+ const assets = await readdir(path.join(root, 'dist/assets'));
+ const css = await readFile(path.join(root, 'dist/assets', assets.find(file => file.endsWith('.css'))), 'utf8');
+ assert.match(css, /body/);
+});
+test('supports TypeScript and custom output configuration', async () => {
+ const root = await fixture({
+ 'index.html': '',
+ 'src/main.ts': 'const answer: number = 42; console.log(answer);',
+ 'iceberg.config.js': "export default { build: { outDir: 'build', minify: false, sourcemap: true } };"
+ });
+ await inRoot(root, () => build());
+ const files = await readdir(path.join(root, 'build/assets'));
+ assert.ok(files.some(file => file.endsWith('.js')));
+ assert.ok(files.some(file => file.endsWith('.js.map')));
+ const js = await readFile(path.join(root, 'build/assets', files.find(file => file.endsWith('.js'))), 'utf8');
+ assert.match(js, /42/);
+ assert.doesNotMatch(js, /: number/);
+});
+test('rejects an HTML entry without a module script', async () => {
+ const root = await fixture({'index.html': 'No script
'});
+ await assert.rejects(() => inRoot(root, () => build()), /module script/);
+});
diff --git a/tests/dev-server.test.mjs b/tests/dev-server.test.mjs
index 0485791..8972752 100644
--- a/tests/dev-server.test.mjs
+++ b/tests/dev-server.test.mjs
@@ -1,24 +1,103 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises';
+import {mkdtemp, mkdir, readFile, writeFile} from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import WebSocket from 'ws';
-import { createServer } from '../dist/index.js';
+import {createServer} from '../dist/index.js';
async function fixture() {
- const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-dev-'));
- await mkdir(path.join(root, 'src'), { recursive: true }); await mkdir(path.join(root, 'public'), { recursive: true });
- await writeFile(path.join(root, 'index.html'), 'Dev');
- await writeFile(path.join(root, 'src/main.ts'), "import './style.css'; import { value } from './value.ts'; import logo from './logo.svg'; document.querySelector('#app').textContent = value + logo;");
- await writeFile(path.join(root, 'src/value.ts'), 'export const value: string = "ready";'); await writeFile(path.join(root, 'src/style.css'), 'body { color: blue; }'); await writeFile(path.join(root, 'public/robots.txt'), 'User-agent: *');
- await writeFile(path.join(root, 'src/logo.svg'), '');
- return root;
+ const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-dev-'));
+ await mkdir(path.join(root, 'src'), {recursive: true});
+ await mkdir(path.join(root, 'public'), {recursive: true});
+ await writeFile(path.join(root, 'index.html'), 'Dev');
+ await writeFile(path.join(root, 'src/main.ts'), "import './style.css'; import { value } from './value.ts'; import logo from './logo.svg'; document.querySelector('#app').textContent = value + logo;");
+ await writeFile(path.join(root, 'src/value.ts'), 'export const value: string = "ready";');
+ await writeFile(path.join(root, 'src/style.css'), 'body { color: blue; }');
+ await writeFile(path.join(root, 'public/robots.txt'), 'User-agent: *');
+ await writeFile(path.join(root, 'src/logo.svg'), '');
+ return root;
}
-async function withServer(fn) { const root = await fixture(); const previous = process.cwd(); process.chdir(root); const server = await createServer({ server: { host: '127.0.0.1', port: 0 } }); try { await server.listen(); return await fn(server, root); } finally { await server.close(); process.chdir(previous); } }
-function waitForMessage(socket, predicate) { return new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('Timed out waiting for WebSocket message')), 3000); socket.on('message', data => { const message = JSON.parse(data.toString()); if (predicate(message)) { clearTimeout(timeout); resolve(message); } }); }); }
-test('serves HTML, transformed TypeScript, CSS, public files, and WebSocket reload events', async () => { await withServer(async (server, root) => { const base = server.url; const html = await (await fetch(base)).text(); assert.match(html, /@iceberg\/client\.js/); const js = await (await fetch(`${base}src/main.ts`)).text(); assert.match(js, /@iceberg\/asset-module/); assert.doesNotMatch(js, /: string/); const assetModuleUrl = `${base}${js.match(/\/\@iceberg\/asset-module\?file=[^"']+/)[0].slice(1)}`; assert.match(await (await fetch(assetModuleUrl)).text(), /export default/); const css = await (await fetch(`${base}src/style.css`)).text(); assert.match(css, /color:\s*(blue|#00f)/); assert.equal(await (await fetch(`${base}robots.txt`)).text(), 'User-agent: *'); assert.equal((await fetch(`${base}.env`)).status, 404); const socket = new WebSocket(`${base.replace('http', 'ws')}__iceberg_ws`); const connected = waitForMessage(socket, message => message.type === 'connected'); await new Promise((resolve, reject) => { socket.once('open', resolve); socket.once('error', reject); }); await connected; const reload = waitForMessage(socket, message => message.type === 'reload'); await writeFile(path.join(root, 'src/main.ts'), 'document.body.dataset.changed = "yes";'); await reload; socket.close(); }); });
+async function withServer(fn) {
+ const root = await fixture();
+ const previous = process.cwd();
+ process.chdir(root);
+ const server = await createServer({server: {host: '127.0.0.1', port: 0}});
+ try {
+ await server.listen();
+ return await fn(server, root);
+ } finally {
+ await server.close();
+ process.chdir(previous);
+ }
+}
-test('sends CSS updates without requiring a page reload', async () => { await withServer(async (server, root) => { const socket = new WebSocket(`${server.url.replace('http', 'ws')}__iceberg_ws`); const connected = waitForMessage(socket, message => message.type === 'connected'); await new Promise((resolve, reject) => { socket.once('open', resolve); socket.once('error', reject); }); await connected; const updatePromise = waitForMessage(socket, message => message.type === 'css-update'); await writeFile(path.join(root, 'src/style.css'), 'body { color: red; }'); const update = await updatePromise; assert.match(update.path, /src[\\/]style\.css/); socket.close(); }); });
-test('falls back to the next port when strictPort is disabled', async () => { await withServer(async (server, root) => { const second = await createServer({ root, server: { host: '127.0.0.1', port: server.port } }); try { await second.listen(); assert.notEqual(second.port, server.port); } finally { await second.close(); } }); });
+function waitForMessage(socket, predicate) {
+ return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error('Timed out waiting for WebSocket message')), 3000);
+ socket.on('message', data => {
+ const message = JSON.parse(data.toString());
+ if (predicate(message)) {
+ clearTimeout(timeout);
+ resolve(message);
+ }
+ });
+ });
+}
+
+test('serves HTML, transformed TypeScript, CSS, public files, and WebSocket reload events', async () => {
+ await withServer(async (server, root) => {
+ const base = server.url;
+ const html = await (await fetch(base)).text();
+ assert.match(html, /@iceberg\/client\.js/);
+ const js = await (await fetch(`${base}src/main.ts`)).text();
+ assert.match(js, /@iceberg\/asset-module/);
+ assert.doesNotMatch(js, /: string/);
+ const assetModuleUrl = `${base}${js.match(/\/\@iceberg\/asset-module\?file=[^"']+/)[0].slice(1)}`;
+ assert.match(await (await fetch(assetModuleUrl)).text(), /export default/);
+ const css = await (await fetch(`${base}src/style.css`)).text();
+ assert.match(css, /color:\s*(blue|#00f)/);
+ assert.equal(await (await fetch(`${base}robots.txt`)).text(), 'User-agent: *');
+ assert.equal((await fetch(`${base}.env`)).status, 404);
+ const socket = new WebSocket(`${base.replace('http', 'ws')}__iceberg_ws`);
+ const connected = waitForMessage(socket, message => message.type === 'connected');
+ await new Promise((resolve, reject) => {
+ socket.once('open', resolve);
+ socket.once('error', reject);
+ });
+ await connected;
+ const reload = waitForMessage(socket, message => message.type === 'reload');
+ await writeFile(path.join(root, 'src/main.ts'), 'document.body.dataset.changed = "yes";');
+ await reload;
+ socket.close();
+ });
+});
+
+test('sends CSS updates without requiring a page reload', async () => {
+ await withServer(async (server, root) => {
+ const socket = new WebSocket(`${server.url.replace('http', 'ws')}__iceberg_ws`);
+ const connected = waitForMessage(socket, message => message.type === 'connected');
+ await new Promise((resolve, reject) => {
+ socket.once('open', resolve);
+ socket.once('error', reject);
+ });
+ await connected;
+ const updatePromise = waitForMessage(socket, message => message.type === 'css-update');
+ await writeFile(path.join(root, 'src/style.css'), 'body { color: red; }');
+ const update = await updatePromise;
+ assert.match(update.path, /src[\\/]style\.css/);
+ socket.close();
+ });
+});
+test('falls back to the next port when strictPort is disabled', async () => {
+ await withServer(async (server, root) => {
+ const second = await createServer({root, server: {host: '127.0.0.1', port: server.port}});
+ try {
+ await second.listen();
+ assert.notEqual(second.port, server.port);
+ } finally {
+ await second.close();
+ }
+ });
+});