vaderjs 1.4.1-hyiuy47 → 1.4.1-li7iuy47

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/binaries/main.js CHANGED
@@ -3,26 +3,33 @@ import { Glob } from "bun";
3
3
  import fs from "fs";
4
4
 
5
5
  import * as Bun from "bun";
6
+
7
+
8
+ let config = await import(process.cwd() + "/vader.config.js")
9
+ .then((m) => (m ? m.default : {}))
10
+ .catch((e) => {
11
+ return {};
12
+ });
13
+
14
+ async function checkIFUptodate() {
15
+ let lts = await fetch("https://registry.npmjs.org/vaderjs").then((res) =>
16
+ res.json()
17
+ );
18
+ let latest = lts["dist-tags"].latest;
19
+ let current = JSON.parse(
20
+ fs.readFileSync(process.cwd() + "/node_modules/vaderjs/package.json")
21
+ ).version;
22
+ return {
23
+ latest,
24
+ current,
25
+ };
26
+ }
6
27
 
7
- import WebSocket from "ws";
8
-
9
- let config = await import(process.cwd() + '/vader.config.js').then((m) => m ? m.default : {}).catch((e) => {
10
-
11
- console.error(e)
12
-
13
- return {}
14
-
15
- })
16
-
17
- import IPCServer from "vaderjs/binaries/IPC/index.js"
18
-
19
- import { exec } from "child_process";
20
-
21
- const IPC = IPCServer
22
-
28
+ import IPCServer from "vaderjs/binaries/IPC/index.js";
23
29
 
30
+ const IPC = IPCServer;
24
31
 
25
- globalThis.isVader = true
32
+ globalThis.isVader = true;
26
33
 
27
34
  /**
28
35
 
@@ -35,18 +42,16 @@ globalThis.isVader = true
35
42
  */
36
43
 
37
44
  globalThis.call = async (fn, args) => {
38
-
39
- return await fn(args) || void 0
40
-
41
- }
45
+ return (await fn(args)) || void 0;
46
+ };
42
47
 
43
48
  /**@description - Used to store hmr websocket clients */
44
49
 
45
- globalThis.clients = []
50
+ globalThis.clients = [];
46
51
 
47
52
  /**@description - Used to keep track of routes */
48
53
 
49
- globalThis.routes = []
54
+ globalThis.routes = [];
50
55
 
51
56
  /**
52
57
 
@@ -54,15 +59,15 @@ globalThis.routes = []
54
59
 
55
60
  */
56
61
 
57
- globalThis.mode = ''
62
+ globalThis.mode = "";
58
63
 
59
64
  /**@usedby @transForm */
60
65
 
61
- globalThis.isBuilding = false
66
+ globalThis.isBuilding = false;
62
67
 
63
- globalThis.hasGenerated = []
68
+ globalThis.hasGenerated = [];
64
69
 
65
- let currentState = ''
70
+ let currentState = "";
66
71
 
67
72
  /**
68
73
 
@@ -70,11 +75,7 @@ let currentState = ''
70
75
 
71
76
  */
72
77
 
73
- let bundleSize = 0
74
-
75
-
76
-
77
-
78
+ let bundleSize = 0;
78
79
 
79
80
  /**
80
81
 
@@ -82,32 +83,48 @@ let bundleSize = 0
82
83
 
83
84
  */
84
85
 
85
- const glob = new Glob("/pages/**/**/*.{,tsx,js,jsx}", { absolute: true });
86
-
87
- const vaderGlob = new Glob("/node_modules/vaderjs/runtime/**/**/*.{,tsx,js}", { absolute: true });
88
-
89
- const srcGlob = new Glob("/src/**/**/*.{jsx,ts,tsx,js}", { absolute: true });
86
+ const glob = new Glob("/pages/**/**/*.{,tsx,js,jsx,md}", {
87
+ absolute: true,
88
+ });
90
89
 
91
- const publicGlob = new Glob("/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}", { absolute: true });
90
+ const vaderGlob = new Glob("/node_modules/vaderjs/runtime/**/**/*.{,tsx,js}", {
91
+ absolute: true,
92
+ });
92
93
 
93
- const distPages = new Glob("/dist/pages/**/**/*.{tsx,js,jsx}", { absolute: true })
94
+ const srcGlob = new Glob("/src/**/**/*.{jsx,ts,tsx,js}", {
95
+ absolute: true,
96
+ });
94
97
 
95
- const distSrc = new Glob("/dist/src/**/**/*.{tsx,js,jsx}", { absolute: true })
98
+ const publicGlob = new Glob(
99
+ "/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}",
100
+ {
101
+ absolute: true,
102
+ }
103
+ );
96
104
 
97
- const distPublic = new Glob("/dist/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}", { absolute: true });
105
+ const distPages = new Glob("/dist/pages/**/**/*.{tsx,js,jsx}", {
106
+ absolute: true,
107
+ });
98
108
 
109
+ const distSrc = new Glob("/dist/src/**/**/*.{tsx,js,jsx}", {
110
+ absolute: true,
111
+ });
99
112
 
113
+ const distPublic = new Glob(
114
+ "/dist/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}",
115
+ {
116
+ absolute: true,
117
+ }
118
+ );
100
119
 
101
120
  const router = new Bun.FileSystemRouter({
121
+ style: "nextjs",
102
122
 
103
- style: "nextjs",
104
-
105
- dir: process.cwd() + '/pages',
123
+ dir: process.cwd() + "/pages",
106
124
 
107
- origin: process.env.ORIGIN || "http://localhost:3000",
108
-
109
- assetPrefix: "_next/static/"
125
+ origin: process.env.ORIGIN || "http://localhost:3000",
110
126
 
127
+ assetPrefix: "_next/static/",
111
128
  });
112
129
 
113
130
  /**
@@ -121,166 +138,184 @@ const router = new Bun.FileSystemRouter({
121
138
  * @returns
122
139
 
123
140
  */
