@eighty4/dank 0.0.1-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib_js/http.js ADDED
@@ -0,0 +1,93 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { createServer, } from 'node:http';
3
+ import { extname, join as fsJoin } from 'node:path';
4
+ import { isProductionBuild } from "./flags.js";
5
+ export function createWebServer(port, frontendFetcher) {
6
+ const serverAddress = 'http://localhost:' + port;
7
+ return createServer((req, res) => {
8
+ if (!req.url || !req.method) {
9
+ res.end();
10
+ }
11
+ else {
12
+ const url = new URL(serverAddress + req.url);
13
+ if (req.method !== 'GET') {
14
+ res.writeHead(405);
15
+ res.end();
16
+ }
17
+ else {
18
+ frontendFetcher(url, convertHeadersToFetch(req.headers), res);
19
+ }
20
+ }
21
+ });
22
+ }
23
+ export function createBuiltDistFilesFetcher(dir, files) {
24
+ return (url, _headers, res) => {
25
+ if (!files.has(url.pathname)) {
26
+ res.writeHead(404);
27
+ res.end();
28
+ }
29
+ else {
30
+ const mimeType = resolveMimeType(url);
31
+ res.setHeader('Content-Type', mimeType);
32
+ const reading = createReadStream(mimeType === 'text/html'
33
+ ? fsJoin(dir, url.pathname, 'index.html')
34
+ : fsJoin(dir, url.pathname));
35
+ reading.pipe(res);
36
+ reading.on('error', err => {
37
+ console.error(`${url.pathname} file read ${reading.path} error ${err.message}`);
38
+ res.statusCode = 500;
39
+ res.end();
40
+ });
41
+ }
42
+ };
43
+ }
44
+ export function createLocalProxyFilesFetcher(port) {
45
+ const proxyAddress = 'http://127.0.0.1:' + port;
46
+ return (url, _headers, res) => {
47
+ fetch(proxyAddress + url.pathname).then(fetchResponse => {
48
+ res.writeHead(fetchResponse.status, convertHeadersFromFetch(fetchResponse.headers));
49
+ fetchResponse.bytes().then(data => res.end(data));
50
+ });
51
+ };
52
+ }
53
+ function resolveMimeType(url) {
54
+ switch (extname(url.pathname)) {
55
+ case '':
56
+ return 'text/html';
57
+ case '.js':
58
+ return 'text/javascript';
59
+ case '.json':
60
+ return 'application/json';
61
+ case '.css':
62
+ return 'text/css';
63
+ case '.svg':
64
+ return 'image/svg+xml';
65
+ case '.png':
66
+ return 'image/png';
67
+ default:
68
+ console.warn('? mime type for', url.pathname);
69
+ if (!isProductionBuild())
70
+ process.exit(1);
71
+ return 'application/octet-stream';
72
+ }
73
+ }
74
+ function convertHeadersFromFetch(from) {
75
+ const to = {};
76
+ for (const name of from.keys()) {
77
+ to[name] = from.get(name);
78
+ }
79
+ return to;
80
+ }
81
+ function convertHeadersToFetch(from) {
82
+ const to = new Headers();
83
+ for (const [name, values] of Object.entries(from)) {
84
+ if (Array.isArray(values)) {
85
+ for (const value of values)
86
+ to.append(name, value);
87
+ }
88
+ else if (values) {
89
+ to.set(name, values);
90
+ }
91
+ }
92
+ return to;
93
+ }
@@ -0,0 +1,37 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { extname, join } from 'node:path';
3
+ export async function writeBuildManifest(buildTag, files) {
4
+ await writeJsonToBuildDir('manifest.json', {
5
+ buildTag,
6
+ files: Array.from(files).map(f => extname(f).length
7
+ ? f
8
+ : f === '/'
9
+ ? '/index.html'
10
+ : f + '/index.html'),
11
+ });
12
+ }
13
+ export async function writeJsonToBuildDir(filename, json) {
14
+ await writeFile(join('./build', filename), JSON.stringify(json, null, 4));
15
+ }
16
+ export async function writeMetafile(filename, json) {
17
+ await writeJsonToBuildDir(join('metafiles', filename), json);
18
+ }
19
+ export async function writeCacheManifest(buildTag, files) {
20
+ await writeJsonToBuildDir('cache.json', {
21
+ apiRoutes: [],
22
+ buildTag,
23
+ files: Array.from(files).map(filenameToWebappPath),
24
+ });
25
+ }
26
+ // drops index.html from path
27
+ function filenameToWebappPath(p) {
28
+ if (p === '/index.html') {
29
+ return '/';
30
+ }
31
+ else if (p.endsWith('/index.html')) {
32
+ return p.substring(0, p.length - '/index.html'.length);
33
+ }
34
+ else {
35
+ return p;
36
+ }
37
+ }
@@ -0,0 +1,43 @@
1
+ import { copyFile, mkdir, readdir, stat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ export async function copyAssets(outRoot) {
4
+ try {
5
+ const stats = await stat('public');
6
+ if (stats.isDirectory()) {
7
+ await mkdir(outRoot, { recursive: true });
8
+ return await recursiveCopyAssets(outRoot);
9
+ }
10
+ else {
11
+ throw Error('./public cannot be a file');
12
+ }
13
+ }
14
+ catch (e) {
15
+ return null;
16
+ }
17
+ }
18
+ async function recursiveCopyAssets(outRoot, dir = '') {
19
+ const copied = [];
20
+ const to = join(outRoot, dir);
21
+ let madeDir = dir === '';
22
+ for (const p of await readdir(join('public', dir))) {
23
+ try {
24
+ const stats = await stat(join('public', dir, p));
25
+ if (stats.isDirectory()) {
26
+ copied.push(...(await recursiveCopyAssets(outRoot, join(dir, p))));
27
+ }
28
+ else {
29
+ if (!madeDir) {
30
+ await mkdir(join(outRoot, dir));
31
+ madeDir = true;
32
+ }
33
+ await copyFile(join('public', dir, p), join(to, p));
34
+ copied.push('/' + join(dir, p).replaceAll('\\', '/'));
35
+ }
36
+ }
37
+ catch (e) {
38
+ console.error('stat error', e);
39
+ process.exit(1);
40
+ }
41
+ }
42
+ return copied;
43
+ }
@@ -0,0 +1,67 @@
1
+ import { mkdir, rm } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { buildWebsite } from "./build.js";
4
+ import { createGlobalDefinitions } from "./define.js";
5
+ import { esbuildDevContext } from "./esbuild.js";
6
+ import { isPreviewBuild } from "./flags.js";
7
+ import { HtmlEntrypoint } from "./html.js";
8
+ import { createBuiltDistFilesFetcher, createLocalProxyFilesFetcher, createWebServer, } from "./http.js";
9
+ import { copyAssets } from "./public.js";
10
+ const isPreview = isPreviewBuild();
11
+ // alternate port for --preview bc of service worker
12
+ const PORT = isPreview ? 4000 : 3000;
13
+ // port for esbuild.serve
14
+ const ESBUILD_PORT = 2999;
15
+ export async function serveWebsite(c) {
16
+ await rm('build', { force: true, recursive: true });
17
+ let frontend;
18
+ if (isPreview) {
19
+ const { dir, files } = await buildWebsite(c);
20
+ frontend = createBuiltDistFilesFetcher(dir, files);
21
+ }
22
+ else {
23
+ const { port } = await startEsbuildWatch(c);
24
+ frontend = createLocalProxyFilesFetcher(port);
25
+ }
26
+ createWebServer(PORT, frontend).listen(PORT);
27
+ console.log(isPreview ? 'preview' : 'dev server', `is live at http://127.0.0.1:${PORT}`);
28
+ return new Promise(() => { });
29
+ }
30
+ async function startEsbuildWatch(c) {
31
+ const watchDir = join('build', 'watch');
32
+ await mkdir(watchDir, { recursive: true });
33
+ await copyAssets(watchDir);
34
+ const entryPointUrls = new Set();
35
+ const entryPoints = [];
36
+ await Promise.all(Object.entries(c.pages).map(async ([url, srcPath]) => {
37
+ const html = await HtmlEntrypoint.readFrom(url, join('pages', srcPath));
38
+ await html.injectPartials();
39
+ if (url !== '/') {
40
+ await mkdir(join(watchDir, url), { recursive: true });
41
+ }
42
+ html.collectScripts()
43
+ .filter(scriptImport => !entryPointUrls.has(scriptImport.in))
44
+ .forEach(scriptImport => {
45
+ entryPointUrls.add(scriptImport.in);
46
+ entryPoints.push({
47
+ in: scriptImport.in,
48
+ out: scriptImport.out,
49
+ });
50
+ });
51
+ html.rewriteHrefs();
52
+ await html.writeTo(watchDir);
53
+ return html;
54
+ }));
55
+ console.log(entryPoints);
56
+ const ctx = await esbuildDevContext(createGlobalDefinitions(), entryPoints, watchDir);
57
+ await ctx.watch();
58
+ await ctx.serve({
59
+ host: '127.0.0.1',
60
+ port: ESBUILD_PORT,
61
+ servedir: watchDir,
62
+ cors: {
63
+ origin: 'http://127.0.0.1:' + PORT,
64
+ },
65
+ });
66
+ return { port: ESBUILD_PORT };
67
+ }
package/lib_js/tag.js ADDED
@@ -0,0 +1,23 @@
1
+ import { exec } from 'node:child_process';
2
+ import { isProductionBuild } from "./flags.js";
3
+ export async function createBuildTag() {
4
+ const now = new Date();
5
+ const ms = now.getUTCMilliseconds() +
6
+ now.getUTCSeconds() * 1000 +
7
+ now.getUTCMinutes() * 1000 * 60 +
8
+ now.getUTCHours() * 1000 * 60 * 60;
9
+ const date = now.toISOString().substring(0, 10);
10
+ const time = String(ms).padStart(8, '0');
11
+ const when = `${date}-${time}`;
12
+ if (isProductionBuild()) {
13
+ const gitHash = await new Promise((res, rej) => exec('git rev-parse --short HEAD', (err, stdout) => {
14
+ if (err)
15
+ rej(err);
16
+ res(stdout.trim());
17
+ }));
18
+ return `${when}-${gitHash}`;
19
+ }
20
+ else {
21
+ return when;
22
+ }
23
+ }
@@ -0,0 +1,4 @@
1
+ export type DankConfig = {
2
+ pages: Record<`/${string}`, `./${string}.html`>;
3
+ };
4
+ export declare function defineConfig(c: Partial<DankConfig>): Promise<DankConfig>;
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@eighty4/dank",
3
+ "version": "0.0.1-0",
4
+ "type": "module",
5
+ "bin": "./lib_js/bin.js",
6
+ "exports": {
7
+ ".": {
8
+ "node": "./lib_js/dank.js",
9
+ "types": "./lib_types/dank.d.ts",
10
+ "import": "./lib/dank.ts"
11
+ }
12
+ },
13
+ "dependencies": {
14
+ "esbuild": "^0.25.10",
15
+ "parse5": "^8.0.0"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^24.5.2",
19
+ "prettier": "^3.6.2",
20
+ "typescript": "^5.9.2"
21
+ },
22
+ "files": [
23
+ "lib/*.ts",
24
+ "lib_js/*.js",
25
+ "lib_types/*.d.ts"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsc && tsc -p tsconfig.exports.json",
29
+ "fmt": "prettier --write .",
30
+ "fmtcheck": "prettier --check .",
31
+ "typecheck": "tsc --noEmit"
32
+ }
33
+ }