@bananacool467/authtics-host 0.1.5 → 0.1.7

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/dist/config.d.ts CHANGED
@@ -11,5 +11,6 @@ export interface AuthticsConfig {
11
11
  autoPageDir?: string;
12
12
  autoFile?: boolean;
13
13
  autoFileDir?: string;
14
+ hasPausedRoute?: boolean;
14
15
  }
15
16
  export declare function defineConfig(config: AuthticsConfig): AuthticsConfig;
package/dist/config.js CHANGED
@@ -13,5 +13,7 @@ export function defineConfig(config) {
13
13
  config.port = 3000;
14
14
  if (config.devMode == undefined)
15
15
  config.devMode = true;
16
+ if (config.hasPausedRoute == undefined)
17
+ config.hasPausedRoute = false;
16
18
  return config;
17
19
  }
@@ -1,2 +1 @@
1
- import 'prismjs/components/prism-javascript';
2
1
  export default function DevPanel(): import("react/jsx-runtime").JSX.Element;
package/dist/devPanel.js CHANGED
@@ -1,9 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import React, { useState, useEffect, useRef } from 'react';
2
+ import { useState, useEffect, useRef } from 'react';
3
3
  import { ShieldCheck, CircleX, ChevronDown, ChevronUp, Bug, AlertTriangle, Info, ArrowLeft, Wifi, Terminal, Route, Globe, ChevronRight, ChevronLeft, Server, TriangleAlert, Eye, Zap } from 'lucide-react';
4
- import Prism from 'prismjs';
5
- import 'prismjs/components/prism-javascript';
6
- Prism.languages.javascript['builtin'] = /\b(window|document|console|navigator|localStorage|sessionStorage|fetch|Promise|setTimeout|setInterval|clearTimeout|clearInterval|requestAnimationFrame|Math|JSON|Object|Array|String|Number|Boolean|Date|RegExp|Error|Map|Set|Symbol|Proxy|Reflect|performance|history|location|screen|crypto|indexedDB|alert|confirm|prompt)\b/;
7
4
  function getCallerSource() {
8
5
  try {
9
6
  const stack = new Error().stack ?? '';
@@ -63,7 +60,7 @@ function Sparkline({ data, color, label, unit }) {
63
60
  return _jsx("circle", { cx: last[0], cy: last[1], r: "2.5", fill: color });
64
61
  })()] }))] })] }));
65
62
  }