141
+ const cssToObj = (css) => {
142
+ let styles = {};
143
+ let currentSelector = "";
144
+
145
+ css.split("\n").forEach((line) => {
146
+ line = line.trim();
147
+
148
+ if (line.endsWith("{")) {
149
+ // Start of a block, extract the selector
150
+ currentSelector = line.slice(0, -1).trim();
151
+ styles[currentSelector] = {};
152
+ } else if (line.endsWith("}")) {
153
+ // End of a block
154
+ currentSelector = "";
155
+ } else if (line.includes(":") && currentSelector) {
156
+ // Inside a block and contains key-value pair
157
+ let [key, value] = line.split(":").map((part) => part.trim());
158
+ styles[currentSelector][key] = value;
159
+ }
160
+ });
124
161
 
125
- function handleReplaceMents(data) {
126
-
127
- data.split('\n').forEach((line, index) => {
128
-
129
- switch (true) {
130
-
131
-
132
-
133
- case line.includes('useReducer') && !line.includes('import'):
134
-
135
- line = line.replaceAll(/\s+/g, " ");
136
-
137
-
138
-
139
- let varTypereducer = line.split("=")[0].trim().split("[")[0].trim();
140
-
141
- let keyreducer = line.split("=")[0].trim().split("[")[1].trim().split(",")[0].trim();
142
-
143
- let setKeyreducer = line.split("=")[0].trim().split(",")[1].trim().replace("]", "");
144
-
145
- let reducer = line.split("=")[1].split("useReducer(")[1];
146
-
147
-
148
-
149
- let newStatereducer = `${varTypereducer} [${keyreducer}, ${setKeyreducer}] = this.useReducer('${keyreducer}', ${line.includes('=>') ? reducer + '=>{' : reducer}`;
150
-
151
-
152
-
153
- data = data.replace(line, newStatereducer);
154
-
155
- break
156
-
157
-
158
-
159
- case line.includes('useState') && !line.includes('import'):
160
-
161
- let varType = line.split("[")[0]
162
-
163
- if (!line.split("=")[0].split(",")[1]) {
164
-
165
- throw new Error('You forgot to value selector (useState) ' + ' at ' + `${file}:${string.split(line)[0].split('\n').length}`)
166
-
167
- }
168
-
169
- let key = line.split("=")[0].split(",")[0].trim().split('[')[1];
170
-
171
-
172
-
173
- if (!line.split("=")[0].split(",")[1]) {
174
-
175
- throw new Error('You forgot to add a setter (useState) ' + ' at ' + `${file}:${string.split(line)[0].split('\n').length}`)
176
-
177
- }
178
-
179
- let setKey = line.split("=")[0].split(",")[1].trim().replace("]", "");
180
-
181
- key = key.replace("[", "").replace(",", "");
182
-
183
- let valuestate = line.split("=")[1].split("useState(")[1];
184
-
185
-
186
-
187
- let regex = /useState\((.*)\)/gs;
188
-
189
- valuestate = valuestate.match(regex) ? valuestate.match(regex)[0].split("useState(")[1].split(")")[0].trim() : valuestate
190
-
191
- let newState = `${varType} [${key}, ${setKey}] = this.useState('${key}', ${valuestate}`;
192
-
193
- data = data.replace(line, newState);
194
-
195
- break;
196
-
197
-
198
-
199
- case line.includes("useRef") && !line.includes("import"):
200
-
201
- line = line.trim();
202
-
203
- let typeref = line.split(" ")[0]
204
-
205
-
162
+ return styles;
163
+ };
206
164
 
207
- let keyref = line.split(typeref)[1].split("=")[0].trim().replace("[", "").replace(",", "");
165
+ function handleReplaceMents(data) {
166
+ data.split("\n").forEach(async (line, index) => {
167
+ switch (true) {
168
+ case line.includes("import") && line.includes("module.css"):
169
+ let path = line.split("from")[1].trim().split(";")[0].trim();
170
+ let name = line.split("import")[1].split("from")[0].trim();
171
+ path = path.replace(";", "");
172
+ path = path.replace(/'/g, "").trim().replace(/"/g, "").trim();
173
+ path = path.replaceAll(".jsx", ".js");
174
+ path = path.replaceAll("../", "");
175
+ let css = fs.readFileSync(process.cwd() + "/" + path, "utf8");
176
+ css = css.replaceAll(".", "");
177
+ let styles = cssToObj(css);
178
+ let style = JSON.stringify(styles);
179
+ let newLine = `let ${name} = ${style}`;
180
+ data = data.replace(line, newLine);
208
181
 
182
+ break;
209
183
 
184
+ case line.includes("useReducer") && !line.includes("import"):
185
+ line = line.replaceAll(/\s+/g, " ");
210
186
 
187
+ let varTypereducer = line.split("=")[0].trim().split("[")[0].trim();
211
188
 
189
+ let keyreducer = line
190
+ .split("=")[0]
191
+ .trim()
192
+ .split("[")[1]
193
+ .trim()
194
+ .split(",")[0]
195
+ .trim();
212
196
 
213
- let valueref = line.split("=")[1].split("useRef(")[1];
197
+ let setKeyreducer = line
198
+ .split("=")[0]
199
+ .trim()
200
+ .split(",")[1]
201
+ .trim()
202
+ .replace("]", "");
214
203
 
204
+ let reducer = line.split("=")[1].split("useReducer(")[1];
215
205
 
206
+ let newStatereducer = `${varTypereducer} [${keyreducer}, ${setKeyreducer}] = this.useReducer('${keyreducer}', ${
207
+ line.includes("=>") ? reducer + "=>{" : reducer
208
+ }`;
216
209
 
217
- let newStateref = `${typeref} ${keyref} = this.useRef('${keyref}', ${valueref}`;
210
+ data = data.replace(line, newStatereducer);
218
211
 
219
- data = data.replace(line, newStateref);
212
+ break;
220
213
 
221
- case line.includes('.jsx') && line.includes('import') || line.includes('.tsx') && line.includes('import'):
214
+ case line.includes("useState") && !line.includes("import"):
215
+ let varType = line.split("[")[0];
222
216
 
223
- let old = line
217
+ if (!line.split("=")[0].split(",")[1]) {
218
+ throw new Error(
219
+ "You forgot to value selector (useState) " +
220
+ " at " +
221
+ `${file}:${string.split(line)[0].split("\n").length}`
222
+ );
223
+ }
224
224
 
225
- line = line.replace('.jsx', '.js')
225
+ let key = line.split("=")[0].split(",")[0].trim().split("[")[1];
226
226
 
227
- line = line.replace('.tsx', '.js')
227
+ if (!line.split("=")[0].split(",")[1]) {
228
+ throw new Error(
229
+ "You forgot to add a setter (useState) " +
230
+ " at " +
231
+ `${file}:${string.split(line)[0].split("\n").length}`
232
+ );
233
+ }
228
234
 
229
- data = data.replace(old, line)
235
+ let setKey = line.split("=")[0].split(",")[1].trim().replace("]", "");
230
236
 
237
+ key = key.replace("[", "").replace(",", "");
231
238
 
239
+ let valuestate = line.split("=")[1].split("useState(")[1];
232
240
 
233
- break;
241
+ let regex = /useState\((.*)\)/gs;
234
242
 
235
- }
243
+ valuestate = valuestate.match(regex)
244
+ ? valuestate
245
+ .match(regex)[0]
246
+ .split("useState(")[1]
247
+ .split(")")[0]
248
+ .trim()
249
+ : valuestate;
236
250
 
237
- })
251
+ let newState = `${varType} [${key}, ${setKey}] = this.useState('${key}', ${valuestate}`;
238
252
 
253
+ data = data.replace(line, newState);
239
254
 
255
+ break;
240
256
 
241
- data = data.replaceAll('jsxDEV', 'Vader.createElement')
257
+ case line.includes("useRef") && !line.includes("import"):
258
+ line = line.trim();
242
259
 
243
- data = data.replaceAll('jsx', 'Vader.createElement')
260
+ let typeref = line.split(" ")[0];
244
261
 
245
- data = data.replaceAll('vaderjs/client', '/vader.js')
262
+ let keyref = line
263
+ .split(typeref)[1]
264
+ .split("=")[0]
265
+ .trim()
266
+ .replace("[", "")
267
+ .replace(",", "");
246
268
 
247
- data = data.replaceAll('.tsx', '.js')
269
+ let valueref = line.split("=")[1].split("useRef(")[1];
248
270
 
249
- let reactImportMatch = data.match(/import React/g);
271
+ let newStateref = `${typeref} ${keyref} = this.useRef('${keyref}', ${valueref}`;
250
272
 
251
- if (reactImportMatch) {
273
+ data = data.replace(line, newStateref);
252
274
 
253
- let fullmatch = data.match(/import React from "react"/g);
275
+ case (line.includes(".jsx") && line.includes("import")) ||
276
+ (line.includes(".tsx") && line.includes("import")):
277
+ let old = line;
254
278
 
255
- if (fullmatch) {
279
+ line = line.replace(".jsx", ".js");
256
280
 
257
- data = data.replaceAll('import React from "react"', '');
281
+ line = line.replace(".tsx", ".js");
258
282
 
259
- }
283
+ data = data.replace(old, line);
260
284
 
285
+ break;
261
286
  }
287
+ });
262
288
 
263
- data = data.replaceAll('.ts', '.js')
289
+ data = data.replaceAll("jsxDEV", "Vader.createElement");
264
290
 
291
+ data = data.replaceAll("jsx", "Vader.createElement");
265
292
 
293
+ data = data.replaceAll("vaderjs/client", "/vader.js");
266
294
 
267
- // check if Vader is imported
295
+ data = data.replaceAll(".tsx", ".js");
268
296
 
269
- let vaderImport = data.match(/import Vader/g);
297
+ let reactImportMatch = data.match(/import React/g);
270
298
 
271
- if (!vaderImport) {
272
-
273
- data = `import Vader from "/vader.js";\n` + data;
299
+ if (reactImportMatch) {
300
+ let fullmatch = data.match(/import React from "react"/g);
274
301
 
302
+ if (fullmatch) {
303
+ data = data.replaceAll('import React from "react"', "");
275
304
  }
305
+ }
276
306
 
277
- return data;
278
-
279
- }
307
+ data = data.replaceAll(".ts", ".js");
280
308
 
309
+ // check if Vader is imported
281
310
 
311
+ let vaderImport = data.match(/import Vader/g);
282
312
 
313
+ if (!vaderImport) {
314
+ data = `import Vader from "/vader.js";\n` + data;
315
+ }
283
316
 
317
+ return data;
318
+ }
284
319
 
285
320
  /**
286
321
 
@@ -295,58 +330,40 @@ function handleReplaceMents(data) {
295
330
  */
296
331
 
297
332
  const ContentType = (url) => {
333
+ switch (url.split(".").pop()) {
334
+ case "css":
335
+ return "text/css";
298
336
 
299
- switch (url.split('.').pop()) {
300
-
301
- case 'css':
302
-
303
- return 'text/css';
304
-
305
- case 'js':
306
-
307
- return 'text/javascript';
308
-
309
- case 'json':
310
-
311
- return 'application/json';
337
+ case "js":
338
+ return "text/javascript";
312
339
 
313
- case 'html':
340
+ case "json":
341
+ return "application/json";
314
342
 
315
- return 'text/html';
343
+ case "html":
344
+ return "text/html";
316
345
 
317
- case 'jpg':
346
+ case "jpg":
347
+ return "image/jpg";
318
348
 
319
- return 'image/jpg';
320
-
321
- case 'png':
322
-
323
- return 'image/png';
324
-
325
- case 'gif':
326
-
327
- return 'image/gif';
328
-
329
- case 'svg':
330
-
331
- return 'image/svg+xml';
332
-
333
- case 'ico':
334
-
335
- return 'image/x-icon';
336
-
337
- default:
338
-
339
- return 'text/html';
340
-
341
-
342
-
343
- }
344
-
345
- }
349
+ case "png":
350
+ return "image/png";
346
351
 
352
+ case "gif":
353
+ return "image/gif";
347
354
 
355
+ case "svg":
356
+ return "image/svg+xml";
348
357
 
358
+ case "webp":
359
+ return "image/webp";
360
+ case "ico":
361
+ return "image/x-icon";
349
362
 
363
+ default:
364
+ return "text/html";
365
+ }
366
+ };
350
367
 
351
368
  /**
352
369
 
@@ -359,76 +376,73 @@ const ContentType = (url) => {
359
376
  */
360
377
 
361
378
  function Server(port) {
379
+ Bun.serve({
380
+ port: port,
362
381
 
363
- Bun.serve({
364
-
365
- port: port,
366
-
367
- async fetch(req, res) {
368
-
369
- const url = new URL(req.url);
370
-
371
- const success = res.upgrade(req);
372
-
373
- if (success) {
374
-
375
- return new Response('Connected', {
376
-
377
- headers: {
378
-
379
- "Content-Type": "text/html"
380
-
381
- }
382
-
383
- })
384
-
385
- }
386
-
387
- if (req.url.includes('.')) {
382
+ async fetch(req, res) {
383
+ const url = new URL(req.url);
388
384
 
389
- if (!fs.existsSync(process.cwd() + '/dist' + url.pathname)) {
385
+ const success = res.upgrade(req);
390
386
 
391
- return new Response('Not Found', {
387
+ if (success) {
388
+ return new Response("Connected", {
389
+ headers: {
390
+ "Content-Type": "text/html",
391
+ },
392
+ });
393
+ }
392
394
 
393
- status: 404,
395
+ if (req.url.includes(".")) {
396
+ if (!fs.existsSync(process.cwd() + "/dist" + url.pathname)) {
397
+ return new Response("Not Found", {
398
+ status: 404,
394
399
 
395
- headers: {
396
-
397
- "Content-Type": "text/html"
398
-
399
- }
400
-
401
- })
402
-
403
- }
404
-
405
- console.log('Serving: ' + url.pathname)
406
-
407
- return new Response(fs.readFileSync(process.cwd() + '/dist/' + url.pathname, 'utf-8'), {
408
-
409
- headers: {
410
-
411
- "Content-Type": ContentType(req.url)
412
-
413
- }
414
-
415
- })
400
+ headers: {
401
+ "Content-Type": "text/html",
402
+ },
403
+ });
404
+ }
416
405
 
406
+ console.log(`HTTP GET: ${url.pathname} -> ${ContentType(req.url)}`);
407
+ return new Response(
408
+ fs.readFileSync(process.cwd() + "/dist" + url.pathname),
409
+ {
410
+ headers: {
411
+ "Content-Type": ContentType(req.url),
412
+ },
413
+ }
414
+ );
415
+ }
416
+
417
+ let matchedRoute =
418
+ router.match(url.pathname) ||
419
+ fs.existsSync(process.cwd() + "/dist" + url.pathname)
420
+ ? {
421
+ filePath: process.cwd() + "/dist" + url.pathname,
422
+ isAbsolute: true,
417
423
  }
424
+ : null;
418
425
 
419
- let matchedRoute = router.match(url.pathname);
420
-
421
- if (matchedRoute) {
426
+ if (matchedRoute) {
427
+ let { filePath, kind, name, params, pathname, query, isAbsolute } =
428
+ matchedRoute;
422
429
 
423
- let { filePath, kind, name, params, pathname, query, } = matchedRoute
430
+ let folder = filePath.split("pages/").pop().split("index.js").shift();
431
+ folder = folder
432
+ .split("/")
433
+ .filter((f) => f !== "dist")
434
+ .join("/");
435
+ let jsFile = filePath.split("pages/").pop().split(".").shift() + ".js";
424
436
 
425
- let folder = url.pathname.split('/')[1]
437
+ let pageContent = isAbsolute
438
+ ? fs.readFileSync(filePath + "/index.html")
439
+ : fs.readFileSync(
440
+ process.cwd() + "/dist/" + folder + "/index.html",
441
+ "utf8"
442
+ );
426
443
 
427
- let jsFile = filePath.split('pages/').pop().split('.').shift() + '.js'
428
-
429
- let pageContent = fs.readFileSync(process.cwd() + '/dist/' + folder + '/index.html', 'utf8')
430
-
431
- globalThis.mode === 'dev' ? pageContent += `
444
+ globalThis.mode === "dev"
445
+ ? (pageContent += `
432
446
 
433
447
  <script type="module">
434
448
 
@@ -448,50 +462,33 @@ function Server(port) {
448
462
 
449
463
  </script>
450
464
 
451
- ` : void 0
452
-
453
- return new Response(pageContent, {
454
-
455
- headers: {
456
-
457
- "Content-Type": "text/html",
458
-
459
- "X-Powered-By": "Vader.js v1.3.3"
460
-
461
- }
462
-
463
- })
464
-
465
- }
466
-
467
-
468
-
469
- return new Response('Not Found', {
470
-
471
- status: 404,
472
-
473
- headers: {
465
+ `)
466
+ : void 0;
474
467
 
475
- "Content-Type": "text/html"
468
+ return new Response(pageContent, {
469
+ headers: {
470
+ "Content-Type": "text/html",
476
471
 
477
- }
472
+ "X-Powered-By": "Vader.js v1.3.3",
473
+ },
474
+ });
475
+ }
478
476
 
479
- })
477
+ return new Response("Not Found", {
478
+ status: 404,
480
479
 
480
+ headers: {
481
+ "Content-Type": "text/html",
481
482
  },
482
-
483
- websocket: {
484
-
485
- open(ws) {
486
-
487
- clients.push(ws)
488
-
489
- },
490
-
491
- }
492
-
493
- })
494
-
483
+ });
484
+ },
485
+
486
+ websocket: {
487
+ open(ws) {
488
+ clients.push(ws);
489
+ },
490
+ },
491
+ });
495
492
  }
496
493
 
497
494
  /**
@@ -511,26 +508,16 @@ function Server(port) {
511
508
  */
512
509
 
513
510
  const write = (file, data) => {
514
-
515
- try {
516
-
517
- if (!fs.existsSync('./dist')) {
518
-
519
- fs.mkdirSync('./dist')
520
-
521
- }
522
-
523
- Bun.write(file, data);
524
-
525
- } catch (error) {
526
-
527
- console.error(error)
528
-
511
+ try {
512
+ if (!fs.existsSync("./dist")) {
513
+ fs.mkdirSync("./dist");
529
514
  }
530
515
 
531
-
532
-
533
- }
516
+ Bun.write(file, data);
517
+ } catch (error) {
518
+ console.error(error);
519
+ }
520
+ };
534
521
 
535
522
  /**
536
523
 
@@ -543,10 +530,8 @@ const write = (file, data) => {
543
530
  */
544
531
 
545
532
  const read = async (file) => {
546
-
547
- return await Bun.file(file).text();
548
-
549
- }
533
+ return await Bun.file(file).text();
534
+ };
550
535
 
551
536
  /**
552
537
 
@@ -556,9 +541,7 @@ const read = async (file) => {
556
541
 
557
542
  */
558
543
 
559
-
560
-
561
- globalThis.integrationStates = []
544
+ globalThis.integrationStates = [];
562
545
 
563
546
  /**
564
547
 
@@ -567,10 +550,8 @@ globalThis.integrationStates = []
567
550
  */
568
551
 
569
552
  globalThis.context = {
570
-
571
- vader: true
572
-
573
- }
553
+ vader: true,
554
+ };
574
555
 
