hadars 0.2.0 → 0.2.1

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.
@@ -0,0 +1,1394 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/cloudflare.ts
31
+ var cloudflare_exports = {};
32
+ __export(cloudflare_exports, {
33
+ createCloudflareHandler: () => createCloudflareHandler
34
+ });
35
+ module.exports = __toCommonJS(cloudflare_exports);
36
+ var import_react = require("react");
37
+
38
+ // src/utils/cookies.ts
39
+ var parseCookies = (cookieString) => {
40
+ const cookies = {};
41
+ if (!cookieString) {
42
+ return cookies;
43
+ }
44
+ const pairs = cookieString.split(";");
45
+ for (const pair of pairs) {
46
+ const index = pair.indexOf("=");
47
+ if (index > -1) {
48
+ const key = pair.slice(0, index).trim();
49
+ const value = pair.slice(index + 1).trim();
50
+ try {
51
+ cookies[key] = decodeURIComponent(value);
52
+ } catch {
53
+ cookies[key] = value;
54
+ }
55
+ }
56
+ }
57
+ return cookies;
58
+ };
59
+
60
+ // src/utils/request.tsx
61
+ var parseRequest = (request) => {
62
+ const url = new URL(request.url);
63
+ const cookies = request.headers.get("Cookie") || "";
64
+ const cookieRecord = parseCookies(cookies);
65
+ return Object.assign(request, { pathname: url.pathname, search: url.search, location: url.pathname + url.search, cookies: cookieRecord });
66
+ };
67
+
68
+ // src/utils/proxyHandler.tsx
69
+ var cloneHeaders = (headers) => {
70
+ return new Headers(headers);
71
+ };
72
+ var getCORSHeaders = (req) => {
73
+ const origin = req.headers.get("Origin") || "*";
74
+ return {
75
+ "Access-Control-Allow-Origin": origin,
76
+ "Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
77
+ "Access-Control-Allow-Headers": req.headers.get("Access-Control-Request-Headers") || "*",
78
+ "Access-Control-Allow-Credentials": "true"
79
+ };
80
+ };
81
+ var createProxyHandler = (options) => {
82
+ const { proxy, proxyCORS } = options;
83
+ if (!proxy) {
84
+ return () => void 0;
85
+ }
86
+ if (typeof proxy === "function") {
87
+ return async (req) => {
88
+ if (req.method === "OPTIONS" && options.proxyCORS) {
89
+ return new Response(null, {
90
+ status: 204,
91
+ headers: getCORSHeaders(req)
92
+ });
93
+ }
94
+ const res = await proxy(req);
95
+ if (res && proxyCORS) {
96
+ const modifiedHeaders = new Headers(res.headers);
97
+ Object.entries(getCORSHeaders(req)).forEach(([key, value]) => {
98
+ modifiedHeaders.set(key, value);
99
+ });
100
+ return new Response(res.body, {
101
+ status: res.status,
102
+ statusText: res.statusText,
103
+ headers: modifiedHeaders
104
+ });
105
+ }
106
+ return res || void 0;
107
+ };
108
+ }
109
+ const proxyRules = Object.entries(proxy).sort((a, b) => b[0].length - a[0].length);
110
+ return async (req) => {
111
+ for (const [path, target] of proxyRules) {
112
+ if (req.pathname.startsWith(path)) {
113
+ if (req.method === "OPTIONS" && proxyCORS) {
114
+ return new Response(null, {
115
+ status: 204,
116
+ headers: getCORSHeaders(req)
117
+ });
118
+ }
119
+ const targetURL = new URL(target);
120
+ targetURL.pathname = targetURL.pathname.replace(/\/$/, "") + req.pathname.slice(path.length);
121
+ targetURL.search = req.search;
122
+ const sendHeaders = cloneHeaders(req.headers);
123
+ sendHeaders.set("Host", targetURL.host);
124
+ const hasBody = !["GET", "HEAD"].includes(req.method);
125
+ const proxyReq = new Request(targetURL.toString(), {
126
+ method: req.method,
127
+ headers: sendHeaders,
128
+ body: hasBody ? req.body : void 0,
129
+ redirect: "follow",
130
+ // Node.js (undici) requires duplex:'half' when body is a ReadableStream
131
+ ...hasBody ? { duplex: "half" } : {}
132
+ });
133
+ const res = await fetch(proxyReq);
134
+ const body = await res.arrayBuffer();
135
+ const clonedRes = new Headers(res.headers);
136
+ clonedRes.delete("content-length");
137
+ clonedRes.delete("content-encoding");
138
+ if (proxyCORS) {
139
+ Object.entries(getCORSHeaders(req)).forEach(([key, value]) => {
140
+ clonedRes.set(key, value);
141
+ });
142
+ }
143
+ return new Response(body, {
144
+ status: res.status,
145
+ statusText: res.statusText,
146
+ headers: clonedRes
147
+ });
148
+ }
149
+ }
150
+ return void 0;
151
+ };
152
+ };
153
+
154
+ // src/slim-react/types.ts
155
+ var SLIM_ELEMENT = Symbol.for("react.element");
156
+ var REACT19_ELEMENT = Symbol.for("react.transitional.element");
157
+ var FRAGMENT_TYPE = Symbol.for("react.fragment");
158
+ var SUSPENSE_TYPE = Symbol.for("react.suspense");
159
+
160
+ // src/slim-react/jsx.ts
161
+ function createElement(type, props, ...children) {
162
+ const normalizedProps = { ...props || {} };
163
+ if (children.length === 1) {
164
+ normalizedProps.children = children[0];
165
+ } else if (children.length > 1) {
166
+ normalizedProps.children = children;
167
+ }
168
+ const key = normalizedProps.key ?? null;
169
+ delete normalizedProps.key;
170
+ return {
171
+ $$typeof: SLIM_ELEMENT,
172
+ type,
173
+ props: normalizedProps,
174
+ key
175
+ };
176
+ }
177
+
178
+ // src/slim-react/renderContext.ts
179
+ var MAP_KEY = "__slimReactContextMap";
180
+ var _g = globalThis;
181
+ if (!("__slimReactContextMap" in _g)) _g[MAP_KEY] = null;
182
+ function swapContextMap(map) {
183
+ const prev = _g[MAP_KEY];
184
+ _g[MAP_KEY] = map;
185
+ return prev;
186
+ }
187
+ function captureMap() {
188
+ return _g[MAP_KEY];
189
+ }
190
+ var UNSUSPEND_KEY = "__hadarsUnsuspend";
191
+ function captureUnsuspend() {
192
+ return _g[UNSUSPEND_KEY];
193
+ }
194
+ function restoreUnsuspend(u) {
195
+ _g[UNSUSPEND_KEY] = u;
196
+ }
197
+ function getContextValue(context) {
198
+ const map = _g[MAP_KEY];
199
+ if (map && map.has(context)) return map.get(context);
200
+ const c = context;
201
+ return "_defaultValue" in c ? c._defaultValue : c._currentValue;
202
+ }
203
+ function pushContextValue(context, value) {
204
+ let map = _g[MAP_KEY];
205
+ if (map === null) {
206
+ map = /* @__PURE__ */ new Map();
207
+ _g[MAP_KEY] = map;
208
+ }
209
+ const c = context;
210
+ const prev = map.has(context) ? map.get(context) : "_defaultValue" in c ? c._defaultValue : c._currentValue;
211
+ map.set(context, value);
212
+ return prev;
213
+ }
214
+ function popContextValue(context, prev) {
215
+ _g[MAP_KEY]?.set(context, prev);
216
+ }
217
+ var GLOBAL_KEY = "__slimReactRenderState";
218
+ var EMPTY = { id: 1, overflow: "" };
219
+ var _stateCache = null;
220
+ function s() {
221
+ if (_stateCache !== null) return _stateCache;
222
+ if (!_g[GLOBAL_KEY]) {
223
+ _g[GLOBAL_KEY] = { currentTreeContext: { ...EMPTY }, localIdCounter: 0, idPrefix: "" };
224
+ }
225
+ _stateCache = _g[GLOBAL_KEY];
226
+ return _stateCache;
227
+ }
228
+ var _treeIdStack = [];
229
+ var _treeOvStack = [];
230
+ var _treeDepth = 0;
231
+ function resetRenderState(idPrefix = "") {
232
+ const st = s();
233
+ st.currentTreeContext.id = EMPTY.id;
234
+ st.currentTreeContext.overflow = EMPTY.overflow;
235
+ st.localIdCounter = 0;
236
+ st.idPrefix = idPrefix;
237
+ _treeDepth = 0;
238
+ }
239
+ function pushTreeContext(totalChildren, index) {
240
+ const st = s();
241
+ const ctx = st.currentTreeContext;
242
+ const depth = _treeDepth++;
243
+ _treeIdStack[depth] = ctx.id;
244
+ _treeOvStack[depth] = ctx.overflow;
245
+ const baseIdWithLeadingBit = ctx.id;
246
+ const baseOverflow = ctx.overflow;
247
+ const baseLength = 31 - Math.clz32(baseIdWithLeadingBit);
248
+ let baseId = baseIdWithLeadingBit & ~(1 << baseLength);
249
+ const slot = index + 1;
250
+ const newBits = 32 - Math.clz32(totalChildren);
251
+ const length = newBits + baseLength;
252
+ if (30 < length) {
253
+ const overflowBits = baseLength - baseLength % 5;
254
+ const overflowStr = (baseId & (1 << overflowBits) - 1).toString(32);
255
+ baseId >>= overflowBits;
256
+ const newBaseLength = baseLength - overflowBits;
257
+ ctx.id = 1 << newBits + newBaseLength | slot << newBaseLength | baseId;
258
+ ctx.overflow = overflowStr + baseOverflow;
259
+ } else {
260
+ ctx.id = 1 << length | slot << baseLength | baseId;
261
+ ctx.overflow = baseOverflow;
262
+ }
263
+ return depth;
264
+ }
265
+ function popTreeContext(depth) {
266
+ const ctx = s().currentTreeContext;
267
+ ctx.id = _treeIdStack[depth];
268
+ ctx.overflow = _treeOvStack[depth];
269
+ _treeDepth = depth;
270
+ }
271
+ function pushComponentScope() {
272
+ const st = s();
273
+ const saved = st.localIdCounter;
274
+ st.localIdCounter = 0;
275
+ return saved;
276
+ }
277
+ function popComponentScope(saved) {
278
+ s().localIdCounter = saved;
279
+ }
280
+ function componentCalledUseId() {
281
+ return s().localIdCounter > 0;
282
+ }
283
+ function snapshotContext() {
284
+ const st = s();
285
+ const ctx = st.currentTreeContext;
286
+ return { tree: { id: ctx.id, overflow: ctx.overflow }, localId: st.localIdCounter, treeDepth: _treeDepth };
287
+ }
288
+ function restoreContext(snap) {
289
+ const st = s();
290
+ const ctx = st.currentTreeContext;
291
+ ctx.id = snap.tree.id;
292
+ ctx.overflow = snap.tree.overflow;
293
+ st.localIdCounter = snap.localId;
294
+ _treeDepth = snap.treeDepth;
295
+ }
296
+ function getTreeId() {
297
+ const { id, overflow } = s().currentTreeContext;
298
+ if (id === 1) return overflow;
299
+ const stripped = (id & ~(1 << 31 - Math.clz32(id))).toString(32);
300
+ return stripped + overflow;
301
+ }
302
+ function makeId() {
303
+ const st = s();
304
+ const treeId = getTreeId();
305
+ const n = st.localIdCounter++;
306
+ let id = "_R_" + st.idPrefix + treeId;
307
+ if (n > 0) id += "H" + n.toString(32);
308
+ return id + "_";
309
+ }
310
+
311
+ // src/slim-react/hooks.ts
312
+ function useState(initialState) {
313
+ const value = typeof initialState === "function" ? initialState() : initialState;
314
+ return [value, () => {
315
+ }];
316
+ }
317
+ function useReducer(_reducer, initialState) {
318
+ return [initialState, () => {
319
+ }];
320
+ }
321
+ function useEffect(_effect, _deps) {
322
+ }
323
+ function useLayoutEffect(_effect, _deps) {
324
+ }
325
+ function useInsertionEffect(_effect, _deps) {
326
+ }
327
+ function useRef(initialValue) {
328
+ return { current: initialValue };
329
+ }
330
+ function useMemo(factory, _deps) {
331
+ return factory();
332
+ }
333
+ function useCallback(callback, _deps) {
334
+ return callback;
335
+ }
336
+ function useDebugValue(_value, _format) {
337
+ }
338
+ function useImperativeHandle(_ref, _createHandle, _deps) {
339
+ }
340
+ function useSyncExternalStore(_subscribe, getSnapshot, getServerSnapshot) {
341
+ return (getServerSnapshot || getSnapshot)();
342
+ }
343
+ function useTransition() {
344
+ return [false, (cb) => cb()];
345
+ }
346
+ function useDeferredValue(value) {
347
+ return value;
348
+ }
349
+ function useOptimistic(passthrough) {
350
+ return [passthrough, () => {
351
+ }];
352
+ }
353
+ function useActionState(_action, initialState, _permalink) {
354
+ return [initialState, () => {
355
+ }, false];
356
+ }
357
+ function use(usable) {
358
+ if (typeof usable === "object" && usable !== null && ("_currentValue" in usable || "_defaultValue" in usable)) {
359
+ return getContextValue(usable);
360
+ }
361
+ const promise = usable;
362
+ if (promise.status === "fulfilled") return promise.value;
363
+ if (promise.status === "rejected") throw promise.reason;
364
+ throw promise;
365
+ }
366
+
367
+ // src/slim-react/dispatcher.ts
368
+ var ReactNS = __toESM(require("react"), 1);
369
+ var _reactInternalsKey = "__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE";
370
+ var _internals = ReactNS[_reactInternalsKey];
371
+ var slimDispatcher = {
372
+ useId: makeId,
373
+ readContext: (ctx) => getContextValue(ctx),
374
+ useContext: (ctx) => getContextValue(ctx),
375
+ useState,
376
+ useReducer,
377
+ useEffect,
378
+ useLayoutEffect,
379
+ useInsertionEffect,
380
+ useRef,
381
+ useMemo,
382
+ useCallback,
383
+ useDebugValue,
384
+ useImperativeHandle,
385
+ useSyncExternalStore,
386
+ useTransition,
387
+ useDeferredValue,
388
+ useOptimistic,
389
+ useActionState,
390
+ use,
391
+ // React internals that compiled output may call
392
+ useMemoCache: (size) => new Array(size).fill(void 0),
393
+ useCacheRefresh: () => () => {
394
+ },
395
+ useHostTransitionStatus: () => false
396
+ };
397
+ function installDispatcher() {
398
+ if (!_internals) return null;
399
+ const prev = _internals.H;
400
+ _internals.H = slimDispatcher;
401
+ return prev;
402
+ }
403
+ function restoreDispatcher(prev) {
404
+ if (_internals) _internals.H = prev;
405
+ }
406
+
407
+ // src/slim-react/render.ts
408
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
409
+ "area",
410
+ "base",
411
+ "br",
412
+ "col",
413
+ "embed",
414
+ "hr",
415
+ "img",
416
+ "input",
417
+ "link",
418
+ "meta",
419
+ "param",
420
+ "source",
421
+ "track",
422
+ "wbr"
423
+ ]);
424
+ var HTML_ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#x27;" };
425
+ var HTML_ESC_RE = /[&<>']/;
426
+ function escapeHtml(str) {
427
+ if (!HTML_ESC_RE.test(str)) return str;
428
+ return str.replace(/[&<>']/g, (c) => HTML_ESC[c]);
429
+ }
430
+ var ATTR_ESC = { "&": "&amp;", '"': "&quot;", "<": "&lt;", ">": "&gt;" };
431
+ var ATTR_ESC_RE = /[&"<>]/;
432
+ function escapeAttr(str) {
433
+ if (!ATTR_ESC_RE.test(str)) return str;
434
+ return str.replace(/[&"<>]/g, (c) => ATTR_ESC[c]);
435
+ }
436
+ var UNITLESS_CSS = /* @__PURE__ */ new Set([
437
+ "animationIterationCount",
438
+ "aspectRatio",
439
+ "borderImageOutset",
440
+ "borderImageSlice",
441
+ "borderImageWidth",
442
+ "boxFlex",
443
+ "boxFlexGroup",
444
+ "boxOrdinalGroup",
445
+ "columnCount",
446
+ "columns",
447
+ "flex",
448
+ "flexGrow",
449
+ "flexPositive",
450
+ "flexShrink",
451
+ "flexNegative",
452
+ "flexOrder",
453
+ "gridArea",
454
+ "gridRow",
455
+ "gridRowEnd",
456
+ "gridRowSpan",
457
+ "gridRowStart",
458
+ "gridColumn",
459
+ "gridColumnEnd",
460
+ "gridColumnSpan",
461
+ "gridColumnStart",
462
+ "fontWeight",
463
+ "lineClamp",
464
+ "lineHeight",
465
+ "opacity",
466
+ "order",
467
+ "orphans",
468
+ "scale",
469
+ "tabSize",
470
+ "widows",
471
+ "zIndex",
472
+ "zoom",
473
+ "fillOpacity",
474
+ "floodOpacity",
475
+ "stopOpacity",
476
+ "strokeDasharray",
477
+ "strokeDashoffset",
478
+ "strokeMiterlimit",
479
+ "strokeOpacity",
480
+ "strokeWidth"
481
+ ]);
482
+ var _cssKeyCache = /* @__PURE__ */ new Map();
483
+ function styleObjectToString(style) {
484
+ let result = "";
485
+ for (const key in style) {
486
+ const value = style[key];
487
+ if (value == null || typeof value === "boolean") continue;
488
+ if (result) result += ";";
489
+ let cssKey = _cssKeyCache.get(key);
490
+ if (cssKey === void 0) {
491
+ cssKey = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
492
+ _cssKeyCache.set(key, cssKey);
493
+ }
494
+ if (typeof value === "number" && value !== 0 && !UNITLESS_CSS.has(key)) {
495
+ result += cssKey + ":" + value + "px";
496
+ } else {
497
+ result += cssKey + ":" + value;
498
+ }
499
+ }
500
+ return result;
501
+ }
502
+ var SVG_ATTR_MAP = {
503
+ // Presentation / geometry
504
+ accentHeight: "accent-height",
505
+ alignmentBaseline: "alignment-baseline",
506
+ arabicForm: "arabic-form",
507
+ baselineShift: "baseline-shift",
508
+ capHeight: "cap-height",
509
+ clipPath: "clip-path",
510
+ clipRule: "clip-rule",
511
+ colorInterpolation: "color-interpolation",
512
+ colorInterpolationFilters: "color-interpolation-filters",
513
+ colorProfile: "color-profile",
514
+ dominantBaseline: "dominant-baseline",
515
+ enableBackground: "enable-background",
516
+ fillOpacity: "fill-opacity",
517
+ fillRule: "fill-rule",
518
+ floodColor: "flood-color",
519
+ floodOpacity: "flood-opacity",
520
+ fontFamily: "font-family",
521
+ fontSize: "font-size",
522
+ fontSizeAdjust: "font-size-adjust",
523
+ fontStretch: "font-stretch",
524
+ fontStyle: "font-style",
525
+ fontVariant: "font-variant",
526
+ fontWeight: "font-weight",
527
+ glyphName: "glyph-name",
528
+ glyphOrientationHorizontal: "glyph-orientation-horizontal",
529
+ glyphOrientationVertical: "glyph-orientation-vertical",
530
+ horizAdvX: "horiz-adv-x",
531
+ horizOriginX: "horiz-origin-x",
532
+ imageRendering: "image-rendering",
533
+ letterSpacing: "letter-spacing",
534
+ lightingColor: "lighting-color",
535
+ markerEnd: "marker-end",
536
+ markerMid: "marker-mid",
537
+ markerStart: "marker-start",
538
+ overlinePosition: "overline-position",
539
+ overlineThickness: "overline-thickness",
540
+ paintOrder: "paint-order",
541
+ panose1: "panose-1",
542
+ pointerEvents: "pointer-events",
543
+ renderingIntent: "rendering-intent",
544
+ shapeRendering: "shape-rendering",
545
+ stopColor: "stop-color",
546
+ stopOpacity: "stop-opacity",
547
+ strikethroughPosition: "strikethrough-position",
548
+ strikethroughThickness: "strikethrough-thickness",
549
+ strokeDasharray: "stroke-dasharray",
550
+ strokeDashoffset: "stroke-dashoffset",
551
+ strokeLinecap: "stroke-linecap",
552
+ strokeLinejoin: "stroke-linejoin",
553
+ strokeMiterlimit: "stroke-miterlimit",
554
+ strokeOpacity: "stroke-opacity",
555
+ strokeWidth: "stroke-width",
556
+ textAnchor: "text-anchor",
557
+ textDecoration: "text-decoration",
558
+ textRendering: "text-rendering",
559
+ underlinePosition: "underline-position",
560
+ underlineThickness: "underline-thickness",
561
+ unicodeBidi: "unicode-bidi",
562
+ unicodeRange: "unicode-range",
563
+ unitsPerEm: "units-per-em",
564
+ vAlphabetic: "v-alphabetic",
565
+ vHanging: "v-hanging",
566
+ vIdeographic: "v-ideographic",
567
+ vMathematical: "v-mathematical",
568
+ vertAdvY: "vert-adv-y",
569
+ vertOriginX: "vert-origin-x",
570
+ vertOriginY: "vert-origin-y",
571
+ wordSpacing: "word-spacing",
572
+ writingMode: "writing-mode",
573
+ xHeight: "x-height",
574
+ // Namespace-prefixed
575
+ xlinkActuate: "xlink:actuate",
576
+ xlinkArcrole: "xlink:arcrole",
577
+ xlinkHref: "xlink:href",
578
+ xlinkRole: "xlink:role",
579
+ xlinkShow: "xlink:show",
580
+ xlinkTitle: "xlink:title",
581
+ xlinkType: "xlink:type",
582
+ xmlBase: "xml:base",
583
+ xmlLang: "xml:lang",
584
+ xmlSpace: "xml:space",
585
+ xmlns: "xmlns",
586
+ xmlnsXlink: "xmlns:xlink",
587
+ // Filter / lighting
588
+ baseFrequency: "baseFrequency",
589
+ colorInterpolation_filters: "color-interpolation-filters",
590
+ diffuseConstant: "diffuseConstant",
591
+ edgeMode: "edgeMode",
592
+ filterUnits: "filterUnits",
593
+ gradientTransform: "gradientTransform",
594
+ gradientUnits: "gradientUnits",
595
+ kernelMatrix: "kernelMatrix",
596
+ kernelUnitLength: "kernelUnitLength",
597
+ lengthAdjust: "lengthAdjust",
598
+ limitingConeAngle: "limitingConeAngle",
599
+ markerHeight: "markerHeight",
600
+ markerWidth: "markerWidth",
601
+ maskContentUnits: "maskContentUnits",
602
+ maskUnits: "maskUnits",
603
+ numOctaves: "numOctaves",
604
+ pathLength: "pathLength",
605
+ patternContentUnits: "patternContentUnits",
606
+ patternTransform: "patternTransform",
607
+ patternUnits: "patternUnits",
608
+ pointsAtX: "pointsAtX",
609
+ pointsAtY: "pointsAtY",
610
+ pointsAtZ: "pointsAtZ",
611
+ preserveAspectRatio: "preserveAspectRatio",
612
+ primitiveUnits: "primitiveUnits",
613
+ refX: "refX",
614
+ refY: "refY",
615
+ repeatCount: "repeatCount",
616
+ repeatDur: "repeatDur",
617
+ specularConstant: "specularConstant",
618
+ specularExponent: "specularExponent",
619
+ spreadMethod: "spreadMethod",
620
+ startOffset: "startOffset",
621
+ stdDeviation: "stdDeviation",
622
+ stitchTiles: "stitchTiles",
623
+ surfaceScale: "surfaceScale",
624
+ systemLanguage: "systemLanguage",
625
+ tableValues: "tableValues",
626
+ targetX: "targetX",
627
+ targetY: "targetY",
628
+ textLength: "textLength",
629
+ viewBox: "viewBox",
630
+ xChannelSelector: "xChannelSelector",
631
+ yChannelSelector: "yChannelSelector"
632
+ };
633
+ var TEXTAREA_SKIP_PROPS = /* @__PURE__ */ new Set(["value", "defaultValue", "children"]);
634
+ var SELECT_SKIP_PROPS = /* @__PURE__ */ new Set(["value", "defaultValue"]);
635
+ var INTERNAL_PROPS = /* @__PURE__ */ new Set([
636
+ "children",
637
+ "key",
638
+ "ref",
639
+ "dangerouslySetInnerHTML",
640
+ "suppressHydrationWarning",
641
+ "suppressContentEditableWarning"
642
+ ]);
643
+ function writeAttributes(writer, props, isSvg, skip) {
644
+ for (const key in props) {
645
+ if (skip !== void 0 && skip.has(key)) continue;
646
+ const value = props[key];
647
+ if (INTERNAL_PROPS.has(key)) continue;
648
+ if (key.length > 2 && key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && key.charCodeAt(2) >= 65 && key.charCodeAt(2) <= 90) continue;
649
+ let attrName;
650
+ if (isSvg && key in SVG_ATTR_MAP) {
651
+ attrName = SVG_ATTR_MAP[key];
652
+ } else {
653
+ attrName = key === "className" ? "class" : key === "htmlFor" ? "for" : key === "tabIndex" ? "tabindex" : key === "defaultValue" ? "value" : key === "defaultChecked" ? "checked" : key;
654
+ }
655
+ if (value === false || value == null) {
656
+ if (value === false && (attrName.charCodeAt(0) === 97 && attrName.startsWith("aria-") || attrName.charCodeAt(0) === 100 && attrName.startsWith("data-"))) {
657
+ writer.write(` ${attrName}="false"`);
658
+ }
659
+ continue;
660
+ }
661
+ if (value === true) {
662
+ if (attrName.charCodeAt(0) === 97 && attrName.startsWith("aria-") || attrName.charCodeAt(0) === 100 && attrName.startsWith("data-")) {
663
+ writer.write(` ${attrName}="true"`);
664
+ } else {
665
+ writer.write(` ${attrName}=""`);
666
+ }
667
+ continue;
668
+ }
669
+ if (key === "style" && typeof value === "object") {
670
+ const styleStr = styleObjectToString(value);
671
+ if (styleStr) writer.write(` style="${escapeAttr(styleStr)}"`);
672
+ continue;
673
+ }
674
+ writer.write(` ${attrName}="${escapeAttr(typeof value === "string" ? value : String(value))}"`);
675
+ }
676
+ }
677
+ var BufferWriter = class _BufferWriter {
678
+ data = "";
679
+ lastWasText = false;
680
+ write(chunk) {
681
+ this.data += chunk;
682
+ this.lastWasText = false;
683
+ }
684
+ text(s2) {
685
+ this.data += s2;
686
+ this.lastWasText = true;
687
+ }
688
+ /** Flush accumulated output into a parent writer and reset. */
689
+ flushTo(target) {
690
+ if (!this.data) return;
691
+ if (target instanceof _BufferWriter) {
692
+ target.data += this.data;
693
+ } else {
694
+ target.write(this.data);
695
+ }
696
+ target.lastWasText = this.lastWasText;
697
+ }
698
+ };
699
+ function renderNode(node, writer, isSvg = false) {
700
+ if (node == null || typeof node === "boolean") return;
701
+ if (typeof node === "string") {
702
+ writer.text(escapeHtml(node));
703
+ return;
704
+ }
705
+ if (typeof node === "number") {
706
+ writer.text(String(node));
707
+ return;
708
+ }
709
+ if (Array.isArray(node)) {
710
+ return renderChildArray(node, writer, isSvg);
711
+ }
712
+ const obj = node;
713
+ if (Symbol.iterator in obj && !("$$typeof" in obj)) {
714
+ return renderChildArray(Array.from(obj), writer, isSvg);
715
+ }
716
+ if ("$$typeof" in obj) {
717
+ const elType = obj["$$typeof"];
718
+ if (elType !== SLIM_ELEMENT && elType !== REACT19_ELEMENT) return;
719
+ const element = node;
720
+ const { type, props } = element;
721
+ if (type === FRAGMENT_TYPE) {
722
+ return renderChildren(props.children, writer, isSvg);
723
+ }
724
+ if (type === SUSPENSE_TYPE) {
725
+ return renderSuspense(props, writer, isSvg);
726
+ }
727
+ if (typeof type === "string") {
728
+ return renderHostElement(type, props, writer, isSvg);
729
+ }
730
+ if (typeof type === "function") {
731
+ return renderComponent(type, props, writer, isSvg);
732
+ }
733
+ if (typeof type === "object" && type !== null) {
734
+ return renderComponent(type, props, writer, isSvg);
735
+ }
736
+ }
737
+ }
738
+ function markSelectedOptionsMulti(children, selectedValues) {
739
+ if (children == null || typeof children === "boolean") return children;
740
+ if (typeof children === "string" || typeof children === "number") return children;
741
+ if (Array.isArray(children)) {
742
+ return children.map((c) => markSelectedOptionsMulti(c, selectedValues));
743
+ }
744
+ if (typeof children === "object" && "$$typeof" in children) {
745
+ const elType = children["$$typeof"];
746
+ if (elType !== SLIM_ELEMENT && elType !== REACT19_ELEMENT) return children;
747
+ const el = children;
748
+ if (el.type === "option") {
749
+ const optValue = el.props.value !== void 0 ? el.props.value : el.props.children;
750
+ const isSelected = selectedValues.has(String(optValue));
751
+ return { ...el, props: { ...el.props, selected: isSelected || void 0 } };
752
+ }
753
+ if (el.type === "optgroup" || el.type === FRAGMENT_TYPE) {
754
+ const newChildren = markSelectedOptionsMulti(el.props.children, selectedValues);
755
+ return { ...el, props: { ...el.props, children: newChildren } };
756
+ }
757
+ }
758
+ return children;
759
+ }
760
+ function renderHostElement(tag, props, writer, isSvg) {
761
+ const childSvg = isSvg || tag === "svg";
762
+ if (tag === "textarea") {
763
+ const textContent = props.value ?? props.defaultValue ?? props.children ?? "";
764
+ writer.write("<textarea");
765
+ writeAttributes(writer, props, false, TEXTAREA_SKIP_PROPS);
766
+ writer.write(">");
767
+ writer.text(escapeHtml(String(textContent)));
768
+ writer.write("</textarea>");
769
+ return;
770
+ }
771
+ if (tag === "select") {
772
+ const selectedValue = props.value ?? props.defaultValue;
773
+ writer.write("<select");
774
+ writeAttributes(writer, props, false, SELECT_SKIP_PROPS);
775
+ writer.write(">");
776
+ const selectedSet = selectedValue == null ? null : Array.isArray(selectedValue) ? new Set(selectedValue.map(String)) : /* @__PURE__ */ new Set([String(selectedValue)]);
777
+ const patchedChildren = selectedSet != null ? markSelectedOptionsMulti(props.children, selectedSet) : props.children;
778
+ const inner2 = renderChildren(patchedChildren, writer, false);
779
+ if (inner2 && typeof inner2.then === "function") {
780
+ return inner2.then(() => {
781
+ writer.write("</select>");
782
+ });
783
+ }
784
+ writer.write("</select>");
785
+ return;
786
+ }
787
+ writer.write(`<${tag}`);
788
+ writeAttributes(writer, props, childSvg);
789
+ if (VOID_ELEMENTS.has(tag)) {
790
+ writer.write("/>");
791
+ return;
792
+ }
793
+ writer.write(">");
794
+ const childContext = tag === "foreignObject" ? false : childSvg;
795
+ let inner = void 0;
796
+ if (props.dangerouslySetInnerHTML) {
797
+ writer.write(props.dangerouslySetInnerHTML.__html);
798
+ } else {
799
+ inner = renderChildren(props.children, writer, childContext);
800
+ }
801
+ if (inner && typeof inner.then === "function") {
802
+ return inner.then(() => {
803
+ writer.write(`</${tag}>`);
804
+ });
805
+ }
806
+ writer.write(`</${tag}>`);
807
+ }
808
+ var REACT_MEMO = Symbol.for("react.memo");
809
+ var REACT_FORWARD_REF = Symbol.for("react.forward_ref");
810
+ var REACT_PROVIDER = Symbol.for("react.provider");
811
+ var REACT_CONTEXT = Symbol.for("react.context");
812
+ var REACT_CONSUMER = Symbol.for("react.consumer");
813
+ var REACT_LAZY = Symbol.for("react.lazy");
814
+ var SUSPENSE_RETRY_LIMIT = Symbol("SuspenseRetryLimit");
815
+ var MAX_COMPONENT_SUSPENSE_RETRIES = 25;
816
+ function patchPromiseStatus(p) {
817
+ const w = p;
818
+ if (w.status) return;
819
+ w.status = "pending";
820
+ w.then(
821
+ (v) => {
822
+ w.status = "fulfilled";
823
+ w.value = v;
824
+ },
825
+ (r) => {
826
+ w.status = "rejected";
827
+ w.reason = r;
828
+ }
829
+ );
830
+ }
831
+ function renderComponent(type, props, writer, isSvg, _suspenseRetries = 0) {
832
+ const typeOf = type.$$typeof;
833
+ if (typeOf === REACT_MEMO) {
834
+ return renderNode(
835
+ { $$typeof: SLIM_ELEMENT, type: type.type, props, key: null },
836
+ writer,
837
+ isSvg
838
+ );
839
+ }
840
+ if (typeOf === REACT_FORWARD_REF) {
841
+ return renderComponent(type.render, props, writer, isSvg);
842
+ }
843
+ if (typeOf === REACT_LAZY) {
844
+ let resolved;
845
+ try {
846
+ resolved = type._init(type._payload);
847
+ } catch (e) {
848
+ if (e && typeof e.then === "function") {
849
+ if (_suspenseRetries + 1 >= MAX_COMPONENT_SUSPENSE_RETRIES) throw SUSPENSE_RETRY_LIMIT;
850
+ patchPromiseStatus(e);
851
+ const m = captureMap();
852
+ const u = captureUnsuspend();
853
+ return e.then(() => {
854
+ swapContextMap(m);
855
+ restoreUnsuspend(u);
856
+ return renderComponent(type, props, writer, isSvg, _suspenseRetries + 1);
857
+ });
858
+ }
859
+ throw e;
860
+ }
861
+ const LazyComp = resolved?.default ?? resolved;
862
+ return renderComponent(LazyComp, props, writer, isSvg);
863
+ }
864
+ if (typeOf === REACT_CONSUMER) {
865
+ const ctx2 = type._context;
866
+ const value = ctx2 ? getContextValue(ctx2) : void 0;
867
+ const result2 = typeof props.children === "function" ? props.children(value) : null;
868
+ const savedScope2 = pushComponentScope();
869
+ const finish = () => popComponentScope(savedScope2);
870
+ const r2 = renderNode(result2, writer, isSvg);
871
+ if (r2 && typeof r2.then === "function") {
872
+ return r2.then(finish);
873
+ }
874
+ finish();
875
+ return;
876
+ }
877
+ const isProvider = "_context" in type || typeOf === REACT_PROVIDER || typeOf === REACT_CONTEXT && "value" in props;
878
+ let prevCtxValue;
879
+ let ctx;
880
+ if (isProvider) {
881
+ ctx = type._context ?? type;
882
+ prevCtxValue = pushContextValue(ctx, props.value);
883
+ }
884
+ const savedScope = pushComponentScope();
885
+ if (isProvider && typeof type !== "function") {
886
+ const finish = () => {
887
+ popComponentScope(savedScope);
888
+ popContextValue(ctx, prevCtxValue);
889
+ };
890
+ const r2 = renderChildren(props.children, writer, isSvg);
891
+ if (r2 && typeof r2.then === "function") {
892
+ const m = captureMap();
893
+ const u = captureUnsuspend();
894
+ return r2.then(
895
+ () => {
896
+ swapContextMap(m);
897
+ restoreUnsuspend(u);
898
+ finish();
899
+ },
900
+ (e) => {
901
+ swapContextMap(m);
902
+ restoreUnsuspend(u);
903
+ finish();
904
+ throw e;
905
+ }
906
+ );
907
+ }
908
+ finish();
909
+ return;
910
+ }
911
+ let result;
912
+ const prevDispatcher = installDispatcher();
913
+ try {
914
+ if (type.prototype && typeof type.prototype.render === "function") {
915
+ const instance = new type(props);
916
+ if (typeof type.getDerivedStateFromProps === "function") {
917
+ const derived = type.getDerivedStateFromProps(props, instance.state ?? {});
918
+ if (derived != null) instance.state = { ...instance.state ?? {}, ...derived };
919
+ }
920
+ result = instance.render();
921
+ } else {
922
+ result = type(props);
923
+ }
924
+ } catch (e) {
925
+ restoreDispatcher(prevDispatcher);
926
+ popComponentScope(savedScope);
927
+ if (isProvider) popContextValue(ctx, prevCtxValue);
928
+ if (e && typeof e.then === "function") {
929
+ if (_suspenseRetries + 1 >= MAX_COMPONENT_SUSPENSE_RETRIES) throw SUSPENSE_RETRY_LIMIT;
930
+ patchPromiseStatus(e);
931
+ const m = captureMap();
932
+ const u = captureUnsuspend();
933
+ return e.then(() => {
934
+ swapContextMap(m);
935
+ restoreUnsuspend(u);
936
+ return renderComponent(type, props, writer, isSvg, _suspenseRetries + 1);
937
+ });
938
+ }
939
+ throw e;
940
+ }
941
+ restoreDispatcher(prevDispatcher);
942
+ let savedIdTree;
943
+ if (!(result instanceof Promise) && componentCalledUseId()) {
944
+ savedIdTree = pushTreeContext(1, 0);
945
+ }
946
+ if (result instanceof Promise) {
947
+ const m = captureMap();
948
+ const u = captureUnsuspend();
949
+ return result.then((resolved) => {
950
+ swapContextMap(m);
951
+ restoreUnsuspend(u);
952
+ let asyncSavedIdTree;
953
+ if (componentCalledUseId()) {
954
+ asyncSavedIdTree = pushTreeContext(1, 0);
955
+ }
956
+ const r2 = renderNode(resolved, writer, isSvg);
957
+ if (r2 && typeof r2.then === "function") {
958
+ const m2 = captureMap();
959
+ const u2 = captureUnsuspend();
960
+ return r2.then(
961
+ () => {
962
+ swapContextMap(m2);
963
+ restoreUnsuspend(u2);
964
+ if (asyncSavedIdTree !== void 0) popTreeContext(asyncSavedIdTree);
965
+ popComponentScope(savedScope);
966
+ if (isProvider) popContextValue(ctx, prevCtxValue);
967
+ },
968
+ (e) => {
969
+ swapContextMap(m2);
970
+ restoreUnsuspend(u2);
971
+ if (asyncSavedIdTree !== void 0) popTreeContext(asyncSavedIdTree);
972
+ popComponentScope(savedScope);
973
+ if (isProvider) popContextValue(ctx, prevCtxValue);
974
+ throw e;
975
+ }
976
+ );
977
+ }
978
+ if (asyncSavedIdTree !== void 0) popTreeContext(asyncSavedIdTree);
979
+ popComponentScope(savedScope);
980
+ if (isProvider) popContextValue(ctx, prevCtxValue);
981
+ }, (e) => {
982
+ swapContextMap(m);
983
+ restoreUnsuspend(u);
984
+ popComponentScope(savedScope);
985
+ if (isProvider) popContextValue(ctx, prevCtxValue);
986
+ throw e;
987
+ });
988
+ }
989
+ const r = renderNode(result, writer, isSvg);
990
+ if (r && typeof r.then === "function") {
991
+ const m = captureMap();
992
+ const u = captureUnsuspend();
993
+ return r.then(
994
+ () => {
995
+ swapContextMap(m);
996
+ restoreUnsuspend(u);
997
+ if (savedIdTree !== void 0) popTreeContext(savedIdTree);
998
+ popComponentScope(savedScope);
999
+ if (isProvider) popContextValue(ctx, prevCtxValue);
1000
+ },
1001
+ (e) => {
1002
+ swapContextMap(m);
1003
+ restoreUnsuspend(u);
1004
+ if (savedIdTree !== void 0) popTreeContext(savedIdTree);
1005
+ popComponentScope(savedScope);
1006
+ if (isProvider) popContextValue(ctx, prevCtxValue);
1007
+ throw e;
1008
+ }
1009
+ );
1010
+ }
1011
+ if (savedIdTree !== void 0) popTreeContext(savedIdTree);
1012
+ popComponentScope(savedScope);
1013
+ if (isProvider) popContextValue(ctx, prevCtxValue);
1014
+ }
1015
+ function renderChildArray(children, writer, isSvg) {
1016
+ return renderChildArrayFrom(children, 0, writer, isSvg);
1017
+ }
1018
+ function renderChildArrayFrom(children, startIndex, writer, isSvg) {
1019
+ const totalChildren = children.length;
1020
+ for (let i = startIndex; i < totalChildren; i++) {
1021
+ const child = children[i];
1022
+ if ((typeof child === "string" || typeof child === "number") && writer.lastWasText) {
1023
+ writer.write("<!-- -->");
1024
+ }
1025
+ const savedTree = pushTreeContext(totalChildren, i);
1026
+ const r = renderNode(child, writer, isSvg);
1027
+ if (r && typeof r.then === "function") {
1028
+ const m = captureMap();
1029
+ const u = captureUnsuspend();
1030
+ return r.then(() => {
1031
+ swapContextMap(m);
1032
+ restoreUnsuspend(u);
1033
+ popTreeContext(savedTree);
1034
+ return renderChildArrayFrom(children, i + 1, writer, isSvg);
1035
+ });
1036
+ }
1037
+ popTreeContext(savedTree);
1038
+ }
1039
+ }
1040
+ function renderChildren(children, writer, isSvg = false) {
1041
+ if (children == null) return;
1042
+ if (Array.isArray(children)) {
1043
+ return renderChildArray(children, writer, isSvg);
1044
+ }
1045
+ return renderNode(children, writer, isSvg);
1046
+ }
1047
+ async function renderSuspense(props, writer, isSvg = false) {
1048
+ const { children, fallback } = props;
1049
+ const snap = snapshotContext();
1050
+ const savedMap = captureMap();
1051
+ const savedMapClone = savedMap ? new Map(savedMap) : null;
1052
+ const buffer = new BufferWriter();
1053
+ try {
1054
+ const r = renderNode(children, buffer, isSvg);
1055
+ if (r && typeof r.then === "function") {
1056
+ const m = captureMap();
1057
+ const u = captureUnsuspend();
1058
+ await r;
1059
+ swapContextMap(m);
1060
+ restoreUnsuspend(u);
1061
+ }
1062
+ writer.write("<!--$-->");
1063
+ buffer.flushTo(writer);
1064
+ writer.write("<!--/$-->");
1065
+ writer.flush?.();
1066
+ } catch (error) {
1067
+ if (error === SUSPENSE_RETRY_LIMIT) {
1068
+ restoreContext(snap);
1069
+ swapContextMap(savedMapClone);
1070
+ writer.write("<!--$?-->");
1071
+ if (fallback) {
1072
+ const r = renderNode(fallback, writer, isSvg);
1073
+ if (r && typeof r.then === "function") {
1074
+ const m = captureMap();
1075
+ const u = captureUnsuspend();
1076
+ await r;
1077
+ swapContextMap(m);
1078
+ restoreUnsuspend(u);
1079
+ }
1080
+ }
1081
+ writer.write("<!--/$-->");
1082
+ } else {
1083
+ throw error;
1084
+ }
1085
+ }
1086
+ }
1087
+ var _streamEncoder = new TextEncoder();
1088
+ var NULL_WRITER = {
1089
+ lastWasText: false,
1090
+ write(_c) {
1091
+ },
1092
+ text(_s) {
1093
+ }
1094
+ };
1095
+ async function renderPreflight(element, options) {
1096
+ const idPrefix = options?.identifierPrefix ?? "";
1097
+ const prev = swapContextMap(null);
1098
+ try {
1099
+ resetRenderState(idPrefix);
1100
+ NULL_WRITER.lastWasText = false;
1101
+ const r = renderNode(element, NULL_WRITER);
1102
+ if (r && typeof r.then === "function") {
1103
+ const m = captureMap();
1104
+ await r;
1105
+ swapContextMap(m);
1106
+ }
1107
+ } finally {
1108
+ swapContextMap(prev);
1109
+ }
1110
+ }
1111
+ async function renderToString(element, options) {
1112
+ const idPrefix = options?.identifierPrefix ?? "";
1113
+ const prev = swapContextMap(null);
1114
+ let output = "";
1115
+ const writer = {
1116
+ lastWasText: false,
1117
+ write(c) {
1118
+ output += c;
1119
+ this.lastWasText = false;
1120
+ },
1121
+ text(s2) {
1122
+ output += s2;
1123
+ this.lastWasText = true;
1124
+ }
1125
+ };
1126
+ try {
1127
+ resetRenderState(idPrefix);
1128
+ const r = renderNode(element, writer);
1129
+ if (r && typeof r.then === "function") {
1130
+ const m = captureMap();
1131
+ await r;
1132
+ swapContextMap(m);
1133
+ }
1134
+ return output;
1135
+ } finally {
1136
+ swapContextMap(prev);
1137
+ }
1138
+ }
1139
+
1140
+ // src/utils/response.tsx
1141
+ var ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
1142
+ var escAttr = (s2) => s2.replace(/[&<>"]/g, (c) => ESC[c] ?? c);
1143
+ var escText = (s2) => s2.replace(/[&<>]/g, (c) => ESC[c] ?? c);
1144
+ var ATTR = {
1145
+ className: "class",
1146
+ htmlFor: "for",
1147
+ httpEquiv: "http-equiv",
1148
+ charSet: "charset",
1149
+ crossOrigin: "crossorigin",
1150
+ noModule: "nomodule",
1151
+ referrerPolicy: "referrerpolicy",
1152
+ fetchPriority: "fetchpriority",
1153
+ hrefLang: "hreflang"
1154
+ };
1155
+ function renderHeadTag(tag, id, opts, selfClose = false) {
1156
+ let attrs = ` id="${escAttr(id)}"`;
1157
+ let inner = "";
1158
+ for (const [k, v] of Object.entries(opts)) {
1159
+ if (k === "key" || k === "children") continue;
1160
+ if (k === "dangerouslySetInnerHTML") {
1161
+ inner = v.__html ?? "";
1162
+ continue;
1163
+ }
1164
+ const attr = ATTR[k] ?? k;
1165
+ if (v === true) attrs += ` ${attr}`;
1166
+ else if (v !== false && v != null) attrs += ` ${attr}="${escAttr(String(v))}"`;
1167
+ }
1168
+ return selfClose ? `<${tag}${attrs}>` : `<${tag}${attrs}>${inner}</${tag}>`;
1169
+ }
1170
+ function buildHeadHtml(seoData) {
1171
+ let html = `<title>${escText(seoData.title ?? "")}</title>`;
1172
+ for (const [id, opts] of Object.entries(seoData.meta))
1173
+ html += renderHeadTag("meta", id, opts, true);
1174
+ for (const [id, opts] of Object.entries(seoData.link))
1175
+ html += renderHeadTag("link", id, opts, true);
1176
+ for (const [id, opts] of Object.entries(seoData.style))
1177
+ html += renderHeadTag("style", id, opts);
1178
+ for (const [id, opts] of Object.entries(seoData.script))
1179
+ html += renderHeadTag("script", id, opts);
1180
+ return html;
1181
+ }
1182
+ var getReactResponse = async (req, opts) => {
1183
+ const App = opts.document.body;
1184
+ const { getInitProps, getFinalProps } = opts.document;
1185
+ const context = {
1186
+ head: { title: "Hadars App", meta: {}, link: {}, style: {}, script: {}, status: 200 }
1187
+ };
1188
+ let props = {
1189
+ ...getInitProps ? await getInitProps(req) : {},
1190
+ location: req.location,
1191
+ context
1192
+ };
1193
+ const unsuspend = { cache: /* @__PURE__ */ new Map() };
1194
+ globalThis.__hadarsUnsuspend = unsuspend;
1195
+ globalThis.__hadarsContext = context;
1196
+ const element = createElement(App, props);
1197
+ try {
1198
+ await renderPreflight(element);
1199
+ } finally {
1200
+ globalThis.__hadarsUnsuspend = null;
1201
+ globalThis.__hadarsContext = null;
1202
+ }
1203
+ const status = context.head.status;
1204
+ const getAppBody = async () => {
1205
+ globalThis.__hadarsUnsuspend = unsuspend;
1206
+ globalThis.__hadarsContext = context;
1207
+ try {
1208
+ return await renderToString(element);
1209
+ } finally {
1210
+ globalThis.__hadarsUnsuspend = null;
1211
+ globalThis.__hadarsContext = null;
1212
+ }
1213
+ };
1214
+ const finalize = async () => {
1215
+ const { context: _, ...restProps } = getFinalProps ? await getFinalProps(props) : props;
1216
+ const serverData = {};
1217
+ let hasServerData = false;
1218
+ for (const [key, entry] of unsuspend.cache) {
1219
+ if (entry.status === "fulfilled") {
1220
+ serverData[key] = entry.value;
1221
+ hasServerData = true;
1222
+ }
1223
+ }
1224
+ return {
1225
+ clientProps: {
1226
+ ...restProps,
1227
+ location: req.location,
1228
+ ...hasServerData ? { __serverData: serverData } : {}
1229
+ }
1230
+ };
1231
+ };
1232
+ return { head: context.head, status, getAppBody, finalize };
1233
+ };
1234
+
1235
+ // src/utils/ssrHandler.ts
1236
+ var HEAD_MARKER = '<meta name="HADARS_HEAD">';
1237
+ var BODY_MARKER = '<meta name="HADARS_BODY">';
1238
+ var encoder = new TextEncoder();
1239
+ async function buildSsrHtml(bodyHtml, clientProps, headHtml, getPrecontentHtml) {
1240
+ const [precontentHtml, postContent] = await Promise.resolve(getPrecontentHtml(headHtml));
1241
+ const scriptContent = JSON.stringify({ hadars: { props: clientProps } }).replace(/</g, "\\u003c");
1242
+ return precontentHtml + `<div id="app">${bodyHtml}</div><script id="hadars" type="application/json">${scriptContent}</script>` + postContent;
1243
+ }
1244
+ var makePrecontentHtmlGetter = (htmlFilePromise) => {
1245
+ let preHead = null;
1246
+ let postHead = null;
1247
+ let postContent = null;
1248
+ return (headHtml) => {
1249
+ if (preHead !== null) {
1250
+ return [preHead + headHtml + postHead, postContent];
1251
+ }
1252
+ return htmlFilePromise.then((html) => {
1253
+ const headEnd = html.indexOf(HEAD_MARKER);
1254
+ const contentStart = html.indexOf(BODY_MARKER);
1255
+ preHead = html.slice(0, headEnd);
1256
+ postHead = html.slice(headEnd + HEAD_MARKER.length, contentStart);
1257
+ postContent = html.slice(contentStart + BODY_MARKER.length);
1258
+ return [preHead + headHtml + postHead, postContent];
1259
+ });
1260
+ };
1261
+ };
1262
+ async function transformStream(data, stream) {
1263
+ const writer = stream.writable.getWriter();
1264
+ writer.write(data);
1265
+ writer.close();
1266
+ const chunks = [];
1267
+ const reader = stream.readable.getReader();
1268
+ while (true) {
1269
+ const { done, value } = await reader.read();
1270
+ if (done) break;
1271
+ chunks.push(value);
1272
+ }
1273
+ const total = chunks.reduce((n, c) => n + c.length, 0);
1274
+ const out = new Uint8Array(total);
1275
+ let offset = 0;
1276
+ for (const c of chunks) {
1277
+ out.set(c, offset);
1278
+ offset += c.length;
1279
+ }
1280
+ return out;
1281
+ }
1282
+ var gzipCompress = (d) => transformStream(d, new globalThis.CompressionStream("gzip"));
1283
+ var gzipDecompress = (d) => transformStream(d, new globalThis.DecompressionStream("gzip"));
1284
+ async function buildCacheEntry(res, ttl) {
1285
+ const buf = await res.arrayBuffer();
1286
+ const body = await gzipCompress(new Uint8Array(buf));
1287
+ const headers = [];
1288
+ res.headers.forEach((v, k) => {
1289
+ if (k.toLowerCase() !== "content-encoding" && k.toLowerCase() !== "content-length") {
1290
+ headers.push([k, v]);
1291
+ }
1292
+ });
1293
+ headers.push(["content-encoding", "gzip"]);
1294
+ return { body, status: res.status, headers, expiresAt: ttl != null ? Date.now() + ttl : null };
1295
+ }
1296
+ async function serveFromEntry(entry, req) {
1297
+ const accept = req.headers.get("Accept-Encoding") ?? "";
1298
+ if (accept.includes("gzip")) {
1299
+ return new Response(entry.body.buffer, { status: entry.status, headers: entry.headers });
1300
+ }
1301
+ const plain = await gzipDecompress(entry.body);
1302
+ const headers = entry.headers.filter(([k]) => k.toLowerCase() !== "content-encoding");
1303
+ return new Response(plain.buffer, { status: entry.status, headers });
1304
+ }
1305
+ function createRenderCache(opts, handler) {
1306
+ const store = /* @__PURE__ */ new Map();
1307
+ const inFlight = /* @__PURE__ */ new Map();
1308
+ return async (req, ctx) => {
1309
+ const hadarsReq = parseRequest(req);
1310
+ const cacheOpts = await opts(hadarsReq);
1311
+ const key = cacheOpts?.key ?? null;
1312
+ if (key != null) {
1313
+ const entry = store.get(key);
1314
+ if (entry) {
1315
+ const expired = entry.expiresAt != null && Date.now() >= entry.expiresAt;
1316
+ if (!expired) return serveFromEntry(entry, req);
1317
+ store.delete(key);
1318
+ }
1319
+ let flight = inFlight.get(key);
1320
+ if (!flight) {
1321
+ const ttl = cacheOpts?.ttl;
1322
+ flight = handler(new Request(req), ctx).then(async (res) => {
1323
+ if (!res || res.status < 200 || res.status >= 300 || res.headers.has("set-cookie")) {
1324
+ return null;
1325
+ }
1326
+ const newEntry2 = await buildCacheEntry(res, ttl);
1327
+ store.set(key, newEntry2);
1328
+ return newEntry2;
1329
+ }).catch(() => null).finally(() => inFlight.delete(key));
1330
+ inFlight.set(key, flight);
1331
+ }
1332
+ const newEntry = await flight;
1333
+ if (newEntry) return serveFromEntry(newEntry, req);
1334
+ }
1335
+ return handler(req, ctx);
1336
+ };
1337
+ }
1338
+
1339
+ // src/cloudflare.ts
1340
+ function createCloudflareHandler(options, bundled) {
1341
+ const fetchHandler = options.fetch;
1342
+ const handleProxy = createProxyHandler(options);
1343
+ const getPrecontentHtml = makePrecontentHtmlGetter(Promise.resolve(bundled.outHtml));
1344
+ const { ssrModule } = bundled;
1345
+ const runHandler = async (req) => {
1346
+ const request = parseRequest(req);
1347
+ if (fetchHandler) {
1348
+ const res = await fetchHandler(request);
1349
+ if (res) return res;
1350
+ }
1351
+ const proxied = await handleProxy(request);
1352
+ if (proxied) return proxied;
1353
+ try {
1354
+ const { default: Component, getInitProps, getFinalProps } = ssrModule;
1355
+ const { head, status, getAppBody, finalize } = await getReactResponse(request, {
1356
+ document: {
1357
+ body: Component,
1358
+ lang: "en",
1359
+ getInitProps,
1360
+ getFinalProps
1361
+ }
1362
+ });
1363
+ if (request.headers.get("Accept") === "application/json") {
1364
+ const { clientProps: clientProps2 } = await finalize();
1365
+ const serverData = clientProps2.__serverData ?? {};
1366
+ return new Response(JSON.stringify({ serverData }), {
1367
+ status,
1368
+ headers: { "Content-Type": "application/json; charset=utf-8" }
1369
+ });
1370
+ }
1371
+ const bodyHtml = await getAppBody();
1372
+ const { clientProps } = await finalize();
1373
+ const headHtml = buildHeadHtml(head);
1374
+ const html = await buildSsrHtml(bodyHtml, clientProps, headHtml, getPrecontentHtml);
1375
+ return new Response(html, {
1376
+ status,
1377
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1378
+ });
1379
+ } catch (err) {
1380
+ console.error("[hadars] SSR render error:", err);
1381
+ return new Response("Internal Server Error", { status: 500 });
1382
+ }
1383
+ };
1384
+ const finalFetch = options.cache ? createRenderCache(options.cache, (req) => runHandler(req)) : (req) => runHandler(req);
1385
+ return {
1386
+ fetch: async (request, _env, ctx) => {
1387
+ return await finalFetch(request, ctx) ?? new Response("Not Found", { status: 404 });
1388
+ }
1389
+ };
1390
+ }
1391
+ // Annotate the CommonJS export names for ESM import in node:
1392
+ 0 && (module.exports = {
1393
+ createCloudflareHandler
1394
+ });