@absolutejs/absolute 0.19.0-beta.270 → 0.19.0-beta.272

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,797 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ function __accessProp(key) {
9
+ return this[key];
10
+ }
11
+ var __toESMCache_node;
12
+ var __toESMCache_esm;
13
+ var __toESM = (mod, isNodeMode, target) => {
14
+ var canCache = mod != null && typeof mod === "object";
15
+ if (canCache) {
16
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
+ var cached = cache.get(mod);
18
+ if (cached)
19
+ return cached;
20
+ }
21
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
22
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ if (canCache)
30
+ cache.set(mod, to);
31
+ return to;
32
+ };
33
+ var __toCommonJS = (from) => {
34
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
35
+ if (entry)
36
+ return entry;
37
+ entry = __defProp({}, "__esModule", { value: true });
38
+ if (from && typeof from === "object" || typeof from === "function") {
39
+ for (var key of __getOwnPropNames(from))
40
+ if (!__hasOwnProp.call(entry, key))
41
+ __defProp(entry, key, {
42
+ get: __accessProp.bind(from, key),
43
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
44
+ });
45
+ }
46
+ __moduleCache.set(from, entry);
47
+ return entry;
48
+ };
49
+ var __moduleCache;
50
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
51
+ var __returnValue = (v) => v;
52
+ function __exportSetter(name, newValue) {
53
+ this[name] = __returnValue.bind(null, newValue);
54
+ }
55
+ var __export = (target, all) => {
56
+ for (var name in all)
57
+ __defProp(target, name, {
58
+ get: all[name],
59
+ enumerable: true,
60
+ configurable: true,
61
+ set: __exportSetter.bind(all, name)
62
+ });
63
+ };
64
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
65
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
66
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
67
+ r = Reflect.decorate(decorators, target, key, desc);
68
+ else
69
+ for (var i = decorators.length - 1;i >= 0; i--)
70
+ if (d = decorators[i])
71
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
72
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
73
+ };
74
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
75
+ var __require = import.meta.require;
76
+
77
+ // src/constants.ts
78
+ var ANGULAR_INIT_TIMEOUT_MS = 500, ANSI_ESCAPE_LENGTH = 3, ASCII_SPACE = 32, BASE_36_RADIX = 36, BUN_BUILD_WARNING_SUPPRESSION = "wildcard sideEffects are not supported yet", BODY_SLICE_LENGTH = 2000, BYTES_PER_KILOBYTE = 1024, CLI_ARGS_OFFSET = 3, CSS_ERROR_RESOLVE_DELAY_MS = 50, CSS_MAX_CHECK_ATTEMPTS = 10, CSS_MAX_PARSE_TIMEOUT_MS = 500, CSS_SHEET_READY_TIMEOUT_MS = 100, DEFAULT_CHUNK_SIZE = 16384, DEFAULT_DEBOUNCE_MS = 15, DEFAULT_PORT = 3000, DEV_SERVER_RESTART_DEBOUNCE_MS = 100, DOM_UPDATE_DELAY_MS = 50, FILE_PROTOCOL_PREFIX_LENGTH = 7, FOCUS_ID_PREFIX_LENGTH = 3, FOCUS_IDX_PREFIX_LENGTH = 4, FOCUS_NAME_PREFIX_LENGTH = 5, HMR_UPDATE_TIMEOUT_MS = 2000, HOOK_SIGNATURE_LENGTH = 12, HOURS_IN_DAY = 24, HOURS_IN_HALF_DAY = 12, MAX_ERROR_LENGTH = 200, MAX_RECONNECT_ATTEMPTS = 60, MILLISECONDS_IN_A_SECOND = 1000, MINUTES_IN_AN_HOUR = 60, SECONDS_IN_A_MINUTE = 60, MILLISECONDS_IN_A_MINUTE, MILLISECONDS_IN_A_DAY, OVERLAY_FADE_DURATION_MS = 150, PING_INTERVAL_MS = 30000, RAF_BATCH_COUNT = 3, RANDOM_ID_END_INDEX = 11, REBUILD_BATCH_DELAY_MS = 10, REBUILD_RELOAD_DELAY_MS = 200, RECONNECT_INITIAL_DELAY_MS = 500, RECONNECT_POLL_INTERVAL_MS = 300, SIGINT_EXIT_CODE = 130, SIGTERM_EXIT_CODE = 143, SVELTE_CSS_LOAD_TIMEOUT_MS = 500, TIME_PRECISION = 2, TWO_THIRDS, UNFOUND_INDEX = -1, WEBSOCKET_NORMAL_CLOSURE = 1000;
79
+ var init_constants = __esm(() => {
80
+ MILLISECONDS_IN_A_MINUTE = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
81
+ MILLISECONDS_IN_A_DAY = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE * MINUTES_IN_AN_HOUR * HOURS_IN_DAY;
82
+ TWO_THIRDS = 2 / 3;
83
+ });
84
+
85
+ // src/utils/ssrErrorPage.ts
86
+ var ssrErrorPage = (framework, error) => {
87
+ const frameworkColors = {
88
+ angular: "#dd0031",
89
+ html: "#e34c26",
90
+ htmx: "#1a365d",
91
+ react: "#61dafb",
92
+ svelte: "#ff3e00",
93
+ vue: "#42b883"
94
+ };
95
+ const accent = frameworkColors[framework] ?? "#94a3b8";
96
+ const label = framework.charAt(0).toUpperCase() + framework.slice(1);
97
+ const message = error instanceof Error ? error.message : String(error);
98
+ return `<!DOCTYPE html>
99
+ <html>
100
+ <head>
101
+ <meta charset="utf-8">
102
+ <meta name="viewport" content="width=device-width, initial-scale=1">
103
+ <title>SSR Error - AbsoluteJS</title>
104
+ <style>
105
+ *{margin:0;padding:0;box-sizing:border-box}
106
+ body{min-height:100vh;background:linear-gradient(135deg,rgba(15,23,42,0.98) 0%,rgba(30,41,59,0.98) 100%);color:#e2e8f0;font-family:"JetBrains Mono","Fira Code",ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:14px;line-height:1.6;display:flex;align-items:flex-start;justify-content:center;padding:32px}
107
+ .card{max-width:720px;width:100%;background:rgba(30,41,59,0.6);border:1px solid rgba(71,85,105,0.5);border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5),0 0 0 1px rgba(255,255,255,0.05);overflow:hidden}
108
+ .header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:20px 24px;background:rgba(15,23,42,0.5);border-bottom:1px solid rgba(71,85,105,0.4)}
109
+ .brand{font-weight:700;font-size:20px;color:#fff;letter-spacing:-0.02em}
110
+ .badge{padding:5px 10px;border-radius:8px;font-size:12px;font-weight:600;background:${accent};color:#fff;opacity:0.95;box-shadow:0 2px 4px rgba(0,0,0,0.2)}
111
+ .kind{color:#94a3b8;font-size:13px;font-weight:500}
112
+ .content{padding:24px}
113
+ .label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px}
114
+ .message{margin:0;padding:16px 20px;background:rgba(239,68,68,0.12);border:1px solid rgba(239,68,68,0.25);border-radius:10px;overflow-x:auto;white-space:pre-wrap;word-break:break-word;color:#fca5a5;font-size:13px;line-height:1.5}
115
+ .hint{margin-top:20px;padding:12px 20px;background:rgba(71,85,105,0.3);border-radius:10px;border:1px solid rgba(71,85,105,0.4);color:#cbd5e1;font-size:13px}
116
+ </style>
117
+ </head>
118
+ <body>
119
+ <div class="card">
120
+ <div class="header">
121
+ <div style="display:flex;align-items:center;gap:12px">
122
+ <span class="brand">AbsoluteJS</span>
123
+ <span class="badge">${label}</span>
124
+ </div>
125
+ <span class="kind">Server Render Error</span>
126
+ </div>
127
+ <div class="content">
128
+ <div class="label">What went wrong</div>
129
+ <pre class="message">${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>
130
+ <div class="hint">A component threw during server-side rendering. Check the terminal for the full stack trace.</div>
131
+ </div>
132
+ </div>
133
+ </body>
134
+ </html>`;
135
+ };
136
+
137
+ // src/utils/stringModifiers.ts
138
+ var normalizeSlug = (str) => str.trim().replace(/\s+/g, "-").replace(/[^A-Za-z0-9\-_]+/g, "").replace(/[-_]{2,}/g, "-"), toKebab = (str) => normalizeSlug(str).replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(), toPascal = (str) => {
139
+ if (!str.includes("-") && !str.includes("_")) {
140
+ return str.charAt(0).toUpperCase() + str.slice(1);
141
+ }
142
+ return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
143
+ }, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
144
+
145
+ // src/utils/resolveConvention.ts
146
+ import { basename } from "path";
147
+ var CONVENTIONS_KEY = "__absoluteConventions", isConventionsMap = (value) => Boolean(value) && typeof value === "object", getMap = () => {
148
+ const value = Reflect.get(globalThis, CONVENTIONS_KEY);
149
+ if (isConventionsMap(value))
150
+ return value;
151
+ const empty = {};
152
+ return empty;
153
+ }, derivePageName = (pagePath) => {
154
+ const base = basename(pagePath);
155
+ const dotIndex = base.indexOf(".");
156
+ const name = dotIndex > 0 ? base.slice(0, dotIndex) : base;
157
+ return toPascal(name);
158
+ }, resolveErrorConventionPath = (framework, pageName) => {
159
+ const conventions = getMap()[framework];
160
+ if (!conventions)
161
+ return;
162
+ return conventions.pages?.[pageName]?.error ?? conventions.defaults?.error;
163
+ }, resolveNotFoundConventionPath = (framework) => getMap()[framework]?.defaults?.notFound, setConventions = (map) => {
164
+ Reflect.set(globalThis, CONVENTIONS_KEY, map);
165
+ }, isDev = () => true, buildErrorProps = (error) => {
166
+ const message = error instanceof Error ? error.message : String(error);
167
+ const stack = isDev() && error instanceof Error ? error.stack : undefined;
168
+ return { error: { message, stack } };
169
+ }, renderReactError = async (conventionPath, errorProps) => {
170
+ const { createElement } = await import("react");
171
+ const { renderToReadableStream } = await import("react-dom/server");
172
+ const mod = await import(conventionPath);
173
+ const [firstKey] = Object.keys(mod);
174
+ const ErrorComponent = mod.default ?? (firstKey ? mod[firstKey] : undefined);
175
+ const element = createElement(ErrorComponent, errorProps);
176
+ const stream = await renderToReadableStream(element);
177
+ return new Response(stream, {
178
+ headers: { "Content-Type": "text/html" },
179
+ status: 500
180
+ });
181
+ }, renderSvelteError = async (conventionPath, errorProps) => {
182
+ const { render } = await import("svelte/server");
183
+ const mod = await import(conventionPath);
184
+ const ErrorComponent = mod.default;
185
+ const { head, body } = render(ErrorComponent, {
186
+ props: errorProps
187
+ });
188
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
189
+ return new Response(html, {
190
+ headers: { "Content-Type": "text/html" },
191
+ status: 500
192
+ });
193
+ }, unescapeVueStyles = (ssrBody) => {
194
+ let styles = "";
195
+ const body = ssrBody.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => {
196
+ styles += `<style>${css.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")}</style>`;
197
+ return "";
198
+ });
199
+ return { body, styles };
200
+ }, renderVueError = async (conventionPath, errorProps) => {
201
+ const { createSSRApp, h } = await import("vue");
202
+ const { renderToString } = await import("vue/server-renderer");
203
+ const mod = await import(conventionPath);
204
+ const ErrorComponent = mod.default;
205
+ const app = createSSRApp({
206
+ render: () => h(ErrorComponent, errorProps)
207
+ });
208
+ const rawBody = await renderToString(app);
209
+ const { styles, body } = unescapeVueStyles(rawBody);
210
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
211
+ return new Response(html, {
212
+ headers: { "Content-Type": "text/html" },
213
+ status: 500
214
+ });
215
+ }, renderAngularError = async (conventionPath, errorProps) => {
216
+ const mod = await import(conventionPath);
217
+ const renderError = mod.default ?? mod.renderError;
218
+ if (typeof renderError !== "function")
219
+ return null;
220
+ const html = renderError(errorProps);
221
+ return new Response(html, {
222
+ headers: { "Content-Type": "text/html" },
223
+ status: 500
224
+ });
225
+ }, logConventionRenderError = (framework, label, renderError) => {
226
+ const message = renderError instanceof Error ? renderError.message : "";
227
+ if (message.includes("Cannot find module") || message.includes("Cannot find package") || message.includes("not found in module")) {
228
+ console.error(`[SSR] Convention ${label} page for ${framework} failed: missing framework package. Ensure the ${framework} runtime is installed (e.g. bun add ${framework === "react" ? "react react-dom" : framework}).`);
229
+ return;
230
+ }
231
+ console.error(`[SSR] Failed to render ${framework} convention ${label} page:`, renderError);
232
+ }, ERROR_RENDERERS, renderConventionError = async (framework, pageName, error) => {
233
+ const conventionPath = resolveErrorConventionPath(framework, pageName);
234
+ if (!conventionPath)
235
+ return null;
236
+ const errorProps = buildErrorProps(error);
237
+ const renderer = ERROR_RENDERERS[framework];
238
+ if (!renderer)
239
+ return null;
240
+ try {
241
+ return await renderer(conventionPath, errorProps);
242
+ } catch (renderError) {
243
+ logConventionRenderError(framework, "error", renderError);
244
+ }
245
+ return null;
246
+ }, renderReactNotFound = async (conventionPath) => {
247
+ const { createElement } = await import("react");
248
+ const { renderToReadableStream } = await import("react-dom/server");
249
+ const mod = await import(conventionPath);
250
+ const [nfKey] = Object.keys(mod);
251
+ const NotFoundComponent = mod.default ?? (nfKey ? mod[nfKey] : undefined);
252
+ const element = createElement(NotFoundComponent);
253
+ const stream = await renderToReadableStream(element);
254
+ return new Response(stream, {
255
+ headers: { "Content-Type": "text/html" },
256
+ status: 404
257
+ });
258
+ }, renderSvelteNotFound = async (conventionPath) => {
259
+ const { render } = await import("svelte/server");
260
+ const mod = await import(conventionPath);
261
+ const NotFoundComponent = mod.default;
262
+ const { head, body } = render(NotFoundComponent);
263
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
264
+ return new Response(html, {
265
+ headers: { "Content-Type": "text/html" },
266
+ status: 404
267
+ });
268
+ }, renderVueNotFound = async (conventionPath) => {
269
+ const { createSSRApp, h } = await import("vue");
270
+ const { renderToString } = await import("vue/server-renderer");
271
+ const mod = await import(conventionPath);
272
+ const NotFoundComponent = mod.default;
273
+ const app = createSSRApp({
274
+ render: () => h(NotFoundComponent)
275
+ });
276
+ const rawBody = await renderToString(app);
277
+ const { styles, body } = unescapeVueStyles(rawBody);
278
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
279
+ return new Response(html, {
280
+ headers: { "Content-Type": "text/html" },
281
+ status: 404
282
+ });
283
+ }, renderAngularNotFound = async (conventionPath) => {
284
+ const mod = await import(conventionPath);
285
+ const renderNotFound = mod.default ?? mod.renderNotFound;
286
+ if (typeof renderNotFound !== "function")
287
+ return null;
288
+ const html = renderNotFound();
289
+ return new Response(html, {
290
+ headers: { "Content-Type": "text/html" },
291
+ status: 404
292
+ });
293
+ }, NOT_FOUND_RENDERERS, renderConventionNotFound = async (framework) => {
294
+ const conventionPath = resolveNotFoundConventionPath(framework);
295
+ if (!conventionPath)
296
+ return null;
297
+ const renderer = NOT_FOUND_RENDERERS[framework];
298
+ if (!renderer)
299
+ return null;
300
+ try {
301
+ return await renderer(conventionPath);
302
+ } catch (renderError) {
303
+ logConventionRenderError(framework, "not-found", renderError);
304
+ }
305
+ return null;
306
+ }, NOT_FOUND_PRIORITY, renderFirstNotFound = async () => {
307
+ for (const framework of NOT_FOUND_PRIORITY) {
308
+ if (!getMap()[framework]?.defaults?.notFound)
309
+ continue;
310
+ const response = await renderConventionNotFound(framework);
311
+ if (response)
312
+ return response;
313
+ }
314
+ return null;
315
+ };
316
+ var init_resolveConvention = __esm(() => {
317
+ ERROR_RENDERERS = {
318
+ angular: renderAngularError,
319
+ react: renderReactError,
320
+ svelte: renderSvelteError,
321
+ vue: renderVueError
322
+ };
323
+ NOT_FOUND_RENDERERS = {
324
+ angular: renderAngularNotFound,
325
+ react: renderReactNotFound,
326
+ svelte: renderSvelteNotFound,
327
+ vue: renderVueNotFound
328
+ };
329
+ NOT_FOUND_PRIORITY = [
330
+ "react",
331
+ "svelte",
332
+ "vue",
333
+ "angular"
334
+ ];
335
+ });
336
+
337
+ // src/utils/registerClientScript.ts
338
+ var scriptRegistry, requestCounter = 0, getRequestId = () => `req_${Date.now()}_${++requestCounter}`, ssrContextGetter = null, registerClientScript = (script, requestId) => {
339
+ const id = requestId || ssrContextGetter?.() || Object.getOwnPropertyDescriptor(globalThis, "__absolutejs_requestId")?.value || getRequestId();
340
+ if (!scriptRegistry.has(id)) {
341
+ scriptRegistry.set(id, new Set);
342
+ }
343
+ scriptRegistry.get(id)?.add(script);
344
+ return id;
345
+ }, setSsrContextGetter = (getter) => {
346
+ ssrContextGetter = getter;
347
+ }, clearAllClientScripts = () => {
348
+ scriptRegistry.clear();
349
+ }, generateClientScriptCode = (scripts) => {
350
+ if (scripts.length === 0) {
351
+ return "";
352
+ }
353
+ const scriptCode = scripts.map((script, index) => {
354
+ const funcString = script.toString();
355
+ const bodyMatch = funcString.match(/\{([\s\S]*)\}/);
356
+ if (!bodyMatch || !bodyMatch[1]) {
357
+ return "";
358
+ }
359
+ const body = bodyMatch[1].trim();
360
+ return `
361
+ (function() {
362
+ var executed = false;
363
+ function executeScript_${index}() {
364
+ if (executed) return;
365
+ executed = true;
366
+ ${body}
367
+ }
368
+
369
+ if (document.readyState === 'complete' || document.readyState === 'interactive') {
370
+ executeScript_${index}();
371
+ } else {
372
+ document.addEventListener('DOMContentLoaded', executeScript_${index});
373
+ }
374
+
375
+ // Watch for hydration-added elements
376
+ var observer = new MutationObserver(function() {
377
+ executeScript_${index}();
378
+ if (executed) observer.disconnect();
379
+ });
380
+ if (!executed) {
381
+ observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
382
+ }
383
+
384
+ // Single fallback timeout
385
+ setTimeout(function() {
386
+ executeScript_${index}();
387
+ observer.disconnect();
388
+ }, 1000);
389
+ })();`;
390
+ }).join(`
391
+ `);
392
+ return `<script>
393
+ (function() {
394
+ ${scriptCode}
395
+ })();
396
+ </script>`;
397
+ }, getAndClearClientScripts = (requestId) => {
398
+ const id = requestId || ssrContextGetter?.();
399
+ if (!id)
400
+ return [];
401
+ const scripts = scriptRegistry.get(id);
402
+ if (!scripts) {
403
+ return [];
404
+ }
405
+ const scriptArray = Array.from(scripts);
406
+ scriptRegistry.delete(id);
407
+ return scriptArray;
408
+ };
409
+ var init_registerClientScript = __esm(() => {
410
+ scriptRegistry = new Map;
411
+ if (typeof globalThis !== "undefined") {
412
+ Object.assign(globalThis, { registerClientScript });
413
+ }
414
+ });
415
+
416
+ // src/angular/injectorPatch.ts
417
+ import { existsSync, readFileSync, writeFileSync } from "fs";
418
+ import { dirname, join, resolve } from "path";
419
+ var applyInjectorPatch = (chunkPath, content) => {
420
+ if (content.includes('Symbol.for("angular.currentInjector")')) {
421
+ return;
422
+ }
423
+ const original = [
424
+ "let _currentInjector = undefined;",
425
+ "function getCurrentInjector() {",
426
+ " return _currentInjector;",
427
+ "}",
428
+ "function setCurrentInjector(injector) {",
429
+ " const former = _currentInjector;",
430
+ " _currentInjector = injector;",
431
+ " return former;",
432
+ "}"
433
+ ].join(`
434
+ `);
435
+ const replacement = [
436
+ 'const _injSym = Symbol.for("angular.currentInjector");',
437
+ "if (!globalThis[_injSym]) globalThis[_injSym] = { v: undefined };",
438
+ "function getCurrentInjector() {",
439
+ " return globalThis[_injSym].v;",
440
+ "}",
441
+ "function setCurrentInjector(injector) {",
442
+ " const former = globalThis[_injSym].v;",
443
+ " globalThis[_injSym].v = injector;",
444
+ " return former;",
445
+ "}"
446
+ ].join(`
447
+ `);
448
+ const patched = content.replace(original, replacement);
449
+ if (patched === content) {
450
+ return;
451
+ }
452
+ writeFileSync(chunkPath, patched, "utf-8");
453
+ }, resolveAngularCoreDir = () => {
454
+ const fromProject = resolve(process.cwd(), "node_modules/@angular/core");
455
+ if (existsSync(join(fromProject, "package.json"))) {
456
+ return fromProject;
457
+ }
458
+ return dirname(__require.resolve("@angular/core/package.json"));
459
+ }, patchAngularInjectorSingleton = () => {
460
+ try {
461
+ const coreDir = resolveAngularCoreDir();
462
+ const chunkPath = join(coreDir, "fesm2022", "_not_found-chunk.mjs");
463
+ const content = readFileSync(chunkPath, "utf-8");
464
+ applyInjectorPatch(chunkPath, content);
465
+ } catch {}
466
+ };
467
+ var init_injectorPatch = __esm(() => {
468
+ patchAngularInjectorSingleton();
469
+ });
470
+
471
+ // src/angular/resolveAngularPackage.ts
472
+ import { existsSync as existsSync2 } from "fs";
473
+ import { resolve as resolve2 } from "path";
474
+ var resolveAngularPackage = (specifier) => {
475
+ const fromProject = resolve2(process.cwd(), "node_modules", specifier);
476
+ if (existsSync2(fromProject)) {
477
+ return fromProject;
478
+ }
479
+ return specifier;
480
+ };
481
+ var init_resolveAngularPackage = () => {};
482
+
483
+ // src/angular/angularPatch.ts
484
+ var exports_angularPatch = {};
485
+ __export(exports_angularPatch, {
486
+ applyPatches: () => applyPatches
487
+ });
488
+ var ensureHead = (doc) => {
489
+ if (!doc || doc.head || !doc.documentElement) {
490
+ return;
491
+ }
492
+ const head = doc.createElement("head");
493
+ doc.documentElement.insertBefore(head, doc.documentElement.firstChild);
494
+ }, applyPatches = async () => {
495
+ const { \u{275}DominoAdapter } = await import(resolveAngularPackage("@angular/platform-server"));
496
+ if (!\u{275}DominoAdapter?.prototype) {
497
+ console.warn("[Angular Patch] \u0275DominoAdapter not found, skipping patches");
498
+ return false;
499
+ }
500
+ const proto = \u{275}DominoAdapter.prototype;
501
+ const origGetBaseHref = proto.getBaseHref;
502
+ proto.getBaseHref = function(doc) {
503
+ if (!doc || !doc.head || typeof doc.head.children === "undefined") {
504
+ return "";
505
+ }
506
+ return origGetBaseHref.call(this, doc);
507
+ };
508
+ const origCreateHtmlDocument = proto.createHtmlDocument;
509
+ proto.createHtmlDocument = function() {
510
+ const doc = origCreateHtmlDocument.call(this);
511
+ ensureHead(doc);
512
+ return doc;
513
+ };
514
+ const origGetDefaultDocument = proto.getDefaultDocument;
515
+ proto.getDefaultDocument = function() {
516
+ const doc = origGetDefaultDocument.call(this);
517
+ ensureHead(doc);
518
+ return doc;
519
+ };
520
+ return true;
521
+ };
522
+ var init_angularPatch = __esm(() => {
523
+ init_resolveAngularPackage();
524
+ });
525
+
526
+ // src/angular/angularDeps.ts
527
+ var initDominoAdapter = (platformServer) => {
528
+ try {
529
+ const DominoAdapter = platformServer.\u{275}DominoAdapter;
530
+ DominoAdapter?.makeCurrent?.();
531
+ } catch (err) {
532
+ console.error("Failed to initialize DominoAdapter:", err);
533
+ }
534
+ }, loadAngularDeps = async () => {
535
+ patchAngularInjectorSingleton();
536
+ await import(resolveAngularPackage("@angular/compiler"));
537
+ const { applyPatches: applyPatches2 } = await Promise.resolve().then(() => (init_angularPatch(), exports_angularPatch));
538
+ await applyPatches2();
539
+ const [platformBrowser, platformServer, common, core] = await Promise.all([
540
+ import(resolveAngularPackage("@angular/platform-browser")),
541
+ import(resolveAngularPackage("@angular/platform-server")),
542
+ import(resolveAngularPackage("@angular/common")),
543
+ import(resolveAngularPackage("@angular/core"))
544
+ ]);
545
+ if (false) {}
546
+ initDominoAdapter(platformServer);
547
+ return {
548
+ APP_BASE_HREF: common.APP_BASE_HREF,
549
+ bootstrapApplication: platformBrowser.bootstrapApplication,
550
+ DomSanitizer: platformBrowser.DomSanitizer,
551
+ provideClientHydration: platformBrowser.provideClientHydration,
552
+ provideServerRendering: platformServer.provideServerRendering,
553
+ provideZonelessChangeDetection: core.provideZonelessChangeDetection,
554
+ reflectComponentType: core.reflectComponentType,
555
+ renderApplication: platformServer.renderApplication,
556
+ Sanitizer: core.Sanitizer,
557
+ SecurityContext: core.SecurityContext
558
+ };
559
+ }, angularDeps = null, getAngularDeps = () => {
560
+ if (!angularDeps) {
561
+ angularDeps = loadAngularDeps();
562
+ }
563
+ return angularDeps;
564
+ };
565
+ var init_angularDeps = __esm(() => {
566
+ init_injectorPatch();
567
+ init_resolveAngularPackage();
568
+ });
569
+
570
+ // src/angular/ssrSanitizer.ts
571
+ var escapeHtml = (str) => String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"), bypassValue = (value) => ({
572
+ changingThisBreaksApplicationSecurity: value
573
+ }), ssrSanitizer = null, getSsrSanitizer = (deps) => {
574
+ if (ssrSanitizer)
575
+ return ssrSanitizer;
576
+ const SsrSanitizerClass = class extends deps.DomSanitizer {
577
+ sanitize(ctx, value) {
578
+ if (value === null)
579
+ return null;
580
+ let strValue;
581
+ let isTrustedHtml = false;
582
+ if (typeof value === "string") {
583
+ strValue = value;
584
+ } else if (typeof value === "object" && "changingThisBreaksApplicationSecurity" in value) {
585
+ strValue = String(value.changingThisBreaksApplicationSecurity);
586
+ isTrustedHtml = true;
587
+ } else {
588
+ strValue = String(value);
589
+ }
590
+ if (ctx === deps.SecurityContext.HTML) {
591
+ if (isTrustedHtml) {
592
+ return strValue;
593
+ }
594
+ return escapeHtml(strValue);
595
+ }
596
+ return strValue;
597
+ }
598
+ bypassSecurityTrustHtml(value) {
599
+ return bypassValue(value);
600
+ }
601
+ bypassSecurityTrustStyle(value) {
602
+ return bypassValue(value);
603
+ }
604
+ bypassSecurityTrustScript(value) {
605
+ return bypassValue(value);
606
+ }
607
+ bypassSecurityTrustUrl(value) {
608
+ return bypassValue(value);
609
+ }
610
+ bypassSecurityTrustResourceUrl(value) {
611
+ return bypassValue(value);
612
+ }
613
+ };
614
+ ssrSanitizer = new SsrSanitizerClass;
615
+ return ssrSanitizer;
616
+ }, resetSsrSanitizer = () => {
617
+ ssrSanitizer = null;
618
+ };
619
+
620
+ // src/angular/ssrRender.ts
621
+ var routePropsCache, cacheRouteData = (pagePath, data) => {
622
+ const cacheKey = pagePath.split("?")[0] ?? pagePath;
623
+ routePropsCache.set(cacheKey, data);
624
+ }, getCachedRouteData = (pagePath) => routePropsCache.get(pagePath), selectorCache, buildDeps = (ssrResult, baseDeps) => {
625
+ if (!ssrResult?.core) {
626
+ return baseDeps;
627
+ }
628
+ const { common, core, platformBrowser, platformServer } = ssrResult;
629
+ return {
630
+ APP_BASE_HREF: common?.APP_BASE_HREF ?? baseDeps.APP_BASE_HREF,
631
+ bootstrapApplication: platformBrowser?.bootstrapApplication ?? baseDeps.bootstrapApplication,
632
+ DomSanitizer: platformBrowser?.DomSanitizer ?? baseDeps.DomSanitizer,
633
+ provideClientHydration: platformBrowser?.provideClientHydration ?? baseDeps.provideClientHydration,
634
+ provideServerRendering: platformServer?.provideServerRendering ?? baseDeps.provideServerRendering,
635
+ provideZonelessChangeDetection: core.provideZonelessChangeDetection,
636
+ reflectComponentType: core.reflectComponentType,
637
+ renderApplication: platformServer?.renderApplication ?? baseDeps.renderApplication,
638
+ Sanitizer: core.Sanitizer,
639
+ SecurityContext: core.SecurityContext
640
+ };
641
+ }, buildProviders = (deps, sanitizer, maybeProps, tokenMap) => {
642
+ const providers = [
643
+ deps.provideServerRendering(),
644
+ deps.provideClientHydration(),
645
+ deps.provideZonelessChangeDetection(),
646
+ { provide: deps.APP_BASE_HREF, useValue: "/" },
647
+ {
648
+ provide: deps.DomSanitizer,
649
+ useValue: sanitizer
650
+ },
651
+ { provide: deps.Sanitizer, useValue: sanitizer }
652
+ ];
653
+ if (!maybeProps) {
654
+ return providers;
655
+ }
656
+ const propProviders = Object.entries(maybeProps).map(([propName, propValue]) => ({
657
+ token: tokenMap.get(toScreamingSnake(propName)),
658
+ value: propValue
659
+ })).filter((entry) => entry.token).map((entry) => ({ provide: entry.token, useValue: entry.value }));
660
+ return [...providers, ...propProviders];
661
+ }, clearSelectorCache = () => selectorCache.clear(), isInjectionToken = (value) => {
662
+ if (!value || typeof value !== "object") {
663
+ return false;
664
+ }
665
+ return "ngMetadataName" in value && value.ngMetadataName === "InjectionToken";
666
+ }, discoverTokens = (pageModule) => new Map(Object.entries(pageModule).filter(([, value]) => isInjectionToken(value))), loadSsrDeps = async (pagePath) => {
667
+ const ssrDepsPath = (pagePath.split("?")[0] ?? pagePath).replace(/\.js$/, ".ssr-deps.js");
668
+ try {
669
+ const ssrDeps = await import(ssrDepsPath);
670
+ const result = {
671
+ common: ssrDeps.__angularCommon,
672
+ core: ssrDeps.__angularCore,
673
+ platformBrowser: ssrDeps.__angularPlatformBrowser,
674
+ platformServer: ssrDeps.__angularPlatformServer
675
+ };
676
+ return result;
677
+ } catch {
678
+ return null;
679
+ }
680
+ }, resolveSelector = (deps, pagePath, PageComponent) => {
681
+ const cached = selectorCache.get(pagePath);
682
+ if (cached) {
683
+ return cached;
684
+ }
685
+ const selector = deps.reflectComponentType(PageComponent)?.selector ?? "ng-app";
686
+ selectorCache.set(pagePath, selector);
687
+ return selector;
688
+ }, injectBeforeClose = (html, snippet) => {
689
+ if (html.includes("</body>")) {
690
+ return html.replace("</body>", `${snippet}</body>`);
691
+ }
692
+ if (html.includes("</html>")) {
693
+ return html.replace("</html>", `${snippet}</html>`);
694
+ }
695
+ return html + snippet;
696
+ }, injectSsrScripts = (html, requestId, indexPath) => {
697
+ let result = html;
698
+ const registeredScripts = getAndClearClientScripts(requestId);
699
+ if (registeredScripts.length > 0) {
700
+ result = injectBeforeClose(result, generateClientScriptCode(registeredScripts));
701
+ }
702
+ if (indexPath) {
703
+ result = injectBeforeClose(result, `<script type="module" src="${indexPath}"></script>`);
704
+ }
705
+ return result;
706
+ }, renderAngularApp = async (deps, PageComponent, providers, document) => {
707
+ const origLog = console.log;
708
+ console.log = (...args) => {
709
+ if (typeof args[0] === "string" && args[0].includes("development mode")) {
710
+ return;
711
+ }
712
+ origLog.apply(console, args);
713
+ };
714
+ const bootstrap = (context) => deps.bootstrapApplication(PageComponent, { providers }, context);
715
+ try {
716
+ return await deps.renderApplication(bootstrap, {
717
+ document,
718
+ platformProviders: [],
719
+ url: "/"
720
+ });
721
+ } finally {
722
+ console.log = origLog;
723
+ }
724
+ };
725
+ var init_ssrRender = __esm(() => {
726
+ init_registerClientScript();
727
+ routePropsCache = new Map;
728
+ selectorCache = new Map;
729
+ });
730
+
731
+ // src/angular/pageHandler.ts
732
+ import { AsyncLocalStorage } from "async_hooks";
733
+ var ssrDirty = false, lastSelector = "angular-page", invalidateAngularSsrCache = () => {
734
+ ssrDirty = true;
735
+ clearSelectorCache();
736
+ }, angularSsrContext, handleAngularPageRequest = async (_importer, pagePath, indexPath, headTag = "<head></head>", ...props) => {
737
+ const requestId = `angular_${Date.now()}_${Math.random().toString(BASE_36_RADIX).substring(2, RANDOM_ID_END_INDEX)}`;
738
+ return angularSsrContext.run(requestId, async () => {
739
+ const [maybeProps] = props;
740
+ cacheRouteData(pagePath, { headTag, props: maybeProps });
741
+ if (ssrDirty) {
742
+ const script = indexPath ? `<script type="module" src="${indexPath}"></script>` : "";
743
+ const html = `<!DOCTYPE html><html>${headTag}<body><${lastSelector}></${lastSelector}>${script}</body></html>`;
744
+ return new Response(html, {
745
+ headers: { "Content-Type": "text/html" }
746
+ });
747
+ }
748
+ try {
749
+ const baseDeps = await getAngularDeps();
750
+ const pageModule = await import(pagePath);
751
+ const PageComponent = pageModule.default;
752
+ const ssrResult = await loadSsrDeps(pagePath);
753
+ const deps = buildDeps(ssrResult, baseDeps);
754
+ const tokenMap = discoverTokens(pageModule);
755
+ const selector = resolveSelector(deps, pagePath, PageComponent);
756
+ lastSelector = selector;
757
+ const htmlString = `<!DOCTYPE html><html>${headTag}<body><${selector}></${selector}></body></html>`;
758
+ if (ssrResult?.core)
759
+ resetSsrSanitizer();
760
+ const sanitizer = getSsrSanitizer(deps);
761
+ const providers = buildProviders(deps, sanitizer, maybeProps, tokenMap);
762
+ const rawHtml = await renderAngularApp(deps, PageComponent, providers, htmlString);
763
+ const html = injectSsrScripts(rawHtml, requestId, indexPath);
764
+ return new Response(html, {
765
+ headers: { "Content-Type": "text/html" }
766
+ });
767
+ } catch (error) {
768
+ console.error("[SSR] Angular render error:", error);
769
+ const pageName = derivePageName(pagePath);
770
+ const conventionResponse = await renderConventionError("angular", pageName, error);
771
+ if (conventionResponse)
772
+ return conventionResponse;
773
+ return new Response(ssrErrorPage("angular", error), {
774
+ headers: { "Content-Type": "text/html" },
775
+ status: 500
776
+ });
777
+ }
778
+ });
779
+ };
780
+ var init_pageHandler = __esm(() => {
781
+ init_constants();
782
+ init_resolveConvention();
783
+ init_registerClientScript();
784
+ init_angularDeps();
785
+ init_ssrRender();
786
+ angularSsrContext = new AsyncLocalStorage;
787
+ setSsrContextGetter(() => angularSsrContext.getStore());
788
+ });
789
+
790
+ // src/angular/server.ts
791
+ init_pageHandler();
792
+ export {
793
+ handleAngularPageRequest
794
+ };
795
+
796
+ //# debugId=A63E56AEF2A815A264756E2164756E21
797
+ //# sourceMappingURL=server.js.map