66
- function installNetworkInterceptor(onFetch, setFetch, onEventSource, setEventSource, onWebSocket, setWebSocket, onResource, setResource, onBytesClient, onBytesServer) {
63
+ function installNetworkInterceptor(onFetch, setFetch, onEventSource, setEventSource, onWebSocket, setWebSocket, onResource, setResource, rmvResource, onBytesClient, onBytesServer) {
67
64
  if (window.__authtics_network_intercepted__)
68
65
  return;
69
66
  window.__authtics_network_intercepted__ = true;
@@ -221,23 +218,60 @@ function installNetworkInterceptor(onFetch, setFetch, onEventSource, setEventSou
221
218
  };
222
219
  window.EventSource.prototype = OriginalEventSource.prototype;
223
220
  Object.assign(window.EventSource, OriginalEventSource);
224
- setTimeout(() => {
221
+ let usedResourcesSlots = [];
222
+ let beforeResources = [];
223
+ let currentResources = [];
224
+ setInterval(() => {
225
+ beforeResources = currentResources;
226
+ currentResources = [];
225
227
  const queryImg = document.querySelectorAll('img');
226
228
  const queryScript = document.querySelectorAll('script');
227
229
  const queryLink = document.querySelectorAll('link');
228
230
  queryImg.forEach((img) => {
229
- if (img.src)
230
- onResource({ url: img.src, type: 'img', id: fetchId++ });
231
+ if (img.src) {
232
+ fetchId++;
233
+ let savedFetchId = fetchId;
234
+ if (!usedResourcesSlots.includes({ url: img.src, type: 'img', id: savedFetchId }))
235
+ onResource({ url: img.src, type: 'img', id: savedFetchId });
236
+ currentResources.push({ url: img.src, type: 'img', id: savedFetchId });
237
+ if (usedResourcesSlots.includes({ url: img.src, type: 'img', id: savedFetchId }))
238
+ setResource({ url: img.src, type: 'img', id: savedFetchId });
239
+ if (!usedResourcesSlots.includes({ url: img.src, type: 'img', id: savedFetchId }))
240
+ usedResourcesSlots.push({ url: img.src, type: 'img', id: savedFetchId });
241
+ }
231
242
  });
232
243
  queryScript.forEach((script) => {
233
- if (script.src)
234
- onResource({ url: script.src, type: 'script', id: fetchId++ });
244
+ if (script.src) {
245
+ fetchId++;
246
+ let savedFetchId = fetchId;
247
+ if (!usedResourcesSlots.includes({ url: script.src, type: 'script', id: savedFetchId }))
248
+ onResource({ url: script.src, type: 'script', id: savedFetchId });
249
+ currentResources.push({ url: script.src, type: 'script', id: savedFetchId });
250
+ if (usedResourcesSlots.includes({ url: script.src, type: 'script', id: savedFetchId }))
251
+ setResource({ url: script.src, type: 'script', id: savedFetchId });
252
+ if (!usedResourcesSlots.includes({ url: script.src, type: 'script', id: savedFetchId }))
253
+ usedResourcesSlots.push({ url: script.src, type: 'script', id: savedFetchId });
254
+ }
235
255
  });
236
256
  queryLink.forEach((link) => {
237
- if (link.href)
238
- onResource({ url: link.href, type: 'link', id: fetchId++ });
257
+ if (link.href) {
258
+ fetchId++;
259
+ let savedFetchId = fetchId;
260
+ if (!usedResourcesSlots.includes({ url: link.href, type: 'link', id: savedFetchId }))
261
+ onResource({ url: link.href, type: 'link', id: savedFetchId });
262
+ currentResources.push({ url: link.href, type: 'link', id: savedFetchId });
263
+ if (usedResourcesSlots.includes({ url: link.href, type: 'link', id: savedFetchId }))
264
+ setResource({ url: link.href, type: 'link', id: savedFetchId });
265
+ if (!usedResourcesSlots.includes({ url: link.href, type: 'link', id: savedFetchId }))
266
+ usedResourcesSlots.push({ url: link.href, type: 'link', id: savedFetchId });
267
+ }
239
268
  });
240
- }, 5000);
269
+ beforeResources.forEach((resource) => {
270
+ if (!currentResources.includes(resource)) {
271
+ rmvResource(resource);
272
+ }
273
+ });
274
+ }, 250);
241
275
  }
242
276
  function installConsoleInterceptor() {
243
277
  if (window.__authtics_intercepted__)
@@ -260,7 +294,7 @@ function installConsoleInterceptor() {
260
294
  });
261
295
  }