575
556
  /**
576
557
 
@@ -583,26 +564,18 @@ globalThis.context = {
583
564
  */
584
565
 
585
566
  function handleIntegrations() {
567
+ if (config?.integrations) {
568
+ config.integrations.forEach((integration) => {
569
+ let int = integration;
586
570
 
587
- if (config?.integrations) {
588
-
589
- config.integrations.forEach((integration) => {
590
-
591
- let int = integration
592
-
593
- globalThis.integrationStates.push(int)
594
-
595
- })
596
-
597
- }
598
-
599
-
600
-
601
- return void 0;
571
+ globalThis.integrationStates.push(int);
572
+ });
573
+ }
602
574
 
575
+ return void 0;
603
576
  }
604
577
 
605
- handleIntegrations()
578
+ handleIntegrations();
606
579
 
607
580
  /**
608
581
 
@@ -615,841 +588,739 @@ handleIntegrations()
615
588
  */
616
589
 
617
590
  async function generateProviderRoutes() {
591
+ if (!config?.host?.provider) {
592
+ console.warn(
593
+ "No provider found in vader.config.js ignoring route generation..."
594
+ );
595
+
596
+ return void 0;
597
+ }
618
598
 
619
- if (!config?.host?.provider) {
599
+ let providerType = [
600
+ {
601
+ provider: "vercel",
620
602
 
621
- console.warn('No provider found in vader.config.js ignoring route generation...')
603
+ file: "vercel.json",
622
604
 
623
- return void 0;
605
+ out: process.cwd() + "/vercel.json",
624
606
 
625
- }
607
+ obj: {
608
+ rewrites: [],
609
+ },
610
+ },
611
+ {
612
+ provider: "cloudflare",
626
613
 
627
- let providerType = [{
614
+ file: "_redirects",
628
615
 
629
- provider: 'vercel',
616
+ out: "dist/_redirects",
617
+ },
618
+ ];
630
619
 
631
- file: 'vercel.json',
620
+ let provider = providerType.find((p) => p.provider === config.host.provider);
632
621
 
633
- out: process.cwd() + '/vercel.json',
622
+ if (provider) {
623
+ let prev = null;
634
624
 
635
- obj: {
625
+ switch (provider.provider) {
626
+ case "vercel":
627
+ if (!fs.existsSync(provider.out)) {
628
+ fs.writeFileSync(
629
+ provider.out,
630
+ JSON.stringify({
631
+ rewrites: [],
632
+ })
633
+ );
634
+ }
636
635
 
637
- rewrites: []
636
+ prev = await read(provider.out);
638
637
 
638
+ if (!prev) {
639
+ prev = [];
640
+ } else {
641
+ prev = JSON.parse(prev).rewrites;
639
642
  }
640
643
 
641
- }, {
644
+ routes.forEach((r) => {
645
+ let previous = prev.find((p) => p.source.includes(r.path));
642
646
 
643
- provider: 'cloudflare',
647
+ if (previous) {
648
+ return void 0;
649
+ }
644
650
 
645
- file: '_redirects',
651
+ prev.push({
652
+ source: "/" + r.path,
646
653
 
647
- out: 'dist/_redirects'
654
+ destination: "/" + r.path + "/index.html",
655
+ });
648
656
 
649
- }]
657
+ if (r.params.length > 0) {
658
+ r.params.forEach((param) => {
659
+ if (!param.paramData) {
660
+ return void 0;
661
+ }
650
662
 
663
+ let parampath = Object.keys(param.paramData)
664
+ .map((p) => `:${p}`)
665
+ .join("/");
651
666
 
667
+ prev.push({
668
+ source: "/" + r.path + "/" + parampath,
652
669
 
653
- let provider = providerType.find((p) => p.provider === config.host.provider)
670
+ destination: "/" + r.path + "/index.html",
671
+ });
672
+ });
673
+ }
654
674
 
655
- if (provider) {
675
+ fs.writeFileSync(
676
+ provider.out,
677
+ JSON.stringify(
678
+ {
679
+ rewrites: prev,
680
+ },
681
+ null,
682
+ 2
683
+ )
684
+ );
685
+ });
656
686
 
657
- let prev = null
687
+ provider.obj.rewrites = prev;
658
688
 
689
+ write(provider.out, JSON.stringify(provider.obj, null, 2));
659
690
 
691
+ break;
660
692
 
661
- switch (provider.provider) {
693
+ case "cloudflare":
694
+ console.warn(
695
+ "Cloudflare is not supported yet refer to their documentation for more information:https://developers.cloudflare.com/pages/configuration/redirects/"
696
+ );
662
697
 
663
- case 'vercel':
698
+ break;
699
+ }
700
+ }
664
701
 
665
- if (!fs.existsSync(provider.out)) {
702
+ return void 0;
703
+ }
666
704
 
667
- fs.writeFileSync(provider.out, JSON.stringify({ rewrites: [] }))
705
+ /**
668
706
 
669
- }
707
+ * @function transform
670
708
 
671
- prev = await read(provider.out);
709
+ * @description - Transforms the jsx files to js files based on file paths
672
710
 
673
- if (!prev) {
711
+ */
674
712
 
675
- prev = []
713
+ async function transForm() {
714
+ return new Promise(async (resolve, reject) => {
715
+ globalThis.isBuilding = true;
716
+
717
+ router.reload();
718
+
719
+ for await (var file of glob.scan(".")) {
720
+ file = file.replace(/\\/g, "/");
721
+
722
+ let isBasePath = file.split("pages/")?.[1]?.split("/").length === 1;
723
+
724
+ let folder =
725
+ file.split("pages/")?.[1]?.split("/").slice(0, -1).join("/") || null;
726
+
727
+ if (isBasePath) {
728
+ folder = "/";
729
+ }
730
+
731
+ if (file.endsWith(".md")) {
732
+ let data = await read(file);
733
+ if (
734
+ integrationStates.find((int) => int?._df && int?._df === "i18mdf")
735
+ ) {
736
+ console.log(
737
+ `Using markdown parser ${
738
+ integrationStates.find((int) => int?._df && int?._df === "i18mdf")
739
+ .name
740
+ } v${
741
+ integrationStates.find((int) => int?._df && int?._df === "i18mdf")
742
+ .version
743
+ }`
744
+ );
745
+ let parser = integrationStates.find(
746
+ (int) => int?._df && int?._df === "i18mdf"
747
+ );
748
+
749
+ parser.parse(data);
750
+ parser._class.stylesheets.forEach((sheet) => {
751
+ parser._class.output =
752
+ `<link rel="stylesheet" href="${sheet}">` + parser._class.output;
753
+ });
754
+ let output = `./dist/${
755
+ isBasePath ? "index.html" : folder + "/index.html"
756
+ }`;
757
+ write(output, parser._class.output);
758
+ }
759
+ continue;
760
+ }
676
761
 
677
- } else {
762
+ let route = isBasePath ? router.match("/") : router.match("/" + folder);
678
763
 
679
- prev = JSON.parse(prev).rewrites
764
+ if (route) {
765
+ let { filePath, kind, name, params, pathname, query } = route;
680
766
 
681
- }
767
+ let data = await read(filePath);
682
768
 
683
- routes.forEach((r) => {
769
+ try {
770
+ data = new Bun.Transpiler({
771
+ loader: "tsx",
772
+ target: "browser",
773
+ }).transformSync(data);
774
+ } catch (e) {
775
+ console.error(e);
776
+ }
684
777
 
685
- let previous = prev.find((p) => p.source.includes(r.path))
778
+ let out = `./dist/${isBasePath ? "index.js" : folder + "/index.js"}`;
686
779
 
687
- if (previous) {
780
+ isBasePath ? (folder = "/") : null;
688
781
 
689
- return void 0;
782
+ data = handleReplaceMents(data);
690
783
 
691
- }
784
+ let isAparam = null;
692
785
 
786
+ if (folder === "") {
787
+ return;
788
+ }
693
789
 
790
+ switch (true) {
791
+ case kind === "dynamic":
792
+ isAparam = true;
694
793
 
695
- prev.push({
794
+ break;
696
795
 
697
- source: '/' + r.path,
796
+ case kind === "catch-all":
797
+ isAparam = true;
698
798
 
699
- destination: '/' + r.path + '/index.html'
799
+ break;
700
800
 
701
- })
801
+ case kind === "optional-catch-all":
802
+ isAparam = true;
702
803
 
804
+ break;
805
+ }
703
806
 
807
+ routes.push({
808
+ path: folder,
809
+ file: out,
810
+ isParam: isAparam,
811
+ params: params,
812
+ query,
813
+ pathname,
814
+ });
704
815
 
705
- if (r.params.length > 0) {
816
+ write(out, data);
706
817
 
707
- r.params.forEach((param) => {
818
+ bundleSize += data.length;
819
+ }
820
+ }
708
821
 
709
- if (!param.paramData) {
822
+ for await (var file of srcGlob.scan(".")) {
823
+ if (!fs.existsSync(process.cwd() + "/dist/src/")) {
824
+ fs.mkdirSync(process.cwd() + "/dist/src/");
825
+ }
710
826
 
711
- return void 0;
827
+ file = file.replace(/\\/g, "/");
712
828
 
713
- }
829
+ switch (file.split(".").pop()) {
830
+ case "ts":
831
+ let transpiler = new Bun.Transpiler({
832
+ loader: "ts",
833
+ target: "browser",
834
+ });
714
835
 
715
- let parampath = Object.keys(param.paramData).map((p) => `:${p}`).join('/')
836
+ let data = await read(file);
716
837
 
717
- prev.push({
838
+ try {
839
+ data = transpiler.transformSync(data);
840
+ } catch (error) {
841
+ console.error(error);
842
+ }
718
843
 
719
- source: '/' + r.path + '/' + parampath,
844
+ file = file.replace(".ts", ".js");
720
845
 
721
- destination: '/' + r.path + '/index.html'
846
+ let path = process.cwd() + "/dist/src/" + file.split("src/").pop();
722
847
 
723
- })
848
+ write(path, data);
724
849
 
725
- })
850
+ bundleSize += data.length;
726
851
 
727
- }
852
+ break;
728
853
 
854
+ case "tsx":
855
+ let transpilerx = new Bun.Transpiler({
856
+ loader: "tsx",
857
+ target: "browser",
858
+ });
729
859
 
860
+ let datax = await read(file);
730
861
 
731
- fs.writeFileSync(provider.out, JSON.stringify({ rewrites: prev }, null, 2))
862
+ try {
863
+ datax = transpilerx.transformSync(datax);
864
+ } catch (error) {
865
+ console.error(error);
866
+ }
732
867
 
868
+ datax = handleReplaceMents(datax);
733
869
 
870
+ file = file.replace(".tsx", ".js");
734
871
 
872
+ let pathx = process.cwd() + "/dist/src/" + file.split("src/").pop();
735
873
 
874
+ write(pathx, datax);
736
875
 
737
- })
876
+ break;
738
877
 
739
- provider.obj.rewrites = prev
878
+ case "jsx":
879
+ let transpilerjx = new Bun.Transpiler({
880
+ loader: "jsx",
881
+ target: "browser",
882
+ });
740
883
 
741
- write(provider.out, JSON.stringify(provider.obj, null, 2))
884
+ let datajx = await read(file);
742
885
 
743
- break;
886
+ let source = transpilerjx.scan(datajx);
744
887
 
745
- case 'cloudflare':
888
+ try {
889
+ datajx = transpilerjx.transformSync(datajx);
890
+ } catch (error) {
891
+ console.error(error);
892
+ }
746
893
 
747
- console.warn('Cloudflare is not supported yet refer to their documentation for more information:https://developers.cloudflare.com/pages/configuration/redirects/')
894
+ datajx = handleReplaceMents(datajx);
748
895
 
749
- break;
896
+ file = file.replace(".jsx", ".js");
750
897
 
751
- }
898
+ let pathjx = process.cwd() + "/dist/src/" + file.split("src/").pop();
752
899
 
900
+ write(pathjx, datajx);
753
901
 
902
+ bundleSize += datajx.length;
754
903
 
904
+ break;
905
+ default:
906
+ break;
907
+ }
908
+ }
909
+
910
+ for await (var file of publicGlob.scan(".")) {
911
+ // works
912
+
913
+ let data = null;
914
+ let isBuff = false;
915
+ file = file.replace(/\\/g, "/");
916
+ if (
917
+ file.endsWith(".png") ||
918
+ file.endsWith(".jpg") ||
919
+ file.endsWith(".jpeg") ||
920
+ file.endsWith(".gif") ||
921
+ file.endsWith(".svg") ||
922
+ file.endsWith(".webp") ||
923
+ file.endsWith(".ico") ||
924
+ file.endsWith(".mp4") ||
925
+ file.endsWith(".webm")
926
+ ) {
927
+ data = Buffer.from(fs.readFileSync(file)).toString("base64");
928
+ isBuff = true;
929
+ }
930
+ data = data || (await read(file));
931
+
932
+ let path = process.cwd() + "/dist/public/" + file.split("public/").pop();
933
+ fs.writeFileSync(path, data, isBuff ? "base64" : "utf8");
934
+
935
+ bundleSize += data.length;
936
+ }
755
937
 
938
+ for await (var file of vaderGlob.scan(".")) {
939
+ file = file.replace(/\\/g, "/");
940
+ if (
941
+ fs.existsSync(
942
+ process.cwd() +
943
+ "/dist/" +
944
+ file.split("node_modules/vaderjs/runtime/").pop()
945
+ )
946
+ ) {
947
+ return;
948
+ }
949
+ let data = await read(file);
950
+
951
+ file = file.replace(/\\/g, "/");
952
+
953
+ write(
954
+ process.cwd() +
955
+ "/dist/" +
956
+ file.split("node_modules/vaderjs/runtime/").pop(),
957
+ data
958
+ );
959
+
960
+ bundleSize += fs.statSync(
961
+ process.cwd() +
962
+ "/dist/" +
963
+ file.split("node_modules/vaderjs/runtime/").pop()
964
+ ).size;
965
+ }
756
966
 
967
+ // clean dist folder
757
968
 
969
+ for await (var file of distPages.scan(".")) {
970
+ file = file.replace(/\\/g, "/");
758
971
 
972
+ let path = process.cwd() + "/pages/" + file.split("dist/pages/").pop();
759
973
 
974
+ path = path.replace(".js", config?.files?.mimeType || ".jsx");
760
975
 
976
+ if (!fs.existsSync(path)) {
977
+ fs.unlinkSync(file);
978
+ }
761
979
  }
762
980
 
763
- return void 0;
981
+ /**
764
982
 
765
- }
983
+ * @function organizeRoutes
766
984
 
985
+ * @description - Organizes routes that have param paths
767
986
 
987
+ */
768
988
 
769
- /**
989
+ const organizeRoutes = () => {
990
+ // if path starts with the same path and is dynamic then they are the same route and push params to the same route
770
991
 
771
- * @function transform
992
+ let newRoutes = [];
772
993
 
773
- * @description - Transforms the jsx files to js files based on file paths
994
+ routes.forEach((route) => {
995
+ let exists = routes.find((r) => {
996
+ if (r.path.includes("[")) {
997
+ r.path = r.path.split("[").shift();
998
+ }
774
999
 
775
- */
1000
+ r.path = r.path
1001
+ .split("/")
1002
+ .filter((p) => p !== "")
1003
+ .join("/");
776
1004
 
1005
+ if (r.isParam) {
1006
+ return r.path === route.path && r.isParam;
1007
+ }
1008
+ });
777
1009
 
1010
+ if (exists) {
1011
+ let b4Params = route.params;
778
1012
 
779
- async function transForm() {
1013
+ route.params = [];
780
1014
 
781
- return new Promise(async (resolve, reject) => {
1015
+ route.params.push(b4Params);
782
1016
 
783
- globalThis.isBuilding = true
1017
+ route.params.push({
1018
+ jsFile: "/" + exists.path + "/index.js",
784
1019
 
785
- router.reload()
1020
+ folder: "/" + exists.path,
786
1021
 
787
- for await (var file of glob.scan('.')) {
1022
+ paramData: exists.params,
1023
+ });
788
1024
 
789
- file = file.replace(/\\/g, '/');
1025
+ route.query = exists.query;
790
1026
 
791
- let isBasePath = file.split('pages/')?.[1]?.split('/').length === 1;
1027
+ newRoutes.push(route);
1028
+ } else if (!exists && !route.isParam) {
1029
+ newRoutes.push(route);
1030
+ }
792
1031
 
1032
+ //remove param route that matched
793
1033
 
1034
+ routes = routes.filter((r) => (exists ? r.path !== exists.path : true));
1035
+ });
794
1036
 
795
- let folder = file.split('pages/')?.[1]?.split('/').slice(0, -1).join('/') || null;
1037
+ globalThis.routes = newRoutes;
1038
+ };
796
1039
 
797
- if (isBasePath) {
1040
+ organizeRoutes();
798
1041
 
799
- folder = '/'
1042
+ generateProviderRoutes();
800
1043
 
801
- }
1044
+ globalThis.isBuilding = false;
802
1045
 
803
- let route = isBasePath ? router.match('/') : router.match('/' + folder)
1046
+ if (!fs.existsSync(process.cwd() + "/_dev/meta")) {
1047
+ fs.mkdirSync(process.cwd() + "/_dev/meta");
1048
+ }
804
1049
 
1050
+ fs.writeFileSync(
1051
+ process.cwd() + "/_dev/meta/routes.json",
1052
+ JSON.stringify(routes, null, 2)
1053
+ );
805
1054
 
1055
+ console.log(`Finished building ${Math.round(bundleSize / 1000)}kb`);
806
1056
 
807
- if (route) {
1057
+ bundleSize = 0;
808
1058
 
809
- let { filePath, kind, name, params, pathname, query, } = route
1059
+ resolve();
1060
+ });
1061
+ }
810
1062
 
811
- let data = await read(filePath);
1063
+ let port = 3000;
1064
+ let hasRan = [];
812
1065
 
813
- try {
1066
+ switch (true) {
1067
+ case process.argv.includes("dev") &&
1068
+ !process.argv.includes("build") &&
1069
+ !process.argv.includes("start"):
1070
+ port = process.argv.includes("-p")
1071
+ ? process.argv[process.argv.indexOf("-p") + 1]
1072
+ : config?.dev?.port || 3000;
1073
+
1074
+ globalThis.oneAndDone = false;
1075
+ let v = await checkIFUptodate();
1076
+
1077
+ console.log(`
1078
+
1079
+ ${
1080
+ v.current !== v.latest
1081
+ ? `Update available: ${v.latest} (current: ${v.current})`
1082
+ : `Vader.js v${v.current}`
1083
+ }
1084
+ - Watching for changes in ./pages
1085
+ - Watching for changes in ./src
1086
+ - Watching for changes in ./public
1087
+ - Serving on port http://localhost:${port}
814
1088
 
815
- data = new Bun.Transpiler({ loader: "tsx", target: "browser", }).transformSync(data);
1089
+ `);
816
1090
 
817
- } catch (e) {
1091
+ globalThis.mode = "dev";
818
1092
 
819
- console.error(e)
1093
+ Server(port);
1094
+ for (var ints in integrationStates) {
1095
+ if (
1096
+ integrationStates &&
1097
+ integrationStates[ints]?.on &&
1098
+ integrationStates[ints].on.includes("dev") &&
1099
+ !hasRan.includes(integrationStates[ints].name)
1100
+ ) {
1101
+ console.log("Starting integration...");
820
1102
 
821
- }
1103
+ let int = integrationStates[ints];
822
1104
 
823
- let out = `./dist/${isBasePath ? 'index.js' : folder + '/index.js'}`;
1105
+ let { name, version, useRuntime, entryPoint, onAction, doOn } = int;
824
1106
 
825
- isBasePath ? folder = '/' : null;
1107
+ globalThis[`isRunning${name}`] = true;
1108
+ console.log(`Using integration: ${name} v${version}`);
826
1109
 
827
- data = handleReplaceMents(data);
1110
+ Bun.spawn({
1111
+ cwd: process.cwd(),
828
1112
 
829
- let isAparam = null
1113
+ isVader: true,
830
1114
 
831
- if (folder === "") {
1115
+ env: {
1116
+ PWD: process.cwd(),
832
1117
 
833
- return
1118
+ isVader: true,
834
1119
 
835
- }
1120
+ FOLDERS: "pages,src,public",
836
1121
 
837
- switch (true) {
1122
+ onExit: (code) => {
1123
+ globalThis.isBuilding = false;
838
1124
 
839
- case kind === 'dynamic':
1125
+ globalThis[`isRunning${name}`] = false;
1126
+ },
1127
+ },
840
1128
 
841
- isAparam = true
1129
+ cmd: [useRuntime || "node", entryPoint],
1130
+ });
842
1131
 
843
- break;
1132
+ hasRan.push(integrationStates[ints].name);
1133
+ }
1134
+ }
844
1135
 
845
- case kind === 'catch-all':
1136
+ transForm();
846
1137
 
847
- isAparam = true
1138
+ Bun.spawn({
1139
+ cwd: process.cwd() + "/node_modules/vaderjs/binaries/",
848
1140
 
849
- break;
1141
+ env: {
1142
+ PWD: process.cwd(),
850
1143
 
851
- case kind === 'optional-catch-all':
1144
+ IPC: IPC,
852
1145
 
853
- isAparam = true
1146
+ FOLDERS: "pages,src,public",
854
1147
 
855
- break;
1148
+ onExit: (code) => {
1149
+ globalThis.isBuilding = false;
856
1150
 
857
- }
1151
+ globalThis.oneAndDone = true;
1152
+ },
1153
+ },
858
1154
 
859
- routes.push({ path: folder, file: out, isParam: isAparam, params: params, query, pathname })
1155
+ cmd: ["node", "watcher.js"],
1156
+ });
860
1157
 
861
- write(out, data);
1158
+ async function runOnChange() {
1159
+ for (var ints in integrationStates) {
1160
+ if (
1161
+ integrationStates &&
1162
+ integrationStates[ints].on &&
1163
+ integrationStates[ints]?.on.includes("dev:change")
1164
+ ) {
1165
+ let int = integrationStates[ints];
862
1166
 
863
- bundleSize += data.length
1167
+ let { name, version, useRuntime, entryPoint, onAction, doOn } = int;
864
1168
 
1169
+ if (globalThis[`isRunning${name}`]) {
1170
+ setTimeout(() => {
1171
+ globalThis[`isRunning${name}`] = false;
1172
+ }, 1000);
1173
+ return void 0;
1174
+ }
865
1175
 
1176
+ globalThis[`isRunning${name}`] = true;
1177
+ console.log(`Using integration: ${name} v${version}`);
866
1178
 
1179
+ Bun.spawn({
1180
+ cwd: process.cwd(),
867
1181
 
1182
+ isVader: true,
868
1183
 
869
- }
1184
+ env: {
1185
+ PWD: process.cwd(),
870
1186
 
1187
+ isVader: true,
871
1188
 
1189
+ FOLDERS: "pages,src,public",
872
1190
 
873
- }
874
-
875
-
876
-
877
- for await (var file of srcGlob.scan('.')) {
878
-
879
- if (!fs.existsSync(process.cwd() + '/dist/src/')) {
880
-
881
- fs.mkdirSync(process.cwd() + '/dist/src/')
882
-
883
- }
884
-
885
- file = file.replace(/\\/g, '/');
886
-
887
- switch (file.split('.').pop()) {
888
-
889
- case 'ts':
890
-
891
- let transpiler = new Bun.Transpiler({ loader: "ts", target: "browser", });
892
-
893
- let data = await read(file);
894
-
895
- try {
896
-
897
- data = transpiler.transformSync(data);
898
-
899
- } catch (error) {
900
-
901
- console.error(error)
902
-
903
- }
904
-
905
- file = file.replace('.ts', '.js')
906
-
907
- let path = process.cwd() + '/dist/src/' + file.split('src/').pop()
908
-
909
- write(path, data);
910
-
911
- bundleSize += data.length
912
-
913
-
914
-
915
- break;
916
-
917
-
918
-
919
- case 'tsx':
920
-
921
- let transpilerx = new Bun.Transpiler({ loader: "tsx", target: "browser", });
922
-
923
- let datax = await read(file);
924
-
925
- try {
926
-
927
- datax = transpilerx.transformSync(datax);
928
-
929
- } catch (error) {
930
-
931
- console.error(error)
932
-
933
- }
934
-
935
- datax = handleReplaceMents(datax);
936
-
937
- file = file.replace('.tsx', '.js')
938
-
939
- let pathx = process.cwd() + '/dist/src/' + file.split('src/').pop()
940
-
941
- write(pathx, datax);
942
-
943
-
944
-
945
-
946
-
947
- break;
948
-
949
- case 'jsx':
950
-
951
- let transpilerjx = new Bun.Transpiler({ loader: "jsx", target: "browser" });
952
-
953
- let datajx = await read(file);
954
-
955
-
956
-
957
- let source = transpilerjx.scan(datajx)
958
-
959
- try {
960
-
961
- datajx = transpilerjx.transformSync(datajx)
962
-
963
- } catch (error) {
964
-
965
- console.error(error)
966
-
967
- }
968
-
969
- datajx = handleReplaceMents(datajx);
970
-
971
- file = file.replace('.jsx', '.js')
972
-
973
- let pathjx = process.cwd() + '/dist/src/' + file.split('src/').pop()
974
-
975
- write(pathjx, datajx);
976
-
977
- bundleSize += datajx.length
978
-
979
- break;
980
-
981
- }
982
-
983
- }
984
-
985
-
986
-
987
-
988
-
989
- for await (var file of publicGlob.scan('.')) {
990
-
991
- let data = await read(file);
992
-
993
- file = file.replace(/\\/g, '/');
994
-
995
- write(process.cwd() + '/dist/public/' + file.split('public/').pop(), data);
996
-
997
- bundleSize += fs.statSync(process.cwd() + '/dist/public/' + file.split('public/').pop()).size
998
-
999
- }
1000
-
1001
- for await (var file of vaderGlob.scan('.')) {
1002
-
1003
- let data = await read(file);
1004
-
1005
- file = file.replace(/\\/g, '/');
1006
-
1007
- write(process.cwd() + '/dist/' + file.split('node_modules/vaderjs/runtime/').pop(), data);
1008
-
1009
- bundleSize += fs.statSync(process.cwd() + '/dist/' + file.split('node_modules/vaderjs/runtime/').pop()).size
1010
-
1011
- }
1012
-
1013
-
1014
-
1015
- // clean dist folder
1016
-
1017
- for await (var file of distPages.scan('.')) {
1018
-
1019
- file = file.replace(/\\/g, '/');
1020
-
1021
- let path = process.cwd() + '/pages/' + file.split('dist/pages/').pop()
1022
-
1023
- path = path.replace('.js', config?.files?.mimeType || '.jsx')
1024
-
1025
-
1026
-
1027
- if (!fs.existsSync(path)) {
1028
-
1029
- fs.unlinkSync(file)
1030
-
1031
- }
1032
-
1033
-
1034
-
1035
- }
1036
-
1037
-
1038
-
1039
-
1040
-
1041
-
1042
-
1043
-
1044
-
1045
-
1046
-
1047
-
1048
-
1049
- /**
1050
-
1051
- * @function organizeRoutes
1052
-
1053
- * @description - Organizes routes that have param paths
1054
-
1055
- */
1056
-
1057
-
1058
-
1059
- const organizeRoutes = () => {
1060
-
1061
- // if path starts with the same path and is dynamic then they are the same route and push params to the same route
1062
-
1063
- let newRoutes = []
1064
-
1065
- routes.forEach((route) => {
1066
-
1067
- let exists = routes.find((r) => {
1068
-
1069
- if (r.path.includes('[')) {
1070
-
1071
- r.path = r.path.split('[').shift()
1072
-
1073
- }
1074
-
1075
-
1076
-
1077
- r.path = r.path.split('/').filter((p) => p !== '').join('/')
1078
-
1079
- if (r.isParam) {
1080
-
1081
- return r.path === route.path && r.isParam
1082
-
1083
- }
1084
-
1085
-
1086
-
1087
- })
1088
-
1089
- if (exists) {
1090
-
1091
- let b4Params = route.params
1092
-
1093
- route.params = []
1094
-
1095
- route.params.push(b4Params)
1096
-
1097
- route.params.push({
1098
-
1099
- jsFile: '/' + exists.path + '/index.js',
1100
-
1101
- folder: '/' + exists.path,
1102
-
1103
- paramData: exists.params
1104
-
1105
- }
1106
-
1107
- )
1108
-
1109
- route.query = exists.query
1110
-
1111
- newRoutes.push(route)
1112
-
1113
- }
1114
-
1115
- else if (!exists && !route.isParam) {
1116
-
1117
- newRoutes.push(route)
1118
-
1119
-
1120
-
1121
- }
1122
-
1123
- //remove param route that matched
1124
-
1125
- routes = routes.filter((r) => exists ? r.path !== exists.path : true)
1126
-
1127
-
1128
-
1129
- })
1130
-
1131
- globalThis.routes = newRoutes
1132
-
1133
- }
1134
-
1135
- organizeRoutes()
1136
-
1137
-
1138
-
1139
-
1140
-
1141
- generateProviderRoutes()
1142
-
1143
- globalThis.isBuilding = false
1144
-
1145
- if (!fs.existsSync(process.cwd() + '/_dev/meta')) {
1146
-
1147
- fs.mkdirSync(process.cwd() + '/_dev/meta')
1148
-
1149
- }
1150
-
1151
- fs.writeFileSync(process.cwd() + '/_dev/meta/routes.json', JSON.stringify(routes, null, 2))
1152
-
1153
- console.log(`Finished building ${Math.round(bundleSize / 1000)}kb`)
1154
-
1155
-
1156
-
1157
- bundleSize = 0
1158
-
1159
- resolve()
1160
-
1161
- });
1162
-
1163
-
1164
-
1165
- }
1166
-
1167
- let port = 3000
1168
-
1169
- switch (true) {
1170
-
1171
- case process.argv.includes('dev') && !process.argv.includes('build') && !process.argv.includes('start'):
1172
-
1173
-
1174
-
1175
- port = process.argv.includes('-p') ? process.argv[process.argv.indexOf('-p') + 1] : config?.dev?.port || 3000
1176
-
1177
- globalThis.oneAndDone = false
1178
-
1179
- console.log(`
1180
-
1181
- Vader.js v${fs.readFileSync(process.cwd() + '/node_modules/vaderjs/package.json', 'utf8').split('"version": "')[1].split('"')[0]}
1182
-
1183
- - Watching for changes in ./pages
1184
-
1185
- - Watching for changes in ./src
1186
-
1187
- - Watching for changes in ./public
1188
-
1189
- - Serving on port ${port}
1190
-
1191
- `)
1192
-
1193
- globalThis.mode = 'dev'
1194
-
1195
- Server(port)
1196
-
1197
- transForm()
1198
-
1199
-
1200
-
1201
- Bun.spawn({
1202
-
1203
- cwd: process.cwd() + '/node_modules/vaderjs/binaries/',
1204
-
1205
- env: {
1206
-
1207
- PWD: process.cwd(),
1208
-
1209
- IPC: IPC,
1210
-
1211
- FOLDERS: 'pages,src,public',
1212
-
1213
- onExit: (code) => {
1214
-
1215
- globalThis.isBuilding = false
1216
-
1217
- globalThis.oneAndDone = true
1218
-
1219
- }
1191
+ onExit: (code) => {
1192
+ globalThis.isBuilding = false;
1220
1193
 
1194
+ globalThis[`isRunning${name}`] = false;
1195
+ },
1221
1196
  },
1222
1197
 
1223
- cmd: ['node', 'watcher.js'],
1224
-
1225
- })
1226
-
1227
- async function runOnChange() {
1228
-
1229
- for (var ints in integrationStates) {
1230
-
1231
- if (integrationStates && integrationStates[ints].on.includes('dev:change')) {
1232
-
1233
- console.log('Starting integration...')
1234
-
1235
- let int = integrationStates[ints]
1236
-
1237
- let { name, version, useRuntime, entryPoint, onAction, doOn } = int
1238
-
1239
- if (globalThis.isBuilding) {
1240
-
1241
- return
1242
-
1243
- }
1244
-
1245
- globalThis.isBuilding = true
1246
-
1247
- Bun.spawn({
1248
-
1249
- cwd: process.cwd(),
1250
-
1251
- isVader: true,
1252
-
1253
- env: {
1254
-
1255
- PWD: process.cwd(),
1256
-
1257
- isVader: true,
1258
-
1259
- FOLDERS: 'pages,src,public',
1260
-
1261
- onExit: (code) => {
1262
-
1263
- globalThis.isBuilding = false
1264
-
1265
- }
1266
-
1267
- },
1268
-
1269
- cmd: [useRuntime || 'node', entryPoint],
1270
-
1271
- })
1272
-
1273
-
1274
-
1275
- console.log(`Using integration: ${name} v${version}`)
1276
-
1277
-
1278
-
1279
- }
1280
-
1281
- }
1198
+ cmd: [useRuntime || "node", entryPoint],
1199
+ });
1282
1200
 
1201
+ console.log(`Using integration: ${name} v${version}`);
1283
1202
  }
1203
+ }
1204
+ }
1284
1205
 
1206
+ IPC.client({
1207
+ use: IPCServer.typeEnums.WATCHER,
1285
1208
 
1209
+ port: 3434,
1210
+ }).Console.read(async (message) => {
1211
+ message = message.msg;
1286
1212
 
1213
+ switch (true) {
1214
+ case message.data?.type === "change":
1215
+ console.log("File changed:", message.data.filename);
1287
1216
 
1217
+ transForm();
1288
1218
 
1289
- IPC.client({
1290
-
1291
- use: IPCServer.typeEnums.WATCHER,
1292
-
1293
- port: 3434
1294
-
1295
- }).Console.read((message) => {
1296
-
1297
- message = message.msg
1298
-
1299
- switch (true) {
1300
-
1301
- case message.data?.type === 'change':
1302
-
1303
- console.log('File changed:', message.data.filename)
1304
-
1305
- transForm()
1306
-
1307
- clients.forEach((client) => {
1308
-
1309
- client.send('reload')
1310
-
1311
- })
1312
-
1313
- runOnChange()
1314
-
1315
-
1316
-
1317
- break;
1318
-
1319
- case message.data?.type === 'add':
1320
-
1321
- console.log('File added:', message.data.filename)
1322
-
1323
- transForm()
1324
-
1325
- break;
1326
-
1327
- }
1328
-
1329
- })
1330
-
1331
-
1332
-
1333
-
1334
-
1335
-
1336
-
1337
- break;
1338
-
1339
- case process.argv.includes('build') && !process.argv.includes('dev') && !process.argv.includes('start'):
1219
+ clients.forEach((client) => {
1220
+ client.send("reload");
1221
+ });
1340
1222
 
1341
- globalThis.devMode = false
1223
+ // reload config
1224
+ config = await import(process.cwd() + "/vader.config.js").then((m) =>
1225
+ m ? m.default : {}
1226
+ );
1342
1227
 
1228
+ runOnChange();
1343
1229
 
1230
+ break;
1344
1231
 
1232
+ case message.data?.type === "add":
1233
+ console.log("File added:", message.data.filename);
1345
1234
 
1235
+ transForm();
1346
1236
 
1237
+ break;
1238
+ }
1239
+ });
1347
1240
 
1241
+ break;
1348
1242
 
1349
- globalThis.mode = 'prod'
1243
+ case process.argv.includes("build") &&
1244
+ !process.argv.includes("dev") &&
1245
+ !process.argv.includes("start"):
1246
+ globalThis.devMode = false;
1350
1247
 
1351
- globalThis.isProduction = true
1248
+ globalThis.mode = "prod";
1352
1249
 
1353
- globalThis.routeStates = []
1250
+ globalThis.isProduction = true;
1354
1251
 
1355
- console.log(`
1252
+ globalThis.routeStates = [];
1356
1253
 
1254
+ console.log(`
1357
1255
  Vader.js v1.3.3
1358
-
1359
1256
  Building to ./dist
1257
+ `);
1360
1258
 
1361
- `)
1362
-
1363
-
1364
-
1365
- await transForm()
1366
-
1367
- for (var ints in integrationStates) {
1368
-
1369
- console.log(integrationStates[ints], 'integrationStates[ints]')
1370
-
1371
- if (integrationStates && integrationStates[ints].on.includes('build')) {
1372
-
1373
- console.log('Starting integration...')
1374
-
1375
- let int = integrationStates[ints]
1376
-
1377
- let { name, version, useRuntime, entryPoint, onAction, doOn } = int
1378
-
1379
- console.log(`Using integration: ${name} v${version} from ${entryPoint}`)
1380
-
1381
-
1382
-
1383
- Bun.spawn({
1384
-
1385
- cwd: process.cwd(),
1386
-
1387
- isVader: true,
1388
-
1389
- env: {
1390
-
1391
- PWD: process.cwd(),
1392
-
1393
- isVader: true,
1394
-
1395
- FOLDERS: 'pages,src,public',
1396
-
1397
- onExit: (code) => {
1398
-
1399
- globalThis.isBuilding = false
1400
-
1401
- }
1402
-
1403
- },
1404
-
1405
- cmd: ["node", entryPoint]
1406
-
1407
- })
1259
+ transForm();
1408
1260
 
1261
+ for (var ints in integrationStates) {
1262
+ if (
1263
+ integrationStates &&
1264
+ integrationStates[ints].on &&
1265
+ integrationStates[ints]?.on.includes("build")
1266
+ ) {
1267
+ console.log("Starting integration...");
1409
1268
 
1269
+ let int = integrationStates[ints];
1410
1270
 
1271
+ let { name, version, useRuntime, entryPoint, onAction, doOn } = int;
1411
1272
 
1273
+ console.log(`Using integration: ${name} v${version}`);
1412
1274
 
1275
+ Bun.spawn({
1276
+ cwd: process.cwd(),
1413
1277
 
1278
+ isVader: true,
1414
1279
 
1415
- }
1280
+ env: {
1281
+ PWD: process.cwd(),
1416
1282
 
1417
- }
1283
+ isVader: true,
1418
1284
 
1285
+ FOLDERS: "pages,src,public",
1419
1286
 
1287
+ onExit: (code) => {
1288
+ globalThis.isBuilding = false;
1289
+ },
1290
+ },
1420
1291
 
1421
- break;
1292
+ cmd: ["node", entryPoint],
1293
+ });
1294
+ }
1295
+ }
1422
1296
 
1423
- case process.argv.includes('start') && !process.argv.includes('dev') && !process.argv.includes('build'):
1297
+ break;
1424
1298
 
1425
- port = process.argv.includes('-p') ? process.argv[process.argv.indexOf('-p') + 1] : config?.host?.prod?.port || 3000
1299
+ case process.argv.includes("start") &&
1300
+ !process.argv.includes("dev") &&
1301
+ !process.argv.includes("build"):
1302
+ port = process.argv.includes("-p")
1303
+ ? process.argv[process.argv.indexOf("-p") + 1]
1304
+ : config?.host?.prod?.port || 3000;
1426
1305
 
1427
- console.log(`
1306
+ console.log(`
1428
1307
 
1429
1308
  Vader.js v1.3.3
1430
1309
 
1431
1310
  Serving ./dist on port ${port}
1432
1311
 
1433
- url: http://localhost:${port}
1312
+ url: ${config?.host?.prod?.hostname || "http://localhost"}:${port}
1434
1313
 
1435
- `)
1314
+ `);
1436
1315
 
1437
- globalThis.devMode = false
1316
+ globalThis.devMode = false;
1438
1317
 
1439
- globalThis.isProduction = true
1318
+ globalThis.isProduction = true;
1440
1319
 
1320
+ Server(port);
1441
1321
 
1322
+ break;
1442
1323
 
1443
- Server(port)
1444
-
1445
- break;
1446
-
1447
- default:
1448
-
1449
-
1450
-
1451
- break;
1452
-
1453
-
1454
-
1455
- }
1324
+ default:
1325
+ break;
1326
+ }