vaderjs 2.0.6 → 2.0.8

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.
Files changed (2) hide show
  1. package/main.js +150 -56
  2. package/package.json +1 -1
package/main.js CHANGED
@@ -4,9 +4,48 @@ import ansiColors from 'ansi-colors'
4
4
  import { Glob } from 'bun'
5
5
  const args = Bun.argv.slice(2)
6
6
  globalThis.isBuilding = false;
7
- import fs from 'fs'
7
+ import fs from 'fs'
8
+ import { spawn } from 'child_process'
9
+ import { platform } from 'os'
8
10
  import path from 'path'
9
11
 
12
+ let bunPath = 'bun'; // Default for Linux/Mac
13
+ if (platform() === 'win32') {
14
+ bunPath ='bun'; // Bun path for Windows
15
+ } else {
16
+ bunPath = path.resolve(process.env.HOME || process.env.USERPROFILE, '.bun', 'bin', 'bun');
17
+ }
18
+ async function checkIfBunInstalled(){
19
+ return new Promise((resolve, reject) => {
20
+ // dont log spawn output
21
+ const install = spawn('bash', ['-c', 'curl -fsSL https://bun.sh/install | bash && export PATH=$HOME/.bun/bin:$PATH'], {
22
+ stdio: 'ignore',
23
+ shell: true, // Allows running shell commands
24
+ });
25
+
26
+ install.on('close', (code) => {
27
+ if (code === 0) {
28
+ console.log('Bun installed successfully.');
29
+ resolve(true);
30
+ } else {
31
+ console.error('Failed to install Bun.');
32
+ reject(new Error('Bun installation failed.'));
33
+ }
34
+ });
35
+
36
+ install.on('error', (err) => {
37
+ console.error('Error during Bun installation:', err);
38
+ reject(err);
39
+ });
40
+ });
41
+ }
42
+
43
+ if(!fs.existsSync(bunPath)){
44
+ console.log('Bun is not installed, installing now...')
45
+ await checkIfBunInstalled()
46
+ }
47
+
48
+
10
49
 