262
296
  function SecuredTab() {
263
- return (_jsxs("div", { style: { display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', padding: '8px 10px', textAlign: 'center', gap: '8px' }, children: [_jsx(CircleX, { size: 32, color: 'red' }), _jsx("span", { style: { color: 'red', fontSize: 24 }, children: "Tab Isn't Accessible" }), _jsx("span", { style: { color: 'red', fontSize: 12 }, children: "To access this tab, you need to set \"dat\" in the Authtics Host config to set restriction and then restart." })] }));
297
+ return (_jsxs("div", { style: { display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', padding: '8px 10px', textAlign: 'center', gap: '8px' }, children: [_jsx(CircleX, { size: 32, color: 'red' }), _jsx("span", { style: { color: 'red', fontSize: 24 }, children: "This Tab Is Currently Not Accessible" }), _jsx("span", { style: { color: 'red', fontSize: 12 }, children: "To access this tab, you need to set \"dat\" in the Authtics Host config to set restriction and then restart." })] }));
264
298
  }
265
299
  function PanelButton({ onClick, onClick2, children, style, fullWidth, disabled }) {
266
300
  const [hovered, setHovered] = useState(false);
@@ -305,31 +339,24 @@ export default function DevPanel() {
305
339
  const [clientInfoOpen, setClientInfoOpen] = useState(false);
306
340
  const [aboutHostOpen, setAboutHostOpen] = useState(false);
307
341
  const [serverInfoOpen, setServerInfoOpen] = useState(false);
308
- const [siteInspectOpen, setSiteInspectOpen] = useState(false);
309
342
  const [hasIssue, setHasIssue] = useState(false);
310
343
  const [ping__, setPing__] = useState(0);
311
344
  const [networkFetches, setNetworkFetches] = useState([]);
312
345
  const [eventSources, setEventSources] = useState([]);
313
- const [usersPaused, setUsersPaused] = useState(false);
314
346
  const [usersPausedRealInfo, setUsersPausedRealInfo] = useState(false);
315
347
  const [webSockets, setWebSockets] = useState([]);
316
348
  const [resourcesFound, setResourcesFound] = useState([]);
317
349
  const [status, setStatus] = useState(200);
318
- const [code, setCode] = useState('');
319
350
  const [pathName, setPathName] = useState(undefined);
320
351
  const [hostName, setHostName] = useState(undefined);
321
352
  const [protocol, setProtocol] = useState(undefined);
322
353
  const [path, setPath] = useState(undefined);
323
- const contextMenuTimeoutMobile = useRef(undefined);
324
- const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 });
325
- const [contextMenuShown, setContextMenuShown] = useState(false);
326
354
  const [isSsr, setIsSsr] = useState(false);
327
355
  const datRestrictionMissingRef = useRef(true);
328
356
  const cpuUsage = useRef(0);
329
357
  const heapUsage = useRef(0);
330
358
  const [datMatch, setDatMatch] = useState(false);
331
359
  const [compilerType, setCompilerType] = useState("?");
332
- const [errorDetail, setErrorDetail] = useState(undefined);
333
360
  const [httpVersion, setHttpVersion] = useState("v?.?");
334
361
  const [errorBoxOpenable, setErrorBoxOpenable] = useState(false);
335
362
  const [uptime, setUptime] = useState("00:00:00:00");
@@ -339,20 +366,19 @@ export default function DevPanel() {
339
366
  const [token, setToken] = useState(null);
340
367
  const [tokenLength, setTokenLength] = useState(0);
341
368
  const [tokenHidden, setTokenHidden] = useState(true);
342
- const [consoleInputFocused, setConsoleInputFocused] = useState(false);
343
- const consoleInputRef = useRef(null);
344
- const overlayRef = useRef(null);
345
369
  const fpsSpanRef = useRef(null);
346
370
  const frameCount = useRef(0);
347
371
  const frames = useRef(0);
348
372
  const consoleScrollRef = useRef(null);
349
373
  const [isAtBottom, setIsAtBottom] = useState(true);
350
374
  const [datRestrictionMissing, setDatRestrictionMissing] = useState(true);
351
- const [pos, setPos] = React.useState({ x: 20, y: 20 });
352
- const [dragging, setDragging] = React.useState(false);
353
- const offset = React.useRef({ x: 0, y: 0 });
354
- const [selected, setSelected] = React.useState(null);
355
- const [rootEl, setRootEl] = useState(null);
375
+ const cookie = {
376
+ set: (k, v) => document.cookie = `${k}=${v}; path=/`,
377
+ get: (k) => Object.fromEntries(document.cookie.split(";")
378
+ .filter(Boolean)
379
+ .map(c => c.trim().split("=")))[k],
380
+ del: (k) => document.cookie = `${k}=; path=/; max-age=0`
381
+ };
356
382
  const [doc, setDoc] = useState(null);
357
383
  const [filters, setFilters] = useState({
358
384
  Log: true, Info: true, Warn: true, Error: true, Debug: false
@@ -381,7 +407,7 @@ export default function DevPanel() {
381
407
  const resp = await fetch('/__authtics_host_apis__/get-file-by-pathname', {
382
408
  method: 'POST',
383
409
  headers: { 'Content-Type': 'application/json' },
384
- body: JSON.stringify({ pathname: window.location.pathname, dat: localStorage.getItem('dat') })
410
+ body: JSON.stringify({ pathname: window.location.pathname, })
385
411
  });
386
412
  if (resp.status === 200) {
387
413
  const data = await resp.json();
@@ -392,7 +418,7 @@ export default function DevPanel() {
392
418
  const resp = await fetch('/__authtics_host_apis__/get-dat-matching', {
393
419
  method: 'POST',
394
420
  headers: { 'Content-Type': 'application/json' },
395
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
421
+ body: JSON.stringify({})
396
422
  });
397
423
  if (resp.status === 200) {
398
424
  const data = await resp.json();
@@ -400,13 +426,12 @@ export default function DevPanel() {
400
426
  const resp3 = await fetch('/__authtics_host_apis__/is-users-paused', {
401
427
  method: 'POST',
402
428
  headers: { 'Content-Type': 'application/json' },
403
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
429
+ body: JSON.stringify({})
404
430
  });
405
431
  let paused = false;
406
432
  if (resp3.status === 200) {
407
433
  const data = await resp3.json();
408
434
  paused = data.paused;
409
- setUsersPaused(paused);
410
435
  setUsersPausedRealInfo(data.realInfo);
411
436
  }
412
437
  if (!data.isMatching && !paused) {
@@ -415,7 +440,7 @@ export default function DevPanel() {
415
440
  const resp2 = await fetch('/__authtics_host_apis__/get-dat-restriction-missing', {
416
441
  method: 'POST',
417
442
  headers: { 'Content-Type': 'application/json' },
418
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
443
+ body: JSON.stringify({})
419
444
  });
420
445
  if (resp2.status === 200) {
421
446
  const data = await resp2.json();
@@ -430,7 +455,7 @@ export default function DevPanel() {
430
455
  const resp = await fetch('/__authtics_host_apis__/get-is-ssr', {
431
456
  method: 'POST',
432
457
  headers: { 'Content-Type': 'application/json' },
433
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
458
+ body: JSON.stringify({})
434
459
  });
435
460
  if (resp.status === 200) {
436
461
  const data = await resp.json();
@@ -441,7 +466,7 @@ export default function DevPanel() {
441
466
  const resp = await fetch('/__authtics_host_apis__/get-cpu_memory', {
442
467
  method: 'POST',
443
468
  headers: { 'Content-Type': 'application/json' },
444
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
469
+ body: JSON.stringify({})
445
470
  });
446
471
  if (resp.status === 200) {
447
472
  const data = await resp.json();
@@ -453,7 +478,7 @@ export default function DevPanel() {
453
478
  const resp = await fetch('/__authtics_host_apis__/get-host-ver', {
454
479
  method: 'POST',
455
480
  headers: { 'Content-Type': 'application/json' },
456
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
481
+ body: JSON.stringify({})
457
482
  });
458
483
  if (resp.status === 200) {
459
484
  const data = await resp.json();
@@ -464,7 +489,7 @@ export default function DevPanel() {
464
489
  const resp = await fetch('/__authtics_host_apis__/get-compiler', {
465
490
  method: 'POST',
466
491
  headers: { 'Content-Type': 'application/json' },
467
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
492
+ body: JSON.stringify({})
468
493
  });
469
494
  if (resp.status === 200) {
470
495
  const data = await resp.json();
@@ -475,7 +500,7 @@ export default function DevPanel() {
475
500
  const resp = await fetch('/__authtics_host_apis__/get-connection', {
476
501
  method: 'POST',
477
502
  headers: { 'Content-Type': 'application/json' },
478
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
503
+ body: JSON.stringify({})
479
504
  });
480
505
  if (resp.status === 200) {
481
506
  const data = await resp.json();
@@ -494,7 +519,7 @@ export default function DevPanel() {
494
519
  const resp = await fetch('/__authtics_host_apis__/get-user-settings', {
495
520
  method: 'POST',
496
521
  headers: { 'Content-Type': 'application/json' },
497
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
522
+ body: JSON.stringify({})
498
523
  });
499
524
  if (resp.status === 200) {
500
525
  const data = await resp.json();
@@ -505,7 +530,7 @@ export default function DevPanel() {
505
530
  const resp = await fetch('/__authtics_host_apis__/get-server-info', {
506
531
  method: 'POST',
507
532
  headers: { 'Content-Type': 'application/json' },
508
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
533
+ body: JSON.stringify({})
509
534
  });
510
535
  if (resp.status === 200) {
511
536
  const data = await resp.json();
@@ -532,30 +557,18 @@ export default function DevPanel() {
532
557
  }, 250);
533
558
  }, 250);
534
559
  }, []);
535
- const datTouchStart = (e) => {
536
- e.preventDefault();
537
- setCursorPosition({ x: e.clientX || e.touches[0].clientX, y: e.clientY || e.touches[0].clientY });
538
- contextMenuTimeoutMobile.current = setTimeout(() => {
539
- setContextMenuShown(true);
540
- clearTimeout(contextMenuTimeoutMobile.current);
541
- }, 1000);
542
- };
543
- const datTouchEnd = (e) => {
544
- e.preventDefault();
545
- clearTimeout(contextMenuTimeoutMobile.current);
546
- };
547
560
  const restart = async () => {
548
- const resp = await fetch('/__authtics_host_apis__/restart', {
561
+ await fetch('/__authtics_host_apis__/restart', {
549
562
  method: 'POST',
550
563
  headers: { 'Content-Type': 'application/json' },
551
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
564
+ body: JSON.stringify({})
552
565
  });
553
566
  };
554
567
  const shutDown = async () => {
555
- const resp = await fetch('/__authtics_host_apis__/shutdown', {
568
+ await fetch('/__authtics_host_apis__/shutdown', {
556
569
  method: 'POST',
557
570
  headers: { 'Content-Type': 'application/json' },
558
- body: JSON.stringify({ dat: localStorage.getItem('dat') })
571
+ body: JSON.stringify({})
559
572
  });
560
573
  };
561
574
  useEffect(() => {
@@ -584,14 +597,13 @@ export default function DevPanel() {
584
597
  ? '320px'
585
598
  : '320px';
586
599
  useEffect(() => {
587
- const dat = localStorage.getItem('dat');
588
600
  const interval = setInterval(async () => {
589
601
  try {
590
602
  const timeStart = Date.now();
591
603
  const resp = await fetch('/__authtics_host_apis__/ping', {
592
604
  method: 'POST',
593
605
  headers: { 'Content-Type': 'application/json' },
594
- body: JSON.stringify({ dat })
606
+ body: JSON.stringify({})
595
607
  });
596
608
  if (resp.status === 200) {
597
609
  const data = await resp.json();
@@ -622,7 +634,7 @@ export default function DevPanel() {
622
634
  }, []);
623
635
  useEffect(() => {
624
636
  installConsoleInterceptor();
625
- installNetworkInterceptor((f) => setNetworkFetches(prev => [...prev.slice(-49), f]), (f) => setNetworkFetches(prev => prev.map(p => p.id === f.id ? f : p)), (f) => setEventSources(prev => [...prev.slice(-49), f]), (f) => setEventSources(prev => prev.map(p => p.id === f.id ? f : p)), (f) => setWebSockets(prev => [...prev.slice(-49), f]), (f) => setWebSockets(prev => prev.map(p => p.id === f.id ? f : p)), (f) => setResourcesFound(prev => [...prev.slice(-49), f]), (f) => setResourcesFound(prev => prev.map(p => p.id === f.id ? f : p)), (sent) => {
637
+ installNetworkInterceptor((f) => setNetworkFetches(prev => [...prev.slice(-49), f]), (f) => setNetworkFetches(prev => prev.map(p => p.id === f.id ? f : p)), (f) => setEventSources(prev => [...prev.slice(-49), f]), (f) => setEventSources(prev => prev.map(p => p.id === f.id ? f : p)), (f) => setWebSockets(prev => [...prev.slice(-49), f]), (f) => setWebSockets(prev => prev.map(p => p.id === f.id ? f : p)), (f) => setResourcesFound(prev => [...prev.slice(-49), f]), (f) => setResourcesFound(prev => prev.map(p => p.id === f.id ? f : p)), (f) => setResourcesFound(prev => prev.filter(p => p.id !== f.id)), (sent) => {
626
638
  pendingSent.current += sent;
627
639
  }, (received) => {
628
640
  pendingReceived.current += received;
@@ -634,12 +646,11 @@ export default function DevPanel() {
634
646
  setHasIssue(true);
635
647
  setErrorMsgs(prev => [...prev, detail.message]);
636
648
  setErrorBoxOpen(true);
637
- setErrorDetail(detail.source);
638
649
  }
639
650
  ;
640
651
  };
641
652
  try {
642
- const existingToken = localStorage.getItem('dat');
653
+ const existingToken = cookie.get('dat');
643
654
  if (existingToken) {
644
655
  setToken(existingToken);
645
656
  let length_ = existingToken?.split('');
@@ -650,7 +661,13 @@ export default function DevPanel() {
650
661
  else {
651
662
  const newToken = generateToken();
652
663
  try {
653
- localStorage.setItem('dat', newToken);
664
+ let localStorageToken;
665
+ try {
666
+ localStorageToken = localStorage.getItem('dat');
667
+ }
668
+ catch (e) {
669
+ }
670
+ cookie.set('dat', localStorageToken || newToken);
654
671
  setToken(newToken);
655
672
  let length_ = newToken?.split('');
656
673
  let length;
@@ -738,23 +755,12 @@ export default function DevPanel() {
738
755
  };
739
756
  __();
740
757
  }, []);
741
- const showSelfConsoleLog = (message) => {
742
- const event = window.dispatchEvent(new CustomEvent('authtics:log', {
743
- detail: {
744
- type: "Eval",
745
- message: message,
746
- time: Date.now(),
747
- source: "console.js"
748
- }
749
- }));
750
- };
751
758
  const pause_Resume_Users = async () => {
752
759
  if (usersPausedRealInfo) {
753
760
  const resp = await fetch('/__authtics_host_apis__/set-users-paused', {
754
761
  method: 'POST',
755
762
  headers: { 'Content-Type': 'application/json' },
756
763
  body: JSON.stringify({
757
- dat: localStorage.getItem('dat'),
758
764
  paused: false
759
765
  })
760
766
  });
@@ -767,7 +773,6 @@ export default function DevPanel() {
767
773
  method: 'POST',
768
774
  headers: { 'Content-Type': 'application/json' },
769
775
  body: JSON.stringify({
770
- dat: localStorage.getItem('dat'),
771
776
  paused: true
772
777
  })
773
778
  });
@@ -776,10 +781,6 @@ export default function DevPanel() {
776
781
  }
777
782
  }
778
783
  };
779
- if (usersPaused) {
780
- doc?.getElementById('root')?.remove();
781
- window.location.href = '/failed-to-handle';
782
- }
783
784
  return (_jsxs(_Fragment, { children: [_jsx("div", { style: {
784
785
  position: 'absolute',
785
786
  zIndex: 999999,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,30 @@
1
+ declare module "http" {
2
+ interface IncomingMessage {
3
+ ip: string | undefined;
4
+ ipType: number;
5
+ body: any;
6
+ cookies: Record<string, string>;
7
+ ua: string | undefined;
8
+ os: any;
9
+ browser: any;
10
+ dat: string | undefined;
11
+ bodySize: number;
12
+ bodyType: string;
13
+ sentTime: number;
14
+ }
15
+ interface ServerResponse {
16
+ redirect: (url: string) => void;
17
+ html: (content: string) => void;
18
+ json: (content: any) => void;
19
+ text: (content: string) => void;
20
+ file: (path_: string) => void;
21
+ status: (code: number) => ServerResponse;
22
+ reload: () => void;
23
+ setCookie: (name: string, value: string) => void;
24
+ rmvCookie: (name: string) => void;
25
+ }
26
+ }
1
27
  import { defineConfig } from './config.js';
2
28
  import App from './cli.js';
3
- import { Route } from './route.js';
4
- import { RouteMap } from './route.js';
5
- export { App, Route, RouteMap, defineConfig };
29
+ import { Route, RouteMap, Paused } from './route.js';
30
+ export { App, Route, RouteMap, Paused, defineConfig };
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { defineConfig } from './config.js';
2
2
  import App from './cli.js';
3
- import { Route } from './route.js';
4
- import { RouteMap } from './route.js';
5
- export { App, Route, RouteMap, defineConfig };
3
+ import { Route, RouteMap, Paused } from './route.js';
4
+ export { App, Route, RouteMap, Paused, defineConfig };
@@ -1,3 +1,3 @@
1
1
  export type CompilerType = 'esbuild' | 'babel';
2
2
  export declare function findFileUpwards(startDir: string, relativePath: string): string | null;
3
- export declare function renderPage(tsxPath: string, reqUrl?: string, showPanel?: boolean, compiler?: CompilerType, hotReload?: boolean, autoPaging?: boolean, autoPageDir?: string, appDir?: string): Promise<string>;
3
+ export declare function renderPage(tsxPath: string, reqUrl?: string, showPanel?: boolean, compiler?: CompilerType, hotReload?: boolean, autoPaging?: boolean, autoPageDir?: string, appDir?: string, fileHandler?: (f: string, p: string) => void, rmvFileHandler?: (p: string) => void, reqDAT?: string | undefined, configDAT?: string | string[] | undefined): Promise<string>;
@@ -38,9 +38,9 @@ async function buildWithEsbuild(virtualContent, resolveDir, platform) {
38
38
  format: isNode ? 'cjs' : 'iife',
39
39
  platform,
40
40
  jsx: 'automatic',
41
- sourcemap: isNode ? false : 'inline',
41
+ sourcemap: isNode ? false : false,
42
42
  target: isNode ? ['node18'] : ['es2020'],
43
- minify: false,
43
+ minify: true,
44
44
  treeShaking: true,
45
45
  external: isNode
46
46
  ? ['react', 'react-dom', 'react-dom/server', 'react/jsx-runtime', 'react/jsx-dev-runtime', 'node:http',
@@ -48,9 +48,16 @@ async function buildWithEsbuild(virtualContent, resolveDir, platform) {
48
48
  'node:fs',
49
49
  'node:url',
50
50
  'tls',
51
- path.join(__dirname, 'cli.js')]
51
+ path.join(__dirname, 'cli.js'),
52
+ path.join(__dirname, 'config.js'),
53
+ path.join(__dirname, 'renderEngine.js'),
54
+ path.join(__dirname, 'rendererTempFiles.js')]
52
55
  : [
53
- path.join(__dirname, 'cli.js')
56
+ path.join(__dirname, 'cli.js'),
57
+ path.join(__dirname, 'cli.js'),
58
+ path.join(__dirname, 'config.js'),
59
+ path.join(__dirname, 'renderEngine.js'),
60
+ path.join(__dirname, 'rendererTempFiles.js')
54
61
  ],
55
62
  });
56
63
  return result.outputFiles[0].text;
@@ -86,7 +93,7 @@ function resolveTemplate(appDir, autoPageDir, autoPaging) {
86
93
  return nextToCli;
87
94
  }
88
95
  function buildHtml(opts) {
89
- const { pageHtml, clientCode, devPanelContainer, templatePath, hotReload } = opts;
96
+ const { pageHtml, clientCode, devPanelContainer, templatePath, hotReload, fileName } = opts;
90
97
  const hmrScript = hotReload ? HMR_SCRIPT : '';
91
98
  if (templatePath && fs.existsSync(templatePath)) {
92
99
  let template = fs.readFileSync(templatePath, "utf-8");
@@ -94,8 +101,8 @@ function buildHtml(opts) {
94
101
  if (contentTag.test(template)) {
95
102
  template = template.replace(contentTag, `<div id="root">${pageHtml}</div>\n ${devPanelContainer}`);
96
103
  template = template.includes("</body>")
97
- ? template.replace("</body>", ` <script>${clientCode}</script>\n${hmrScript}</body>`)
98
- : template + `\n<script>${clientCode}</script>${hmrScript}`;
104
+ ? template.replace("</body>", ` ${fileName ? `<script src="${fileName}"></script>` : `<script>${clientCode}</script>`}\n${hmrScript}</body>`)
105
+ : template + `\n${fileName ? `<script src="${fileName}"></script>` : `<script>${clientCode}</script>`}\n${hmrScript}`;
99
106
  return template;
100
107
  }
101
108
  console.warn('[authtics] _template.html has no <authtics_host_content /> — using default layout.');
@@ -109,7 +116,7 @@ function buildHtml(opts) {
109
116
  <body>
110
117
  <div id="root">${pageHtml}</div>
111
118
  ${devPanelContainer}
112
- <script>${clientCode}</script>
119
+ ${fileName ? `<script src="${fileName}"></script>` : `<script>${clientCode}</script>`}
113
120
  ${hmrScript}
114
121
  </body>
115
122
  </html>`;
@@ -131,21 +138,13 @@ function isCacheValid(tsxPath, tempPath, serverCjsPath, templatePath, devPanelPa
131
138
  return false;
132
139
  }
133
140
  }
134
- const HMR_SCRIPT = `
135
- <script>
136
- (function() {
137
- const es = new EventSource('/__authtics_hmr__');
138
- es.onmessage = function(e) { if (e.data === 'reload') window.location.reload(); };
139
- es.onerror = function() { setTimeout(function() { window.location.reload(); }, 1000); };
140
- })();
141
- </script>
142
- `;
143
- export async function renderPage(tsxPath, reqUrl, showPanel = true, compiler = 'esbuild', hotReload = false, autoPaging = true, autoPageDir, appDir) {
141
+ const HMR_SCRIPT = `<script>(function(){const es=new EventSource('/hmr');es.onmessage=function(e){if (e.data === 'reload') window.location.reload()};es.onerror=function(){setTimeout(function(){window.location.reload()},1000)};})();</script>`;
142
+ export async function renderPage(tsxPath, reqUrl, showPanel = true, compiler = 'esbuild', hotReload = false, autoPaging = true, autoPageDir, appDir, fileHandler, rmvFileHandler, reqDAT, configDAT) {
144
143
  ensureTempDirs();
145
144
  if (!fs.existsSync(tsxPath)) {
146
145
  throw new Error(`renderPage: source file not found: ${tsxPath}`);
147
146
  }
148
- const usesDevPanel = showPanel && devPanelPath !== null;
147
+ let usesDevPanel = showPanel && devPanelPath !== null;
149
148
  const templatePath = resolveTemplate(appDir, autoPageDir, autoPaging);
150
149
  const tempPath = tempFileForTsx(tsxPath);
151
150
  const serverCjsPath = tempPath.replace(/\.json$/, ".server.cjs");
@@ -191,6 +190,7 @@ export async function renderPage(tsxPath, reqUrl, showPanel = true, compiler = '
191
190
  fs.writeFileSync(serverCjsPath, serverCode, "utf-8");
192
191
  writeTempFile(tempPath, JSON.stringify({ clientCode }));
193
192
  }
193
+ fileHandler ? fileHandler(clientCode, `/${tempPath.substring(tempPath.lastIndexOf('/') + 1).replace(".json", ".js").replace(".tsx_", ".").toLowerCase()}`) : null;
194
194
  const serverModule = await import(`${serverCjsPath}?t=${Date.now()}`);
195
195
  const exports = serverModule.default ?? serverModule;
196
196
  const PageComponent = exports.default ?? exports.Page ?? exports.page ?? null;
@@ -205,5 +205,5 @@ export async function renderPage(tsxPath, reqUrl, showPanel = true, compiler = '
205
205
  const devPanelContainer = usesDevPanel
206
206
  ? `<div id="authtics-dev-panel-root">${devPanelHtml}</div>`
207
207
  : "";
208
- return buildHtml({ pageHtml, clientCode, devPanelContainer, templatePath, hotReload });
208
+ return buildHtml({ pageHtml, clientCode, devPanelContainer, templatePath, hotReload, fileName: `/${tempPath.substring(tempPath.lastIndexOf('/') + 1).replace(".json", ".js").replace(".tsx_", ".").toLowerCase()}` });
209
209
  }
@@ -1,5 +1,6 @@
1
1
  export declare function ensureTempDirs(): void;
2
2
  export declare function tempFileForTsx(tsxPath: string): string;
3
+ export declare function tempFileForDev(): string;
3
4
  export declare function isTempUpToDate(tsxPath: string, tempPath: string): boolean;
4
5
  export declare function writeTempFile(tempPath: string, content: string): void;
5
6
  export declare function readTempFile(tempPath: string): string;
@@ -1,12 +1,15 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  const AUTHTICS_DIR = path.join(process.cwd(), ".authtics_host");
4
+ const DEV_CACHE_DIR = path.join(AUTHTICS_DIR, "dev-cache");
4
5
  const CACHE_DIR = path.join(AUTHTICS_DIR, "cache");
5
6
  export function ensureTempDirs() {
6
7
  if (!fs.existsSync(AUTHTICS_DIR))
7
8
  fs.mkdirSync(AUTHTICS_DIR, { recursive: true });
8
9
  if (!fs.existsSync(CACHE_DIR))
9
10
  fs.mkdirSync(CACHE_DIR, { recursive: true });
11
+ if (!fs.existsSync(DEV_CACHE_DIR))
12
+ fs.mkdirSync(DEV_CACHE_DIR, { recursive: true });
10
13
  }
11
14
  export function tempFileForTsx(tsxPath) {
12
15
  ensureTempDirs();
@@ -14,6 +17,10 @@ export function tempFileForTsx(tsxPath) {
14
17
  const hash = simpleHash(tsxPath);
15
18
  return path.join(CACHE_DIR, `${base}_${hash}.json`);
16
19
  }
20
+ export function tempFileForDev() {
21
+ ensureTempDirs();
22
+ return path.join(DEV_CACHE_DIR, "page.cache.json");
23
+ }
17
24
  export function isTempUpToDate(tsxPath, tempPath) {
18
25
  try {
19
26
  const srcMtime = fs.statSync(tsxPath).mtimeMs;
package/dist/route.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  export declare function RouteMap({ children }: {
2
2
  children?: React.ReactNode;
3
3
  }): import("react/jsx-runtime").JSX.Element;
4
+ export declare function Paused({ page, statusCode }: {
5
+ page: Function;
6
+ statusCode?: number;
7
+ }): import("react/jsx-runtime").JSX.Element;
4
8
  export declare function Route({ page, statusCode, at }: {
5
9
  page: Function;
6
10
  statusCode?: number;
package/dist/route.js CHANGED
@@ -15,20 +15,27 @@ export function RouteMap({ children }) {
15
15
  const childrenToProcess = Array.isArray(childArray.current)
16
16
  ? childArray.current
17
17
  : [childArray.current];
18
+ setCurrentlyAwaiting(false);
18
19
  childrenToProcess.forEach((child) => {
19
- if (child?.props?.at === path) {
20
+ if (child?.type?.name === "Paused") {
21
+ if (window.__paused__ === true) {
22
+ matched.current = child.props;
23
+ }
24
+ }
25
+ if (child?.props?.at === path && !window.__paused__ && !matched.current) {
20
26
  matched.current = child.props;
21
27
  }
22
28
  });
23
- if (!matched.current) {
24
- childrenToProcess.forEach((child) => {
25
- if (child?.props?.at === undefined) {
26
- matched.current = child.props;
27
- setAt404(true);
28
- }
29
- });
30
- }
31
- setCurrentlyAwaiting(false);
29
+ setTimeout(() => {
30
+ if (!matched.current && !window.__paused__) {
31
+ childrenToProcess.forEach((child) => {
32
+ if (child?.props?.at === undefined && child?.type?.name !== "Paused" && !window.__paused__) {
33
+ matched.current = child.props;
34
+ setAt404(true);
35
+ }
36
+ });
37
+ }
38
+ }, 500);
32
39
  }, [path]);
33
40
  useEffect(() => {
34
41
  if (matched.current && !At404) {
@@ -50,6 +57,9 @@ export function RouteMap({ children }) {
50
57
  return _jsx(_Fragment, {});
51
58
  return _jsx(NotFound, {});
52
59
  }
60
+ export function Paused({ page, statusCode }) {
61
+ return (_jsx(_Fragment, {}));
62
+ }
53
63
  export function Route({ page, statusCode, at }) {
54
64
  return (_jsx(_Fragment, {}));
55
65
  }