@lytjs/ssr 6.0.0 → 6.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -109,6 +109,7 @@ var VirtualList = defineComponent({
109
109
  buffer: { type: Number, default: 5 },
110
110
  class: { type: String, default: "" }
111
111
  },
112
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
112
113
  setup(props, { slots }) {
113
114
  const scrollTop = signal(0);
114
115
  const visibleCount = computedSignal(() => {
@@ -142,6 +143,7 @@ var VirtualList = defineComponent({
142
143
  return () => {
143
144
  const items = visibleData().map((item, index) => {
144
145
  const actualIndex = startIndex() + index;
146
+ const slotContent = slots?.default?.({ item, index: actualIndex });
145
147
  return createVNode(
146
148
  "div",
147
149
  {
@@ -149,7 +151,7 @@ var VirtualList = defineComponent({
149
151
  style: `height: ${props.itemHeight}px;`,
150
152
  "data-index": actualIndex
151
153
  },
152
- slots.default?.({ item, index: actualIndex })
154
+ slotContent
153
155
  );
154
156
  });
155
157
  return createVNode(
@@ -183,6 +185,38 @@ var VirtualList = defineComponent({
183
185
  }
184
186
  });
185
187
  var DEFAULT_CHUNK_SIZE = 4096;
188
+ var DEFAULT_TIMEOUT = 3e4;
189
+ var DEFAULT_FALLBACK_HTML = '<div id="lyt-fallback">\u670D\u52A1\u6B63\u5728\u52A0\u8F7D\u4E2D...</div>';
190
+ var StreamTimeoutError = class extends Error {
191
+ constructor(message = "Stream rendering timeout") {
192
+ super(message);
193
+ this.name = "StreamTimeoutError";
194
+ }
195
+ };
196
+ var FlowController = class {
197
+ constructor(maxBytesPerSecond) {
198
+ this.bytesSentInSecond = 0;
199
+ this.lastSecondTimestamp = Date.now();
200
+ this.maxBytesPerSecond = maxBytesPerSecond;
201
+ }
202
+ /**
203
+ * 尝试发送字节,如超出速率则等待
204
+ */
205
+ async waitForRateLimit(byteCount) {
206
+ const now = Date.now();
207
+ if (now - this.lastSecondTimestamp >= 1e3) {
208
+ this.bytesSentInSecond = 0;
209
+ this.lastSecondTimestamp = now;
210
+ }
211
+ if (this.bytesSentInSecond + byteCount > this.maxBytesPerSecond) {
212
+ const waitTime = 1e3 - (now - this.lastSecondTimestamp);
213
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
214
+ this.bytesSentInSecond = 0;
215
+ this.lastSecondTimestamp = Date.now();
216
+ }
217
+ this.bytesSentInSecond += byteCount;
218
+ }
219
+ };
186
220
  var SUSPENSE_TYPE = "Suspense";
187
221
  function isSuspenseVNode(vnode) {
188
222
  return isObject(vnode) && (typeof vnode.type === "object" && vnode.type !== null && "__suspense" in vnode.type || isString(vnode.type) && vnode.type === SUSPENSE_TYPE);
@@ -254,11 +288,32 @@ function renderToStream(vnode, options) {
254
288
  const {
255
289
  chunkSize = DEFAULT_CHUNK_SIZE,
256
290
  onShellReady,
257
- onError
291
+ onError,
292
+ timeout = DEFAULT_TIMEOUT,
293
+ fallbackHtml = DEFAULT_FALLBACK_HTML,
294
+ maxBytesPerSecond,
295
+ errorRecovery = true
258
296
  } = options || {};
259
297
  const encoder = new TextEncoder();
298
+ const flowController = maxBytesPerSecond ? new FlowController(maxBytesPerSecond) : null;
299
+ let timeoutId = null;
260
300
  return new ReadableStream({
261
301
  start(controller) {
302
+ timeoutId = setTimeout(() => {
303
+ try {
304
+ if (errorRecovery) {
305
+ console.warn("Stream rendering timed out, using fallback HTML");
306
+ controller.enqueue(encoder.encode(fallbackHtml));
307
+ controller.close();
308
+ onError?.(new StreamTimeoutError("Stream rendering timed out"));
309
+ } else {
310
+ controller.error(new StreamTimeoutError("Stream rendering timed out"));
311
+ }
312
+ } catch (err) {
313
+ const error = err instanceof Error ? err : new Error(String(err));
314
+ onError?.(error);
315
+ }
316
+ }, timeout);
262
317
  try {
263
318
  const suspenseBoundaryIndex = [];
264
319
  const chunks = collectChunks(vnode, suspenseBoundaryIndex);
@@ -269,29 +324,64 @@ function renderToStream(vnode, options) {
269
324
  const shellHtml = shellChunks.join("");
270
325
  const byteChunks = splitIntoByteChunks(shellHtml, chunkSize);
271
326
  for (const chunk of byteChunks) {
272
- controller.enqueue(encoder.encode(chunk));
327
+ sendChunk(controller, encoder, chunk);
273
328
  }
274
329
  onShellReady?.();
275
330
  const remainingChunks = chunks.slice(shellBoundary);
276
331
  const remainingHtml = remainingChunks.join("");
277
332
  const remainingByteChunks = splitIntoByteChunks(remainingHtml, chunkSize);
278
333
  for (const chunk of remainingByteChunks) {
279
- controller.enqueue(encoder.encode(chunk));
334
+ sendChunk(controller, encoder, chunk);
280
335
  }
281
336
  } else {
282
337
  const byteChunks = splitIntoByteChunks(fullHtml, chunkSize);
283
338
  for (const chunk of byteChunks) {
284
- controller.enqueue(encoder.encode(chunk));
339
+ sendChunk(controller, encoder, chunk);
285
340
  }
286
341
  }
342
+ if (timeoutId) {
343
+ clearTimeout(timeoutId);
344
+ timeoutId = null;
345
+ }
287
346
  controller.close();
288
347
  } catch (err) {
348
+ if (timeoutId) {
349
+ clearTimeout(timeoutId);
350
+ timeoutId = null;
351
+ }
289
352
  const error = err instanceof Error ? err : new Error(String(err));
290
353
  onError?.(error);
291
- controller.error(error);
354
+ if (errorRecovery) {
355
+ try {
356
+ console.warn("Error occurred during stream rendering, using fallback HTML");
357
+ controller.enqueue(encoder.encode(fallbackHtml));
358
+ controller.close();
359
+ } catch (_) {
360
+ controller.error(error);
361
+ }
362
+ } else {
363
+ controller.error(error);
364
+ }
365
+ }
366
+ },
367
+ cancel(reason) {
368
+ if (timeoutId) {
369
+ clearTimeout(timeoutId);
292
370
  }
371
+ console.warn("Stream cancelled:", reason);
293
372
  }
294
373
  });
374
+ function sendChunk(controller, encoder2, chunk) {
375
+ const encoded = encoder2.encode(chunk);
376
+ if (flowController) {
377
+ (async () => {
378
+ await flowController.waitForRateLimit(encoded.length);
379
+ controller.enqueue(encoded);
380
+ })();
381
+ } else {
382
+ controller.enqueue(encoded);
383
+ }
384
+ }
295
385
  }
296
386
  function renderToStreamAsync(vnode, options) {
297
387
  const {
@@ -433,7 +523,12 @@ var DEFAULT_SSG_OPTIONS = {
433
523
  siteName: "LytJS Site",
434
524
  hashMode: false,
435
525
  globalScripts: [],
436
- globalStyles: []
526
+ globalStyles: [],
527
+ isr: {
528
+ revalidate: 60,
529
+ enabled: false,
530
+ fallback: false
531
+ }
437
532
  };
438
533
  function normalizePath(path) {
439
534
  let normalized = path.startsWith("/") ? path : `/${path}`;
@@ -552,6 +647,376 @@ function validatePages(pages) {
552
647
  }
553
648
  return errors;
554
649
  }
650
+ var ISRCacheManager = class {
651
+ constructor() {
652
+ this.cache = /* @__PURE__ */ new Map();
653
+ this.revalidateTasks = /* @__PURE__ */ new Map();
654
+ }
655
+ /**
656
+ * 获取缓存的页面
657
+ */
658
+ get(path) {
659
+ return this.cache.get(path);
660
+ }
661
+ /**
662
+ * 设置缓存
663
+ */
664
+ set(path, html) {
665
+ this.cache.set(path, {
666
+ html,
667
+ timestamp: Date.now(),
668
+ isRevalidating: false
669
+ });
670
+ }
671
+ /**
672
+ * 检查是否需要重新验证
673
+ */
674
+ needsRevalidation(path, revalidateSeconds) {
675
+ const entry = this.cache.get(path);
676
+ if (!entry) return true;
677
+ const age = (Date.now() - entry.timestamp) / 1e3;
678
+ return age > revalidateSeconds && !entry.isRevalidating;
679
+ }
680
+ /**
681
+ * 标记为正在重新生成
682
+ */
683
+ markRevalidating(path) {
684
+ const entry = this.cache.get(path);
685
+ if (entry) {
686
+ entry.isRevalidating = true;
687
+ }
688
+ }
689
+ /**
690
+ * 完成重新生成
691
+ */
692
+ finishRevalidation(path, html) {
693
+ this.set(path, html);
694
+ this.revalidateTasks.delete(path);
695
+ }
696
+ /**
697
+ * 获取正在进行的重新生成任务
698
+ */
699
+ getRevalidateTask(path) {
700
+ return this.revalidateTasks.get(path);
701
+ }
702
+ /**
703
+ * 设置重新生成任务
704
+ */
705
+ setRevalidateTask(path, task) {
706
+ this.revalidateTasks.set(path, task);
707
+ }
708
+ /**
709
+ * 清除过期的缓存
710
+ */
711
+ clearExpired(maxAgeSeconds) {
712
+ const now = Date.now();
713
+ let cleared = 0;
714
+ for (const [path, entry] of this.cache) {
715
+ const age = (now - entry.timestamp) / 1e3;
716
+ if (age > maxAgeSeconds) {
717
+ this.cache.delete(path);
718
+ cleared++;
719
+ }
720
+ }
721
+ return cleared;
722
+ }
723
+ /**
724
+ * 获取缓存统计信息
725
+ */
726
+ getStats() {
727
+ return {
728
+ total: this.cache.size,
729
+ paths: Array.from(this.cache.keys())
730
+ };
731
+ }
732
+ };
733
+ var isrCache = new ISRCacheManager();
734
+ function createISRMiddleware(options) {
735
+ const { staticPages, revalidate = 60, enabled = true, regenerate } = options;
736
+ for (const [path, html] of staticPages) {
737
+ isrCache.set(path, html);
738
+ }
739
+ return async (req, res, next) => {
740
+ if (!enabled) {
741
+ return next();
742
+ }
743
+ let path = req.path;
744
+ if (path.endsWith("/")) {
745
+ path = path + "index.html";
746
+ } else if (!path.endsWith(".html")) {
747
+ path = path + "/index.html";
748
+ }
749
+ const cached = isrCache.get(path);
750
+ if (cached) {
751
+ res.setHeader("Cache-Control", `s-maxage=${revalidate}, stale-while-revalidate`);
752
+ res.setHeader("X-ISR-Cache", "HIT");
753
+ res.setHeader("X-ISR-Timestamp", cached.timestamp.toString());
754
+ res.send(cached.html);
755
+ if (isrCache.needsRevalidation(path, revalidate) && regenerate) {
756
+ isrCache.markRevalidating(path);
757
+ try {
758
+ const newHtml = await regenerate(path);
759
+ isrCache.finishRevalidation(path, newHtml);
760
+ } catch (error) {
761
+ console.error("[ISR] Revalidation failed for", path, error);
762
+ const entry = isrCache.get(path);
763
+ if (entry) {
764
+ entry.isRevalidating = false;
765
+ }
766
+ }
767
+ }
768
+ } else {
769
+ if (regenerate) {
770
+ try {
771
+ const html = await regenerate(path);
772
+ isrCache.set(path, html);
773
+ res.setHeader("X-ISR-Cache", "MISS");
774
+ res.send(html);
775
+ } catch (error) {
776
+ next(error);
777
+ }
778
+ } else {
779
+ next();
780
+ }
781
+ }
782
+ };
783
+ }
784
+ async function revalidateOnDemand(path, regenerate) {
785
+ const existingTask = isrCache.getRevalidateTask(path);
786
+ if (existingTask) {
787
+ return existingTask;
788
+ }
789
+ const task = (async () => {
790
+ isrCache.markRevalidating(path);
791
+ try {
792
+ const html = await regenerate();
793
+ isrCache.finishRevalidation(path, html);
794
+ return html;
795
+ } catch (error) {
796
+ const entry = isrCache.get(path);
797
+ if (entry) {
798
+ entry.isRevalidating = false;
799
+ }
800
+ throw error;
801
+ }
802
+ })();
803
+ isrCache.setRevalidateTask(path, task);
804
+ return task;
805
+ }
806
+ function getISRCacheStats() {
807
+ return isrCache.getStats();
808
+ }
809
+ function clearISRCache(path, maxAge) {
810
+ if (path) {
811
+ const cache = isrCache.cache;
812
+ cache.delete(path);
813
+ } else if (maxAge) {
814
+ isrCache.clearExpired(maxAge);
815
+ }
816
+ }
817
+ var ServerComponentStateManager = class {
818
+ constructor() {
819
+ /** 注册的组件 */
820
+ this.registrations = /* @__PURE__ */ new Map();
821
+ /** 正在执行的预取请求 */
822
+ this.pendingPrefetches = /* @__PURE__ */ new Map();
823
+ /** 组件初始化状态 */
824
+ this.initializationStates = /* @__PURE__ */ new Map();
825
+ }
826
+ /**
827
+ * 注册服务端组件
828
+ */
829
+ register(name, registration) {
830
+ this.registrations.set(name, registration);
831
+ }
832
+ /**
833
+ * 取消注册服务端组件
834
+ */
835
+ unregister(name) {
836
+ this.registrations.delete(name);
837
+ }
838
+ /**
839
+ * 获取已注册的组件
840
+ */
841
+ getRegistration(name) {
842
+ return this.registrations.get(name);
843
+ }
844
+ /**
845
+ * 初始化服务端组件
846
+ */
847
+ async initializeComponent(name, context) {
848
+ const registration = this.registrations.get(name);
849
+ if (!registration) {
850
+ throw new Error(`Server component ${name} not registered`);
851
+ }
852
+ if (this.initializationStates.get(name)) {
853
+ return;
854
+ }
855
+ if (registration.onServerInit) {
856
+ await Promise.resolve(registration.onServerInit(context));
857
+ }
858
+ this.initializationStates.set(name, true);
859
+ }
860
+ /**
861
+ * 清理服务端组件
862
+ */
863
+ async cleanupComponent(name, context) {
864
+ const registration = this.registrations.get(name);
865
+ if (!registration) {
866
+ return;
867
+ }
868
+ if (registration.onServerCleanup) {
869
+ await Promise.resolve(registration.onServerCleanup(context));
870
+ }
871
+ this.initializationStates.delete(name);
872
+ }
873
+ /**
874
+ * 预取组件数据(带缓存)
875
+ */
876
+ async prefetchComponentData(name, context, cacheKey) {
877
+ const registration = this.registrations.get(name);
878
+ if (!registration || !registration.prefetch) {
879
+ return { data: {} };
880
+ }
881
+ const key = cacheKey || `${name}-${JSON.stringify(context)}`;
882
+ const existing = this.pendingPrefetches.get(key);
883
+ if (existing) {
884
+ return existing;
885
+ }
886
+ const promise = registration.prefetch(context).finally(() => {
887
+ this.pendingPrefetches.delete(key);
888
+ });
889
+ this.pendingPrefetches.set(key, promise);
890
+ return promise;
891
+ }
892
+ /**
893
+ * 清除所有缓存
894
+ */
895
+ clearAll() {
896
+ this.registrations.clear();
897
+ this.pendingPrefetches.clear();
898
+ this.initializationStates.clear();
899
+ }
900
+ };
901
+ var stateManager = new ServerComponentStateManager();
902
+ function registerServerComponent(name, registration) {
903
+ stateManager.register(name, registration);
904
+ }
905
+ function unregisterServerComponent(name) {
906
+ stateManager.unregister(name);
907
+ }
908
+ function collectPrefetchComponents(vnode) {
909
+ const components = [];
910
+ collectComponentsRecursive(vnode, components);
911
+ return components;
912
+ }
913
+ function collectComponentsRecursive(vnode, result) {
914
+ if (!isObject(vnode)) {
915
+ return;
916
+ }
917
+ const node = vnode;
918
+ if (isArray(vnode)) {
919
+ for (const child of vnode) {
920
+ collectComponentsRecursive(child, result);
921
+ }
922
+ return;
923
+ }
924
+ if (isFunction(node.type)) {
925
+ const compName = node.type.name;
926
+ if (compName && stateManager.getRegistration(compName)) {
927
+ if (!result.includes(compName)) {
928
+ result.push(compName);
929
+ }
930
+ }
931
+ }
932
+ const children = node.children;
933
+ if (isArray(children)) {
934
+ for (const child of children) {
935
+ collectComponentsRecursive(child, result);
936
+ }
937
+ } else if (isObject(children)) {
938
+ collectComponentsRecursive(children, result);
939
+ }
940
+ }
941
+ async function prefetchAllComponents(components, context) {
942
+ const results = {};
943
+ const promises = [];
944
+ for (const name of components) {
945
+ const promise = stateManager.prefetchComponentData(name, context).then((result) => {
946
+ results[name] = result;
947
+ }).catch((err) => {
948
+ console.warn(`Prefetch failed for component ${name}`, err);
949
+ results[name] = { data: {} };
950
+ });
951
+ promises.push(promise);
952
+ }
953
+ await Promise.all(promises);
954
+ return results;
955
+ }
956
+ function safeSerializeState(state) {
957
+ const seen = /* @__PURE__ */ new WeakSet();
958
+ return JSON.stringify(state, (_key, value) => {
959
+ if (typeof value === "object" && value !== null) {
960
+ if (seen.has(value)) {
961
+ return "[Circular]";
962
+ }
963
+ seen.add(value);
964
+ }
965
+ if (value instanceof Date) {
966
+ return { __type: "Date", value: value.toISOString() };
967
+ }
968
+ if (value instanceof RegExp) {
969
+ return { __type: "RegExp", source: value.source, flags: value.flags };
970
+ }
971
+ if (value instanceof Set) {
972
+ return { __type: "Set", values: Array.from(value) };
973
+ }
974
+ if (value instanceof Map) {
975
+ return { __type: "Map", entries: Array.from(value.entries()) };
976
+ }
977
+ return value;
978
+ });
979
+ }
980
+ function safeDeserializeState(serialized) {
981
+ return JSON.parse(serialized, (_key, value) => {
982
+ if (typeof value === "object" && value !== null && "__type" in value) {
983
+ const typedValue = value;
984
+ switch (typedValue.__type) {
985
+ case "Date":
986
+ return new Date(typedValue.value);
987
+ case "RegExp":
988
+ return new RegExp(typedValue.source, typedValue.flags);
989
+ case "Set":
990
+ return new Set(typedValue.values);
991
+ case "Map":
992
+ return new Map(typedValue.entries);
993
+ }
994
+ }
995
+ return value;
996
+ });
997
+ }
998
+ function buildDehydratedState(prefetchResults) {
999
+ const state = {};
1000
+ for (const [name, result] of Object.entries(prefetchResults)) {
1001
+ state[name] = {
1002
+ componentName: name,
1003
+ props: {},
1004
+ data: result.data
1005
+ };
1006
+ }
1007
+ return state;
1008
+ }
1009
+ function ServerComponent(options) {
1010
+ return function(target) {
1011
+ registerServerComponent(options.name, {
1012
+ name: options.name,
1013
+ render: target.render || (() => ({ type: "div" })),
1014
+ prefetch: options.prefetch,
1015
+ onServerInit: options.onInit,
1016
+ onServerCleanup: options.onCleanup
1017
+ });
1018
+ };
1019
+ }
555
1020
  var HYDRATE_ATTR = "data-hydrate";
556
1021
  var HYDRATE_STRATEGY_ATTR = "data-hydrate-strategy";
557
1022
  var DEHYDRATED_STATE_ID = "__LYT_DEHYDRATED_STATE__";
@@ -717,6 +1182,6 @@ function createDehydratedState(vnode, initialState) {
717
1182
  return `<script id="${DEHYDRATED_STATE_ID}" type="application/json">${safeJson}</script>`;
718
1183
  }
719
1184
 
720
- export { VirtualList, createDehydratedState, createHydrationMarkers, render_default as default, generateRouteManifest, generateStaticPages, getHydrationStrategy, renderToHtml, renderToStream, renderToStreamAsync, renderToStreamEnhanced, renderToString, resetComponentIdCounter, serializeHydrationState, validatePages, writeStaticFiles };
1185
+ export { ServerComponent, VirtualList, buildDehydratedState, clearISRCache, collectPrefetchComponents, createDehydratedState, createHydrationMarkers, createISRMiddleware, render_default as default, generateRouteManifest, generateStaticPages, getHydrationStrategy, getISRCacheStats, prefetchAllComponents, registerServerComponent, renderToHtml, renderToStream, renderToStreamAsync, renderToStreamEnhanced, renderToString, resetComponentIdCounter, revalidateOnDemand, safeDeserializeState, safeSerializeState, serializeHydrationState, stateManager, unregisterServerComponent, validatePages, writeStaticFiles };
721
1186
  //# sourceMappingURL=index.mjs.map
722
1187
  //# sourceMappingURL=index.mjs.map