11
50
  if (!fs.existsSync(process.cwd() + '/app') && !args.includes('init')) {
12
51
  console.error(`App directory not found in ${process.cwd()}/app`)
@@ -75,15 +114,16 @@ if (!fs.existsSync(process.cwd() + '/jsconfig.json')) {
75
114
  await Bun.write(process.cwd() + '/jsconfig.json', JSON.stringify(json, null, 4))
76
115
  }
77
116
 
78
- var bindes = []
117
+ globalThis.bindes = []
79
118
  var fnmap = []
80
119
  const vader = {
120
+ isDev: mode === 'development',
81
121
  onFileChange: (file, cb) => {
82
122
  fs.watch(file, cb)
83
123
  },
84
124
  runCommand: (cmd) => {
85
125
  return new Promise((resolve, reject) => {
86
- Bun.spawn(cmd, {
126
+ let c = Bun.spawn(cmd, {
87
127
  stdout: 'inherit',
88
128
  cwd: process.cwd(),
89
129
  onExit({ exitCode: code }) {
@@ -95,6 +135,11 @@ const vader = {
95
135
  }
96
136
  })
97
137
 
138
+ setTimeout(() => {
139
+ c.kill()
140
+ reject()
141
+ }, 5000)
142
+
98
143
 
99
144
  })
100
145
  },
@@ -105,6 +150,7 @@ const vader = {
105
150
  },
106
151
  injectHTML: (html) => {
107
152
  bindes.push(html)
153
+ globalThis.bindes = bindes
108
154
  },
109
155
  }
110
156
  const handleReplacements = (code) => {
@@ -160,8 +206,9 @@ const handleReplacements = (code) => {
160
206
  line = b4
161
207
  }
162
208
  if (!hasImport && line.includes('useRef')) {
209
+ line = line.replace(' ', '')
163
210
  let b4 = line
164
- let key = line.split(' ')[1].split('=')[0]
211
+ let key = line.split('=')[0].split(' ').filter(Boolean)[1]
165
212
  b4 = line.replace('useRef(', `this.useRef('${key}',`)
166
213
  line = b4
167
214
  }
@@ -172,12 +219,14 @@ const handleReplacements = (code) => {
172
219
  return c
173
220
  }
174
221
 
175
-
222
+ if (!fs.existsSync(process.cwd() + '/dev/bundler.js')) {
223
+ fs.mkdirSync(process.cwd() + '/dev', { recursive: true })
224
+ fs.copyFileSync(require.resolve('vaderjs/bundler/index.js'), process.cwd() + '/dev/bundler.js')
225
+ }
176
226
  let start = Date.now()
177
227
  async function generateApp() {
178
228
  globalThis.isBuilding = true;
179
- console.log(ansiColors.green('Building...'))
180
- console.log(`Starting build at ${new Date().toLocaleTimeString()}`)
229
+ console.log(ansiColors.green('Building...'))
181
230
  let plugins = config.plugins || []
182
231
  for (let plugin of plugins) {
183
232
  if (plugin.onBuildStart) {
@@ -201,24 +250,43 @@ async function generateApp() {
201
250
 
202
251
  let r = routes.routes[route]
203
252
  let code = await Bun.file(r).text()
253
+ code = handleReplacements(code)
204
254
  let size = code.length / 1024
205
255
  r = r.replace(process.cwd().replace(/\\/g, '/') + '/app', '')
206
- var beforeR = r
207
256
  r = r.replace('.jsx', '.js').replace('.tsx', '.js')
208
257
  fs.mkdirSync(path.join(process.cwd() + '/dist', path.dirname(r)), { recursive: true })
209
- fs.writeFileSync(process.cwd() + '/dist/' + path.dirname(r) + '/' + path.basename(r), `
210
- let route = window.location.pathname.split('/').filter(v => v !== '')
211
- let params = {
212
- ${Object.keys(routes.match(route).params || {}).length > 0 ? Object.keys(routes.match(route).params || {}).map(p => {
213
- return `${p}: route[${Object.keys(routes.match(route).params).indexOf(p) + Object.keys(routes.match(route).params).length}]`
214
- }).join(',') : ""}
215
- }
216
- \n${code}
217
- `)
258
+ let params = routes.match(route).params || {}
259
+ let base = routes.match(route)
260
+ let paramIndexes = []
261
+ for (let param in params) {
262
+ let routes = base.pathname.split('/')
263
+ let index = routes.indexOf('[' + param + ']')
264
+ paramIndexes.push(index)
265
+ }
266
+
267
+ // dont return
268
+
269
+ fs.writeFileSync(
270
+ process.cwd() + '/dist/' + path.dirname(r) + '/' + path.basename(r),
271
+ `
272
+ let route = window.location.pathname.split('/').filter(Boolean)
273
+ let params = {
274
+ // get index tehn do route[index]
275
+ ${Object.keys(params).map((param, i) => {
276
+ if (paramIndexes[i] !== -1) {
277
+ var r_copy = r;
278
+ r_copy = r_copy.split('/').filter(Boolean)
279
+ var index = paramIndexes[i] - 1
280
+ return `${param}: route[${index}]`
281
+ }
282
+ }).join(',\n')}
283
+ }
284
+
285
+ \n${code}
286
+ `
287
+ );
218
288
  fs.mkdirSync(process.cwd() + '/dev', { recursive: true })
219
- if (!fs.existsSync(process.cwd() + '/dev/bundler.js')) {
220
- fs.copyFileSync(require.resolve('vaderjs/bundler/index.js'), process.cwd() + '/dev/bundler.js')
221
- }
289
+
222
290
 
223
291
  if (!fs.existsSync(process.cwd() + '/dev/readme.md')) {
224
292
  fs.writeFileSync(process.cwd() + '/dev/readme.md', `# Please do not edit the bundler.js file in the dev directory. This file is automatically generated by the bundler. \n\n`)
@@ -227,37 +295,32 @@ async function generateApp() {
227
295
  fs.writeFileSync(process.cwd() + '/dist/src/vader/index.js', await new Bun.Transpiler({
228
296
  loader: 'ts',
229
297
  }).transformSync(await Bun.file(require.resolve('vaderjs')).text()))
230
-
231
298
  Bun.spawn({
232
- cmd: ['bun', 'run', './dev/bundler.js'],
299
+ cmd: [bunPath, 'run', './dev/bundler.js'] ,
233
300
  cwd: process.cwd(),
234
301
  stdout: 'inherit',
235
302
  env: {
236
- ENTRYPOINT: path.join(process.cwd() + '/dist/' + path.dirname(r) + '/' + path.basename(r)),
237
- ROOT: process.cwd() + '/app/',
303
+ ENTRYPOINT: path.join(process.cwd(), 'dist', path.dirname(r), path.basename(r)),
304
+ ROOT: path.join(process.cwd(), 'app/'),
238
305
  OUT: path.dirname(r),
239
- file: process.cwd() + '/dist/' + path.dirname(r) + '/' + path.basename(r),
306
+ file: path.join(process.cwd(), 'dist', path.dirname(r), path.basename(r)),
240
307
  DEV: mode === 'development',
241
308
  size,
242
309
  bindes: bindes.join('\n'),
243
- isTs: beforeR.endsWith(".tsx"),
244
310
  filePath: r,
245
-
246
- isJsx: beforeR.endsWith('.tsx') || beforeR.endsWith(".jsx"),
247
311
  isAppFile: true,
248
- INPUT: `../app/${beforeR}`,
312
+ isJsx: true,
313
+ INPUT: `../app/${r.replace('.js', '.jsx').replace('.tsx', '.js')}`,
249
314
  },
250
315
  onExit({ exitCode: code }) {
251
316
  if (code === 0) {
252
- bindes = []
253
- console.log(`Built ${r} in ${Date.now() - start}ms`)
254
- resolve()
317
+ bindes = [];
318
+ resolve();
255
319
  } else {
256
- reject()
320
+ reject();
257
321
  }
258
- }
259
- })
260
-
322
+ },
323
+ });
261
324
  })
262
325
 
263
326
  switch (host_provider) {
@@ -297,6 +360,7 @@ async function generateApp() {
297
360
  await plugin.onBuildFinish(vader)
298
361
  }
299
362
  }
363
+
300
364
  })
301
365
 
302
366
 
@@ -304,7 +368,7 @@ async function generateApp() {
304
368
 
305
369
  function handleFiles() {
306
370
  return new Promise(async (resolve, reject) => {
307
- try {
371
+ try {
308
372
  let glob = new Glob('public/**/*')
309
373
  for await (var i of glob.scan()) {
310
374
  let file = i
@@ -319,15 +383,15 @@ function handleFiles() {
319
383
  var file = i
320
384
  fs.mkdirSync(path.join(process.cwd() + '/dist', path.dirname(file)), { recursive: true })
321
385
  // turn jsx to js
322
- if (file.endsWith('.jsx') || file.endsWith('.tsx')) {
386
+ if (file.includes('.jsx') || file.includes('.tsx')) {
323
387
  let code = await Bun.file(file).text()
324
388
 
325
389
  code = handleReplacements(code)
326
- var url = file
390
+
327
391
  file = file.replace('.jsx', '.js').replace('.tsx', '.js')
328
392
  fs.writeFileSync(path.join(process.cwd() + '/dist', file.replace('.jsx', '.js').replace('.tsx', '.js')), code)
329
393
  await Bun.spawn({
330
- cmd: ['bun', 'run', './dev/bundler.js'],
394
+ cmd: [bunPath, 'run', './dev/bundler.js'],
331
395
  cwd: process.cwd(),
332
396
  stdout: 'inherit',
333
397
  env: {
@@ -339,9 +403,8 @@ function handleFiles() {
339
403
  DEV: mode === 'development',
340
404
  size: code.length / 1024,
341
405
  filePath: file.replace('.jsx', '.js'),
342
- isJsx: url.endsWith('.tsx') || url.endsWith(".jsx"),
343
- isAppFile: false,
344
- INPUT: path.join(process.cwd(), url),
406
+ isTs: file.includes('.tsx'),
407
+ INPUT: path.join(process.cwd(), file.replace('.js', '.jsx').replace('.tsx', '.js')),
345
408
  },
346
409
  onExit({ exitCode: code }) {
347
410
  if (code === 0) {
@@ -351,13 +414,13 @@ function handleFiles() {
351
414
  }
352
415
  }
353
416
  })
354
- } else if (file.endsWith('.ts')) {
417
+ } else if (file.includes('.ts')) {
355
418
  let code = await Bun.file(file).text()
356
419
  code = handleReplacements(code)
357
420
  file = file.replace('.ts', '.js')
358
421
  fs.writeFileSync(path.join(process.cwd() + '/dist', file.replace('.ts', '.js')), code)
359
422
  await Bun.spawn({
360
- cmd: ['bun', 'run', './dev/bundler.js'],
423
+ cmd: [bunPath, 'run', './dev/bundler.js'],
361
424
  cwd: process.cwd(),
362
425
  stdout: 'inherit',
363
426
  env: {
@@ -392,8 +455,8 @@ function handleFiles() {
392
455
  globalThis.clients = []
393
456
 
394
457
  if (mode === 'development') {
395
- await handleFiles()
396
458
  await generateApp()
459
+ await handleFiles()
397
460
  const watcher = fs.watch(path.join(process.cwd() + '/'), { recursive: true })
398
461
  let isBuilding = false; // Flag to track build status
399
462
 
@@ -403,10 +466,10 @@ if (mode === 'development') {
403
466
  // Function to handle file changes with debounce
404
467
  const handleFileChangeDebounced = async (change, file) => {
405
468
  if (file.endsWith('.tsx') || file.endsWith('.jsx') || file.endsWith('.css') || file.endsWith('.ts')
406
- && !file.includes('node_module')
469
+ && !file.includes('node_module')
407
470
  ) {
408
471
  // delete files cache
409
- if (file.endsWith('vader.config.ts')) {
472
+ if (file.endsWith('vader.config.ts')){
410
473
  delete require.cache[require.resolve(process.cwd() + '/vader.config.ts')]
411
474
 
412
475
  config = require(process.cwd() + '/vader.config.ts').default
@@ -447,13 +510,14 @@ if (mode === 'development') {
447
510
  else if (mode == 'production') {
448
511
  await handleFiles()
449
512
  await generateApp()
513
+
514
+ console.log(`Build complete in ${Date.now() - start}ms at ${new Date().toLocaleTimeString()}`);
450
515
  }
451
516
  else {
452
517
  if (isBuilding) console.log(`Build complete in ${Date.now() - start}ms at ${new Date().toLocaleTimeString()}`);
453
-
518
+
454
519
  }
455
520
 
456
-
457
521
  if (mode == 'development' || mode == 'serve') {
458
522
  let server = Bun.serve({
459
523
  port: port || 8080,
@@ -494,27 +558,54 @@ if (mode == 'development' || mode == 'serve') {
494
558
  style: 'nextjs'
495
559
  })
496
560
  router.reload()
497
- let route = router.match(url.pathname)
561
+ let route = router.match(url.pathname)
498
562
  if (!route) {
499
563
  return new Response('Not found', { status: 404 })
500
564
  }
501
565
  let p = route.pathname;
502
566
  let base = path.dirname(route.filePath)
503
567
  base = base.replace(/\\/g, '/')
504
- base = base.replace(path.join(process.cwd() + '/app').replace(/\\/g, '/'), '');
505
- base = base.replace(/\\/g, '/').replace(/\/app(\/|$)/, '/dist$1');
506
- base = process.cwd() + '/dist/' + base;
568
+ base = base.replace(path.join(process.cwd() + '/app').replace(/\\/g, '/'), '')
569
+ base = base.replace(/\\/g, '/').replace('/app', '/dist')
570
+ base = process.cwd() + "/dist/" + base
571
+ if(!fs.existsSync(path.join(base, 'index.html'))){
572
+ return new Response(`
573
+ <html>
574
+ <head>
575
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
576
+ <meta http-equiv="refresh" content="5">
577
+ </head>
578
+ <body>
579
+ <p>Rerouting to display changes from server</p>
580
+ </body>
581
+ `, {
582
+ headers: {
583
+ 'Content-Type': 'text/html',
584
+ 'Cache-Control': 'no-cache'
585
+ }
586
+ })
587
+ }
507
588
  let data = await Bun.file(path.join(base, 'index.html')).text()
508
589
  if (mode == "development") {
509
590
  return new Response(data + `
510
591
  <script>
511
- let ws = new WebSocket('ws://localhost:${server.port}')
592
+ let ws = new WebSocket(\`\${location.protocol === 'https:' ? 'wss' : 'ws'}://\${location.host}\`)
512
593
  ws.onmessage = (e) => {
513
594
  if(e.data === 'reload'){
514
595
  console.log('Reloading to display changes from server')
515
596
  window.location.reload()
516
597
  }
517
598
  }
599
+ ws.onopen = () => {
600
+ console.log('Connected to hmr server')
601
+ }
602
+
603
+ ws.onclose = () => {
604
+ // try to reconnect
605
+ console.log('Reconnecting to hmr server')
606
+ ws = new WebSocket(\`\${location.protocol === 'https:' ? 'wss' : 'ws'}://\${location.host}\`)
607
+ }
608
+
518
609
  </script>
519
610
  `, {
520
611
  headers: {
@@ -533,4 +624,7 @@ if (mode == 'development' || mode == 'serve') {
533
624
  })
534
625
 
535
626
  console.log(ansiColors.green('Server started at http://localhost:' + port || 8080))
536
- }
627
+ }
628
+
629
+
630
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vaderjs",
3
- "version": "2.0.6",
3
+ "version": "2.0.8",
4
4
  "description": "A simple and powerful JavaScript library for building modern web applications.",
5
5
  "bin": {
6
6
  "vaderjs": "./main.js"