-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
186 lines (157 loc) · 6.16 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// deno-lint-ignore-file prefer-const
// import { serve } from 'jsr:@std/http'
import { parseArgs } from "jsr:@std/cli";
import { Application, Router } from "jsr:@oak/oak";
import type { RollupCache } from "rollup";
import { LocalPath } from './localpath.ts';
import { ImportMapGenerator } from "./importmap.ts";
import { RollupBundleSet, InlineRollupOptions, InlineRollup } from "./rollup.ts";
let args = parseArgs(Deno.args, {
boolean: ['help'],
string: ['host', 'port'],
default: {
'host': '127.0.0.1',
'port': false,
},
});
if (args.help) {
console.log(`django-deno rollup server. Usage: ${import.meta.filename} --host=hostname --port=port`)
Deno.exit(1);
}
const httpHost = args.host;
if (!args.port) {
console.log("Missing 'port' arg");
Deno.exit(1);
}
const httpPort = Number(args.port);
const apiStatus = {
"server": "Django deno server",
"version": "0.2.0",
"pid": Deno.pid,
};
type CacheEntries = Record<string, RollupCache>;
class Site {
importMapGenerator: ImportMapGenerator;
entries: CacheEntries;
constructor(importMapGenerator: ImportMapGenerator) {
this.importMapGenerator = importMapGenerator;
this.entries = {};
}
public hasCache(cachePath: string) {
return typeof this.entries[cachePath] !== 'undefined';
}
public getCache(cachePath: string) {
return this.entries[cachePath];
}
public setCache(cachePath: string, cache: RollupCache) {
this.entries[cachePath] = cache;
}
}
interface Sites {
[index: string]: Site;
};
let sites: Sites = {};
const router = new Router();
router
.get("/status/", (context, next) => {
context.response.body = apiStatus;
})
.post("/maps/", async (context, next) => {
const value = await context.request.body.json();
const siteId = value['site_id'];
sites[siteId] = new Site(
new ImportMapGenerator({
baseMap: value['base_map'],
importMap: value['import_map'],
})
);
context.response.body = apiStatus;
context.response.status = 200;
})
.post("/rollup/", async (context, next) => {
// HTTP POST
let responseFields;
const value = await context.request.body.json();
if (typeof sites[value.site_id] === 'undefined' ) {
responseFields = InlineRollup.getErrorResponse(
new Error(`sites for site_id=${value.site_id} is undefined`)
);
responseFields.toOakContext(context);
return;
}
const site = sites[value.site_id];
let basedir: string;
let filename: string;
for (let valArg of ['filename', 'basedir', 'options']) {
if (typeof value[valArg] === 'undefined') {
context.response.body = `No {valArg} arg specified`;
context.response.status = 500;
return;
}
}
basedir = value['basedir'];
filename = value['filename'];
let baseDirLocalPath = new LocalPath(basedir);
let fullPathParts = baseDirLocalPath.split();
fullPathParts.push(filename);
let entryPointLocalPath = LocalPath.fromPathParts(fullPathParts);
let cachePath: string = entryPointLocalPath.path;
console.log(`=== Entry point "${entryPointLocalPath.path}" ===`);
let inlineRollupOptions = new InlineRollupOptions(value['options']);
// https://github.com/lucacasonato/dext.ts/issues/65
if (inlineRollupOptions.withCache && site.hasCache(cachePath)) {
inlineRollupOptions.cache = site.getCache(cachePath);
} else {
inlineRollupOptions.cache = undefined;
}
let foundBundles = new RollupBundleSet();
if (!inlineRollupOptions.inlineFileMap) {
inlineRollupOptions.chunkFileNames = "[name].js";
inlineRollupOptions.manualChunks = (id: string, { getModuleInfo }): string | null | undefined => {
let fullLocalPath = LocalPath.getFullLocalPath(id);
// https://flaviocopes.com/typescript-object-destructuring/
// const { name, age }: { name: string; age: number } = body.value
let matchingBundle = inlineRollupOptions.getBundleChunk(fullLocalPath);
let moduleInfo = getModuleInfo(id);
if (moduleInfo && matchingBundle && matchingBundle.name) {
// Keep singleton matchingBundle.
matchingBundle = foundBundles.add(matchingBundle);
let isVirtualEntry: boolean = false;
if (matchingBundle.isWriteEntryPoint(entryPointLocalPath)) {
if (matchingBundle.isVirtualEntry(fullLocalPath)) {
isVirtualEntry = matchingBundle.setVirtualEntryPoint(moduleInfo);
}
if (isVirtualEntry) {
console.log(`Bundle "${matchingBundle.name}", virtual entry point "${fullLocalPath.path}"`);
matchingBundle.addSkipChunk(fullLocalPath);
} else {
console.log(`Bundle "${matchingBundle.name}", module "${fullLocalPath.path}"`);
}
} else {
matchingBundle.addSkipChunk(fullLocalPath);
}
return matchingBundle.name;
}
}
}
let inlineRollup = new InlineRollup(site.importMapGenerator, inlineRollupOptions);
let rollupOutput = await inlineRollup.generate(basedir, filename);
if (rollupOutput instanceof Error) {
responseFields = InlineRollup.getErrorResponse(rollupOutput);
} else {
responseFields = inlineRollup.getRollupResponse(baseDirLocalPath, entryPointLocalPath, rollupOutput, foundBundles);
}
/**
* Warning: never use rollup cache for different source settings, eg. inline and bundled chunks at the same time.
* Otherwise, it would cause cache incoherency and hard to track bugs.
*/
if (inlineRollupOptions.withCache && inlineRollupOptions.cache) {
site.setCache(cachePath, inlineRollupOptions.cache);
}
responseFields.toOakContext(context);
});
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ hostname: httpHost, port: httpPort });
Deno.stdout.write(new TextEncoder().encode(`Server listening on ${httpHost}:${httpPort}`));