@absolutejs/absolute 0.19.0-beta.695 → 0.19.0-beta.697

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +1 -1
  2. package/dist/angular/browser.js +48 -40
  3. package/dist/angular/browser.js.map +4 -4
  4. package/dist/angular/index.js +2308 -2232
  5. package/dist/angular/index.js.map +14 -13
  6. package/dist/angular/server.js +2279 -2203
  7. package/dist/angular/server.js.map +14 -14
  8. package/dist/build.js +42796 -6393
  9. package/dist/build.js.map +9 -20
  10. package/dist/cli/index.js +9 -2
  11. package/dist/core/streamingSlotRegistrar.js +24 -16
  12. package/dist/core/streamingSlotRegistrar.js.map +2 -2
  13. package/dist/core/streamingSlotRegistry.js +42 -29
  14. package/dist/core/streamingSlotRegistry.js.map +2 -2
  15. package/dist/index.js +42693 -5631
  16. package/dist/index.js.map +19 -24
  17. package/dist/react/components/index.js +24 -16
  18. package/dist/react/components/index.js.map +2 -2
  19. package/dist/react/index.js +922 -868
  20. package/dist/react/index.js.map +12 -12
  21. package/dist/react/server.js +903 -848
  22. package/dist/react/server.js.map +11 -11
  23. package/dist/src/build/compileTailwind.d.ts +3 -0
  24. package/dist/src/core/pageHandlers.d.ts +0 -2
  25. package/dist/src/core/ssrCache.d.ts +3 -0
  26. package/dist/svelte/index.js +963 -899
  27. package/dist/svelte/index.js.map +14 -13
  28. package/dist/svelte/server.js +777 -712
  29. package/dist/svelte/server.js.map +12 -12
  30. package/dist/types/build.d.ts +5 -4
  31. package/dist/types/index.d.ts +0 -1
  32. package/dist/types/island.d.ts +14 -11
  33. package/dist/vue/components/index.js +24 -16
  34. package/dist/vue/components/index.js.map +2 -2
  35. package/dist/vue/index.js +1040 -976
  36. package/dist/vue/index.js.map +12 -12
  37. package/dist/vue/server.js +908 -841
  38. package/dist/vue/server.js.map +11 -11
  39. package/package.json +16 -8
@@ -78,99 +78,6 @@ var __legacyMetadataTS = (k, v) => {
78
78
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
79
79
  var __require = import.meta.require;
80
80
 
81
- // src/core/streamingSlotRegistrar.ts
82
- var STREAMING_SLOT_REGISTRAR_KEY, STREAMING_SLOT_WARNING_STORAGE_KEY, STREAMING_SLOT_COLLECTION_STORAGE_KEY, getRegisteredStreamingSlotRegistrar = () => {
83
- const value = Reflect.get(globalThis, STREAMING_SLOT_REGISTRAR_KEY);
84
- if (typeof value === "function" || value === null) {
85
- return value;
86
- }
87
- return;
88
- }, isObjectRecord = (value) => Boolean(value) && typeof value === "object", isStreamingSlotWarningController = (value) => isObjectRecord(value) && ("maybeWarn" in value) && typeof value.maybeWarn === "function", isStreamingSlotCollectionController = (value) => isObjectRecord(value) && ("isCollecting" in value) && typeof value.isCollecting === "function", getWarningController = () => {
89
- const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY);
90
- if (value === null || typeof value === "undefined")
91
- return;
92
- return isStreamingSlotWarningController(value) ? value : undefined;
93
- }, getCollectionController = () => {
94
- const value = Reflect.get(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY);
95
- if (value === null || typeof value === "undefined")
96
- return;
97
- return isStreamingSlotCollectionController(value) ? value : undefined;
98
- }, hasRegisteredStreamingSlotRegistrar = () => typeof getRegisteredStreamingSlotRegistrar() === "function", isStreamingSlotCollectionActive = () => getCollectionController()?.isCollecting() === true, registerStreamingSlot = (slot) => {
99
- getRegisteredStreamingSlotRegistrar()?.(slot);
100
- }, setStreamingSlotCollectionController = (controller) => {
101
- Reflect.set(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY, controller);
102
- }, setStreamingSlotRegistrar = (nextRegistrar) => {
103
- Reflect.set(globalThis, STREAMING_SLOT_REGISTRAR_KEY, nextRegistrar);
104
- }, setStreamingSlotWarningController = (controller) => {
105
- Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY, controller);
106
- }, warnMissingStreamingSlotCollector = (primitiveName) => {
107
- if (isStreamingSlotCollectionActive()) {
108
- return;
109
- }
110
- getWarningController()?.maybeWarn(primitiveName);
111
- };
112
- var init_streamingSlotRegistrar = __esm(() => {
113
- STREAMING_SLOT_REGISTRAR_KEY = Symbol.for("absolutejs.streamingSlotRegistrar");
114
- STREAMING_SLOT_WARNING_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotWarningController");
115
- STREAMING_SLOT_COLLECTION_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotCollectionController");
116
- });
117
-
118
- // src/core/streamingSlotRegistry.ts
119
- var STREAMING_SLOT_STORAGE_KEY, isObjectRecord2 = (value) => Boolean(value) && typeof value === "object", isAsyncLocalStorage = (value) => isObjectRecord2(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function", getStorageGlobal = () => {
120
- const value = Reflect.get(globalThis, STREAMING_SLOT_STORAGE_KEY);
121
- if (value === null || typeof value === "undefined") {
122
- return value;
123
- }
124
- return isAsyncLocalStorage(value) ? value : undefined;
125
- }, isServerRuntime = () => typeof process !== "undefined" && typeof process.versions?.node === "string", ensureAsyncLocalStorage = async () => {
126
- const storage = getStorageGlobal();
127
- if (typeof storage !== "undefined") {
128
- return storage;
129
- }
130
- if (!isServerRuntime()) {
131
- Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, null);
132
- return getStorageGlobal();
133
- }
134
- const mod = await import("async_hooks");
135
- Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, new mod.AsyncLocalStorage);
136
- return getStorageGlobal();
137
- }, getActiveSlotStore = () => {
138
- const storage = getStorageGlobal();
139
- if (!storage)
140
- return;
141
- return storage.getStore();
142
- }, registerStreamingSlot2 = (slot) => {
143
- const store = getActiveSlotStore();
144
- if (!store)
145
- return;
146
- store.set(slot.id, slot);
147
- }, hasActiveStreamingSlotRegistry = () => getActiveSlotStore() !== undefined, runWithStreamingSlotRegistry = async (task) => {
148
- const storage = await ensureAsyncLocalStorage();
149
- if (!storage) {
150
- const slots = [];
151
- return {
152
- result: await task(),
153
- slots
154
- };
155
- }
156
- return storage.run(new Map, async () => {
157
- const result = await task();
158
- const store = storage.getStore();
159
- return {
160
- result,
161
- slots: store ? [...store.values()] : []
162
- };
163
- });
164
- };
165
- var init_streamingSlotRegistry = __esm(() => {
166
- init_streamingSlotRegistrar();
167
- STREAMING_SLOT_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotAsyncLocalStorage");
168
- setStreamingSlotRegistrar(registerStreamingSlot2);
169
- setStreamingSlotCollectionController({
170
- isCollecting: () => getActiveSlotStore() !== undefined
171
- });
172
- });
173
-
174
81
  // src/constants.ts
175
82
  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, EXCLUDE_LAST_OFFSET = -1, HTTP_STATUS_OK = 200, HTTP_STATUS_BAD_REQUEST = 400, HTTP_STATUS_NOT_FOUND = 404, 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, REACT_STREAM_SLOT_FAST_DELAY_MS = 5, REACT_STREAM_SLOT_SLOW_DELAY_MS = 20, 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;
176
83
  var init_constants = __esm(() => {
@@ -179,1838 +86,1396 @@ var init_constants = __esm(() => {
179
86
  TWO_THIRDS = 2 / 3;
180
87
  });
181
88
 
182
- // src/core/islandPageContext.ts
183
- var BOOTSTRAP_MANIFEST_KEY = "BootstrapClient", ISLAND_MARKER = 'data-island="true"', MANIFEST_MARKER = "__ABSOLUTE_MANIFEST__", ISLAND_STATE_MARKER = "__ABS_ISLAND_STATE__", CLOSING_HEAD_TAG = "</head>", buildIslandsHeadMarkup = (manifest) => {
184
- const manifestScript = `<script>window.__ABSOLUTE_MANIFEST__ = ${JSON.stringify(manifest)}</script>`;
185
- const islandStateScript = `<script>window.__ABS_ISLAND_STATE__ = ${JSON.stringify(globalThis.__ABS_ISLAND_STATE__ ?? {})}</script>`;
186
- const bootstrapPath = manifest[BOOTSTRAP_MANIFEST_KEY];
187
- const bootstrapScript = bootstrapPath ? `<script type="module" src="${bootstrapPath}"></script>` : "";
188
- return `${manifestScript}${islandStateScript}${bootstrapScript}`;
189
- }, injectHeadMarkup = (html, markup) => {
190
- const closingHeadIndex = html.indexOf("</head>");
191
- if (closingHeadIndex >= 0) {
192
- return `${html.slice(0, closingHeadIndex)}${markup}${html.slice(closingHeadIndex)}`;
89
+ // src/utils/stringModifiers.ts
90
+ 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) => {
91
+ if (!str.includes("-") && !str.includes("_")) {
92
+ return str.charAt(0).toUpperCase() + str.slice(1);
193
93
  }
194
- const openingBodyIndex = html.indexOf("<body");
195
- if (openingBodyIndex >= 0) {
196
- const bodyStart = html.indexOf(">", openingBodyIndex);
197
- if (bodyStart >= 0) {
198
- return `${html.slice(0, openingBodyIndex)}<head>${markup}</head>${html.slice(openingBodyIndex)}`;
94
+ return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
95
+ }, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
96
+
97
+ // src/utils/registerClientScript.ts
98
+ var scriptRegistry, requestCounter = 0, getRequestId = () => `req_${Date.now()}_${++requestCounter}`, ssrContextGetter = null, getSsrContextId = () => ssrContextGetter?.() || Object.getOwnPropertyDescriptor(globalThis, "__absolutejs_requestId")?.value, registerClientScript = (script, requestId) => {
99
+ const id = requestId || getSsrContextId() || getRequestId();
100
+ if (!scriptRegistry.has(id)) {
101
+ scriptRegistry.set(id, new Set);
102
+ }
103
+ scriptRegistry.get(id)?.add(script);
104
+ return id;
105
+ }, setSsrContextGetter = (getter) => {
106
+ ssrContextGetter = getter;
107
+ }, clearAllClientScripts = () => {
108
+ scriptRegistry.clear();
109
+ }, generateClientScriptCode = (scripts) => {
110
+ if (scripts.length === 0) {
111
+ return "";
112
+ }
113
+ const scriptCode = scripts.map((script, index) => {
114
+ const funcString = script.toString();
115
+ const bodyMatch = funcString.match(/\{([\s\S]*)\}/);
116
+ if (!bodyMatch || !bodyMatch[1]) {
117
+ return "";
199
118
  }
119
+ const body = bodyMatch[1].trim();
120
+ return `
121
+ (function() {
122
+ var executed = false;
123
+ function executeScript_${index}() {
124
+ if (executed) return;
125
+ executed = true;
126
+ ${body}
127
+ }
128
+
129
+ if (document.readyState === 'complete' || document.readyState === 'interactive') {
130
+ executeScript_${index}();
131
+ } else {
132
+ document.addEventListener('DOMContentLoaded', executeScript_${index});
133
+ }
134
+
135
+ // Watch for hydration-added elements
136
+ var observer = new MutationObserver(function() {
137
+ executeScript_${index}();
138
+ if (executed) observer.disconnect();
139
+ });
140
+ if (!executed) {
141
+ observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
142
+ }
143
+
144
+ // Single fallback timeout
145
+ setTimeout(function() {
146
+ executeScript_${index}();
147
+ observer.disconnect();
148
+ }, 1000);
149
+ })();`;
150
+ }).join(`
151
+ `);
152
+ return `<script>
153
+ (function() {
154
+ ${scriptCode}
155
+ })();
156
+ </script>`;
157
+ }, getAndClearClientScripts = (requestId) => {
158
+ const id = requestId || ssrContextGetter?.();
159
+ if (!id)
160
+ return [];
161
+ const scripts = scriptRegistry.get(id);
162
+ if (!scripts) {
163
+ return [];
200
164
  }
201
- return `<!DOCTYPE html><html><head>${markup}</head><body>${html}</body></html>`;
202
- }, streamChunkToString = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true }), flushSafePendingText = (controller, encoder, pending, lookbehind) => {
203
- if (pending.length <= lookbehind) {
204
- return pending;
165
+ const scriptArray = Array.from(scripts);
166
+ scriptRegistry.delete(id);
167
+ return scriptArray;
168
+ };
169
+ var init_registerClientScript = __esm(() => {
170
+ scriptRegistry = new Map;
171
+ if (typeof globalThis !== "undefined") {
172
+ Object.assign(globalThis, { registerClientScript });
205
173
  }
206
- const safeText = pending.slice(0, pending.length - lookbehind);
207
- controller.enqueue(encoder.encode(safeText));
208
- return pending.slice(-lookbehind);
209
- }, updateInjectedState = (consumed, injected, pending) => {
210
- if (consumed.done) {
211
- return { done: true, injected, pending };
174
+ });
175
+
176
+ // src/angular/injectorPatch.ts
177
+ import { existsSync, readFileSync, writeFileSync } from "fs";
178
+ import { dirname, join, resolve } from "path";
179
+ var applyInjectorPatch = (chunkPath, content) => {
180
+ if (content.includes('Symbol.for("angular.currentInjector")')) {
181
+ return;
212
182
  }
213
- return {
214
- done: false,
215
- injected: consumed.injected,
216
- pending: consumed.pending
217
- };
218
- }, readStreamChunk = async (reader) => {
219
- const { done, value } = await reader.read();
220
- if (done || !value) {
221
- return { done, value: undefined };
183
+ const original = [
184
+ "let _currentInjector = undefined;",
185
+ "function getCurrentInjector() {",
186
+ " return _currentInjector;",
187
+ "}",
188
+ "function setCurrentInjector(injector) {",
189
+ " const former = _currentInjector;",
190
+ " _currentInjector = injector;",
191
+ " return former;",
192
+ "}"
193
+ ].join(`
194
+ `);
195
+ const replacement = [
196
+ 'const _injSym = Symbol.for("angular.currentInjector");',
197
+ "if (!globalThis[_injSym]) globalThis[_injSym] = { v: undefined };",
198
+ "function getCurrentInjector() {",
199
+ " return globalThis[_injSym].v;",
200
+ "}",
201
+ "function setCurrentInjector(injector) {",
202
+ " const former = globalThis[_injSym].v;",
203
+ " globalThis[_injSym].v = injector;",
204
+ " return former;",
205
+ "}"
206
+ ].join(`
207
+ `);
208
+ const patched = content.replace(original, replacement);
209
+ if (patched === content) {
210
+ return;
222
211
  }
223
- return { done, value };
224
- }, pipeStreamWithHeadInjection = (stream, markup) => {
225
- const encoder = new TextEncoder;
226
- const decoder = new TextDecoder;
227
- const lookbehind = CLOSING_HEAD_TAG.length - 1;
228
- const processPending = (controller, pending, injected) => {
229
- if (injected) {
230
- controller.enqueue(encoder.encode(pending));
231
- return { injected, pending: "" };
232
- }
233
- const headIndex = pending.indexOf(CLOSING_HEAD_TAG);
234
- if (headIndex >= 0) {
235
- const next = `${pending.slice(0, headIndex)}${markup}${pending.slice(headIndex)}`;
236
- controller.enqueue(encoder.encode(next));
237
- return { injected: true, pending: "" };
238
- }
239
- return {
240
- injected,
241
- pending: flushSafePendingText(controller, encoder, pending, lookbehind)
242
- };
243
- };
244
- const finishHeadInjectionStream = (controller, pending, injected) => {
245
- let finalPending = pending + decoder.decode();
246
- if (!injected) {
247
- finalPending = injectHeadMarkup(finalPending, markup);
248
- }
249
- if (finalPending.length > 0) {
250
- controller.enqueue(encoder.encode(finalPending));
251
- }
252
- controller.close();
253
- };
254
- const consumeHeadChunk = async (controller, reader, pending, injected) => {
255
- const { done, value } = await readStreamChunk(reader);
256
- if (done || !value) {
257
- return { done, injected, pending };
258
- }
259
- const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
260
- return {
261
- done,
262
- injected: processed.injected,
263
- pending: processed.pending
264
- };
265
- };
266
- const runHeadInjectionLoop = async (controller, reader) => {
267
- const consumeNextHeadChunk = async (injected, pending) => {
268
- const consumed = await consumeHeadChunk(controller, reader, pending, injected);
269
- const nextState = updateInjectedState(consumed, injected, pending);
270
- if (nextState.done) {
271
- return { injected, pending };
272
- }
273
- return consumeNextHeadChunk(nextState.injected, nextState.pending);
274
- };
275
- return consumeNextHeadChunk(false, "");
276
- };
277
- return new ReadableStream({
278
- async start(controller) {
279
- const reader = stream.getReader();
280
- try {
281
- const { injected, pending } = await runHeadInjectionLoop(controller, reader);
282
- finishHeadInjectionStream(controller, pending, injected);
283
- } catch (error) {
284
- controller.error(error);
285
- }
286
- }
287
- });
288
- }, pipeStreamWithIslandMarkerDetection = (stream, markup) => {
289
- const encoder = new TextEncoder;
290
- const decoder = new TextDecoder;
291
- const lookbehind = Math.max(ISLAND_MARKER.length, BYTES_PER_KILOBYTE);
292
- const processPending = (controller, pending, injected) => {
293
- if (injected) {
294
- controller.enqueue(encoder.encode(pending));
295
- return { injected, pending: "" };
296
- }
297
- const markerIndex = pending.indexOf(ISLAND_MARKER);
298
- if (markerIndex >= 0) {
299
- const tagStart = pending.lastIndexOf("<", markerIndex);
300
- const injectAt = tagStart >= 0 ? tagStart : markerIndex;
301
- const next = `${pending.slice(0, injectAt)}${markup}${pending.slice(injectAt)}`;
302
- controller.enqueue(encoder.encode(next));
303
- return { injected: true, pending: "" };
304
- }
305
- return {
306
- injected,
307
- pending: flushSafePendingText(controller, encoder, pending, lookbehind)
308
- };
309
- };
310
- const finishIslandMarkerStream = (controller, pending) => {
311
- const finalPending = pending + decoder.decode();
312
- if (finalPending.length > 0) {
313
- controller.enqueue(encoder.encode(finalPending));
212
+ writeFileSync(chunkPath, patched, "utf-8");
213
+ }, resolveAngularCoreDir = () => {
214
+ const fromProject = resolve(process.cwd(), "node_modules/@angular/core");
215
+ if (existsSync(join(fromProject, "package.json"))) {
216
+ return fromProject;
217
+ }
218
+ return dirname(__require.resolve("@angular/core/package.json"));
219
+ }, patchAngularInjectorSingleton = () => {
220
+ try {
221
+ const coreDir = resolveAngularCoreDir();
222
+ const chunkPath = join(coreDir, "fesm2022", "_not_found-chunk.mjs");
223
+ const content = readFileSync(chunkPath, "utf-8");
224
+ applyInjectorPatch(chunkPath, content);
225
+ } catch {}
226
+ };
227
+ var init_injectorPatch = __esm(() => {
228
+ patchAngularInjectorSingleton();
229
+ });
230
+
231
+ // src/angular/resolveAngularPackage.ts
232
+ import { existsSync as existsSync2 } from "fs";
233
+ import { resolve as resolve2 } from "path";
234
+ var resolveAngularPackage = (specifier) => {
235
+ const fromProject = resolve2(process.cwd(), "node_modules", specifier);
236
+ if (existsSync2(fromProject)) {
237
+ return fromProject;
238
+ }
239
+ return specifier;
240
+ };
241
+ var init_resolveAngularPackage = () => {};
242
+
243
+ // src/angular/angularPatch.ts
244
+ var exports_angularPatch = {};
245
+ __export(exports_angularPatch, {
246
+ applyPatches: () => applyPatches
247
+ });
248
+ var ensureHead = (doc) => {
249
+ if (!doc || doc.head || !doc.documentElement) {
250
+ return;
251
+ }
252
+ const head = doc.createElement("head");
253
+ doc.documentElement.insertBefore(head, doc.documentElement.firstChild);
254
+ }, applyPatches = async () => {
255
+ const { \u{275}DominoAdapter } = await import(resolveAngularPackage("@angular/platform-server"));
256
+ if (!\u{275}DominoAdapter?.prototype) {
257
+ console.warn("[Angular Patch] \u0275DominoAdapter not found, skipping patches");
258
+ return false;
259
+ }
260
+ const proto = \u{275}DominoAdapter.prototype;
261
+ const origGetBaseHref = proto.getBaseHref;
262
+ proto.getBaseHref = function(doc) {
263
+ if (!doc || !doc.head || typeof doc.head.children === "undefined") {
264
+ return "";
314
265
  }
315
- controller.close();
266
+ return origGetBaseHref.call(this, doc);
316
267
  };
317
- const consumeIslandChunk = async (controller, reader, pending, injected) => {
318
- const { done, value } = await readStreamChunk(reader);
319
- if (done || !value) {
320
- return { done, injected, pending };
321
- }
322
- const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
323
- return {
324
- done,
325
- injected: processed.injected,
326
- pending: processed.pending
327
- };
268
+ const origCreateHtmlDocument = proto.createHtmlDocument;
269
+ proto.createHtmlDocument = function() {
270
+ const doc = origCreateHtmlDocument.call(this);
271
+ ensureHead(doc);
272
+ return doc;
328
273
  };
329
- const runIslandMarkerLoop = async (controller, reader) => {
330
- const consumeNextIslandChunk = async (injected, pending) => {
331
- const consumed = await consumeIslandChunk(controller, reader, pending, injected);
332
- const nextState = updateInjectedState(consumed, injected, pending);
333
- if (nextState.done) {
334
- return { injected, pending };
335
- }
336
- return consumeNextIslandChunk(nextState.injected, nextState.pending);
337
- };
338
- return consumeNextIslandChunk(false, "");
274
+ const origGetDefaultDocument = proto.getDefaultDocument;
275
+ proto.getDefaultDocument = function() {
276
+ const doc = origGetDefaultDocument.call(this);
277
+ ensureHead(doc);
278
+ return doc;
339
279
  };
340
- return new ReadableStream({
341
- async start(controller) {
342
- const reader = stream.getReader();
343
- try {
344
- const { pending } = await runIslandMarkerLoop(controller, reader);
345
- finishIslandMarkerStream(controller, pending);
346
- } catch (error) {
347
- controller.error(error);
348
- }
349
- }
350
- });
351
- }, htmlContainsIslands = (html) => html.includes(ISLAND_MARKER), injectIslandPageContext = (html, options) => {
352
- const manifest = globalThis.__absoluteManifest;
353
- const hasIslands = options?.hasIslands ?? htmlContainsIslands(html);
354
- if (!manifest || !hasIslands) {
355
- return html;
356
- }
357
- if (html.includes(MANIFEST_MARKER) || html.includes(ISLAND_STATE_MARKER)) {
358
- return html;
359
- }
360
- return injectHeadMarkup(html, buildIslandsHeadMarkup(manifest));
361
- }, injectIslandPageContextStream = (stream, options) => {
362
- const manifest = globalThis.__absoluteManifest;
363
- if (!manifest)
364
- return stream;
365
- const markup = buildIslandsHeadMarkup(manifest);
366
- if (options?.hasIslands === true) {
367
- return pipeStreamWithHeadInjection(stream, markup);
280
+ return true;
281
+ };
282
+ var init_angularPatch = __esm(() => {
283
+ init_resolveAngularPackage();
284
+ });
285
+
286
+ // src/angular/angularDeps.ts
287
+ var initDominoAdapter = (platformServer) => {
288
+ try {
289
+ const DominoAdapter = platformServer.\u{275}DominoAdapter;
290
+ DominoAdapter?.makeCurrent?.();
291
+ } catch (err) {
292
+ console.error("Failed to initialize DominoAdapter:", err);
368
293
  }
369
- if (options?.hasIslands === false) {
370
- return stream;
294
+ }, loadAngularDeps = async () => {
295
+ patchAngularInjectorSingleton();
296
+ await import(resolveAngularPackage("@angular/compiler"));
297
+ const { applyPatches: applyPatches2 } = await Promise.resolve().then(() => (init_angularPatch(), exports_angularPatch));
298
+ await applyPatches2();
299
+ const [platformBrowser, platformServer, common, core] = await Promise.all([
300
+ import(resolveAngularPackage("@angular/platform-browser")),
301
+ import(resolveAngularPackage("@angular/platform-server")),
302
+ import(resolveAngularPackage("@angular/common")),
303
+ import(resolveAngularPackage("@angular/core"))
304
+ ]);
305
+ if (false) {}
306
+ initDominoAdapter(platformServer);
307
+ return {
308
+ APP_BASE_HREF: common.APP_BASE_HREF,
309
+ bootstrapApplication: platformBrowser.bootstrapApplication,
310
+ DomSanitizer: platformBrowser.DomSanitizer,
311
+ provideClientHydration: platformBrowser.provideClientHydration,
312
+ provideServerRendering: platformServer.provideServerRendering,
313
+ provideZonelessChangeDetection: core.provideZonelessChangeDetection,
314
+ reflectComponentType: core.reflectComponentType,
315
+ renderApplication: platformServer.renderApplication,
316
+ Sanitizer: core.Sanitizer,
317
+ SecurityContext: core.SecurityContext
318
+ };
319
+ }, angularDeps = null, getAngularDeps = () => {
320
+ if (!angularDeps) {
321
+ angularDeps = loadAngularDeps();
371
322
  }
372
- return pipeStreamWithIslandMarkerDetection(stream, markup);
373
- }, setCurrentIslandManifest = (manifest) => {
374
- globalThis.__absoluteManifest = manifest;
323
+ return angularDeps;
375
324
  };
376
- var init_islandPageContext = __esm(() => {
377
- init_constants();
325
+ var init_angularDeps = __esm(() => {
326
+ init_injectorPatch();
327
+ init_resolveAngularPackage();
378
328
  });
379
329
 
380
- // src/utils/ssrErrorPage.ts
381
- var ssrErrorPage = (framework, error) => {
382
- const frameworkColors = {
383
- angular: "#dd0031",
384
- html: "#e34c26",
385
- htmx: "#1a365d",
386
- react: "#61dafb",
387
- svelte: "#ff3e00",
388
- vue: "#42b883"
330
+ // src/core/currentIslandRegistry.ts
331
+ var requireCurrentIslandRegistry = () => {
332
+ const registry = globalThis.__absoluteIslandRegistry;
333
+ if (!registry) {
334
+ throw new Error("No island registry is active. Configure `islands.registry` in absolute.config.ts before rendering <Island />.");
335
+ }
336
+ return registry;
337
+ }, setCurrentIslandRegistry = (registry) => {
338
+ globalThis.__absoluteIslandRegistry = registry;
339
+ };
340
+
341
+ // src/angular/ssrRender.ts
342
+ var routePropsCache, cacheRouteData = (pagePath, data) => {
343
+ const cacheKey = pagePath.split("?")[0] ?? pagePath;
344
+ routePropsCache.set(cacheKey, data);
345
+ }, getCachedRouteData = (pagePath) => routePropsCache.get(pagePath), selectorCache, buildDeps = (ssrResult, baseDeps) => {
346
+ if (!ssrResult?.core) {
347
+ return baseDeps;
348
+ }
349
+ const { common, core, platformBrowser, platformServer } = ssrResult;
350
+ return {
351
+ APP_BASE_HREF: common?.APP_BASE_HREF ?? baseDeps.APP_BASE_HREF,
352
+ bootstrapApplication: platformBrowser?.bootstrapApplication ?? baseDeps.bootstrapApplication,
353
+ DomSanitizer: platformBrowser?.DomSanitizer ?? baseDeps.DomSanitizer,
354
+ provideClientHydration: platformBrowser?.provideClientHydration ?? baseDeps.provideClientHydration,
355
+ provideServerRendering: platformServer?.provideServerRendering ?? baseDeps.provideServerRendering,
356
+ provideZonelessChangeDetection: core.provideZonelessChangeDetection,
357
+ reflectComponentType: core.reflectComponentType,
358
+ renderApplication: platformServer?.renderApplication ?? baseDeps.renderApplication,
359
+ Sanitizer: core.Sanitizer,
360
+ SecurityContext: core.SecurityContext
389
361
  };
390
- const accent = frameworkColors[framework] ?? "#94a3b8";
391
- const label = framework.charAt(0).toUpperCase() + framework.slice(1);
392
- const message = error instanceof Error ? error.message : String(error);
393
- return `<!DOCTYPE html>
394
- <html>
395
- <head>
396
- <meta charset="utf-8">
397
- <meta name="viewport" content="width=device-width, initial-scale=1">
398
- <title>SSR Error - AbsoluteJS</title>
399
- <style>
400
- *{margin:0;padding:0;box-sizing:border-box}
401
- 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}
402
- .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}
403
- .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)}
404
- .brand{font-weight:700;font-size:20px;color:#fff;letter-spacing:-0.02em}
405
- .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)}
406
- .kind{color:#94a3b8;font-size:13px;font-weight:500}
407
- .content{padding:24px}
408
- .label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px}
409
- .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}
410
- .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}
411
- </style>
412
- </head>
413
- <body>
414
- <div class="card">
415
- <div class="header">
416
- <div style="display:flex;align-items:center;gap:12px">
417
- <span class="brand">AbsoluteJS</span>
418
- <span class="badge">${label}</span>
419
- </div>
420
- <span class="kind">Server Render Error</span>
421
- </div>
422
- <div class="content">
423
- <div class="label">What went wrong</div>
424
- <pre class="message">${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>
425
- <div class="hint">A component threw during server-side rendering. Check the terminal for the full stack trace.</div>
426
- </div>
427
- </div>
428
- </body>
429
- </html>`;
362
+ }, buildProviders = (deps, sanitizer, maybeProps, tokenMap) => {
363
+ const providers = [
364
+ deps.provideServerRendering(),
365
+ deps.provideClientHydration(),
366
+ deps.provideZonelessChangeDetection(),
367
+ { provide: deps.APP_BASE_HREF, useValue: "/" },
368
+ {
369
+ provide: deps.DomSanitizer,
370
+ useValue: sanitizer
371
+ },
372
+ { provide: deps.Sanitizer, useValue: sanitizer }
373
+ ];
374
+ if (!maybeProps) {
375
+ return providers;
376
+ }
377
+ const propProviders = Object.entries(maybeProps).map(([propName, propValue]) => ({
378
+ token: tokenMap.get(toScreamingSnake(propName)),
379
+ value: propValue
380
+ })).filter((entry) => entry.token).map((entry) => ({ provide: entry.token, useValue: entry.value }));
381
+ return [...providers, ...propProviders];
382
+ }, clearSelectorCache = () => selectorCache.clear(), isInjectionToken = (value) => {
383
+ if (!value || typeof value !== "object") {
384
+ return false;
385
+ }
386
+ return "ngMetadataName" in value && value.ngMetadataName === "InjectionToken";
387
+ }, discoverTokens = (pageModule) => new Map(Object.entries(pageModule).filter(([, value]) => isInjectionToken(value))), loadSsrDeps = async (pagePath) => {
388
+ const ssrDepsPath = (pagePath.split("?")[0] ?? pagePath).replace(/\.js$/, ".ssr-deps.js");
389
+ try {
390
+ const ssrDeps = await import(ssrDepsPath);
391
+ const result = {
392
+ common: ssrDeps.__angularCommon,
393
+ core: ssrDeps.__angularCore,
394
+ platformBrowser: ssrDeps.__angularPlatformBrowser,
395
+ platformServer: ssrDeps.__angularPlatformServer
396
+ };
397
+ return result;
398
+ } catch {
399
+ return null;
400
+ }
401
+ }, resolveSelector = (deps, pagePath, PageComponent) => {
402
+ const cached = selectorCache.get(pagePath);
403
+ if (cached) {
404
+ return cached;
405
+ }
406
+ const selector = deps.reflectComponentType(PageComponent)?.selector ?? "ng-app";
407
+ selectorCache.set(pagePath, selector);
408
+ return selector;
409
+ }, injectBeforeClose = (html, snippet) => {
410
+ if (html.includes("</body>")) {
411
+ return html.replace("</body>", `${snippet}</body>`);
412
+ }
413
+ if (html.includes("</html>")) {
414
+ return html.replace("</html>", `${snippet}</html>`);
415
+ }
416
+ return html + snippet;
417
+ }, injectSsrScripts = (html, requestId, indexPath, props) => {
418
+ let result = html;
419
+ const registeredScripts = getAndClearClientScripts(requestId);
420
+ if (registeredScripts.length > 0) {
421
+ result = injectBeforeClose(result, generateClientScriptCode(registeredScripts));
422
+ }
423
+ if (props) {
424
+ result = injectBeforeClose(result, `<script>window.__ABS_ANGULAR_PAGE_PROPS__ = ${JSON.stringify(props)};</script>`);
425
+ }
426
+ if (indexPath) {
427
+ const escapedIndexPath = JSON.stringify(indexPath);
428
+ result = injectBeforeClose(result, `<script>import(${escapedIndexPath});</script>`);
429
+ }
430
+ return result;
431
+ }, renderAngularApp = async (deps, PageComponent, providers, document2) => {
432
+ const bootstrap = (context) => deps.bootstrapApplication(PageComponent, { providers }, context);
433
+ return withSuppressedAngularDevLogs(() => deps.renderApplication(bootstrap, {
434
+ document: document2,
435
+ platformProviders: [],
436
+ url: "/"
437
+ }));
438
+ }, withSuppressedAngularDevLogs = async (render) => {
439
+ const origLog = console.log;
440
+ console.log = (...args) => {
441
+ if (typeof args[0] === "string" && args[0].includes("development mode")) {
442
+ return;
443
+ }
444
+ origLog.apply(console, args);
445
+ };
446
+ try {
447
+ return await render();
448
+ } finally {
449
+ console.log = origLog;
450
+ }
430
451
  };
452
+ var init_ssrRender = __esm(() => {
453
+ init_registerClientScript();
454
+ routePropsCache = new Map;
455
+ selectorCache = new Map;
456
+ });
431
457
 
432
- // src/utils/stringModifiers.ts
433
- 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) => {
434
- if (!str.includes("-") && !str.includes("_")) {
435
- return str.charAt(0).toUpperCase() + str.slice(1);
458
+ // src/angular/islands.ts
459
+ var exports_islands = {};
460
+ __export(exports_islands, {
461
+ renderAngularIslandToHtml: () => renderAngularIslandToHtml,
462
+ mountAngularIsland: () => mountAngularIsland,
463
+ getAngularIslandSelector: () => getAngularIslandSelector
464
+ });
465
+ var angularIslandSelector = "abs-angular-island", getAngularIslandSelector = (_islandId) => angularIslandSelector, getSelectorFromRenderedIsland = (rootElement) => {
466
+ const firstChild = rootElement.firstElementChild;
467
+ if (!(firstChild instanceof HTMLElement)) {
468
+ return null;
436
469
  }
437
- return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
438
- }, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
439
-
440
- // src/utils/resolveConvention.ts
441
- import { basename } from "path";
442
- var CONVENTIONS_KEY = "__absoluteConventions", isConventionsMap = (value) => Boolean(value) && typeof value === "object", getMap = () => {
443
- const value = Reflect.get(globalThis, CONVENTIONS_KEY);
444
- if (isConventionsMap(value))
445
- return value;
446
- const empty = {};
447
- return empty;
448
- }, derivePageName = (pagePath) => {
449
- const base = basename(pagePath);
450
- const dotIndex = base.indexOf(".");
451
- const name = dotIndex > 0 ? base.slice(0, dotIndex) : base;
452
- return toPascal(name);
453
- }, resolveErrorConventionPath = (framework, pageName) => {
454
- const conventions = getMap()[framework];
455
- if (!conventions)
456
- return;
457
- return conventions.pages?.[pageName]?.error ?? conventions.defaults?.error;
458
- }, resolveNotFoundConventionPath = (framework) => getMap()[framework]?.defaults?.notFound, setConventions = (map) => {
459
- Reflect.set(globalThis, CONVENTIONS_KEY, map);
460
- }, isDev = () => true, buildErrorProps = (error) => {
461
- const message = error instanceof Error ? error.message : String(error);
462
- const stack = isDev() && error instanceof Error ? error.stack : undefined;
463
- return { error: { message, stack } };
464
- }, renderReactError = async (conventionPath, errorProps) => {
465
- const { createElement } = await import("react");
466
- const { renderToReadableStream } = await import("react-dom/server");
467
- const mod = await import(conventionPath);
468
- const [firstKey] = Object.keys(mod);
469
- const ErrorComponent = mod.default ?? (firstKey ? mod[firstKey] : undefined);
470
- const element = createElement(ErrorComponent, errorProps);
471
- const stream = await renderToReadableStream(element);
472
- return new Response(stream, {
473
- headers: { "Content-Type": "text/html" },
474
- status: 500
475
- });
476
- }, renderSvelteError = async (conventionPath, errorProps) => {
477
- const { render } = await import("svelte/server");
478
- const mod = await import(conventionPath);
479
- const ErrorComponent = mod.default;
480
- const { head, body } = render(ErrorComponent, {
481
- props: errorProps
482
- });
483
- const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
484
- return new Response(html, {
485
- headers: { "Content-Type": "text/html" },
486
- status: 500
487
- });
488
- }, unescapeVueStyles = (ssrBody) => {
489
- let styles = "";
490
- const body = ssrBody.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => {
491
- styles += `<style>${css.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")}</style>`;
492
- return "";
493
- });
494
- return { body, styles };
495
- }, renderVueError = async (conventionPath, errorProps) => {
496
- const { createSSRApp, h } = await import("vue");
497
- const { renderToString } = await import("vue/server-renderer");
498
- const mod = await import(conventionPath);
499
- const ErrorComponent = mod.default;
500
- const app = createSSRApp({
501
- render: () => h(ErrorComponent, errorProps)
502
- });
503
- const rawBody = await renderToString(app);
504
- const { styles, body } = unescapeVueStyles(rawBody);
505
- const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
506
- return new Response(html, {
507
- headers: { "Content-Type": "text/html" },
508
- status: 500
509
- });
510
- }, renderAngularError = async (conventionPath, errorProps) => {
511
- const mod = await import(conventionPath);
512
- const renderError = mod.default ?? mod.renderError;
513
- if (typeof renderError !== "function")
470
+ const selector = firstChild.tagName.toLowerCase();
471
+ return selector.length > 0 ? selector : null;
472
+ }, getClientAngularComponentSelector = (component) => {
473
+ const maybeDef = Reflect.get(component, "\u0275cmp");
474
+ if (typeof maybeDef !== "object" || maybeDef === null) {
514
475
  return null;
515
- const html = renderError(errorProps);
516
- return new Response(html, {
517
- headers: { "Content-Type": "text/html" },
518
- status: 500
519
- });
520
- }, logConventionRenderError = (framework, label, renderError) => {
521
- const message = renderError instanceof Error ? renderError.message : "";
522
- if (message.includes("Cannot find module") || message.includes("Cannot find package") || message.includes("not found in module")) {
523
- 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}).`);
524
- return;
525
476
  }
526
- console.error(`[SSR] Failed to render ${framework} convention ${label} page:`, renderError);
527
- }, ERROR_RENDERERS, renderConventionError = async (framework, pageName, error) => {
528
- const conventionPath = resolveErrorConventionPath(framework, pageName);
529
- if (!conventionPath)
477
+ const maybeSelectors = Reflect.get(maybeDef, "selectors");
478
+ if (!Array.isArray(maybeSelectors)) {
530
479
  return null;
531
- const errorProps = buildErrorProps(error);
532
- const renderer = ERROR_RENDERERS[framework];
533
- if (!renderer)
480
+ }
481
+ const [firstSelectorGroup] = maybeSelectors;
482
+ if (!Array.isArray(firstSelectorGroup)) {
534
483
  return null;
535
- try {
536
- return await renderer(conventionPath, errorProps);
537
- } catch (renderError) {
538
- logConventionRenderError(framework, "error", renderError);
539
484
  }
540
- return null;
541
- }, renderReactNotFound = async (conventionPath) => {
542
- const { createElement } = await import("react");
543
- const { renderToReadableStream } = await import("react-dom/server");
544
- const mod = await import(conventionPath);
545
- const [nfKey] = Object.keys(mod);
546
- const NotFoundComponent = mod.default ?? (nfKey ? mod[nfKey] : undefined);
547
- const element = createElement(NotFoundComponent);
548
- const stream = await renderToReadableStream(element);
549
- return new Response(stream, {
550
- headers: { "Content-Type": "text/html" },
551
- status: 404
552
- });
553
- }, renderSvelteNotFound = async (conventionPath) => {
554
- const { render } = await import("svelte/server");
555
- const mod = await import(conventionPath);
556
- const NotFoundComponent = mod.default;
557
- const { head, body } = render(NotFoundComponent);
558
- const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
559
- return new Response(html, {
560
- headers: { "Content-Type": "text/html" },
561
- status: 404
562
- });
563
- }, renderVueNotFound = async (conventionPath) => {
564
- const { createSSRApp, h } = await import("vue");
565
- const { renderToString } = await import("vue/server-renderer");
566
- const mod = await import(conventionPath);
567
- const NotFoundComponent = mod.default;
568
- const app = createSSRApp({
569
- render: () => h(NotFoundComponent)
570
- });
571
- const rawBody = await renderToString(app);
572
- const { styles, body } = unescapeVueStyles(rawBody);
573
- const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
574
- return new Response(html, {
575
- headers: { "Content-Type": "text/html" },
576
- status: 404
577
- });
578
- }, renderAngularNotFound = async (conventionPath) => {
579
- const mod = await import(conventionPath);
580
- const renderNotFound = mod.default ?? mod.renderNotFound;
581
- if (typeof renderNotFound !== "function")
582
- return null;
583
- const html = renderNotFound();
584
- return new Response(html, {
585
- headers: { "Content-Type": "text/html" },
586
- status: 404
485
+ const [selector] = firstSelectorGroup;
486
+ return typeof selector === "string" && selector.length > 0 ? selector : null;
487
+ }, createAngularIslandApp = async () => {
488
+ const { EnvironmentInjector, provideZonelessChangeDetection } = await import("@angular/core");
489
+ const { createApplication } = await import("@angular/platform-browser");
490
+ const app = await createApplication({
491
+ providers: [provideZonelessChangeDetection()]
587
492
  });
588
- }, NOT_FOUND_RENDERERS, renderConventionNotFound = async (framework) => {
589
- const conventionPath = resolveNotFoundConventionPath(framework);
590
- if (!conventionPath)
591
- return null;
592
- const renderer = NOT_FOUND_RENDERERS[framework];
593
- if (!renderer)
493
+ const environmentInjector = app.injector.get(EnvironmentInjector);
494
+ return { app, environmentInjector };
495
+ }, angularIslandAppPromise = null, getAngularIslandApp = async () => {
496
+ if (!angularIslandAppPromise) {
497
+ angularIslandAppPromise = createAngularIslandApp();
498
+ }
499
+ return angularIslandAppPromise;
500
+ }, wrapperMetadataCache, requestRenderCache, getRequestRenderCache = () => {
501
+ const requestId = getSsrContextId();
502
+ if (!requestId) {
594
503
  return null;
595
- try {
596
- return await renderer(conventionPath);
597
- } catch (renderError) {
598
- logConventionRenderError(framework, "not-found", renderError);
599
504
  }
600
- return null;
601
- }, NOT_FOUND_PRIORITY, renderFirstNotFound = async () => {
602
- for (const framework of NOT_FOUND_PRIORITY) {
603
- if (!getMap()[framework]?.defaults?.notFound)
604
- continue;
605
- const response = await renderConventionNotFound(framework);
606
- if (response)
607
- return response;
505
+ const cached = requestRenderCache.get(requestId);
506
+ if (cached) {
507
+ return cached;
608
508
  }
609
- return null;
610
- };
611
- var init_resolveConvention = __esm(() => {
612
- ERROR_RENDERERS = {
613
- angular: renderAngularError,
614
- react: renderReactError,
615
- svelte: renderSvelteError,
616
- vue: renderVueError
617
- };
618
- NOT_FOUND_RENDERERS = {
619
- angular: renderAngularNotFound,
620
- react: renderReactNotFound,
621
- svelte: renderSvelteNotFound,
622
- vue: renderVueNotFound
623
- };
624
- NOT_FOUND_PRIORITY = [
625
- "react",
626
- "svelte",
627
- "vue",
628
- "angular"
629
- ];
630
- });
509
+ const renderCache = new Map;
510
+ requestRenderCache.set(requestId, renderCache);
511
+ return renderCache;
512
+ }, getAngularIslandWrapperKey = (component, _islandId) => {
513
+ const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
514
+ return `${componentName}:${angularIslandSelector}`;
515
+ }, getIslandRenderCacheKey = (component, props) => {
516
+ const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
517
+ return `${componentName}:${JSON.stringify(props)}`;
518
+ }, buildAngularIslandWrapperMetadata = async (component, islandId, wrapperKey) => {
519
+ const { Component, InjectionToken, inject } = await import("@angular/core");
520
+ const { NgComponentOutlet } = await import("@angular/common");
521
+ const deps = await getAngularDeps();
522
+ const selector = getAngularIslandSelector(islandId);
523
+ const propsToken = new InjectionToken(`${wrapperKey}:props`);
631
524
 
632
- // src/utils/registerClientScript.ts
633
- var scriptRegistry, requestCounter = 0, getRequestId = () => `req_${Date.now()}_${++requestCounter}`, ssrContextGetter = null, getSsrContextId = () => ssrContextGetter?.() || Object.getOwnPropertyDescriptor(globalThis, "__absolutejs_requestId")?.value, registerClientScript = (script, requestId) => {
634
- const id = requestId || getSsrContextId() || getRequestId();
635
- if (!scriptRegistry.has(id)) {
636
- scriptRegistry.set(id, new Set);
525
+ class AngularIslandWrapperComponent {
526
+ component = component;
527
+ props = inject(propsToken);
637
528
  }
638
- scriptRegistry.get(id)?.add(script);
639
- return id;
640
- }, setSsrContextGetter = (getter) => {
641
- ssrContextGetter = getter;
642
- }, clearAllClientScripts = () => {
643
- scriptRegistry.clear();
644
- }, generateClientScriptCode = (scripts) => {
645
- if (scripts.length === 0) {
646
- return "";
529
+ return {
530
+ deps,
531
+ propsToken,
532
+ selector,
533
+ WrapperComponent: Component({
534
+ imports: [NgComponentOutlet, component],
535
+ selector,
536
+ standalone: true,
537
+ template: '<ng-container *ngComponentOutlet="component; inputs: props"></ng-container>'
538
+ })(AngularIslandWrapperComponent)
539
+ };
540
+ }, createAngularIslandWrapper = async (component, islandId) => {
541
+ const wrapperKey = getAngularIslandWrapperKey(component, islandId);
542
+ const cached = wrapperMetadataCache.get(wrapperKey);
543
+ if (cached) {
544
+ return cached;
647
545
  }
648
- const scriptCode = scripts.map((script, index) => {
649
- const funcString = script.toString();
650
- const bodyMatch = funcString.match(/\{([\s\S]*)\}/);
651
- if (!bodyMatch || !bodyMatch[1]) {
652
- return "";
653
- }
654
- const body = bodyMatch[1].trim();
655
- return `
656
- (function() {
657
- var executed = false;
658
- function executeScript_${index}() {
659
- if (executed) return;
660
- executed = true;
661
- ${body}
662
- }
663
-
664
- if (document.readyState === 'complete' || document.readyState === 'interactive') {
665
- executeScript_${index}();
666
- } else {
667
- document.addEventListener('DOMContentLoaded', executeScript_${index});
668
- }
669
-
670
- // Watch for hydration-added elements
671
- var observer = new MutationObserver(function() {
672
- executeScript_${index}();
673
- if (executed) observer.disconnect();
674
- });
675
- if (!executed) {
676
- observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
677
- }
678
-
679
- // Single fallback timeout
680
- setTimeout(function() {
681
- executeScript_${index}();
682
- observer.disconnect();
683
- }, 1000);
684
- })();`;
685
- }).join(`
686
- `);
687
- return `<script>
688
- (function() {
689
- ${scriptCode}
690
- })();
691
- </script>`;
692
- }, getAndClearClientScripts = (requestId) => {
693
- const id = requestId || ssrContextGetter?.();
694
- if (!id)
695
- return [];
696
- const scripts = scriptRegistry.get(id);
697
- if (!scripts) {
698
- return [];
546
+ const metadataPromise = buildAngularIslandWrapperMetadata(component, islandId, wrapperKey);
547
+ wrapperMetadataCache.set(wrapperKey, metadataPromise);
548
+ return metadataPromise;
549
+ }, extractAngularIslandRoot = (html, selector) => {
550
+ const openTag = `<${selector}`;
551
+ const start = html.indexOf(openTag);
552
+ if (start < 0) {
553
+ throw new Error(`Could not find Angular island root "${selector}".`);
699
554
  }
700
- const scriptArray = Array.from(scripts);
701
- scriptRegistry.delete(id);
702
- return scriptArray;
703
- };
704
- var init_registerClientScript = __esm(() => {
705
- scriptRegistry = new Map;
706
- if (typeof globalThis !== "undefined") {
707
- Object.assign(globalThis, { registerClientScript });
555
+ const endTag = `</${selector}>`;
556
+ const end = html.indexOf(endTag, start);
557
+ if (end < 0) {
558
+ throw new Error(`Could not close Angular island root "${selector}".`);
559
+ }
560
+ return html.slice(start, end + endTag.length);
561
+ }, mountAngularIsland = async (component, element, props, islandId) => {
562
+ await import("@angular/compiler");
563
+ const { createComponent, inputBinding } = await import("@angular/core");
564
+ const selector = getAngularIslandSelector(islandId);
565
+ const { app, environmentInjector } = await getAngularIslandApp();
566
+ let rootElement = element.querySelector(selector);
567
+ if (!(rootElement instanceof HTMLElement)) {
568
+ element.innerHTML = `<${selector}></${selector}>`;
569
+ rootElement = element.querySelector(selector);
570
+ }
571
+ if (!(rootElement instanceof HTMLElement))
572
+ return app;
573
+ const componentSelector = getClientAngularComponentSelector(component) ?? getSelectorFromRenderedIsland(rootElement);
574
+ if (!componentSelector)
575
+ return app;
576
+ rootElement.innerHTML = `<${componentSelector}></${componentSelector}>`;
577
+ const hostElement = rootElement.querySelector(componentSelector);
578
+ if (!(hostElement instanceof HTMLElement))
579
+ return app;
580
+ const bindings = Object.entries(props).map(([key, value]) => inputBinding(key, () => value));
581
+ const componentRef = createComponent(component, {
582
+ bindings,
583
+ environmentInjector,
584
+ hostElement
585
+ });
586
+ app.attachView(componentRef.hostView);
587
+ componentRef.changeDetectorRef.detectChanges();
588
+ window.__ABS_ANGULAR_ISLAND_APPS__ ??= [];
589
+ window.__ABS_ANGULAR_ISLAND_APPS__.push(app);
590
+ return app;
591
+ }, renderAngularIslandToHtml = async (component, props, islandId) => {
592
+ const requestCache = getRequestRenderCache();
593
+ const renderCacheKey = getIslandRenderCacheKey(component, props);
594
+ const cachedHtml = requestCache?.get(renderCacheKey);
595
+ if (cachedHtml) {
596
+ return cachedHtml;
708
597
  }
598
+ const { deps, propsToken, selector, WrapperComponent } = await createAngularIslandWrapper(component, islandId);
599
+ const providers = [
600
+ deps.provideServerRendering(),
601
+ deps.provideZonelessChangeDetection(),
602
+ { provide: deps.APP_BASE_HREF, useValue: "/" },
603
+ { provide: propsToken, useValue: props }
604
+ ];
605
+ const document2 = `<!DOCTYPE html><html><body><${selector}></${selector}></body></html>`;
606
+ const html = await withSuppressedAngularDevLogs(() => deps.renderApplication((context) => deps.bootstrapApplication(WrapperComponent, { providers }, context), {
607
+ document: document2,
608
+ platformProviders: [],
609
+ url: "/"
610
+ }));
611
+ const islandHtml = extractAngularIslandRoot(html, selector);
612
+ requestCache?.set(renderCacheKey, islandHtml);
613
+ return islandHtml;
614
+ };
615
+ var init_islands = __esm(() => {
616
+ init_angularDeps();
617
+ init_ssrRender();
618
+ init_registerClientScript();
619
+ wrapperMetadataCache = new Map;
620
+ requestRenderCache = new Map;
709
621
  });
710
622
 
711
- // src/angular/injectorPatch.ts
712
- import { existsSync, readFileSync, writeFileSync } from "fs";
713
- import { dirname, join, resolve } from "path";
714
- var applyInjectorPatch = (chunkPath, content) => {
715
- if (content.includes('Symbol.for("angular.currentInjector")')) {
716
- return;
717
- }
718
- const original = [
719
- "let _currentInjector = undefined;",
720
- "function getCurrentInjector() {",
721
- " return _currentInjector;",
722
- "}",
723
- "function setCurrentInjector(injector) {",
724
- " const former = _currentInjector;",
725
- " _currentInjector = injector;",
726
- " return former;",
727
- "}"
728
- ].join(`
729
- `);
730
- const replacement = [
731
- 'const _injSym = Symbol.for("angular.currentInjector");',
732
- "if (!globalThis[_injSym]) globalThis[_injSym] = { v: undefined };",
733
- "function getCurrentInjector() {",
734
- " return globalThis[_injSym].v;",
735
- "}",
736
- "function setCurrentInjector(injector) {",
737
- " const former = globalThis[_injSym].v;",
738
- " globalThis[_injSym].v = injector;",
739
- " return former;",
740
- "}"
741
- ].join(`
742
- `);
743
- const patched = content.replace(original, replacement);
744
- if (patched === content) {
745
- return;
746
- }
747
- writeFileSync(chunkPath, patched, "utf-8");
748
- }, resolveAngularCoreDir = () => {
749
- const fromProject = resolve(process.cwd(), "node_modules/@angular/core");
750
- if (existsSync(join(fromProject, "package.json"))) {
751
- return fromProject;
752
- }
753
- return dirname(__require.resolve("@angular/core/package.json"));
754
- }, patchAngularInjectorSingleton = () => {
755
- try {
756
- const coreDir = resolveAngularCoreDir();
757
- const chunkPath = join(coreDir, "fesm2022", "_not_found-chunk.mjs");
758
- const content = readFileSync(chunkPath, "utf-8");
759
- applyInjectorPatch(chunkPath, content);
760
- } catch {}
761
- };
762
- var init_injectorPatch = __esm(() => {
763
- patchAngularInjectorSingleton();
623
+ // src/core/islandSsr.ts
624
+ var renderAngularIslandToHtmlInternal = async (component, props, islandId) => {
625
+ const { renderAngularIslandToHtml: renderAngularIslandToHtml2 } = await Promise.resolve().then(() => (init_islands(), exports_islands));
626
+ return renderAngularIslandToHtml2(component, props, islandId);
627
+ }, renderAngularIslandToHtml2, renderReactIslandToHtml = (component, props) => import("react").then(({ createElement }) => import("react-dom/server").then(({ renderToStaticMarkup }) => renderToStaticMarkup(createElement(component, props)))), renderSvelteIslandToHtml = (component, props) => import("svelte/server").then(({ render }) => {
628
+ const { body } = render(component, { props });
629
+ return body;
630
+ }), renderVueIslandToHtml = (component, props) => import("vue").then(({ createSSRApp, h }) => {
631
+ const app = createSSRApp({
632
+ render: () => h(component, props)
633
+ });
634
+ return import("vue/server-renderer").then(({ renderToString }) => renderToString(app));
635
+ });
636
+ var init_islandSsr = __esm(() => {
637
+ renderAngularIslandToHtml2 = renderAngularIslandToHtmlInternal;
764
638
  });
765
639
 
766
- // src/angular/resolveAngularPackage.ts
767
- import { existsSync as existsSync2 } from "fs";
768
- import { resolve as resolve2 } from "path";
769
- var resolveAngularPackage = (specifier) => {
770
- const fromProject = resolve2(process.cwd(), "node_modules", specifier);
771
- if (existsSync2(fromProject)) {
772
- return fromProject;
640
+ // src/build/resolvePackageImport.ts
641
+ import { resolve as resolve3, join as join2 } from "path";
642
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
643
+ var resolveExportPath = (entry, conditions) => {
644
+ if (typeof entry === "string")
645
+ return entry;
646
+ if (!entry || typeof entry !== "object")
647
+ return null;
648
+ for (const condition of conditions) {
649
+ const target = Reflect.get(entry, condition);
650
+ if (typeof target === "string") {
651
+ return target;
652
+ }
653
+ }
654
+ return null;
655
+ }, resolvePackageImport = (specifier, conditions = ["import"]) => {
656
+ if (specifier.startsWith(".") || specifier.startsWith("/"))
657
+ return null;
658
+ const parts = specifier.split("/");
659
+ const isScoped = specifier.startsWith("@");
660
+ const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
661
+ const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
662
+ const exportKey = subpath ? `./${subpath}` : ".";
663
+ const currentPackageJsonPath = resolve3(process.cwd(), "package.json");
664
+ const currentPackageJson = existsSync3(currentPackageJsonPath) ? JSON.parse(readFileSync2(currentPackageJsonPath, "utf-8")) : null;
665
+ const currentPackageDir = currentPackageJson?.name === packageName ? process.cwd() : null;
666
+ const packageDir = currentPackageDir ?? resolve3(process.cwd(), "node_modules", packageName ?? "");
667
+ const packageJsonPath = join2(packageDir, "package.json");
668
+ if (!existsSync3(packageJsonPath))
669
+ return null;
670
+ try {
671
+ const packageJson = currentPackageDir && currentPackageJson ? currentPackageJson : JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
672
+ const { exports } = packageJson;
673
+ if (!exports)
674
+ return null;
675
+ const entry = exports[exportKey];
676
+ if (!entry)
677
+ return null;
678
+ const importPath = resolveExportPath(entry, conditions);
679
+ if (!importPath)
680
+ return null;
681
+ if (currentPackageDir && importPath.startsWith("./dist/")) {
682
+ const sourceCandidate = resolve3(packageDir, importPath.replace(/^\.\/dist\//, "./src/"));
683
+ if (existsSync3(sourceCandidate)) {
684
+ return sourceCandidate;
685
+ }
686
+ }
687
+ const resolved = resolve3(packageDir, importPath);
688
+ return existsSync3(resolved) ? resolved : null;
689
+ } catch {
690
+ return null;
773
691
  }
774
- return specifier;
775
692
  };
776
- var init_resolveAngularPackage = () => {};
693
+ var init_resolvePackageImport = () => {};
777
694
 
778
- // src/angular/angularPatch.ts
779
- var exports_angularPatch = {};
780
- __export(exports_angularPatch, {
781
- applyPatches: () => applyPatches
782
- });
783
- var ensureHead = (doc) => {
784
- if (!doc || doc.head || !doc.documentElement) {
785
- return;
695
+ // src/svelte/lowerIslandSyntax.ts
696
+ var ISLAND_TAG_RE, extractBracedExpression = (text, braceStart) => {
697
+ let depth = 0;
698
+ for (let index = braceStart;index < text.length; index += 1) {
699
+ const char = text[index];
700
+ if (char === "{")
701
+ depth += 1;
702
+ if (char === "}")
703
+ depth -= 1;
704
+ if (depth === 0) {
705
+ return text.slice(braceStart + 1, index).trim();
706
+ }
786
707
  }
787
- const head = doc.createElement("head");
788
- doc.documentElement.insertBefore(head, doc.documentElement.firstChild);
789
- }, applyPatches = async () => {
790
- const { \u{275}DominoAdapter } = await import(resolveAngularPackage("@angular/platform-server"));
791
- if (!\u{275}DominoAdapter?.prototype) {
792
- console.warn("[Angular Patch] \u0275DominoAdapter not found, skipping patches");
793
- return false;
708
+ return null;
709
+ }, extractIslandAttribute = (attributeString, name) => {
710
+ const quotedMatch = attributeString.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`));
711
+ if (quotedMatch?.[1]) {
712
+ return { expression: JSON.stringify(quotedMatch[1]), found: true };
794
713
  }
795
- const proto = \u{275}DominoAdapter.prototype;
796
- const origGetBaseHref = proto.getBaseHref;
797
- proto.getBaseHref = function(doc) {
798
- if (!doc || !doc.head || typeof doc.head.children === "undefined") {
799
- return "";
714
+ const attributeIndex = attributeString.search(new RegExp(`\\b${name}\\s*=\\s*\\{`));
715
+ if (attributeIndex < 0) {
716
+ return { expression: "", found: false };
717
+ }
718
+ const braceStart = attributeString.indexOf("{", attributeIndex);
719
+ if (braceStart < 0) {
720
+ return { expression: "", found: false };
721
+ }
722
+ const expression = extractBracedExpression(attributeString, braceStart);
723
+ if (expression === null) {
724
+ return { expression: "", found: false };
725
+ }
726
+ return { expression, found: true };
727
+ }, lowerSvelteIslandSyntax = (source, _mode = "server") => {
728
+ if (!source.includes("<Island")) {
729
+ return { code: source, transformed: false };
730
+ }
731
+ let islandIndex = 0;
732
+ const transformedMarkup = source.replace(ISLAND_TAG_RE, (fullMatch, attributeString) => {
733
+ const framework = extractIslandAttribute(attributeString, "framework");
734
+ const component = extractIslandAttribute(attributeString, "component");
735
+ if (!framework.found || !component.found) {
736
+ return fullMatch;
800
737
  }
801
- return origGetBaseHref.call(this, doc);
802
- };
803
- const origCreateHtmlDocument = proto.createHtmlDocument;
804
- proto.createHtmlDocument = function() {
805
- const doc = origCreateHtmlDocument.call(this);
806
- ensureHead(doc);
807
- return doc;
808
- };
809
- const origGetDefaultDocument = proto.getDefaultDocument;
810
- proto.getDefaultDocument = function() {
811
- const doc = origGetDefaultDocument.call(this);
812
- ensureHead(doc);
813
- return doc;
738
+ const hydrate = extractIslandAttribute(attributeString, "hydrate");
739
+ const props = extractIslandAttribute(attributeString, "props");
740
+ const slotId = `absolute-svelte-island-${islandIndex.toString(BASE_36_RADIX)}`;
741
+ islandIndex += 1;
742
+ const resolveExpression = `await __absoluteResolveIslandHtml(${JSON.stringify(slotId)}, { component: ${component.expression}, framework: ${framework.expression}, hydrate: ${hydrate.found ? hydrate.expression : JSON.stringify("load")}, props: ${props.found ? props.expression : "{}"} })`;
743
+ return `<div data-absolute-island-slot="${slotId}" style="display: contents">{@html ${resolveExpression}}</div>`;
744
+ });
745
+ const importLine = 'import { resolveIslandHtml as __absoluteResolveIslandHtml } from "@absolutejs/absolute/svelte";';
746
+ if (transformedMarkup.includes("<script")) {
747
+ return {
748
+ code: transformedMarkup.replace(/<script(\s[^>]*)?>/, (match) => `${match}
749
+ ${importLine}
750
+ `),
751
+ transformed: true
752
+ };
753
+ }
754
+ return {
755
+ code: `<script lang="ts">
756
+ ${importLine}
757
+ </script>
758
+ ${transformedMarkup}`,
759
+ transformed: true
814
760
  };
815
- return true;
816
761
  };
817
- var init_angularPatch = __esm(() => {
818
- init_resolveAngularPackage();
762
+ var init_lowerIslandSyntax = __esm(() => {
763
+ init_constants();
764
+ ISLAND_TAG_RE = /<Island\b([\s\S]*?)\/>/g;
819
765
  });
820
766
 
821
- // src/angular/angularDeps.ts
822
- var initDominoAdapter = (platformServer) => {
823
- try {
824
- const DominoAdapter = platformServer.\u{275}DominoAdapter;
825
- DominoAdapter?.makeCurrent?.();
826
- } catch (err) {
827
- console.error("Failed to initialize DominoAdapter:", err);
767
+ // src/svelte/lowerAwaitSlotSyntax.ts
768
+ var AWAIT_BLOCK_RE, escapeTemplateLiteral = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${"), markupToTemplateLiteral = (markup) => {
769
+ const escaped = escapeTemplateLiteral(markup.trim());
770
+ const withExpressions = escaped.replace(/\{([^{}]+)\}/g, (_, expression) => `\${${String(expression).trim()}}`);
771
+ return `\`${withExpressions}\``;
772
+ }, lowerSvelteAwaitSlotSyntax = (source) => {
773
+ if (!source.includes("{#await")) {
774
+ return { code: source, transformed: false };
775
+ }
776
+ let awaitIndex = 0;
777
+ let transformed = false;
778
+ const lowered = source.replace(AWAIT_BLOCK_RE, (fullMatch, awaitExpression, pendingMarkup, thenIdentifier, thenMarkup, catchIdentifier, catchMarkup) => {
779
+ const trimmedAwaitExpression = awaitExpression.trim();
780
+ if (!trimmedAwaitExpression) {
781
+ return fullMatch;
782
+ }
783
+ const slotId = `absolute-svelte-await-${awaitIndex.toString(BASE_36_RADIX)}`;
784
+ awaitIndex += 1;
785
+ transformed = true;
786
+ const thenValueIdentifier = thenIdentifier?.trim() || "__awaitValue";
787
+ const catchValueIdentifier = catchIdentifier?.trim() || "__awaitError";
788
+ const fallbackHtml = markupToTemplateLiteral(pendingMarkup);
789
+ const resolvedHtml = markupToTemplateLiteral(thenMarkup);
790
+ const rejectedHtml = typeof catchMarkup === "string" ? markupToTemplateLiteral(catchMarkup) : null;
791
+ const catchBranch = rejectedHtml ? `catch (${catchValueIdentifier}) { return ${rejectedHtml}; }` : "catch (_absoluteAwaitError) { throw _absoluteAwaitError; }";
792
+ return `<AbsoluteAwaitSlot id="${slotId}" fallbackHtml={${fallbackHtml}} resolve={async () => { try { const ${thenValueIdentifier} = await (${trimmedAwaitExpression}); return ${resolvedHtml}; } ${catchBranch} }} />`;
793
+ });
794
+ if (!transformed) {
795
+ return { code: source, transformed: false };
796
+ }
797
+ const importLine = 'import AbsoluteAwaitSlot from "@absolutejs/absolute/svelte/components/AwaitSlot.svelte";';
798
+ if (lowered.includes("<script")) {
799
+ return {
800
+ code: lowered.replace(/<script(\s[^>]*)?>/, (match) => `${match}
801
+ ${importLine}
802
+ `),
803
+ transformed: true
804
+ };
828
805
  }
829
- }, loadAngularDeps = async () => {
830
- patchAngularInjectorSingleton();
831
- await import(resolveAngularPackage("@angular/compiler"));
832
- const { applyPatches: applyPatches2 } = await Promise.resolve().then(() => (init_angularPatch(), exports_angularPatch));
833
- await applyPatches2();
834
- const [platformBrowser, platformServer, common, core] = await Promise.all([
835
- import(resolveAngularPackage("@angular/platform-browser")),
836
- import(resolveAngularPackage("@angular/platform-server")),
837
- import(resolveAngularPackage("@angular/common")),
838
- import(resolveAngularPackage("@angular/core"))
839
- ]);
840
- if (false) {}
841
- initDominoAdapter(platformServer);
842
806
  return {
843
- APP_BASE_HREF: common.APP_BASE_HREF,
844
- bootstrapApplication: platformBrowser.bootstrapApplication,
845
- DomSanitizer: platformBrowser.DomSanitizer,
846
- provideClientHydration: platformBrowser.provideClientHydration,
847
- provideServerRendering: platformServer.provideServerRendering,
848
- provideZonelessChangeDetection: core.provideZonelessChangeDetection,
849
- reflectComponentType: core.reflectComponentType,
850
- renderApplication: platformServer.renderApplication,
851
- Sanitizer: core.Sanitizer,
852
- SecurityContext: core.SecurityContext
807
+ code: `<script lang="ts">
808
+ ${importLine}
809
+ </script>
810
+ ${lowered}`,
811
+ transformed: true
853
812
  };
854
- }, angularDeps = null, getAngularDeps = () => {
855
- if (!angularDeps) {
856
- angularDeps = loadAngularDeps();
857
- }
858
- return angularDeps;
859
813
  };
860
- var init_angularDeps = __esm(() => {
861
- init_injectorPatch();
862
- init_resolveAngularPackage();
814
+ var init_lowerAwaitSlotSyntax = __esm(() => {
815
+ init_constants();
816
+ AWAIT_BLOCK_RE = /\{#await\s+([^}]+)\}([\s\S]*?)\{:then(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?)(?:\{:catch(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?))?\{\/await\}/g;
863
817
  });
864
818
 
865
- // src/core/currentIslandRegistry.ts
866
- var requireCurrentIslandRegistry = () => {
867
- const registry = globalThis.__absoluteIslandRegistry;
868
- if (!registry) {
869
- throw new Error("No island registry is active. Configure `islands.registry` in absolute.config.ts before rendering <Island />.");
870
- }
871
- return registry;
872
- }, setCurrentIslandRegistry = (registry) => {
873
- globalThis.__absoluteIslandRegistry = registry;
874
- };
875
-
876
- // src/angular/ssrRender.ts
877
- var routePropsCache, cacheRouteData = (pagePath, data) => {
878
- const cacheKey = pagePath.split("?")[0] ?? pagePath;
879
- routePropsCache.set(cacheKey, data);
880
- }, getCachedRouteData = (pagePath) => routePropsCache.get(pagePath), selectorCache, buildDeps = (ssrResult, baseDeps) => {
881
- if (!ssrResult?.core) {
882
- return baseDeps;
883
- }
884
- const { common, core, platformBrowser, platformServer } = ssrResult;
885
- return {
886
- APP_BASE_HREF: common?.APP_BASE_HREF ?? baseDeps.APP_BASE_HREF,
887
- bootstrapApplication: platformBrowser?.bootstrapApplication ?? baseDeps.bootstrapApplication,
888
- DomSanitizer: platformBrowser?.DomSanitizer ?? baseDeps.DomSanitizer,
889
- provideClientHydration: platformBrowser?.provideClientHydration ?? baseDeps.provideClientHydration,
890
- provideServerRendering: platformServer?.provideServerRendering ?? baseDeps.provideServerRendering,
891
- provideZonelessChangeDetection: core.provideZonelessChangeDetection,
892
- reflectComponentType: core.reflectComponentType,
893
- renderApplication: platformServer?.renderApplication ?? baseDeps.renderApplication,
894
- Sanitizer: core.Sanitizer,
895
- SecurityContext: core.SecurityContext
896
- };
897
- }, buildProviders = (deps, sanitizer, maybeProps, tokenMap) => {
898
- const providers = [
899
- deps.provideServerRendering(),
900
- deps.provideClientHydration(),
901
- deps.provideZonelessChangeDetection(),
902
- { provide: deps.APP_BASE_HREF, useValue: "/" },
903
- {
904
- provide: deps.DomSanitizer,
905
- useValue: sanitizer
906
- },
907
- { provide: deps.Sanitizer, useValue: sanitizer }
908
- ];
909
- if (!maybeProps) {
910
- return providers;
819
+ // src/build/stylePreprocessor.ts
820
+ var exports_stylePreprocessor = {};
821
+ __export(exports_stylePreprocessor, {
822
+ stylePreprocessorPlugin: () => stylePreprocessorPlugin,
823
+ isStylePath: () => isStylePath,
824
+ isStyleModulePath: () => isStyleModulePath,
825
+ isPreprocessableStylePath: () => isPreprocessableStylePath,
826
+ getStyleBaseName: () => getStyleBaseName,
827
+ getCssOutputExtension: () => getCssOutputExtension,
828
+ createSvelteStylePreprocessor: () => createSvelteStylePreprocessor,
829
+ createStyleTransformConfig: () => createStyleTransformConfig,
830
+ createStylePreprocessorPlugin: () => createStylePreprocessorPlugin,
831
+ compileStyleSource: () => compileStyleSource,
832
+ compileStyleFileIfNeededSync: () => compileStyleFileIfNeededSync,
833
+ compileStyleFileIfNeeded: () => compileStyleFileIfNeeded
834
+ });
835
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
836
+ import { readFile } from "fs/promises";
837
+ import { createRequire } from "module";
838
+ import { dirname as dirname2, extname, isAbsolute, join as join3, relative, resolve as resolve4 } from "path";
839
+ import { fileURLToPath } from "url";
840
+ var CSS_EXTENSION_PATTERN, STYLE_EXTENSION_PATTERN, STYLE_MODULE_EXTENSION_PATTERN, STYLE_LANGUAGE_PATTERN, importOptionalPeer, requireOptionalPeer, requireFromCwd, isPreprocessableStylePath = (filePath) => STYLE_EXTENSION_PATTERN.test(filePath), isStyleModulePath = (filePath) => STYLE_MODULE_EXTENSION_PATTERN.test(filePath), isStylePath = (filePath) => /\.(css|s[ac]ss|less|styl(?:us)?)$/i.test(filePath), getStyleBaseName = (filePath) => filePath.replace(/\.(css|s[ac]ss|less|styl(?:us)?)$/i, ""), getStyleLanguage = (filePathOrLanguage) => {
841
+ const normalized = filePathOrLanguage.toLowerCase();
842
+ if (normalized === "scss" || normalized.endsWith(".scss"))
843
+ return "scss";
844
+ if (normalized === "sass" || normalized.endsWith(".sass"))
845
+ return "sass";
846
+ if (normalized === "less" || normalized.endsWith(".less"))
847
+ return "less";
848
+ if (normalized === "styl" || normalized === "stylus" || normalized.endsWith(".styl") || normalized.endsWith(".stylus"))
849
+ return "stylus";
850
+ return null;
851
+ }, missingDependencyError = (name, filePath) => new Error(`Unable to compile ${filePath}: install optional dependency "${name}" to use this stylesheet preprocessor.`), requireOptionalPeerSync = (specifier) => {
852
+ try {
853
+ return requireFromCwd(specifier);
854
+ } catch {
855
+ return requireOptionalPeer(specifier);
911
856
  }
912
- const propProviders = Object.entries(maybeProps).map(([propName, propValue]) => ({
913
- token: tokenMap.get(toScreamingSnake(propName)),
914
- value: propValue
915
- })).filter((entry) => entry.token).map((entry) => ({ provide: entry.token, useValue: entry.value }));
916
- return [...providers, ...propProviders];
917
- }, clearSelectorCache = () => selectorCache.clear(), isInjectionToken = (value) => {
918
- if (!value || typeof value !== "object") {
919
- return false;
857
+ }, normalizeLoadPaths = (filePath, paths = []) => [
858
+ dirname2(filePath),
859
+ process.cwd(),
860
+ ...paths.map((path) => resolve4(process.cwd(), path))
861
+ ], tsconfigAliasCache, stripJsonComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"), normalizeAliasEntries = (aliases) => Object.entries(aliases ?? {}).map(([pattern, value]) => ({
862
+ pattern,
863
+ replacements: Array.isArray(value) ? value : [value]
864
+ })), readTsconfigAliases = () => {
865
+ const cwd = process.cwd();
866
+ if (tsconfigAliasCache?.cwd === cwd)
867
+ return tsconfigAliasCache;
868
+ const tsconfigPath = resolve4(cwd, "tsconfig.json");
869
+ const empty = { aliases: [], baseUrl: cwd, cwd };
870
+ if (!existsSync4(tsconfigPath)) {
871
+ tsconfigAliasCache = empty;
872
+ return empty;
920
873
  }
921
- return "ngMetadataName" in value && value.ngMetadataName === "InjectionToken";
922
- }, discoverTokens = (pageModule) => new Map(Object.entries(pageModule).filter(([, value]) => isInjectionToken(value))), loadSsrDeps = async (pagePath) => {
923
- const ssrDepsPath = (pagePath.split("?")[0] ?? pagePath).replace(/\.js$/, ".ssr-deps.js");
924
874
  try {
925
- const ssrDeps = await import(ssrDepsPath);
926
- const result = {
927
- common: ssrDeps.__angularCommon,
928
- core: ssrDeps.__angularCore,
929
- platformBrowser: ssrDeps.__angularPlatformBrowser,
930
- platformServer: ssrDeps.__angularPlatformServer
875
+ const parsed = JSON.parse(stripJsonComments(readFileSync3(tsconfigPath, "utf-8")));
876
+ const compilerOptions = parsed.compilerOptions ?? {};
877
+ const baseUrl = resolve4(cwd, compilerOptions.baseUrl ?? ".");
878
+ tsconfigAliasCache = {
879
+ aliases: normalizeAliasEntries(compilerOptions.paths),
880
+ baseUrl,
881
+ cwd
931
882
  };
932
- return result;
933
883
  } catch {
934
- return null;
935
- }
936
- }, resolveSelector = (deps, pagePath, PageComponent) => {
937
- const cached = selectorCache.get(pagePath);
938
- if (cached) {
939
- return cached;
940
- }
941
- const selector = deps.reflectComponentType(PageComponent)?.selector ?? "ng-app";
942
- selectorCache.set(pagePath, selector);
943
- return selector;
944
- }, injectBeforeClose = (html, snippet) => {
945
- if (html.includes("</body>")) {
946
- return html.replace("</body>", `${snippet}</body>`);
947
- }
948
- if (html.includes("</html>")) {
949
- return html.replace("</html>", `${snippet}</html>`);
884
+ tsconfigAliasCache = empty;
950
885
  }
951
- return html + snippet;
952
- }, injectSsrScripts = (html, requestId, indexPath, props) => {
953
- let result = html;
954
- const registeredScripts = getAndClearClientScripts(requestId);
955
- if (registeredScripts.length > 0) {
956
- result = injectBeforeClose(result, generateClientScriptCode(registeredScripts));
886
+ return tsconfigAliasCache;
887
+ }, getAliasEntries = (config) => {
888
+ const tsconfig = readTsconfigAliases();
889
+ return {
890
+ aliases: [...normalizeAliasEntries(config?.aliases), ...tsconfig.aliases],
891
+ baseUrl: tsconfig.baseUrl
892
+ };
893
+ }, aliasPatternToRegExp = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("(.+)")}$`), resolveAliasTargets = (specifier, config) => {
894
+ const { aliases, baseUrl } = getAliasEntries(config);
895
+ const targets = [];
896
+ for (const alias of aliases) {
897
+ const match = specifier.match(aliasPatternToRegExp(alias.pattern));
898
+ if (!match)
899
+ continue;
900
+ const wildcard = match[1] ?? "";
901
+ for (const replacement of alias.replacements) {
902
+ targets.push(resolve4(baseUrl, replacement.replace("*", wildcard)));
903
+ }
957
904
  }
958
- if (props) {
959
- result = injectBeforeClose(result, `<script>window.__ABS_ANGULAR_PAGE_PROPS__ = ${JSON.stringify(props)};</script>`);
905
+ return targets;
906
+ }, getLanguageExtensions = (language) => {
907
+ if (language === "less")
908
+ return [".less", ".css"];
909
+ if (language === "stylus")
910
+ return [".styl", ".stylus", ".css"];
911
+ return [".scss", ".sass", ".css"];
912
+ }, getCandidatePaths = (basePath, language) => {
913
+ const ext = extname(basePath);
914
+ const paths = ext ? [basePath] : getLanguageExtensions(language).flatMap((extension) => [
915
+ `${basePath}${extension}`,
916
+ join3(basePath, `index${extension}`)
917
+ ]);
918
+ if (language === "scss" || language === "sass") {
919
+ return paths.flatMap((path) => {
920
+ const dir = dirname2(path);
921
+ const base = path.slice(dir.length + 1);
922
+ return [path, join3(dir, `_${base}`)];
923
+ });
960
924
  }
961
- if (indexPath) {
962
- const escapedIndexPath = JSON.stringify(indexPath);
963
- result = injectBeforeClose(result, `<script>import(${escapedIndexPath});</script>`);
925
+ return paths;
926
+ }, resolveImportPath = (specifier, fromDirectory, loadPaths, language, config) => {
927
+ const rawCandidates = [
928
+ ...resolveAliasTargets(specifier, config),
929
+ isAbsolute(specifier) ? specifier : resolve4(fromDirectory, specifier),
930
+ ...loadPaths.map((path) => resolve4(path, specifier))
931
+ ];
932
+ for (const candidate of rawCandidates.flatMap((path) => getCandidatePaths(path, language))) {
933
+ if (existsSync4(candidate))
934
+ return candidate;
964
935
  }
965
- return result;
966
- }, renderAngularApp = async (deps, PageComponent, providers, document2) => {
967
- const bootstrap = (context) => deps.bootstrapApplication(PageComponent, { providers }, context);
968
- return withSuppressedAngularDevLogs(() => deps.renderApplication(bootstrap, {
969
- document: document2,
970
- platformProviders: [],
971
- url: "/"
972
- }));
973
- }, withSuppressedAngularDevLogs = async (render) => {
974
- const origLog = console.log;
975
- console.log = (...args) => {
976
- if (typeof args[0] === "string" && args[0].includes("development mode")) {
977
- return;
978
- }
979
- origLog.apply(console, args);
936
+ return null;
937
+ }, isExternalCssUrl = (url) => /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(url), splitCssUrl = (url) => {
938
+ const markerIndex = url.search(/[?#]/);
939
+ if (markerIndex === -1)
940
+ return { marker: "", path: url };
941
+ return {
942
+ marker: url.slice(markerIndex),
943
+ path: url.slice(0, markerIndex)
980
944
  };
981
- try {
982
- return await render();
983
- } finally {
984
- console.log = origLog;
985
- }
986
- };
987
- var init_ssrRender = __esm(() => {
988
- init_registerClientScript();
989
- routePropsCache = new Map;
990
- selectorCache = new Map;
991
- });
992
-
993
- // src/angular/islands.ts
994
- var exports_islands = {};
995
- __export(exports_islands, {
996
- renderAngularIslandToHtml: () => renderAngularIslandToHtml,
997
- mountAngularIsland: () => mountAngularIsland,
998
- getAngularIslandSelector: () => getAngularIslandSelector
999
- });
1000
- var angularIslandSelector = "abs-angular-island", getAngularIslandSelector = (_islandId) => angularIslandSelector, getSelectorFromRenderedIsland = (rootElement) => {
1001
- const firstChild = rootElement.firstElementChild;
1002
- if (!(firstChild instanceof HTMLElement)) {
1003
- return null;
945
+ }, rebaseCssUrls = (contents, sourceFile, entryFile) => {
946
+ const sourceDir = dirname2(sourceFile);
947
+ const entryDir = dirname2(entryFile);
948
+ if (sourceDir === entryDir)
949
+ return contents;
950
+ return contents.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (match, quote, rawUrl) => {
951
+ const trimmedUrl = rawUrl.trim();
952
+ if (!trimmedUrl || isExternalCssUrl(trimmedUrl))
953
+ return match;
954
+ const { marker, path } = splitCssUrl(trimmedUrl);
955
+ const rebased = relative(entryDir, resolve4(sourceDir, path)).replace(/\\/g, "/");
956
+ const normalized = rebased.startsWith(".") ? rebased : `./${rebased}`;
957
+ const nextQuote = quote || '"';
958
+ return `url(${nextQuote}${normalized}${marker}${nextQuote})`;
959
+ });
960
+ }, rewriteAliasedStyleImports = (contents, sourceFile, loadPaths, language, config) => contents.replace(/(@(?:use|forward|import|require)\s+)(["'])([^"']+)\2/g, (match, prefix, quote, specifier) => {
961
+ if (specifier.startsWith(".") || isAbsolute(specifier) || isExternalCssUrl(specifier))
962
+ return match;
963
+ const resolved = resolveImportPath(specifier, dirname2(sourceFile), loadPaths, language, config);
964
+ return resolved ? `${prefix}${quote}${resolved}${quote}` : match;
965
+ }), preprocessLoadedStyle = (contents, sourceFile, entryFile, loadPaths = [], language, config) => {
966
+ const rebased = rebaseCssUrls(contents, sourceFile, entryFile);
967
+ return language ? rewriteAliasedStyleImports(rebased, sourceFile, loadPaths, language, config) : rebased;
968
+ }, extractCssModuleExports = (css) => {
969
+ const exports = {};
970
+ const nextCss = css.replace(/:export\s*\{([^}]*)\}/g, (_, body) => {
971
+ for (const declaration of body.split(";")) {
972
+ const separator = declaration.indexOf(":");
973
+ if (separator === -1)
974
+ continue;
975
+ const key = declaration.slice(0, separator).trim();
976
+ const value = declaration.slice(separator + 1).trim();
977
+ if (key && value)
978
+ exports[key] = value;
979
+ }
980
+ return "";
981
+ });
982
+ return { css: nextCss, exports };
983
+ }, getSassOptions = (config, language) => ({
984
+ ...config?.sass ?? {},
985
+ ...language === "scss" ? config?.scss ?? {} : {}
986
+ }), getLessOptions = (config) => config?.less ?? {}, getStylusOptions = (config) => config?.stylus ?? {}, createStyleTransformConfig = (stylePreprocessors, postcss) => postcss === undefined ? stylePreprocessors : { ...stylePreprocessors ?? {}, postcss }, withAdditionalData = (contents, additionalData) => additionalData ? `${additionalData}
987
+ ${contents}` : contents, normalizePostcssModule = (mod) => {
988
+ if (mod && typeof mod === "object" && "default" in mod) {
989
+ return mod.default ?? mod;
1004
990
  }
1005
- const selector = firstChild.tagName.toLowerCase();
1006
- return selector.length > 0 ? selector : null;
1007
- }, getClientAngularComponentSelector = (component) => {
1008
- const maybeDef = Reflect.get(component, "\u0275cmp");
1009
- if (typeof maybeDef !== "object" || maybeDef === null) {
1010
- return null;
991
+ return mod;
992
+ }, loadPostcssConfigFile = async (configPath) => {
993
+ const resolved = resolve4(process.cwd(), configPath);
994
+ const loaded = resolved.endsWith(".cjs") || resolved.endsWith(".cts") ? requireOptionalPeerSync(resolved) : await importOptionalPeer(`${new URL(`file://${resolved}`).href}?t=${Date.now()}`);
995
+ const config = normalizePostcssModule(loaded);
996
+ const value = typeof config === "function" ? await config({
997
+ cwd: process.cwd(),
998
+ env: "development"
999
+ }) : config;
1000
+ return normalizePostcssModule(value) ?? {};
1001
+ }, normalizePostcssPlugins = (plugins) => {
1002
+ if (!plugins)
1003
+ return [];
1004
+ if (Array.isArray(plugins))
1005
+ return plugins.filter(Boolean);
1006
+ const resolved = [];
1007
+ for (const [specifier, options] of Object.entries(plugins)) {
1008
+ if (options === false)
1009
+ continue;
1010
+ const mod = normalizePostcssModule(requireOptionalPeerSync(specifier));
1011
+ const plugin = typeof mod === "function" ? mod(options === true ? undefined : options) : mod;
1012
+ if (plugin)
1013
+ resolved.push(plugin);
1011
1014
  }
1012
- const maybeSelectors = Reflect.get(maybeDef, "selectors");
1013
- if (!Array.isArray(maybeSelectors)) {
1015
+ return resolved;
1016
+ }, resolvePostcssConfig = async (config) => {
1017
+ const inlineConfig = config?.postcss;
1018
+ if (!inlineConfig)
1014
1019
  return null;
1015
- }
1016
- const [firstSelectorGroup] = maybeSelectors;
1017
- if (!Array.isArray(firstSelectorGroup)) {
1020
+ const fileConfig = inlineConfig.config ? await loadPostcssConfigFile(inlineConfig.config) : {};
1021
+ const plugins = [
1022
+ ...normalizePostcssPlugins(fileConfig.plugins),
1023
+ ...normalizePostcssPlugins(inlineConfig.plugins)
1024
+ ];
1025
+ if (plugins.length === 0)
1018
1026
  return null;
1027
+ return {
1028
+ options: {
1029
+ ...fileConfig.options ?? {},
1030
+ ...inlineConfig.options ?? {}
1031
+ },
1032
+ plugins
1033
+ };
1034
+ }, runPostcss = async (css, filePath, config) => {
1035
+ const postcssConfig = await resolvePostcssConfig(config);
1036
+ if (!postcssConfig)
1037
+ return css;
1038
+ let postcssModule;
1039
+ try {
1040
+ postcssModule = await importOptionalPeer("postcss");
1041
+ } catch {
1042
+ throw missingDependencyError("postcss", filePath);
1019
1043
  }
1020
- const [selector] = firstSelectorGroup;
1021
- return typeof selector === "string" && selector.length > 0 ? selector : null;
1022
- }, createAngularIslandApp = async () => {
1023
- const { EnvironmentInjector, provideZonelessChangeDetection } = await import("@angular/core");
1024
- const { createApplication } = await import("@angular/platform-browser");
1025
- const app = await createApplication({
1026
- providers: [provideZonelessChangeDetection()]
1044
+ const postcss = postcssModule.default ?? postcssModule;
1045
+ const result = await postcss(postcssConfig.plugins).process(css, {
1046
+ from: filePath,
1047
+ map: false,
1048
+ ...postcssConfig.options
1027
1049
  });
1028
- const environmentInjector = app.injector.get(EnvironmentInjector);
1029
- return { app, environmentInjector };
1030
- }, angularIslandAppPromise = null, getAngularIslandApp = async () => {
1031
- if (!angularIslandAppPromise) {
1032
- angularIslandAppPromise = createAngularIslandApp();
1033
- }
1034
- return angularIslandAppPromise;
1035
- }, wrapperMetadataCache, requestRenderCache, getRequestRenderCache = () => {
1036
- const requestId = getSsrContextId();
1037
- if (!requestId) {
1038
- return null;
1039
- }
1040
- const cached = requestRenderCache.get(requestId);
1041
- if (cached) {
1042
- return cached;
1050
+ return result.css;
1051
+ }, createSassImporter = (entryFile, loadPaths, language, config) => ({
1052
+ canonicalize(specifier, options) {
1053
+ const fromDirectory = options.containingUrl ? dirname2(fileURLToPath(options.containingUrl)) : dirname2(entryFile);
1054
+ const resolved = resolveImportPath(specifier, fromDirectory, loadPaths, language, config);
1055
+ return resolved ? new URL(`file://${resolved}`) : null;
1056
+ },
1057
+ load(canonicalUrl) {
1058
+ const filePath = fileURLToPath(canonicalUrl);
1059
+ const fileLanguage = getStyleLanguage(filePath);
1060
+ if (fileLanguage !== "scss" && fileLanguage !== "sass" && fileLanguage !== null)
1061
+ return null;
1062
+ return {
1063
+ contents: preprocessLoadedStyle(readFileSync3(filePath, "utf-8"), filePath, entryFile, loadPaths, language, config),
1064
+ syntax: filePath.endsWith(".sass") ? "indented" : "scss"
1065
+ };
1043
1066
  }
1044
- const renderCache = new Map;
1045
- requestRenderCache.set(requestId, renderCache);
1046
- return renderCache;
1047
- }, getAngularIslandWrapperKey = (component, _islandId) => {
1048
- const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
1049
- return `${componentName}:${angularIslandSelector}`;
1050
- }, getIslandRenderCacheKey = (component, props) => {
1051
- const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
1052
- return `${componentName}:${JSON.stringify(props)}`;
1053
- }, buildAngularIslandWrapperMetadata = async (component, islandId, wrapperKey) => {
1054
- const { Component, InjectionToken, inject } = await import("@angular/core");
1055
- const { NgComponentOutlet } = await import("@angular/common");
1056
- const deps = await getAngularDeps();
1057
- const selector = getAngularIslandSelector(islandId);
1058
- const propsToken = new InjectionToken(`${wrapperKey}:props`);
1059
-
1060
- class AngularIslandWrapperComponent {
1061
- component = component;
1062
- props = inject(propsToken);
1067
+ }), createLessFileManager = (entryFile, loadPaths, config) => ({
1068
+ install(less, pluginManager) {
1069
+ const baseManager = new less.FileManager;
1070
+ const manager = Object.create(baseManager);
1071
+ manager.supports = (filename, currentDirectory) => Boolean(resolveImportPath(filename, resolve4(currentDirectory), loadPaths, "less", config));
1072
+ manager.loadFile = async (filename, currentDirectory) => {
1073
+ const resolved = resolveImportPath(filename, resolve4(currentDirectory), loadPaths, "less", config);
1074
+ if (!resolved) {
1075
+ throw new Error(`Unable to resolve Less import "${filename}"`);
1076
+ }
1077
+ return {
1078
+ contents: preprocessLoadedStyle(await readFile(resolved, "utf-8"), resolved, entryFile, loadPaths, "less", config),
1079
+ filename: resolved
1080
+ };
1081
+ };
1082
+ pluginManager.addFileManager(manager);
1063
1083
  }
1064
- return {
1065
- deps,
1066
- propsToken,
1067
- selector,
1068
- WrapperComponent: Component({
1069
- imports: [NgComponentOutlet, component],
1070
- selector,
1071
- standalone: true,
1072
- template: '<ng-container *ngComponentOutlet="component; inputs: props"></ng-container>'
1073
- })(AngularIslandWrapperComponent)
1074
- };
1075
- }, createAngularIslandWrapper = async (component, islandId) => {
1076
- const wrapperKey = getAngularIslandWrapperKey(component, islandId);
1077
- const cached = wrapperMetadataCache.get(wrapperKey);
1078
- if (cached) {
1079
- return cached;
1084
+ }), renderStylus = async (contents, filePath, loadPaths, options) => {
1085
+ let stylus;
1086
+ try {
1087
+ const stylusModule = await importOptionalPeer("stylus");
1088
+ stylus = stylusModule.default ?? stylusModule;
1089
+ } catch {
1090
+ throw missingDependencyError("stylus", filePath);
1080
1091
  }
1081
- const metadataPromise = buildAngularIslandWrapperMetadata(component, islandId, wrapperKey);
1082
- wrapperMetadataCache.set(wrapperKey, metadataPromise);
1083
- return metadataPromise;
1084
- }, extractAngularIslandRoot = (html, selector) => {
1085
- const openTag = `<${selector}`;
1086
- const start = html.indexOf(openTag);
1087
- if (start < 0) {
1088
- throw new Error(`Could not find Angular island root "${selector}".`);
1089
- }
1090
- const endTag = `</${selector}>`;
1091
- const end = html.indexOf(endTag, start);
1092
- if (end < 0) {
1093
- throw new Error(`Could not close Angular island root "${selector}".`);
1094
- }
1095
- return html.slice(start, end + endTag.length);
1096
- }, mountAngularIsland = async (component, element, props, islandId) => {
1097
- await import("@angular/compiler");
1098
- const { createComponent, inputBinding } = await import("@angular/core");
1099
- const selector = getAngularIslandSelector(islandId);
1100
- const { app, environmentInjector } = await getAngularIslandApp();
1101
- let rootElement = element.querySelector(selector);
1102
- if (!(rootElement instanceof HTMLElement)) {
1103
- element.innerHTML = `<${selector}></${selector}>`;
1104
- rootElement = element.querySelector(selector);
1105
- }
1106
- if (!(rootElement instanceof HTMLElement))
1107
- return app;
1108
- const componentSelector = getClientAngularComponentSelector(component) ?? getSelectorFromRenderedIsland(rootElement);
1109
- if (!componentSelector)
1110
- return app;
1111
- rootElement.innerHTML = `<${componentSelector}></${componentSelector}>`;
1112
- const hostElement = rootElement.querySelector(componentSelector);
1113
- if (!(hostElement instanceof HTMLElement))
1114
- return app;
1115
- const bindings = Object.entries(props).map(([key, value]) => inputBinding(key, () => value));
1116
- const componentRef = createComponent(component, {
1117
- bindings,
1118
- environmentInjector,
1119
- hostElement
1120
- });
1121
- app.attachView(componentRef.hostView);
1122
- componentRef.changeDetectorRef.detectChanges();
1123
- window.__ABS_ANGULAR_ISLAND_APPS__ ??= [];
1124
- window.__ABS_ANGULAR_ISLAND_APPS__.push(app);
1125
- return app;
1126
- }, renderAngularIslandToHtml = async (component, props, islandId) => {
1127
- const requestCache = getRequestRenderCache();
1128
- const renderCacheKey = getIslandRenderCacheKey(component, props);
1129
- const cachedHtml = requestCache?.get(renderCacheKey);
1130
- if (cachedHtml) {
1131
- return cachedHtml;
1132
- }
1133
- const { deps, propsToken, selector, WrapperComponent } = await createAngularIslandWrapper(component, islandId);
1134
- const providers = [
1135
- deps.provideServerRendering(),
1136
- deps.provideZonelessChangeDetection(),
1137
- { provide: deps.APP_BASE_HREF, useValue: "/" },
1138
- { provide: propsToken, useValue: props }
1139
- ];
1140
- const document2 = `<!DOCTYPE html><html><body><${selector}></${selector}></body></html>`;
1141
- const html = await withSuppressedAngularDevLogs(() => deps.renderApplication((context) => deps.bootstrapApplication(WrapperComponent, { providers }, context), {
1142
- document: document2,
1143
- platformProviders: [],
1144
- url: "/"
1145
- }));
1146
- const islandHtml = extractAngularIslandRoot(html, selector);
1147
- requestCache?.set(renderCacheKey, islandHtml);
1148
- return islandHtml;
1149
- };
1150
- var init_islands = __esm(() => {
1151
- init_angularDeps();
1152
- init_ssrRender();
1153
- init_registerClientScript();
1154
- wrapperMetadataCache = new Map;
1155
- requestRenderCache = new Map;
1156
- });
1157
-
1158
- // src/core/islandSsr.ts
1159
- var renderAngularIslandToHtmlInternal = async (component, props, islandId) => {
1160
- const { renderAngularIslandToHtml: renderAngularIslandToHtml2 } = await Promise.resolve().then(() => (init_islands(), exports_islands));
1161
- return renderAngularIslandToHtml2(component, props, islandId);
1162
- }, renderAngularIslandToHtml2, renderReactIslandToHtml = (component, props) => import("react").then(({ createElement }) => import("react-dom/server").then(({ renderToStaticMarkup }) => renderToStaticMarkup(createElement(component, props)))), renderSvelteIslandToHtml = (component, props) => import("svelte/server").then(({ render }) => {
1163
- const { body } = render(component, { props });
1164
- return body;
1165
- }), renderVueIslandToHtml = (component, props) => import("vue").then(({ createSSRApp, h }) => {
1166
- const app = createSSRApp({
1167
- render: () => h(component, props)
1168
- });
1169
- return import("vue/server-renderer").then(({ renderToString }) => renderToString(app));
1170
- });
1171
- var init_islandSsr = __esm(() => {
1172
- renderAngularIslandToHtml2 = renderAngularIslandToHtmlInternal;
1173
- });
1174
-
1175
- // src/build/resolvePackageImport.ts
1176
- import { resolve as resolve3, join as join2 } from "path";
1177
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
1178
- var resolveExportPath = (entry, conditions) => {
1179
- if (typeof entry === "string")
1180
- return entry;
1181
- if (!entry || typeof entry !== "object")
1182
- return null;
1183
- for (const condition of conditions) {
1184
- const target = Reflect.get(entry, condition);
1185
- if (typeof target === "string") {
1186
- return target;
1092
+ return new Promise((resolveCss, reject) => {
1093
+ const renderer = stylus(contents);
1094
+ renderer.set("filename", filePath);
1095
+ for (const [key, value] of Object.entries(options.options ?? {})) {
1096
+ renderer.set(key, value);
1187
1097
  }
1188
- }
1189
- return null;
1190
- }, resolvePackageImport = (specifier, conditions = ["import"]) => {
1191
- if (specifier.startsWith(".") || specifier.startsWith("/"))
1192
- return null;
1193
- const parts = specifier.split("/");
1194
- const isScoped = specifier.startsWith("@");
1195
- const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
1196
- const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
1197
- const exportKey = subpath ? `./${subpath}` : ".";
1198
- const currentPackageJsonPath = resolve3(process.cwd(), "package.json");
1199
- const currentPackageJson = existsSync3(currentPackageJsonPath) ? JSON.parse(readFileSync2(currentPackageJsonPath, "utf-8")) : null;
1200
- const currentPackageDir = currentPackageJson?.name === packageName ? process.cwd() : null;
1201
- const packageDir = currentPackageDir ?? resolve3(process.cwd(), "node_modules", packageName ?? "");
1202
- const packageJsonPath = join2(packageDir, "package.json");
1203
- if (!existsSync3(packageJsonPath))
1204
- return null;
1205
- try {
1206
- const packageJson = currentPackageDir && currentPackageJson ? currentPackageJson : JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
1207
- const { exports } = packageJson;
1208
- if (!exports)
1209
- return null;
1210
- const entry = exports[exportKey];
1211
- if (!entry)
1212
- return null;
1213
- const importPath = resolveExportPath(entry, conditions);
1214
- if (!importPath)
1215
- return null;
1216
- if (currentPackageDir && importPath.startsWith("./dist/")) {
1217
- const sourceCandidate = resolve3(packageDir, importPath.replace(/^\.\/dist\//, "./src/"));
1218
- if (existsSync3(sourceCandidate)) {
1219
- return sourceCandidate;
1220
- }
1098
+ for (const path of loadPaths)
1099
+ renderer.include(path);
1100
+ renderer.render((error, css) => {
1101
+ if (error)
1102
+ reject(error);
1103
+ else
1104
+ resolveCss(css ?? "");
1105
+ });
1106
+ });
1107
+ }, compileStyleSource = async (filePath, source, languageHint, config) => {
1108
+ const language = getStyleLanguage(languageHint ?? filePath);
1109
+ const rawContents = source ?? await readFile(filePath, "utf-8");
1110
+ if (language === "scss" || language === "sass") {
1111
+ const options = getSassOptions(config, language);
1112
+ const packageName = options.implementation ?? "sass";
1113
+ let sass;
1114
+ try {
1115
+ sass = await importOptionalPeer(packageName);
1116
+ } catch {
1117
+ throw missingDependencyError(packageName, filePath);
1221
1118
  }
1222
- const resolved = resolve3(packageDir, importPath);
1223
- return existsSync3(resolved) ? resolved : null;
1224
- } catch {
1225
- return null;
1119
+ const contents = withAdditionalData(rawContents, options.additionalData);
1120
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
1121
+ const result = sass.compileString(contents, {
1122
+ importers: [
1123
+ createSassImporter(filePath, loadPaths, language, config)
1124
+ ],
1125
+ loadPaths,
1126
+ style: "expanded",
1127
+ syntax: language === "sass" ? "indented" : "scss",
1128
+ url: new URL(`file://${filePath}`)
1129
+ });
1130
+ return runPostcss(result.css, filePath, config);
1226
1131
  }
1227
- };
1228
- var init_resolvePackageImport = () => {};
1229
-
1230
- // src/svelte/lowerIslandSyntax.ts
1231
- var ISLAND_TAG_RE, extractBracedExpression = (text, braceStart) => {
1232
- let depth = 0;
1233
- for (let index = braceStart;index < text.length; index += 1) {
1234
- const char = text[index];
1235
- if (char === "{")
1236
- depth += 1;
1237
- if (char === "}")
1238
- depth -= 1;
1239
- if (depth === 0) {
1240
- return text.slice(braceStart + 1, index).trim();
1132
+ if (language === "less") {
1133
+ const options = getLessOptions(config);
1134
+ let lessModule;
1135
+ try {
1136
+ lessModule = await importOptionalPeer("less");
1137
+ } catch {
1138
+ throw missingDependencyError("less", filePath);
1241
1139
  }
1140
+ const less = lessModule.render ? lessModule : lessModule.default;
1141
+ const render = less?.render;
1142
+ if (!render)
1143
+ throw missingDependencyError("less", filePath);
1144
+ const contents = withAdditionalData(rawContents, options.additionalData);
1145
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
1146
+ const result = await render(contents, {
1147
+ ...options.options ?? {},
1148
+ filename: filePath,
1149
+ paths: loadPaths,
1150
+ plugins: [
1151
+ ...options.options?.plugins ?? [],
1152
+ createLessFileManager(filePath, loadPaths, config)
1153
+ ]
1154
+ });
1155
+ return runPostcss(result.css, filePath, config);
1242
1156
  }
1243
- return null;
1244
- }, extractIslandAttribute = (attributeString, name) => {
1245
- const quotedMatch = attributeString.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`));
1246
- if (quotedMatch?.[1]) {
1247
- return { expression: JSON.stringify(quotedMatch[1]), found: true };
1248
- }
1249
- const attributeIndex = attributeString.search(new RegExp(`\\b${name}\\s*=\\s*\\{`));
1250
- if (attributeIndex < 0) {
1251
- return { expression: "", found: false };
1252
- }
1253
- const braceStart = attributeString.indexOf("{", attributeIndex);
1254
- if (braceStart < 0) {
1255
- return { expression: "", found: false };
1256
- }
1257
- const expression = extractBracedExpression(attributeString, braceStart);
1258
- if (expression === null) {
1259
- return { expression: "", found: false };
1260
- }
1261
- return { expression, found: true };
1262
- }, lowerSvelteIslandSyntax = (source, _mode = "server") => {
1263
- if (!source.includes("<Island")) {
1264
- return { code: source, transformed: false };
1157
+ if (language === "stylus") {
1158
+ const options = getStylusOptions(config);
1159
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
1160
+ const contents = withAdditionalData(preprocessLoadedStyle(rawContents, filePath, filePath, loadPaths, "stylus", config), options.additionalData);
1161
+ return runPostcss(await renderStylus(contents, filePath, loadPaths, options), filePath, config);
1265
1162
  }
1266
- let islandIndex = 0;
1267
- const transformedMarkup = source.replace(ISLAND_TAG_RE, (fullMatch, attributeString) => {
1268
- const framework = extractIslandAttribute(attributeString, "framework");
1269
- const component = extractIslandAttribute(attributeString, "component");
1270
- if (!framework.found || !component.found) {
1271
- return fullMatch;
1272
- }
1273
- const hydrate = extractIslandAttribute(attributeString, "hydrate");
1274
- const props = extractIslandAttribute(attributeString, "props");
1275
- const slotId = `absolute-svelte-island-${islandIndex.toString(BASE_36_RADIX)}`;
1276
- islandIndex += 1;
1277
- const resolveExpression = `await __absoluteResolveIslandHtml(${JSON.stringify(slotId)}, { component: ${component.expression}, framework: ${framework.expression}, hydrate: ${hydrate.found ? hydrate.expression : JSON.stringify("load")}, props: ${props.found ? props.expression : "{}"} })`;
1278
- return `<div data-absolute-island-slot="${slotId}" style="display: contents">{@html ${resolveExpression}}</div>`;
1279
- });
1280
- const importLine = 'import { resolveIslandHtml as __absoluteResolveIslandHtml } from "@absolutejs/absolute/svelte";';
1281
- if (transformedMarkup.includes("<script")) {
1282
- return {
1283
- code: transformedMarkup.replace(/<script(\s[^>]*)?>/, (match) => `${match}
1284
- ${importLine}
1285
- `),
1286
- transformed: true
1163
+ return runPostcss(rawContents, filePath, config);
1164
+ }, createStylePreprocessorPlugin = (config) => ({
1165
+ name: "absolute-style-preprocessor",
1166
+ setup(build) {
1167
+ const cssModuleSources = new Map;
1168
+ build.onResolve({ filter: /^absolute-style-module:/ }, ({ path }) => ({
1169
+ namespace: "absolute-style-module",
1170
+ path: path.slice("absolute-style-module:".length)
1171
+ }));
1172
+ build.onLoad({ filter: /\.module\.css$/i, namespace: "absolute-style-module" }, async ({ path }) => {
1173
+ const source = cssModuleSources.get(path);
1174
+ if (!source) {
1175
+ throw new Error(`Unable to resolve CSS module source for ${path}`);
1176
+ }
1177
+ return {
1178
+ contents: source.css,
1179
+ loader: "css"
1180
+ };
1181
+ });
1182
+ build.onLoad({ filter: STYLE_EXTENSION_PATTERN }, async ({ path }) => {
1183
+ if (isStyleModulePath(path)) {
1184
+ const cssModulePath = path.replace(STYLE_EXTENSION_PATTERN, ".css");
1185
+ const compiled = await compileStyleSource(path, undefined, undefined, config);
1186
+ const { css, exports } = extractCssModuleExports(compiled);
1187
+ cssModuleSources.set(cssModulePath, { css, exports });
1188
+ const exportSource = Object.keys(exports).length > 0 ? `import styles from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)}; export default Object.assign({}, styles, ${JSON.stringify(exports)});` : `export { default } from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)};`;
1189
+ return {
1190
+ contents: exportSource,
1191
+ loader: "js"
1192
+ };
1193
+ }
1194
+ return {
1195
+ contents: await compileStyleSource(path, undefined, undefined, config),
1196
+ loader: "css"
1197
+ };
1198
+ });
1199
+ build.onLoad({ filter: CSS_EXTENSION_PATTERN }, async ({ path }) => ({
1200
+ contents: await compileStyleSource(path, undefined, undefined, config),
1201
+ loader: "css"
1202
+ }));
1203
+ }
1204
+ }), stylePreprocessorPlugin, createSvelteStylePreprocessor = (config) => ({
1205
+ style: async ({
1206
+ attributes,
1207
+ content,
1208
+ filename
1209
+ }) => {
1210
+ const language = typeof attributes.lang === "string" ? attributes.lang : typeof attributes.type === "string" ? attributes.type.replace(/^text\//, "") : null;
1211
+ if (!language || !STYLE_LANGUAGE_PATTERN.test(language))
1212
+ return;
1213
+ const path = filename ?? `style.${language}`;
1214
+ return {
1215
+ code: await compileStyleSource(path, content, language, config)
1287
1216
  };
1288
1217
  }
1289
- return {
1290
- code: `<script lang="ts">
1291
- ${importLine}
1292
- </script>
1293
- ${transformedMarkup}`,
1294
- transformed: true
1295
- };
1296
- };
1297
- var init_lowerIslandSyntax = __esm(() => {
1298
- init_constants();
1299
- ISLAND_TAG_RE = /<Island\b([\s\S]*?)\/>/g;
1300
- });
1301
-
1302
- // src/svelte/lowerAwaitSlotSyntax.ts
1303
- var AWAIT_BLOCK_RE, escapeTemplateLiteral = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${"), markupToTemplateLiteral = (markup) => {
1304
- const escaped = escapeTemplateLiteral(markup.trim());
1305
- const withExpressions = escaped.replace(/\{([^{}]+)\}/g, (_, expression) => `\${${String(expression).trim()}}`);
1306
- return `\`${withExpressions}\``;
1307
- }, lowerSvelteAwaitSlotSyntax = (source) => {
1308
- if (!source.includes("{#await")) {
1309
- return { code: source, transformed: false };
1218
+ }), compileStyleFileIfNeeded = async (filePath, config) => {
1219
+ if (!isPreprocessableStylePath(filePath)) {
1220
+ return runPostcss(await readFile(filePath, "utf-8"), filePath, config);
1310
1221
  }
1311
- let awaitIndex = 0;
1312
- let transformed = false;
1313
- const lowered = source.replace(AWAIT_BLOCK_RE, (fullMatch, awaitExpression, pendingMarkup, thenIdentifier, thenMarkup, catchIdentifier, catchMarkup) => {
1314
- const trimmedAwaitExpression = awaitExpression.trim();
1315
- if (!trimmedAwaitExpression) {
1316
- return fullMatch;
1222
+ return compileStyleSource(filePath, undefined, undefined, config);
1223
+ }, compileStyleFileIfNeededSync = (filePath, config) => {
1224
+ const rawContents = readFileSync3(filePath, "utf-8");
1225
+ const language = getStyleLanguage(filePath);
1226
+ if (config?.postcss) {
1227
+ throw new Error(`Unable to compile ${filePath}: PostCSS preprocessing is async-only.`);
1228
+ }
1229
+ if (language === "scss" || language === "sass") {
1230
+ const options = getSassOptions(config, language);
1231
+ const packageName = options.implementation ?? "sass";
1232
+ let sass;
1233
+ try {
1234
+ sass = requireOptionalPeerSync(packageName);
1235
+ } catch {
1236
+ throw missingDependencyError(packageName, filePath);
1317
1237
  }
1318
- const slotId = `absolute-svelte-await-${awaitIndex.toString(BASE_36_RADIX)}`;
1319
- awaitIndex += 1;
1320
- transformed = true;
1321
- const thenValueIdentifier = thenIdentifier?.trim() || "__awaitValue";
1322
- const catchValueIdentifier = catchIdentifier?.trim() || "__awaitError";
1323
- const fallbackHtml = markupToTemplateLiteral(pendingMarkup);
1324
- const resolvedHtml = markupToTemplateLiteral(thenMarkup);
1325
- const rejectedHtml = typeof catchMarkup === "string" ? markupToTemplateLiteral(catchMarkup) : null;
1326
- const catchBranch = rejectedHtml ? `catch (${catchValueIdentifier}) { return ${rejectedHtml}; }` : "catch (_absoluteAwaitError) { throw _absoluteAwaitError; }";
1327
- return `<AbsoluteAwaitSlot id="${slotId}" fallbackHtml={${fallbackHtml}} resolve={async () => { try { const ${thenValueIdentifier} = await (${trimmedAwaitExpression}); return ${resolvedHtml}; } ${catchBranch} }} />`;
1328
- });
1329
- if (!transformed) {
1330
- return { code: source, transformed: false };
1238
+ const contents = withAdditionalData(rawContents, options.additionalData);
1239
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
1240
+ return sass.compileString(contents, {
1241
+ importers: [
1242
+ createSassImporter(filePath, loadPaths, language, config)
1243
+ ],
1244
+ loadPaths,
1245
+ style: "expanded",
1246
+ syntax: language === "sass" ? "indented" : "scss",
1247
+ url: new URL(`file://${filePath}`)
1248
+ }).css;
1331
1249
  }
1332
- const importLine = 'import AbsoluteAwaitSlot from "@absolutejs/absolute/svelte/components/AwaitSlot.svelte";';
1333
- if (lowered.includes("<script")) {
1334
- return {
1335
- code: lowered.replace(/<script(\s[^>]*)?>/, (match) => `${match}
1336
- ${importLine}
1337
- `),
1338
- transformed: true
1339
- };
1250
+ if (language === "less") {
1251
+ throw new Error(`Unable to compile ${filePath}: Less styleUrl preprocessing is async-only. Import the Less file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
1340
1252
  }
1341
- return {
1342
- code: `<script lang="ts">
1343
- ${importLine}
1344
- </script>
1345
- ${lowered}`,
1346
- transformed: true
1347
- };
1348
- };
1349
- var init_lowerAwaitSlotSyntax = __esm(() => {
1350
- init_constants();
1351
- AWAIT_BLOCK_RE = /\{#await\s+([^}]+)\}([\s\S]*?)\{:then(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?)(?:\{:catch(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?))?\{\/await\}/g;
1253
+ if (language === "stylus") {
1254
+ throw new Error(`Unable to compile ${filePath}: Stylus styleUrl preprocessing is async-only. Import the Stylus file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
1255
+ }
1256
+ return rawContents;
1257
+ }, getCssOutputExtension = (filePath) => isPreprocessableStylePath(filePath) ? ".css" : extname(filePath);
1258
+ var init_stylePreprocessor = __esm(() => {
1259
+ CSS_EXTENSION_PATTERN = /\.css$/i;
1260
+ STYLE_EXTENSION_PATTERN = /\.(s[ac]ss|less|styl(?:us)?)$/i;
1261
+ STYLE_MODULE_EXTENSION_PATTERN = /\.module\.(s[ac]ss|less|styl(?:us)?)$/i;
1262
+ STYLE_LANGUAGE_PATTERN = /^(s[ac]ss|less|styl(?:us)?)$/i;
1263
+ importOptionalPeer = new Function("specifier", "return import(specifier)");
1264
+ requireOptionalPeer = new Function("specifier", "return require(specifier)");
1265
+ requireFromCwd = createRequire(join3(process.cwd(), "package.json"));
1266
+ stylePreprocessorPlugin = createStylePreprocessorPlugin();
1352
1267
  });
1353
1268
 
1354
- // src/build/stylePreprocessor.ts
1355
- var exports_stylePreprocessor = {};
1356
- __export(exports_stylePreprocessor, {
1357
- stylePreprocessorPlugin: () => stylePreprocessorPlugin,
1358
- isStylePath: () => isStylePath,
1359
- isStyleModulePath: () => isStyleModulePath,
1360
- isPreprocessableStylePath: () => isPreprocessableStylePath,
1361
- getStyleBaseName: () => getStyleBaseName,
1362
- getCssOutputExtension: () => getCssOutputExtension,
1363
- createSvelteStylePreprocessor: () => createSvelteStylePreprocessor,
1364
- createStyleTransformConfig: () => createStyleTransformConfig,
1365
- createStylePreprocessorPlugin: () => createStylePreprocessorPlugin,
1366
- compileStyleSource: () => compileStyleSource,
1367
- compileStyleFileIfNeededSync: () => compileStyleFileIfNeededSync,
1368
- compileStyleFileIfNeeded: () => compileStyleFileIfNeeded
1369
- });
1370
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
1371
- import { readFile } from "fs/promises";
1372
- import { createRequire } from "module";
1373
- import { dirname as dirname2, extname, isAbsolute, join as join3, relative, resolve as resolve4 } from "path";
1374
- import { fileURLToPath } from "url";
1375
- var CSS_EXTENSION_PATTERN, STYLE_EXTENSION_PATTERN, STYLE_MODULE_EXTENSION_PATTERN, STYLE_LANGUAGE_PATTERN, importOptionalPeer, requireOptionalPeer, requireFromCwd, isPreprocessableStylePath = (filePath) => STYLE_EXTENSION_PATTERN.test(filePath), isStyleModulePath = (filePath) => STYLE_MODULE_EXTENSION_PATTERN.test(filePath), isStylePath = (filePath) => /\.(css|s[ac]ss|less|styl(?:us)?)$/i.test(filePath), getStyleBaseName = (filePath) => filePath.replace(/\.(css|s[ac]ss|less|styl(?:us)?)$/i, ""), getStyleLanguage = (filePathOrLanguage) => {
1376
- const normalized = filePathOrLanguage.toLowerCase();
1377
- if (normalized === "scss" || normalized.endsWith(".scss"))
1378
- return "scss";
1379
- if (normalized === "sass" || normalized.endsWith(".sass"))
1380
- return "sass";
1381
- if (normalized === "less" || normalized.endsWith(".less"))
1382
- return "less";
1383
- if (normalized === "styl" || normalized === "stylus" || normalized.endsWith(".styl") || normalized.endsWith(".stylus"))
1384
- return "stylus";
1269
+ // src/core/svelteServerModule.ts
1270
+ import { mkdir, readdir } from "fs/promises";
1271
+ import { basename as basename2, dirname as dirname3, extname as extname2, join as join4, relative as relative2, resolve as resolve5 } from "path";
1272
+ var serverCacheRoot, compiledModuleCache, originalSourcePathCache, transpiler, ensureRelativeImportPath = (from, target) => {
1273
+ const importPath = relative2(dirname3(from), target).replace(/\\/g, "/");
1274
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
1275
+ }, processDirectoryEntries = (entries, dir, targetFileName, stack) => {
1276
+ for (const entry of entries) {
1277
+ const entryPath = join4(dir, entry.name);
1278
+ if (entry.isDirectory())
1279
+ stack.push(entryPath);
1280
+ if (entry.isFile() && entry.name === targetFileName) {
1281
+ return entryPath;
1282
+ }
1283
+ }
1385
1284
  return null;
1386
- }, missingDependencyError = (name, filePath) => new Error(`Unable to compile ${filePath}: install optional dependency "${name}" to use this stylesheet preprocessor.`), requireOptionalPeerSync = (specifier) => {
1387
- try {
1388
- return requireFromCwd(specifier);
1389
- } catch {
1390
- return requireOptionalPeer(specifier);
1285
+ }, searchDirectoryLevel = async (dirs, targetFileName) => {
1286
+ if (dirs.length === 0)
1287
+ return null;
1288
+ const nextStack = [];
1289
+ const dirEntries = await Promise.all(dirs.map(async (dir) => ({
1290
+ dir,
1291
+ entries: await readdir(dir, {
1292
+ encoding: "utf-8",
1293
+ withFileTypes: true
1294
+ })
1295
+ })));
1296
+ for (const { dir, entries } of dirEntries) {
1297
+ const found = processDirectoryEntries(entries, dir, targetFileName, nextStack);
1298
+ if (found)
1299
+ return found;
1391
1300
  }
1392
- }, normalizeLoadPaths = (filePath, paths = []) => [
1393
- dirname2(filePath),
1394
- process.cwd(),
1395
- ...paths.map((path) => resolve4(process.cwd(), path))
1396
- ], tsconfigAliasCache, stripJsonComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"), normalizeAliasEntries = (aliases) => Object.entries(aliases ?? {}).map(([pattern, value]) => ({
1397
- pattern,
1398
- replacements: Array.isArray(value) ? value : [value]
1399
- })), readTsconfigAliases = () => {
1400
- const cwd = process.cwd();
1401
- if (tsconfigAliasCache?.cwd === cwd)
1402
- return tsconfigAliasCache;
1403
- const tsconfigPath = resolve4(cwd, "tsconfig.json");
1404
- const empty = { aliases: [], baseUrl: cwd, cwd };
1405
- if (!existsSync4(tsconfigPath)) {
1406
- tsconfigAliasCache = empty;
1407
- return empty;
1301
+ return searchDirectoryLevel(nextStack, targetFileName);
1302
+ }, findSourceFileByBasename = async (searchRoot, targetFileName) => searchDirectoryLevel([searchRoot], targetFileName), normalizeBuiltSvelteFileName = (sourcePath) => basename2(sourcePath).replace(/-[a-z0-9]{6,}(?=\.svelte$)/i, ""), resolveOriginalSourcePath = async (sourcePath) => {
1303
+ const cachedPath = originalSourcePathCache.get(sourcePath);
1304
+ if (cachedPath !== undefined) {
1305
+ return cachedPath;
1408
1306
  }
1409
- try {
1410
- const parsed = JSON.parse(stripJsonComments(readFileSync3(tsconfigPath, "utf-8")));
1411
- const compilerOptions = parsed.compilerOptions ?? {};
1412
- const baseUrl = resolve4(cwd, compilerOptions.baseUrl ?? ".");
1413
- tsconfigAliasCache = {
1414
- aliases: normalizeAliasEntries(compilerOptions.paths),
1415
- baseUrl,
1416
- cwd
1417
- };
1418
- } catch {
1419
- tsconfigAliasCache = empty;
1420
- }
1421
- return tsconfigAliasCache;
1422
- }, getAliasEntries = (config) => {
1423
- const tsconfig = readTsconfigAliases();
1424
- return {
1425
- aliases: [...normalizeAliasEntries(config?.aliases), ...tsconfig.aliases],
1426
- baseUrl: tsconfig.baseUrl
1427
- };
1428
- }, aliasPatternToRegExp = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("(.+)")}$`), resolveAliasTargets = (specifier, config) => {
1429
- const { aliases, baseUrl } = getAliasEntries(config);
1430
- const targets = [];
1431
- for (const alias of aliases) {
1432
- const match = specifier.match(aliasPatternToRegExp(alias.pattern));
1433
- if (!match)
1434
- continue;
1435
- const wildcard = match[1] ?? "";
1436
- for (const replacement of alias.replacements) {
1437
- targets.push(resolve4(baseUrl, replacement.replace("*", wildcard)));
1438
- }
1307
+ if (!sourcePath.includes(`${join4(process.cwd(), "build")}${process.platform === "win32" ? "" : "/"}`) && !sourcePath.includes("/build/")) {
1308
+ originalSourcePathCache.set(sourcePath, sourcePath);
1309
+ return sourcePath;
1439
1310
  }
1440
- return targets;
1441
- }, getLanguageExtensions = (language) => {
1442
- if (language === "less")
1443
- return [".less", ".css"];
1444
- if (language === "stylus")
1445
- return [".styl", ".stylus", ".css"];
1446
- return [".scss", ".sass", ".css"];
1447
- }, getCandidatePaths = (basePath, language) => {
1448
- const ext = extname(basePath);
1449
- const paths = ext ? [basePath] : getLanguageExtensions(language).flatMap((extension) => [
1450
- `${basePath}${extension}`,
1451
- join3(basePath, `index${extension}`)
1452
- ]);
1453
- if (language === "scss" || language === "sass") {
1454
- return paths.flatMap((path) => {
1455
- const dir = dirname2(path);
1456
- const base = path.slice(dir.length + 1);
1457
- return [path, join3(dir, `_${base}`)];
1458
- });
1311
+ const resolvedSourcePath = await findSourceFileByBasename(join4(process.cwd(), "src"), normalizeBuiltSvelteFileName(sourcePath));
1312
+ const nextPath = resolvedSourcePath ?? sourcePath;
1313
+ originalSourcePathCache.set(sourcePath, nextPath);
1314
+ return nextPath;
1315
+ }, resolveRelativeModule = async (spec, from) => {
1316
+ if (!spec.startsWith(".")) {
1317
+ return null;
1459
1318
  }
1460
- return paths;
1461
- }, resolveImportPath = (specifier, fromDirectory, loadPaths, language, config) => {
1462
- const rawCandidates = [
1463
- ...resolveAliasTargets(specifier, config),
1464
- isAbsolute(specifier) ? specifier : resolve4(fromDirectory, specifier),
1465
- ...loadPaths.map((path) => resolve4(path, specifier))
1319
+ const basePath = resolve5(dirname3(from), spec);
1320
+ const candidates = [
1321
+ basePath,
1322
+ `${basePath}.ts`,
1323
+ `${basePath}.js`,
1324
+ `${basePath}.mjs`,
1325
+ `${basePath}.cjs`,
1326
+ `${basePath}.json`,
1327
+ join4(basePath, "index.ts"),
1328
+ join4(basePath, "index.js"),
1329
+ join4(basePath, "index.mjs"),
1330
+ join4(basePath, "index.cjs"),
1331
+ join4(basePath, "index.json")
1466
1332
  ];
1467
- for (const candidate of rawCandidates.flatMap((path) => getCandidatePaths(path, language))) {
1468
- if (existsSync4(candidate))
1469
- return candidate;
1333
+ const existResults = await Promise.all(candidates.map((candidate) => Bun.file(candidate).exists()));
1334
+ const foundIndex = existResults.indexOf(true);
1335
+ return foundIndex >= 0 ? candidates[foundIndex] ?? null : null;
1336
+ }, getCachedModulePath = (sourcePath) => {
1337
+ const relativeSourcePath = relative2(process.cwd(), sourcePath).replace(/\\/g, "/");
1338
+ const normalizedSourcePath = relativeSourcePath.startsWith("..") ? sourcePath.replace(/[:\\/]/g, "_") : relativeSourcePath;
1339
+ return join4(serverCacheRoot, `${normalizedSourcePath}.server.js`);
1340
+ }, resolveSvelteImport = async (spec, from) => {
1341
+ if (!spec.startsWith(".") && !spec.startsWith("/")) {
1342
+ const resolved = resolvePackageImport(spec);
1343
+ return resolved && resolved.endsWith(".svelte") ? resolved : null;
1344
+ }
1345
+ if (spec.startsWith("/")) {
1346
+ return spec;
1347
+ }
1348
+ if (!spec.startsWith(".")) {
1349
+ return null;
1350
+ }
1351
+ const explicitPath = resolve5(dirname3(from), spec);
1352
+ if (extname2(explicitPath) === ".svelte") {
1353
+ return explicitPath;
1354
+ }
1355
+ const candidate = `${explicitPath}.svelte`;
1356
+ if (await Bun.file(candidate).exists() === true) {
1357
+ return candidate;
1470
1358
  }
1471
1359
  return null;
1472
- }, isExternalCssUrl = (url) => /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(url), splitCssUrl = (url) => {
1473
- const markerIndex = url.search(/[?#]/);
1474
- if (markerIndex === -1)
1475
- return { marker: "", path: url };
1476
- return {
1477
- marker: url.slice(markerIndex),
1478
- path: url.slice(0, markerIndex)
1479
- };
1480
- }, rebaseCssUrls = (contents, sourceFile, entryFile) => {
1481
- const sourceDir = dirname2(sourceFile);
1482
- const entryDir = dirname2(entryFile);
1483
- if (sourceDir === entryDir)
1484
- return contents;
1485
- return contents.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (match, quote, rawUrl) => {
1486
- const trimmedUrl = rawUrl.trim();
1487
- if (!trimmedUrl || isExternalCssUrl(trimmedUrl))
1488
- return match;
1489
- const { marker, path } = splitCssUrl(trimmedUrl);
1490
- const rebased = relative(entryDir, resolve4(sourceDir, path)).replace(/\\/g, "/");
1491
- const normalized = rebased.startsWith(".") ? rebased : `./${rebased}`;
1492
- const nextQuote = quote || '"';
1493
- return `url(${nextQuote}${normalized}${marker}${nextQuote})`;
1494
- });
1495
- }, rewriteAliasedStyleImports = (contents, sourceFile, loadPaths, language, config) => contents.replace(/(@(?:use|forward|import|require)\s+)(["'])([^"']+)\2/g, (match, prefix, quote, specifier) => {
1496
- if (specifier.startsWith(".") || isAbsolute(specifier) || isExternalCssUrl(specifier))
1497
- return match;
1498
- const resolved = resolveImportPath(specifier, dirname2(sourceFile), loadPaths, language, config);
1499
- return resolved ? `${prefix}${quote}${resolved}${quote}` : match;
1500
- }), preprocessLoadedStyle = (contents, sourceFile, entryFile, loadPaths = [], language, config) => {
1501
- const rebased = rebaseCssUrls(contents, sourceFile, entryFile);
1502
- return language ? rewriteAliasedStyleImports(rebased, sourceFile, loadPaths, language, config) : rebased;
1503
- }, extractCssModuleExports = (css) => {
1504
- const exports = {};
1505
- const nextCss = css.replace(/:export\s*\{([^}]*)\}/g, (_, body) => {
1506
- for (const declaration of body.split(";")) {
1507
- const separator = declaration.indexOf(":");
1508
- if (separator === -1)
1509
- continue;
1510
- const key = declaration.slice(0, separator).trim();
1511
- const value = declaration.slice(separator + 1).trim();
1512
- if (key && value)
1513
- exports[key] = value;
1360
+ }, writeIfChanged = async (path, content) => {
1361
+ const targetFile = Bun.file(path);
1362
+ const exists = await targetFile.exists();
1363
+ if (exists) {
1364
+ const currentContent = await targetFile.text();
1365
+ if (currentContent === content) {
1366
+ return;
1514
1367
  }
1515
- return "";
1516
- });
1517
- return { css: nextCss, exports };
1518
- }, getSassOptions = (config, language) => ({
1519
- ...config?.sass ?? {},
1520
- ...language === "scss" ? config?.scss ?? {} : {}
1521
- }), getLessOptions = (config) => config?.less ?? {}, getStylusOptions = (config) => config?.stylus ?? {}, createStyleTransformConfig = (stylePreprocessors, postcss) => postcss === undefined ? stylePreprocessors : { ...stylePreprocessors ?? {}, postcss }, withAdditionalData = (contents, additionalData) => additionalData ? `${additionalData}
1522
- ${contents}` : contents, normalizePostcssModule = (mod) => {
1523
- if (mod && typeof mod === "object" && "default" in mod) {
1524
- return mod.default ?? mod;
1525
- }
1526
- return mod;
1527
- }, loadPostcssConfigFile = async (configPath) => {
1528
- const resolved = resolve4(process.cwd(), configPath);
1529
- const loaded = resolved.endsWith(".cjs") || resolved.endsWith(".cts") ? requireOptionalPeerSync(resolved) : await importOptionalPeer(`${new URL(`file://${resolved}`).href}?t=${Date.now()}`);
1530
- const config = normalizePostcssModule(loaded);
1531
- const value = typeof config === "function" ? await config({
1532
- cwd: process.cwd(),
1533
- env: "development"
1534
- }) : config;
1535
- return normalizePostcssModule(value) ?? {};
1536
- }, normalizePostcssPlugins = (plugins) => {
1537
- if (!plugins)
1538
- return [];
1539
- if (Array.isArray(plugins))
1540
- return plugins.filter(Boolean);
1541
- const resolved = [];
1542
- for (const [specifier, options] of Object.entries(plugins)) {
1543
- if (options === false)
1544
- continue;
1545
- const mod = normalizePostcssModule(requireOptionalPeerSync(specifier));
1546
- const plugin = typeof mod === "function" ? mod(options === true ? undefined : options) : mod;
1547
- if (plugin)
1548
- resolved.push(plugin);
1549
1368
  }
1550
- return resolved;
1551
- }, resolvePostcssConfig = async (config) => {
1552
- const inlineConfig = config?.postcss;
1553
- if (!inlineConfig)
1554
- return null;
1555
- const fileConfig = inlineConfig.config ? await loadPostcssConfigFile(inlineConfig.config) : {};
1556
- const plugins = [
1557
- ...normalizePostcssPlugins(fileConfig.plugins),
1558
- ...normalizePostcssPlugins(inlineConfig.plugins)
1559
- ];
1560
- if (plugins.length === 0)
1561
- return null;
1562
- return {
1563
- options: {
1564
- ...fileConfig.options ?? {},
1565
- ...inlineConfig.options ?? {}
1566
- },
1567
- plugins
1568
- };
1569
- }, runPostcss = async (css, filePath, config) => {
1570
- const postcssConfig = await resolvePostcssConfig(config);
1571
- if (!postcssConfig)
1572
- return css;
1573
- let postcssModule;
1574
- try {
1575
- postcssModule = await importOptionalPeer("postcss");
1576
- } catch {
1577
- throw missingDependencyError("postcss", filePath);
1369
+ await Bun.write(path, content);
1370
+ }, compileSvelteServerModule = async (sourcePath) => {
1371
+ const cachedModulePath = compiledModuleCache.get(sourcePath);
1372
+ if (cachedModulePath) {
1373
+ return cachedModulePath;
1578
1374
  }
1579
- const postcss = postcssModule.default ?? postcssModule;
1580
- const result = await postcss(postcssConfig.plugins).process(css, {
1581
- from: filePath,
1582
- map: false,
1583
- ...postcssConfig.options
1584
- });
1585
- return result.css;
1586
- }, createSassImporter = (entryFile, loadPaths, language, config) => ({
1587
- canonicalize(specifier, options) {
1588
- const fromDirectory = options.containingUrl ? dirname2(fileURLToPath(options.containingUrl)) : dirname2(entryFile);
1589
- const resolved = resolveImportPath(specifier, fromDirectory, loadPaths, language, config);
1590
- return resolved ? new URL(`file://${resolved}`) : null;
1591
- },
1592
- load(canonicalUrl) {
1593
- const filePath = fileURLToPath(canonicalUrl);
1594
- const fileLanguage = getStyleLanguage(filePath);
1595
- if (fileLanguage !== "scss" && fileLanguage !== "sass" && fileLanguage !== null)
1375
+ const resolutionSourcePath = await resolveOriginalSourcePath(sourcePath);
1376
+ const source = await Bun.file(sourcePath).text();
1377
+ const { compile, preprocess } = await import("svelte/compiler");
1378
+ const loweredAwaitSource = lowerSvelteAwaitSlotSyntax(source);
1379
+ const loweredSource = lowerSvelteIslandSyntax(loweredAwaitSource.code, "server");
1380
+ const preprocessed = await preprocess(loweredSource.code, createSvelteStylePreprocessor());
1381
+ let transpiled = sourcePath.endsWith(".ts") || sourcePath.endsWith(".svelte.ts") ? transpiler.transformSync(preprocessed.code) : preprocessed.code;
1382
+ const childImportSpecs = Array.from(transpiled.matchAll(/from\s+['"]([^'"]+)['"]/g)).map((match) => match[1]).filter((value) => value !== undefined);
1383
+ const resolvedChildModules = await Promise.all(childImportSpecs.map((spec) => resolveSvelteImport(spec, resolutionSourcePath)));
1384
+ const resolvedModuleImports = await Promise.all(childImportSpecs.map((spec) => resolveRelativeModule(spec, resolutionSourcePath)));
1385
+ const childModulePaths = new Map;
1386
+ const rewrittenModulePaths = new Map;
1387
+ const compiledChildren = await Promise.all(childImportSpecs.map(async (spec, index) => {
1388
+ const resolvedChild = resolvedChildModules[index];
1389
+ if (!spec || !resolvedChild)
1596
1390
  return null;
1597
1391
  return {
1598
- contents: preprocessLoadedStyle(readFileSync3(filePath, "utf-8"), filePath, entryFile, loadPaths, language, config),
1599
- syntax: filePath.endsWith(".sass") ? "indented" : "scss"
1392
+ compiledPath: await compileSvelteServerModule(resolvedChild),
1393
+ resolvedChild,
1394
+ spec
1600
1395
  };
1396
+ }));
1397
+ for (const result of compiledChildren) {
1398
+ if (!result)
1399
+ continue;
1400
+ childModulePaths.set(result.spec, result.compiledPath);
1401
+ childModulePaths.set(result.resolvedChild, result.compiledPath);
1601
1402
  }
1602
- }), createLessFileManager = (entryFile, loadPaths, config) => ({
1603
- install(less, pluginManager) {
1604
- const baseManager = new less.FileManager;
1605
- const manager = Object.create(baseManager);
1606
- manager.supports = (filename, currentDirectory) => Boolean(resolveImportPath(filename, resolve4(currentDirectory), loadPaths, "less", config));
1607
- manager.loadFile = async (filename, currentDirectory) => {
1608
- const resolved = resolveImportPath(filename, resolve4(currentDirectory), loadPaths, "less", config);
1609
- if (!resolved) {
1610
- throw new Error(`Unable to resolve Less import "${filename}"`);
1611
- }
1612
- return {
1613
- contents: preprocessLoadedStyle(await readFile(resolved, "utf-8"), resolved, entryFile, loadPaths, "less", config),
1614
- filename: resolved
1615
- };
1616
- };
1617
- pluginManager.addFileManager(manager);
1618
- }
1619
- }), renderStylus = async (contents, filePath, loadPaths, options) => {
1620
- let stylus;
1621
- try {
1622
- const stylusModule = await importOptionalPeer("stylus");
1623
- stylus = stylusModule.default ?? stylusModule;
1624
- } catch {
1625
- throw missingDependencyError("stylus", filePath);
1626
- }
1627
- return new Promise((resolveCss, reject) => {
1628
- const renderer = stylus(contents);
1629
- renderer.set("filename", filePath);
1630
- for (const [key, value] of Object.entries(options.options ?? {})) {
1631
- renderer.set(key, value);
1632
- }
1633
- for (const path of loadPaths)
1634
- renderer.include(path);
1635
- renderer.render((error, css) => {
1636
- if (error)
1637
- reject(error);
1638
- else
1639
- resolveCss(css ?? "");
1640
- });
1641
- });
1642
- }, compileStyleSource = async (filePath, source, languageHint, config) => {
1643
- const language = getStyleLanguage(languageHint ?? filePath);
1644
- const rawContents = source ?? await readFile(filePath, "utf-8");
1645
- if (language === "scss" || language === "sass") {
1646
- const options = getSassOptions(config, language);
1647
- const packageName = options.implementation ?? "sass";
1648
- let sass;
1649
- try {
1650
- sass = await importOptionalPeer(packageName);
1651
- } catch {
1652
- throw missingDependencyError(packageName, filePath);
1653
- }
1654
- const contents = withAdditionalData(rawContents, options.additionalData);
1655
- const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
1656
- const result = sass.compileString(contents, {
1657
- importers: [
1658
- createSassImporter(filePath, loadPaths, language, config)
1659
- ],
1660
- loadPaths,
1661
- style: "expanded",
1662
- syntax: language === "sass" ? "indented" : "scss",
1663
- url: new URL(`file://${filePath}`)
1664
- });
1665
- return runPostcss(result.css, filePath, config);
1666
- }
1667
- if (language === "less") {
1668
- const options = getLessOptions(config);
1669
- let lessModule;
1670
- try {
1671
- lessModule = await importOptionalPeer("less");
1672
- } catch {
1673
- throw missingDependencyError("less", filePath);
1674
- }
1675
- const less = lessModule.render ? lessModule : lessModule.default;
1676
- const render = less?.render;
1677
- if (!render)
1678
- throw missingDependencyError("less", filePath);
1679
- const contents = withAdditionalData(rawContents, options.additionalData);
1680
- const loadPaths = normalizeLoadPaths(filePath, options.paths);
1681
- const result = await render(contents, {
1682
- ...options.options ?? {},
1683
- filename: filePath,
1684
- paths: loadPaths,
1685
- plugins: [
1686
- ...options.options?.plugins ?? [],
1687
- createLessFileManager(filePath, loadPaths, config)
1688
- ]
1689
- });
1690
- return runPostcss(result.css, filePath, config);
1691
- }
1692
- if (language === "stylus") {
1693
- const options = getStylusOptions(config);
1694
- const loadPaths = normalizeLoadPaths(filePath, options.paths);
1695
- const contents = withAdditionalData(preprocessLoadedStyle(rawContents, filePath, filePath, loadPaths, "stylus", config), options.additionalData);
1696
- return runPostcss(await renderStylus(contents, filePath, loadPaths, options), filePath, config);
1697
- }
1698
- return runPostcss(rawContents, filePath, config);
1699
- }, createStylePreprocessorPlugin = (config) => ({
1700
- name: "absolute-style-preprocessor",
1701
- setup(build) {
1702
- const cssModuleSources = new Map;
1703
- build.onResolve({ filter: /^absolute-style-module:/ }, ({ path }) => ({
1704
- namespace: "absolute-style-module",
1705
- path: path.slice("absolute-style-module:".length)
1706
- }));
1707
- build.onLoad({ filter: /\.module\.css$/i, namespace: "absolute-style-module" }, async ({ path }) => {
1708
- const source = cssModuleSources.get(path);
1709
- if (!source) {
1710
- throw new Error(`Unable to resolve CSS module source for ${path}`);
1711
- }
1712
- return {
1713
- contents: source.css,
1714
- loader: "css"
1715
- };
1716
- });
1717
- build.onLoad({ filter: STYLE_EXTENSION_PATTERN }, async ({ path }) => {
1718
- if (isStyleModulePath(path)) {
1719
- const cssModulePath = path.replace(STYLE_EXTENSION_PATTERN, ".css");
1720
- const compiled = await compileStyleSource(path, undefined, undefined, config);
1721
- const { css, exports } = extractCssModuleExports(compiled);
1722
- cssModuleSources.set(cssModulePath, { css, exports });
1723
- const exportSource = Object.keys(exports).length > 0 ? `import styles from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)}; export default Object.assign({}, styles, ${JSON.stringify(exports)});` : `export { default } from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)};`;
1724
- return {
1725
- contents: exportSource,
1726
- loader: "js"
1727
- };
1728
- }
1729
- return {
1730
- contents: await compileStyleSource(path, undefined, undefined, config),
1731
- loader: "css"
1732
- };
1733
- });
1734
- build.onLoad({ filter: CSS_EXTENSION_PATTERN }, async ({ path }) => ({
1735
- contents: await compileStyleSource(path, undefined, undefined, config),
1736
- loader: "css"
1737
- }));
1403
+ for (let index = 0;index < childImportSpecs.length; index += 1) {
1404
+ const spec = childImportSpecs[index];
1405
+ const resolvedModuleImport = resolvedModuleImports[index];
1406
+ if (!spec || !resolvedModuleImport)
1407
+ continue;
1408
+ if (resolvedChildModules[index])
1409
+ continue;
1410
+ rewrittenModulePaths.set(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), resolvedModuleImport));
1738
1411
  }
1739
- }), stylePreprocessorPlugin, createSvelteStylePreprocessor = (config) => ({
1740
- style: async ({
1741
- attributes,
1742
- content,
1743
- filename
1744
- }) => {
1745
- const language = typeof attributes.lang === "string" ? attributes.lang : typeof attributes.type === "string" ? attributes.type.replace(/^text\//, "") : null;
1746
- if (!language || !STYLE_LANGUAGE_PATTERN.test(language))
1747
- return;
1748
- const path = filename ?? `style.${language}`;
1749
- return {
1750
- code: await compileStyleSource(path, content, language, config)
1751
- };
1412
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
1413
+ transpiled = transpiled.replaceAll(spec, resolvedModuleImport);
1752
1414
  }
1753
- }), compileStyleFileIfNeeded = async (filePath, config) => {
1754
- if (!isPreprocessableStylePath(filePath)) {
1755
- return runPostcss(await readFile(filePath, "utf-8"), filePath, config);
1415
+ let compiledCode = compile(transpiled, {
1416
+ css: "injected",
1417
+ experimental: {
1418
+ async: loweredAwaitSource.transformed || loweredSource.transformed
1419
+ },
1420
+ filename: resolutionSourcePath,
1421
+ generate: "server"
1422
+ }).js.code;
1423
+ for (const [spec, compiledChildPath] of childModulePaths) {
1424
+ compiledCode = compiledCode.replaceAll(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), compiledChildPath));
1756
1425
  }
1757
- return compileStyleSource(filePath, undefined, undefined, config);
1758
- }, compileStyleFileIfNeededSync = (filePath, config) => {
1759
- const rawContents = readFileSync3(filePath, "utf-8");
1760
- const language = getStyleLanguage(filePath);
1761
- if (config?.postcss) {
1762
- throw new Error(`Unable to compile ${filePath}: PostCSS preprocessing is async-only.`);
1426
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
1427
+ compiledCode = compiledCode.replaceAll(spec, resolvedModuleImport);
1763
1428
  }
1764
- if (language === "scss" || language === "sass") {
1765
- const options = getSassOptions(config, language);
1766
- const packageName = options.implementation ?? "sass";
1767
- let sass;
1768
- try {
1769
- sass = requireOptionalPeerSync(packageName);
1770
- } catch {
1771
- throw missingDependencyError(packageName, filePath);
1772
- }
1773
- const contents = withAdditionalData(rawContents, options.additionalData);
1774
- const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
1775
- return sass.compileString(contents, {
1776
- importers: [
1777
- createSassImporter(filePath, loadPaths, language, config)
1778
- ],
1779
- loadPaths,
1780
- style: "expanded",
1781
- syntax: language === "sass" ? "indented" : "scss",
1782
- url: new URL(`file://${filePath}`)
1783
- }).css;
1429
+ const compiledModulePath = getCachedModulePath(sourcePath);
1430
+ await mkdir(dirname3(compiledModulePath), { recursive: true });
1431
+ await writeIfChanged(compiledModulePath, compiledCode);
1432
+ compiledModuleCache.set(sourcePath, compiledModulePath);
1433
+ return compiledModulePath;
1434
+ };
1435
+ var init_svelteServerModule = __esm(() => {
1436
+ init_resolvePackageImport();
1437
+ init_lowerIslandSyntax();
1438
+ init_lowerAwaitSlotSyntax();
1439
+ init_stylePreprocessor();
1440
+ serverCacheRoot = join4(process.cwd(), ".absolutejs", "islands", "svelte");
1441
+ compiledModuleCache = new Map;
1442
+ originalSourcePathCache = new Map;
1443
+ transpiler = new Bun.Transpiler({
1444
+ loader: "ts",
1445
+ target: "browser"
1446
+ });
1447
+ });
1448
+
1449
+ // src/core/islandManifest.ts
1450
+ var toIslandFrameworkSegment = (framework) => framework[0]?.toUpperCase() + framework.slice(1), collectFrameworkIslands = (manifest, prefix) => {
1451
+ const entries = {};
1452
+ let found = false;
1453
+ for (const [key, value] of Object.entries(manifest)) {
1454
+ if (!key.startsWith(prefix))
1455
+ continue;
1456
+ const component = key.slice(prefix.length);
1457
+ if (!component)
1458
+ continue;
1459
+ entries[component] = value;
1460
+ found = true;
1784
1461
  }
1785
- if (language === "less") {
1786
- throw new Error(`Unable to compile ${filePath}: Less styleUrl preprocessing is async-only. Import the Less file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
1462
+ return found ? entries : undefined;
1463
+ }, getIslandManifestEntries = (manifest) => {
1464
+ const islands = {};
1465
+ const frameworks = ["react", "svelte", "vue", "angular"];
1466
+ for (const framework of frameworks) {
1467
+ const prefix = `Island${toIslandFrameworkSegment(framework)}`;
1468
+ const entries = collectFrameworkIslands(manifest, prefix);
1469
+ if (entries)
1470
+ islands[framework] = entries;
1787
1471
  }
1788
- if (language === "stylus") {
1789
- throw new Error(`Unable to compile ${filePath}: Stylus styleUrl preprocessing is async-only. Import the Stylus file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
1790
- }
1791
- return rawContents;
1792
- }, getCssOutputExtension = (filePath) => isPreprocessableStylePath(filePath) ? ".css" : extname(filePath);
1793
- var init_stylePreprocessor = __esm(() => {
1794
- CSS_EXTENSION_PATTERN = /\.css$/i;
1795
- STYLE_EXTENSION_PATTERN = /\.(s[ac]ss|less|styl(?:us)?)$/i;
1796
- STYLE_MODULE_EXTENSION_PATTERN = /\.module\.(s[ac]ss|less|styl(?:us)?)$/i;
1797
- STYLE_LANGUAGE_PATTERN = /^(s[ac]ss|less|styl(?:us)?)$/i;
1798
- importOptionalPeer = new Function("specifier", "return import(specifier)");
1799
- requireOptionalPeer = new Function("specifier", "return require(specifier)");
1800
- requireFromCwd = createRequire(join3(process.cwd(), "package.json"));
1801
- stylePreprocessorPlugin = createStylePreprocessorPlugin();
1802
- });
1803
-
1804
- // src/core/svelteServerModule.ts
1805
- import { mkdir, readdir } from "fs/promises";
1806
- import { basename as basename2, dirname as dirname3, extname as extname2, join as join4, relative as relative2, resolve as resolve5 } from "path";
1807
- var serverCacheRoot, compiledModuleCache, originalSourcePathCache, transpiler, ensureRelativeImportPath = (from, target) => {
1808
- const importPath = relative2(dirname3(from), target).replace(/\\/g, "/");
1809
- return importPath.startsWith(".") ? importPath : `./${importPath}`;
1810
- }, processDirectoryEntries = (entries, dir, targetFileName, stack) => {
1811
- for (const entry of entries) {
1812
- const entryPath = join4(dir, entry.name);
1813
- if (entry.isDirectory())
1814
- stack.push(entryPath);
1815
- if (entry.isFile() && entry.name === targetFileName) {
1816
- return entryPath;
1817
- }
1818
- }
1819
- return null;
1820
- }, searchDirectoryLevel = async (dirs, targetFileName) => {
1821
- if (dirs.length === 0)
1822
- return null;
1823
- const nextStack = [];
1824
- const dirEntries = await Promise.all(dirs.map(async (dir) => ({
1825
- dir,
1826
- entries: await readdir(dir, {
1827
- encoding: "utf-8",
1828
- withFileTypes: true
1829
- })
1830
- })));
1831
- for (const { dir, entries } of dirEntries) {
1832
- const found = processDirectoryEntries(entries, dir, targetFileName, nextStack);
1833
- if (found)
1834
- return found;
1835
- }
1836
- return searchDirectoryLevel(nextStack, targetFileName);
1837
- }, findSourceFileByBasename = async (searchRoot, targetFileName) => searchDirectoryLevel([searchRoot], targetFileName), normalizeBuiltSvelteFileName = (sourcePath) => basename2(sourcePath).replace(/-[a-z0-9]{6,}(?=\.svelte$)/i, ""), resolveOriginalSourcePath = async (sourcePath) => {
1838
- const cachedPath = originalSourcePathCache.get(sourcePath);
1839
- if (cachedPath !== undefined) {
1840
- return cachedPath;
1841
- }
1842
- if (!sourcePath.includes(`${join4(process.cwd(), "build")}${process.platform === "win32" ? "" : "/"}`) && !sourcePath.includes("/build/")) {
1843
- originalSourcePathCache.set(sourcePath, sourcePath);
1844
- return sourcePath;
1845
- }
1846
- const resolvedSourcePath = await findSourceFileByBasename(join4(process.cwd(), "src"), normalizeBuiltSvelteFileName(sourcePath));
1847
- const nextPath = resolvedSourcePath ?? sourcePath;
1848
- originalSourcePathCache.set(sourcePath, nextPath);
1849
- return nextPath;
1850
- }, resolveRelativeModule = async (spec, from) => {
1851
- if (!spec.startsWith(".")) {
1852
- return null;
1853
- }
1854
- const basePath = resolve5(dirname3(from), spec);
1855
- const candidates = [
1856
- basePath,
1857
- `${basePath}.ts`,
1858
- `${basePath}.js`,
1859
- `${basePath}.mjs`,
1860
- `${basePath}.cjs`,
1861
- `${basePath}.json`,
1862
- join4(basePath, "index.ts"),
1863
- join4(basePath, "index.js"),
1864
- join4(basePath, "index.mjs"),
1865
- join4(basePath, "index.cjs"),
1866
- join4(basePath, "index.json")
1867
- ];
1868
- const existResults = await Promise.all(candidates.map((candidate) => Bun.file(candidate).exists()));
1869
- const foundIndex = existResults.indexOf(true);
1870
- return foundIndex >= 0 ? candidates[foundIndex] ?? null : null;
1871
- }, getCachedModulePath = (sourcePath) => {
1872
- const relativeSourcePath = relative2(process.cwd(), sourcePath).replace(/\\/g, "/");
1873
- const normalizedSourcePath = relativeSourcePath.startsWith("..") ? sourcePath.replace(/[:\\/]/g, "_") : relativeSourcePath;
1874
- return join4(serverCacheRoot, `${normalizedSourcePath}.server.js`);
1875
- }, resolveSvelteImport = async (spec, from) => {
1876
- if (!spec.startsWith(".") && !spec.startsWith("/")) {
1877
- const resolved = resolvePackageImport(spec);
1878
- return resolved && resolved.endsWith(".svelte") ? resolved : null;
1879
- }
1880
- if (spec.startsWith("/")) {
1881
- return spec;
1882
- }
1883
- if (!spec.startsWith(".")) {
1884
- return null;
1885
- }
1886
- const explicitPath = resolve5(dirname3(from), spec);
1887
- if (extname2(explicitPath) === ".svelte") {
1888
- return explicitPath;
1889
- }
1890
- const candidate = `${explicitPath}.svelte`;
1891
- if (await Bun.file(candidate).exists() === true) {
1892
- return candidate;
1893
- }
1894
- return null;
1895
- }, writeIfChanged = async (path, content) => {
1896
- const targetFile = Bun.file(path);
1897
- const exists = await targetFile.exists();
1898
- if (exists) {
1899
- const currentContent = await targetFile.text();
1900
- if (currentContent === content) {
1901
- return;
1902
- }
1903
- }
1904
- await Bun.write(path, content);
1905
- }, compileSvelteServerModule = async (sourcePath) => {
1906
- const cachedModulePath = compiledModuleCache.get(sourcePath);
1907
- if (cachedModulePath) {
1908
- return cachedModulePath;
1909
- }
1910
- const resolutionSourcePath = await resolveOriginalSourcePath(sourcePath);
1911
- const source = await Bun.file(sourcePath).text();
1912
- const { compile, preprocess } = await import("svelte/compiler");
1913
- const loweredAwaitSource = lowerSvelteAwaitSlotSyntax(source);
1914
- const loweredSource = lowerSvelteIslandSyntax(loweredAwaitSource.code, "server");
1915
- const preprocessed = await preprocess(loweredSource.code, createSvelteStylePreprocessor());
1916
- let transpiled = sourcePath.endsWith(".ts") || sourcePath.endsWith(".svelte.ts") ? transpiler.transformSync(preprocessed.code) : preprocessed.code;
1917
- const childImportSpecs = Array.from(transpiled.matchAll(/from\s+['"]([^'"]+)['"]/g)).map((match) => match[1]).filter((value) => value !== undefined);
1918
- const resolvedChildModules = await Promise.all(childImportSpecs.map((spec) => resolveSvelteImport(spec, resolutionSourcePath)));
1919
- const resolvedModuleImports = await Promise.all(childImportSpecs.map((spec) => resolveRelativeModule(spec, resolutionSourcePath)));
1920
- const childModulePaths = new Map;
1921
- const rewrittenModulePaths = new Map;
1922
- const compiledChildren = await Promise.all(childImportSpecs.map(async (spec, index) => {
1923
- const resolvedChild = resolvedChildModules[index];
1924
- if (!spec || !resolvedChild)
1925
- return null;
1926
- return {
1927
- compiledPath: await compileSvelteServerModule(resolvedChild),
1928
- resolvedChild,
1929
- spec
1930
- };
1931
- }));
1932
- for (const result of compiledChildren) {
1933
- if (!result)
1934
- continue;
1935
- childModulePaths.set(result.spec, result.compiledPath);
1936
- childModulePaths.set(result.resolvedChild, result.compiledPath);
1937
- }
1938
- for (let index = 0;index < childImportSpecs.length; index += 1) {
1939
- const spec = childImportSpecs[index];
1940
- const resolvedModuleImport = resolvedModuleImports[index];
1941
- if (!spec || !resolvedModuleImport)
1942
- continue;
1943
- if (resolvedChildModules[index])
1944
- continue;
1945
- rewrittenModulePaths.set(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), resolvedModuleImport));
1946
- }
1947
- for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
1948
- transpiled = transpiled.replaceAll(spec, resolvedModuleImport);
1949
- }
1950
- let compiledCode = compile(transpiled, {
1951
- css: "injected",
1952
- experimental: {
1953
- async: loweredAwaitSource.transformed || loweredSource.transformed
1954
- },
1955
- filename: resolutionSourcePath,
1956
- generate: "server"
1957
- }).js.code;
1958
- for (const [spec, compiledChildPath] of childModulePaths) {
1959
- compiledCode = compiledCode.replaceAll(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), compiledChildPath));
1960
- }
1961
- for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
1962
- compiledCode = compiledCode.replaceAll(spec, resolvedModuleImport);
1963
- }
1964
- const compiledModulePath = getCachedModulePath(sourcePath);
1965
- await mkdir(dirname3(compiledModulePath), { recursive: true });
1966
- await writeIfChanged(compiledModulePath, compiledCode);
1967
- compiledModuleCache.set(sourcePath, compiledModulePath);
1968
- return compiledModulePath;
1969
- };
1970
- var init_svelteServerModule = __esm(() => {
1971
- init_resolvePackageImport();
1972
- init_lowerIslandSyntax();
1973
- init_lowerAwaitSlotSyntax();
1974
- init_stylePreprocessor();
1975
- serverCacheRoot = join4(process.cwd(), ".absolutejs", "islands", "svelte");
1976
- compiledModuleCache = new Map;
1977
- originalSourcePathCache = new Map;
1978
- transpiler = new Bun.Transpiler({
1979
- loader: "ts",
1980
- target: "browser"
1981
- });
1982
- });
1983
-
1984
- // src/core/islandManifest.ts
1985
- var toIslandFrameworkSegment = (framework) => framework[0]?.toUpperCase() + framework.slice(1), collectFrameworkIslands = (manifest, prefix) => {
1986
- const entries = {};
1987
- let found = false;
1988
- for (const [key, value] of Object.entries(manifest)) {
1989
- if (!key.startsWith(prefix))
1990
- continue;
1991
- const component = key.slice(prefix.length);
1992
- if (!component)
1993
- continue;
1994
- entries[component] = value;
1995
- found = true;
1996
- }
1997
- return found ? entries : undefined;
1998
- }, getIslandManifestEntries = (manifest) => {
1999
- const islands = {};
2000
- const frameworks = ["react", "svelte", "vue", "angular"];
2001
- for (const framework of frameworks) {
2002
- const prefix = `Island${toIslandFrameworkSegment(framework)}`;
2003
- const entries = collectFrameworkIslands(manifest, prefix);
2004
- if (entries)
2005
- islands[framework] = entries;
2006
- }
2007
- return islands;
2008
- }, getIslandManifestKey = (framework, component) => `Island${toIslandFrameworkSegment(framework)}${component}`;
2009
-
2010
- // src/core/islands.ts
2011
- function getIslandComponent(component) {
2012
- if (isIslandComponentDefinition(component)) {
2013
- return component.component;
1472
+ return islands;
1473
+ }, getIslandManifestKey = (framework, component) => `Island${toIslandFrameworkSegment(framework)}${component}`;
1474
+
1475
+ // src/core/islands.ts
1476
+ function getIslandComponent(component) {
1477
+ if (isIslandComponentDefinition(component)) {
1478
+ return component.component;
2014
1479
  }
2015
1480
  return component;
2016
1481
  }
@@ -2173,102 +1638,24 @@ var init_renderIslandMarkup = __esm(() => {
2173
1638
  resolvedServerBuildComponentCache = new Map;
2174
1639
  });
2175
1640
 
2176
- // src/angular/lowerServerIslands.ts
2177
- var ANGULAR_ISLAND_TAG_RE, ATTRIBUTE_RE, islandFrameworks, islandHydrationModes, decodeHtmlAttribute = (value) => value.replaceAll("&quot;", '"').replaceAll("&#34;", '"').replaceAll("&apos;", "'").replaceAll("&#39;", "'").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">"), isRecord3 = (value) => typeof value === "object" && value !== null, isIslandFramework = (value) => islandFrameworks.some((framework) => framework === value), isIslandHydrate = (value) => islandHydrationModes.some((mode) => mode === value), parseAttributes = (attributeString) => {
2178
- const attributes = new Map;
2179
- let match = ATTRIBUTE_RE.exec(attributeString);
2180
- while (match) {
2181
- const [, key, doubleQuotedValue, singleQuotedValue] = match;
2182
- match = ATTRIBUTE_RE.exec(attributeString);
2183
- if (!key)
2184
- continue;
2185
- attributes.set(key, decodeHtmlAttribute(doubleQuotedValue ?? singleQuotedValue ?? ""));
1641
+ // src/core/devRouteRegistrationCallsite.ts
1642
+ var exports_devRouteRegistrationCallsite = {};
1643
+ __export(exports_devRouteRegistrationCallsite, {
1644
+ patchElysiaRouteRegistrationCallsites: () => patchElysiaRouteRegistrationCallsites,
1645
+ getCurrentRouteRegistrationCallsite: () => getCurrentRouteRegistrationCallsite
1646
+ });
1647
+ import { AsyncLocalStorage } from "async_hooks";
1648
+ import { Elysia } from "elysia";
1649
+ var ROUTE_CALLSITE_STORAGE_KEY, ROUTE_CALLSITE_PATCHED_KEY, ROUTE_METHOD_NAMES, isObjectRecord3 = (value) => Boolean(value) && typeof value === "object", isAsyncLocalStorage2 = (value) => isObjectRecord3(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function", getRouteCallsiteStorage = () => {
1650
+ const value = Reflect.get(globalThis, ROUTE_CALLSITE_STORAGE_KEY);
1651
+ if (value === null || typeof value === "undefined") {
1652
+ return;
2186
1653
  }
2187
- ATTRIBUTE_RE.lastIndex = 0;
2188
- return attributes;
2189
- }, parseAngularIslandProps = (attributeString) => {
2190
- const attributes = parseAttributes(attributeString);
2191
- const component = attributes.get("component");
2192
- const framework = attributes.get("framework");
2193
- const hydrate = attributes.get("hydrate") ?? "load";
2194
- const serializedProps = attributes.get("data-abs-props") ?? "{}";
2195
- if (!component || !framework) {
2196
- return null;
2197
- }
2198
- if (!isIslandFramework(framework) || !isIslandHydrate(hydrate)) {
2199
- return null;
2200
- }
2201
- let parsedProps = {};
2202
- try {
2203
- const candidate = JSON.parse(serializedProps);
2204
- parsedProps = isRecord3(candidate) ? candidate : {};
2205
- } catch {}
2206
- return {
2207
- component,
2208
- framework,
2209
- hydrate,
2210
- props: parsedProps
2211
- };
2212
- }, lowerAngularServerIslands = async (html) => {
2213
- if (!ANGULAR_ISLAND_TAG_RE.test(html)) {
2214
- return html;
2215
- }
2216
- const registry = requireCurrentIslandRegistry();
2217
- ANGULAR_ISLAND_TAG_RE.lastIndex = 0;
2218
- const segments = [];
2219
- let lastIndex = 0;
2220
- let match = ANGULAR_ISLAND_TAG_RE.exec(html);
2221
- while (match) {
2222
- const [fullMatch, rawAttributeString] = match;
2223
- const attributeString = rawAttributeString ?? "";
2224
- segments.push({
2225
- before: html.slice(lastIndex, match.index),
2226
- fullMatch,
2227
- props: parseAngularIslandProps(attributeString)
2228
- });
2229
- lastIndex = match.index + fullMatch.length;
2230
- match = ANGULAR_ISLAND_TAG_RE.exec(html);
2231
- }
2232
- ANGULAR_ISLAND_TAG_RE.lastIndex = 0;
2233
- const renderedSegments = await Promise.all(segments.map(async (segment) => segment.before + (segment.props ? await renderIslandMarkup(registry, segment.props) : segment.fullMatch)));
2234
- return renderedSegments.join("") + html.slice(lastIndex);
2235
- };
2236
- var init_lowerServerIslands = __esm(() => {
2237
- init_renderIslandMarkup();
2238
- ANGULAR_ISLAND_TAG_RE = /<absolute-island\b([^>]*)>[\s\S]*?<\/absolute-island>/gi;
2239
- ATTRIBUTE_RE = /([A-Za-z_:][-A-Za-z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
2240
- islandFrameworks = [
2241
- "react",
2242
- "svelte",
2243
- "vue",
2244
- "angular"
2245
- ];
2246
- islandHydrationModes = [
2247
- "load",
2248
- "idle",
2249
- "visible",
2250
- "none"
2251
- ];
2252
- });
2253
-
2254
- // src/core/devRouteRegistrationCallsite.ts
2255
- var exports_devRouteRegistrationCallsite = {};
2256
- __export(exports_devRouteRegistrationCallsite, {
2257
- patchElysiaRouteRegistrationCallsites: () => patchElysiaRouteRegistrationCallsites,
2258
- getCurrentRouteRegistrationCallsite: () => getCurrentRouteRegistrationCallsite
2259
- });
2260
- import { AsyncLocalStorage } from "async_hooks";
2261
- import { Elysia } from "elysia";
2262
- var ROUTE_CALLSITE_STORAGE_KEY, ROUTE_CALLSITE_PATCHED_KEY, ROUTE_METHOD_NAMES, isObjectRecord3 = (value) => Boolean(value) && typeof value === "object", isAsyncLocalStorage2 = (value) => isObjectRecord3(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function", getRouteCallsiteStorage = () => {
2263
- const value = Reflect.get(globalThis, ROUTE_CALLSITE_STORAGE_KEY);
2264
- if (value === null || typeof value === "undefined") {
2265
- return;
2266
- }
2267
- return isAsyncLocalStorage2(value) ? value : undefined;
2268
- }, ensureRouteCallsiteStorage = () => {
2269
- const existing = getRouteCallsiteStorage();
2270
- if (existing) {
2271
- return existing;
1654
+ return isAsyncLocalStorage2(value) ? value : undefined;
1655
+ }, ensureRouteCallsiteStorage = () => {
1656
+ const existing = getRouteCallsiteStorage();
1657
+ if (existing) {
1658
+ return existing;
2272
1659
  }
2273
1660
  const storage = new AsyncLocalStorage;
2274
1661
  Reflect.set(globalThis, ROUTE_CALLSITE_STORAGE_KEY, storage);
@@ -2337,56 +1724,6 @@ var init_devRouteRegistrationCallsite = __esm(() => {
2337
1724
  ];
2338
1725
  });
2339
1726
 
2340
- // src/angular/ssrSanitizer.ts
2341
- var escapeHtml = (str) => String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"), bypassValue = (value) => ({
2342
- changingThisBreaksApplicationSecurity: value
2343
- }), ssrSanitizer = null, getSsrSanitizer = (deps) => {
2344
- if (ssrSanitizer)
2345
- return ssrSanitizer;
2346
- const SsrSanitizerClass = class extends deps.DomSanitizer {
2347
- sanitize(ctx, value) {
2348
- if (value === null)
2349
- return null;
2350
- let strValue;
2351
- let isTrustedHtml = false;
2352
- if (typeof value === "string") {
2353
- strValue = value;
2354
- } else if (typeof value === "object" && "changingThisBreaksApplicationSecurity" in value) {
2355
- strValue = String(value.changingThisBreaksApplicationSecurity);
2356
- isTrustedHtml = true;
2357
- } else {
2358
- strValue = String(value);
2359
- }
2360
- if (ctx === deps.SecurityContext.HTML) {
2361
- if (isTrustedHtml) {
2362
- return strValue;
2363
- }
2364
- return escapeHtml(strValue);
2365
- }
2366
- return strValue;
2367
- }
2368
- bypassSecurityTrustHtml(value) {
2369
- return bypassValue(value);
2370
- }
2371
- bypassSecurityTrustStyle(value) {
2372
- return bypassValue(value);
2373
- }
2374
- bypassSecurityTrustScript(value) {
2375
- return bypassValue(value);
2376
- }
2377
- bypassSecurityTrustUrl(value) {
2378
- return bypassValue(value);
2379
- }
2380
- bypassSecurityTrustResourceUrl(value) {
2381
- return bypassValue(value);
2382
- }
2383
- };
2384
- ssrSanitizer = new SsrSanitizerClass;
2385
- return ssrSanitizer;
2386
- }, resetSsrSanitizer = () => {
2387
- ssrSanitizer = null;
2388
- };
2389
-
2390
1727
  // src/client/streamSwap.ts
2391
1728
  var streamSwapRuntime = () => {
2392
1729
  const SLOT_PATCH_EVENT = "absolutejs:slot-patch";
@@ -3063,53 +2400,6 @@ var init_streamingSlots = __esm(() => {
3063
2400
  };
3064
2401
  });
3065
2402
 
3066
- // src/core/responseEnhancers.ts
3067
- var toResponse = async (responseLike) => responseLike, cloneHeaders = (response) => {
3068
- const headers = new Headers(response.headers);
3069
- return headers;
3070
- }, enhanceHtmlResponseWithStreamingSlots = (response, {
3071
- nonce,
3072
- onError,
3073
- runtimePlacement,
3074
- runtimePreludeScript,
3075
- streamingSlots = [],
3076
- policy
3077
- } = {}) => {
3078
- if (!response.body || streamingSlots.length === 0) {
3079
- return response;
3080
- }
3081
- const body = appendStreamingSlotPatchesToStream(response.body, streamingSlots, {
3082
- nonce,
3083
- onError,
3084
- policy,
3085
- runtimePlacement,
3086
- runtimePreludeScript
3087
- });
3088
- return new Response(body, {
3089
- headers: cloneHeaders(response),
3090
- status: response.status,
3091
- statusText: response.statusText
3092
- });
3093
- }, withStreamingSlots = async (responseLike, options = {}) => enhanceHtmlResponseWithStreamingSlots(await toResponse(responseLike), options), mergeStreamingSlots = (registered, explicit) => {
3094
- const merged = new Map;
3095
- for (const slot of registered)
3096
- merged.set(slot.id, slot);
3097
- for (const slot of explicit)
3098
- merged.set(slot.id, slot);
3099
- return [...merged.values()];
3100
- }, withRegisteredStreamingSlots = async (renderResponse, options = {}) => {
3101
- const { result, slots } = await runWithStreamingSlotRegistry(renderResponse);
3102
- const explicit = options.streamingSlots ?? [];
3103
- return withStreamingSlots(result, {
3104
- ...options,
3105
- streamingSlots: mergeStreamingSlots(slots, explicit)
3106
- });
3107
- };
3108
- var init_responseEnhancers = __esm(() => {
3109
- init_streamingSlots();
3110
- init_streamingSlotRegistry();
3111
- });
3112
-
3113
2403
  // src/utils/getDurationString.ts
3114
2404
  var getDurationString = (duration) => {
3115
2405
  let durationString;
@@ -3252,63 +2542,12 @@ var init_logger = __esm(() => {
3252
2542
  };
3253
2543
  });
3254
2544
 
3255
- // src/core/streamingSlotWarningScope.ts
3256
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3257
- var STREAMING_SLOT_WARNING_STORAGE_KEY2, isObjectRecord4 = (value) => Boolean(value) && typeof value === "object", isAsyncLocalStorage3 = (value) => isObjectRecord4(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function", getWarningStorage = () => {
3258
- const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2);
3259
- if (value === null || typeof value === "undefined") {
3260
- return;
3261
- }
3262
- return isAsyncLocalStorage3(value) ? value : undefined;
3263
- }, ensureWarningStorage = () => {
3264
- const existing = getWarningStorage();
3265
- if (existing) {
3266
- return existing;
3267
- }
3268
- const storage = new AsyncLocalStorage2;
3269
- Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2, storage);
3270
- return storage;
3271
- }, normalizeCallsitePath2 = (value) => value.replace(`${process.cwd()}/`, "").replace(process.cwd(), "").replace(/^\.\/+/, ""), formatWarningCallsite = (callsite) => {
3272
- const match = callsite.match(/^(.*?)(:\d+:\d+)$/);
3273
- if (!match) {
3274
- return `\x1B[36m${callsite}\x1B[0m`;
3275
- }
3276
- return `\x1B[36m${match[1]}\x1B[33m${match[2]}\x1B[0m`;
3277
- }, extractCallsiteFromStack = (stack) => {
3278
- const frames = stack.split(`
3279
- `).slice(1).map((line) => line.trim());
3280
- for (const frame of frames) {
3281
- if (frame.includes("/node_modules/") || frame.includes("/dist/") || frame.includes("/src/react/pageHandler.") || frame.includes("/src/vue/pageHandler.") || frame.includes("/src/svelte/pageHandler.") || frame.includes("/src/angular/pageHandler.") || frame.includes("/src/core/streamingSlotWarningScope.")) {
3282
- continue;
3283
- }
3284
- const locationMatch = frame.match(/\((\/[^)]+:\d+:\d+)\)$/) ?? frame.match(/at (\/[^ ]+:\d+:\d+)$/);
3285
- if (locationMatch?.[1]) {
3286
- return normalizeCallsitePath2(locationMatch[1]);
3287
- }
3288
- }
3289
- return;
3290
- }, buildMissingCollectorWarning = (primitiveName, handlerCallsite) => `${primitiveName} rendered during SSR without streaming slot collection enabled. Add { collectStreamingSlots: true } to this page handler to enable out-of-order streaming for this route.${handlerCallsite ? ` Update ${formatWarningCallsite(handlerCallsite)}.` : ""}`, captureStreamingSlotWarningCallsite = () => {
3291
- if (false) {}
3292
- const { stack } = new Error;
3293
- if (!stack) {
3294
- return;
3295
- }
3296
- return extractCallsiteFromStack(stack);
3297
- }, runWithStreamingSlotWarningScope = (task, metadata) => ensureWarningStorage().run({ handlerCallsite: metadata?.handlerCallsite, hasWarned: false }, task);
3298
- var init_streamingSlotWarningScope = __esm(() => {
3299
- init_logger();
3300
- init_streamingSlotRegistrar();
3301
- STREAMING_SLOT_WARNING_STORAGE_KEY2 = Symbol.for("absolutejs.streamingSlotWarningAsyncLocalStorage");
3302
- setStreamingSlotWarningController({
3303
- maybeWarn: (primitiveName) => {
3304
- const store = getWarningStorage()?.getStore();
3305
- if (!store || store.hasWarned) {
3306
- return;
3307
- }
3308
- store.hasWarned = true;
3309
- logWarn(buildMissingCollectorWarning(primitiveName, store.handlerCallsite));
3310
- }
3311
- });
2545
+ // src/core/ssrCache.ts
2546
+ var dirtyFrameworks, markSsrCacheDirty = (framework) => {
2547
+ dirtyFrameworks.add(framework);
2548
+ }, isSsrCacheDirty = (framework) => dirtyFrameworks.has(framework);
2549
+ var init_ssrCache = __esm(() => {
2550
+ dirtyFrameworks = new Set;
3312
2551
  });
3313
2552
 
3314
2553
  // src/islands/sourceMetadata.ts
@@ -4557,133 +3796,985 @@ if (!document.querySelector(_sel)) {
4557
3796
  (document.getElementById('root') || document.body).appendChild(document.createElement(_sel));
4558
3797
  }
4559
3798
 
4560
- var providers = [provideZonelessChangeDetection()];
4561
- if (!window.__HMR_SKIP_HYDRATION__ && !pageHasIslands) {
4562
- providers.push(provideClientHydration());
4563
- }
4564
- delete window.__HMR_SKIP_HYDRATION__;
4565
- providers.push.apply(providers, propProviders);
4566
- window.__ABS_SLOT_HYDRATION_PENDING__ = pageHasRawStreamingSlots;
3799
+ var providers = [provideZonelessChangeDetection()];
3800
+ if (!window.__HMR_SKIP_HYDRATION__ && !pageHasIslands) {
3801
+ providers.push(provideClientHydration());
3802
+ }
3803
+ delete window.__HMR_SKIP_HYDRATION__;
3804
+ providers.push.apply(providers, propProviders);
3805
+ window.__ABS_SLOT_HYDRATION_PENDING__ = pageHasRawStreamingSlots;
3806
+
3807
+ if (pageHasRawStreamingSlots) {
3808
+ window.__ABS_SLOT_HYDRATION_PENDING__ = false;
3809
+ if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
3810
+ requestAnimationFrame(function() {
3811
+ window.__ABS_SLOT_FLUSH__();
3812
+ });
3813
+ }
3814
+ } else {
3815
+ bootstrapApplication(${componentClassName}, {
3816
+ providers: providers
3817
+ }).then(function (appRef) {
3818
+ window.__ANGULAR_APP__ = appRef;
3819
+ window.__ABS_SLOT_HYDRATION_PENDING__ = false;
3820
+ if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
3821
+ requestAnimationFrame(function() {
3822
+ window.__ABS_SLOT_FLUSH__();
3823
+ });
3824
+ }
3825
+ });
3826
+ }
3827
+ `.trim() : `
3828
+ import '@angular/compiler';
3829
+ import { bootstrapApplication } from '@angular/platform-browser';
3830
+ import { provideClientHydration } from '@angular/platform-browser';
3831
+ import { enableProdMode, provideZonelessChangeDetection } from '@angular/core';
3832
+ import * as pageModule from '${normalizedImportPath}';
3833
+
3834
+ var ${componentClassName} = pageModule.default;
3835
+ var toScreamingSnake = function(str) {
3836
+ return str.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();
3837
+ };
3838
+ var isInjectionToken = function(value) {
3839
+ return Boolean(value) && typeof value === 'object' && value.ngMetadataName === 'InjectionToken';
3840
+ };
3841
+ var pageProps = window.__ABS_ANGULAR_PAGE_PROPS__ || {};
3842
+ var pageHasIslands = Boolean(pageModule.__ABSOLUTE_PAGE_HAS_ISLANDS__) || Boolean(document.querySelector('[data-island="true"]'));
3843
+ var pageHasRawStreamingSlots = Boolean(document.querySelector('[data-absolute-raw-slot="true"]'));
3844
+ var pageHasStreamingSlots = Boolean(document.querySelector('[data-absolute-slot="true"]'));
3845
+ var propProviders = Object.entries(pageProps).map(function(entry) {
3846
+ var propName = entry[0];
3847
+ var propValue = entry[1];
3848
+ var token = pageModule[toScreamingSnake(propName)];
3849
+ return isInjectionToken(token) ? { provide: token, useValue: propValue } : null;
3850
+ }).filter(Boolean);
3851
+
3852
+ enableProdMode();
3853
+
3854
+ var providers = [provideZonelessChangeDetection()].concat(propProviders);
3855
+ if (!pageHasIslands) {
3856
+ providers.unshift(provideClientHydration());
3857
+ }
3858
+ window.__ABS_SLOT_HYDRATION_PENDING__ = pageHasRawStreamingSlots;
3859
+
3860
+ if (pageHasRawStreamingSlots) {
3861
+ window.__ABS_SLOT_HYDRATION_PENDING__ = false;
3862
+ if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
3863
+ requestAnimationFrame(function() {
3864
+ window.__ABS_SLOT_FLUSH__();
3865
+ });
3866
+ }
3867
+ } else {
3868
+ bootstrapApplication(${componentClassName}, {
3869
+ providers: providers
3870
+ }).then(function (appRef) {
3871
+ window.__ANGULAR_APP__ = appRef;
3872
+ window.__ABS_SLOT_HYDRATION_PENDING__ = false;
3873
+ if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
3874
+ requestAnimationFrame(function() {
3875
+ window.__ABS_SLOT_FLUSH__();
3876
+ });
3877
+ }
3878
+ });
3879
+ }
3880
+ `.trim();
3881
+ const indexHash = Bun.hash(hydration).toString(BASE_36_RADIX);
3882
+ const indexUnchanged = cachedWrapper?.indexHash === indexHash;
3883
+ await fs.writeFile(clientFile, hydration, "utf-8");
3884
+ wrapperOutputCache.set(resolvedEntry, {
3885
+ indexHash,
3886
+ serverHash: serverContentHash
3887
+ });
3888
+ return {
3889
+ clientPath: clientFile,
3890
+ indexUnchanged,
3891
+ serverPath: rawServerFile
3892
+ };
3893
+ });
3894
+ const results = await Promise.all(compileTasks);
3895
+ const serverPaths = results.map((r) => r.serverPath);
3896
+ const clientPaths = results.map((r) => r.clientPath);
3897
+ return {
3898
+ allIndexesUnchanged: hmr && results.every((r) => r.indexUnchanged),
3899
+ clientPaths,
3900
+ serverPaths
3901
+ };
3902
+ };
3903
+ var init_compileAngular = __esm(() => {
3904
+ init_constants();
3905
+ init_sourceMetadata();
3906
+ init_lowerDeferSyntax();
3907
+ init_stylePreprocessor();
3908
+ devClientDir = resolveDevClientDir();
3909
+ hmrClientPath = join5(devClientDir, "hmrClient.ts").replace(/\\/g, "/");
3910
+ hmrRuntimePath = join5(devClientDir, "handlers", "angularRuntime.ts").replace(/\\/g, "/");
3911
+ jitContentCache = new Map;
3912
+ wrapperOutputCache = new Map;
3913
+ });
3914
+
3915
+ // src/core/streamingSlotRegistrar.ts
3916
+ var STREAMING_SLOT_REGISTRAR_KEY = Symbol.for("absolutejs.streamingSlotRegistrar");
3917
+ var STREAMING_SLOT_WARNING_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotWarningController");
3918
+ var STREAMING_SLOT_COLLECTION_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotCollectionController");
3919
+ var getRegisteredStreamingSlotRegistrar = () => {
3920
+ const value = Reflect.get(globalThis, STREAMING_SLOT_REGISTRAR_KEY);
3921
+ if (typeof value === "function" || value === null) {
3922
+ return value;
3923
+ }
3924
+ return;
3925
+ };
3926
+ var isObjectRecord = (value) => Boolean(value) && typeof value === "object";
3927
+ var isStreamingSlotWarningController = (value) => isObjectRecord(value) && ("maybeWarn" in value) && typeof value.maybeWarn === "function";
3928
+ var isStreamingSlotCollectionController = (value) => isObjectRecord(value) && ("isCollecting" in value) && typeof value.isCollecting === "function";
3929
+ var getWarningController = () => {
3930
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY);
3931
+ if (value === null || typeof value === "undefined")
3932
+ return;
3933
+ return isStreamingSlotWarningController(value) ? value : undefined;
3934
+ };
3935
+ var getCollectionController = () => {
3936
+ const value = Reflect.get(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY);
3937
+ if (value === null || typeof value === "undefined")
3938
+ return;
3939
+ return isStreamingSlotCollectionController(value) ? value : undefined;
3940
+ };
3941
+ var hasRegisteredStreamingSlotRegistrar = () => typeof getRegisteredStreamingSlotRegistrar() === "function";
3942
+ var isStreamingSlotCollectionActive = () => getCollectionController()?.isCollecting() === true;
3943
+ var registerStreamingSlot = (slot) => {
3944
+ getRegisteredStreamingSlotRegistrar()?.(slot);
3945
+ };
3946
+ var setStreamingSlotCollectionController = (controller) => {
3947
+ Reflect.set(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY, controller);
3948
+ };
3949
+ var setStreamingSlotRegistrar = (nextRegistrar) => {
3950
+ Reflect.set(globalThis, STREAMING_SLOT_REGISTRAR_KEY, nextRegistrar);
3951
+ };
3952
+ var setStreamingSlotWarningController = (controller) => {
3953
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY, controller);
3954
+ };
3955
+ var warnMissingStreamingSlotCollector = (primitiveName) => {
3956
+ if (isStreamingSlotCollectionActive()) {
3957
+ return;
3958
+ }
3959
+ getWarningController()?.maybeWarn(primitiveName);
3960
+ };
3961
+
3962
+ // src/core/streamingSlotRegistry.ts
3963
+ var STREAMING_SLOT_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotAsyncLocalStorage");
3964
+ var isObjectRecord2 = (value) => Boolean(value) && typeof value === "object";
3965
+ var isAsyncLocalStorage = (value) => isObjectRecord2(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
3966
+ var getStorageGlobal = () => {
3967
+ const value = Reflect.get(globalThis, STREAMING_SLOT_STORAGE_KEY);
3968
+ if (value === null || typeof value === "undefined") {
3969
+ return value;
3970
+ }
3971
+ return isAsyncLocalStorage(value) ? value : undefined;
3972
+ };
3973
+ var isServerRuntime = () => typeof process !== "undefined" && typeof process.versions?.node === "string";
3974
+ var ensureAsyncLocalStorage = async () => {
3975
+ const storage = getStorageGlobal();
3976
+ if (typeof storage !== "undefined") {
3977
+ return storage;
3978
+ }
3979
+ if (!isServerRuntime()) {
3980
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, null);
3981
+ return getStorageGlobal();
3982
+ }
3983
+ const mod = await import("async_hooks");
3984
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, new mod.AsyncLocalStorage);
3985
+ return getStorageGlobal();
3986
+ };
3987
+ var getActiveSlotStore = () => {
3988
+ const storage = getStorageGlobal();
3989
+ if (!storage)
3990
+ return;
3991
+ return storage.getStore();
3992
+ };
3993
+ var registerStreamingSlot2 = (slot) => {
3994
+ const store = getActiveSlotStore();
3995
+ if (!store)
3996
+ return;
3997
+ store.set(slot.id, slot);
3998
+ };
3999
+ setStreamingSlotRegistrar(registerStreamingSlot2);
4000
+ setStreamingSlotCollectionController({
4001
+ isCollecting: () => getActiveSlotStore() !== undefined
4002
+ });
4003
+ var hasActiveStreamingSlotRegistry = () => getActiveSlotStore() !== undefined;
4004
+ var runWithStreamingSlotRegistry = async (task) => {
4005
+ const storage = await ensureAsyncLocalStorage();
4006
+ if (!storage) {
4007
+ const slots = [];
4008
+ return {
4009
+ result: await task(),
4010
+ slots
4011
+ };
4012
+ }
4013
+ return storage.run(new Map, async () => {
4014
+ const result = await task();
4015
+ const store = storage.getStore();
4016
+ return {
4017
+ result,
4018
+ slots: store ? [...store.values()] : []
4019
+ };
4020
+ });
4021
+ };
4022
+
4023
+ // src/angular/pageHandler.ts
4024
+ init_constants();
4025
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
4026
+ import { mkdir as mkdir2, symlink } from "fs/promises";
4027
+ import { tmpdir } from "os";
4028
+ import { basename as basename4, dirname as dirname5, join as join6, resolve as resolve7 } from "path";
4029
+
4030
+ // src/core/islandPageContext.ts
4031
+ init_constants();
4032
+ var BOOTSTRAP_MANIFEST_KEY = "BootstrapClient";
4033
+ var ISLAND_MARKER = 'data-island="true"';
4034
+ var MANIFEST_MARKER = "__ABSOLUTE_MANIFEST__";
4035
+ var ISLAND_STATE_MARKER = "__ABS_ISLAND_STATE__";
4036
+ var CLOSING_HEAD_TAG = "</head>";
4037
+ var buildIslandsHeadMarkup = (manifest) => {
4038
+ const manifestScript = `<script>window.__ABSOLUTE_MANIFEST__ = ${JSON.stringify(manifest)}</script>`;
4039
+ const islandStateScript = `<script>window.__ABS_ISLAND_STATE__ = ${JSON.stringify(globalThis.__ABS_ISLAND_STATE__ ?? {})}</script>`;
4040
+ const bootstrapPath = manifest[BOOTSTRAP_MANIFEST_KEY];
4041
+ const bootstrapScript = bootstrapPath ? `<script type="module" src="${bootstrapPath}"></script>` : "";
4042
+ return `${manifestScript}${islandStateScript}${bootstrapScript}`;
4043
+ };
4044
+ var injectHeadMarkup = (html, markup) => {
4045
+ const closingHeadIndex = html.indexOf("</head>");
4046
+ if (closingHeadIndex >= 0) {
4047
+ return `${html.slice(0, closingHeadIndex)}${markup}${html.slice(closingHeadIndex)}`;
4048
+ }
4049
+ const openingBodyIndex = html.indexOf("<body");
4050
+ if (openingBodyIndex >= 0) {
4051
+ const bodyStart = html.indexOf(">", openingBodyIndex);
4052
+ if (bodyStart >= 0) {
4053
+ return `${html.slice(0, openingBodyIndex)}<head>${markup}</head>${html.slice(openingBodyIndex)}`;
4054
+ }
4055
+ }
4056
+ return `<!DOCTYPE html><html><head>${markup}</head><body>${html}</body></html>`;
4057
+ };
4058
+ var streamChunkToString = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true });
4059
+ var flushSafePendingText = (controller, encoder, pending, lookbehind) => {
4060
+ if (pending.length <= lookbehind) {
4061
+ return pending;
4062
+ }
4063
+ const safeText = pending.slice(0, pending.length - lookbehind);
4064
+ controller.enqueue(encoder.encode(safeText));
4065
+ return pending.slice(-lookbehind);
4066
+ };
4067
+ var updateInjectedState = (consumed, injected, pending) => {
4068
+ if (consumed.done) {
4069
+ return { done: true, injected, pending };
4070
+ }
4071
+ return {
4072
+ done: false,
4073
+ injected: consumed.injected,
4074
+ pending: consumed.pending
4075
+ };
4076
+ };
4077
+ var readStreamChunk = async (reader) => {
4078
+ const { done, value } = await reader.read();
4079
+ if (done || !value) {
4080
+ return { done, value: undefined };
4081
+ }
4082
+ return { done, value };
4083
+ };
4084
+ var pipeStreamWithHeadInjection = (stream, markup) => {
4085
+ const encoder = new TextEncoder;
4086
+ const decoder = new TextDecoder;
4087
+ const lookbehind = CLOSING_HEAD_TAG.length - 1;
4088
+ const processPending = (controller, pending, injected) => {
4089
+ if (injected) {
4090
+ controller.enqueue(encoder.encode(pending));
4091
+ return { injected, pending: "" };
4092
+ }
4093
+ const headIndex = pending.indexOf(CLOSING_HEAD_TAG);
4094
+ if (headIndex >= 0) {
4095
+ const next = `${pending.slice(0, headIndex)}${markup}${pending.slice(headIndex)}`;
4096
+ controller.enqueue(encoder.encode(next));
4097
+ return { injected: true, pending: "" };
4098
+ }
4099
+ return {
4100
+ injected,
4101
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
4102
+ };
4103
+ };
4104
+ const finishHeadInjectionStream = (controller, pending, injected) => {
4105
+ let finalPending = pending + decoder.decode();
4106
+ if (!injected) {
4107
+ finalPending = injectHeadMarkup(finalPending, markup);
4108
+ }
4109
+ if (finalPending.length > 0) {
4110
+ controller.enqueue(encoder.encode(finalPending));
4111
+ }
4112
+ controller.close();
4113
+ };
4114
+ const consumeHeadChunk = async (controller, reader, pending, injected) => {
4115
+ const { done, value } = await readStreamChunk(reader);
4116
+ if (done || !value) {
4117
+ return { done, injected, pending };
4118
+ }
4119
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
4120
+ return {
4121
+ done,
4122
+ injected: processed.injected,
4123
+ pending: processed.pending
4124
+ };
4125
+ };
4126
+ const runHeadInjectionLoop = async (controller, reader) => {
4127
+ const consumeNextHeadChunk = async (injected, pending) => {
4128
+ const consumed = await consumeHeadChunk(controller, reader, pending, injected);
4129
+ const nextState = updateInjectedState(consumed, injected, pending);
4130
+ if (nextState.done) {
4131
+ return { injected, pending };
4132
+ }
4133
+ return consumeNextHeadChunk(nextState.injected, nextState.pending);
4134
+ };
4135
+ return consumeNextHeadChunk(false, "");
4136
+ };
4137
+ return new ReadableStream({
4138
+ async start(controller) {
4139
+ const reader = stream.getReader();
4140
+ try {
4141
+ const { injected, pending } = await runHeadInjectionLoop(controller, reader);
4142
+ finishHeadInjectionStream(controller, pending, injected);
4143
+ } catch (error) {
4144
+ controller.error(error);
4145
+ }
4146
+ }
4147
+ });
4148
+ };
4149
+ var pipeStreamWithIslandMarkerDetection = (stream, markup) => {
4150
+ const encoder = new TextEncoder;
4151
+ const decoder = new TextDecoder;
4152
+ const lookbehind = Math.max(ISLAND_MARKER.length, BYTES_PER_KILOBYTE);
4153
+ const processPending = (controller, pending, injected) => {
4154
+ if (injected) {
4155
+ controller.enqueue(encoder.encode(pending));
4156
+ return { injected, pending: "" };
4157
+ }
4158
+ const markerIndex = pending.indexOf(ISLAND_MARKER);
4159
+ if (markerIndex >= 0) {
4160
+ const tagStart = pending.lastIndexOf("<", markerIndex);
4161
+ const injectAt = tagStart >= 0 ? tagStart : markerIndex;
4162
+ const next = `${pending.slice(0, injectAt)}${markup}${pending.slice(injectAt)}`;
4163
+ controller.enqueue(encoder.encode(next));
4164
+ return { injected: true, pending: "" };
4165
+ }
4166
+ return {
4167
+ injected,
4168
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
4169
+ };
4170
+ };
4171
+ const finishIslandMarkerStream = (controller, pending) => {
4172
+ const finalPending = pending + decoder.decode();
4173
+ if (finalPending.length > 0) {
4174
+ controller.enqueue(encoder.encode(finalPending));
4175
+ }
4176
+ controller.close();
4177
+ };
4178
+ const consumeIslandChunk = async (controller, reader, pending, injected) => {
4179
+ const { done, value } = await readStreamChunk(reader);
4180
+ if (done || !value) {
4181
+ return { done, injected, pending };
4182
+ }
4183
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
4184
+ return {
4185
+ done,
4186
+ injected: processed.injected,
4187
+ pending: processed.pending
4188
+ };
4189
+ };
4190
+ const runIslandMarkerLoop = async (controller, reader) => {
4191
+ const consumeNextIslandChunk = async (injected, pending) => {
4192
+ const consumed = await consumeIslandChunk(controller, reader, pending, injected);
4193
+ const nextState = updateInjectedState(consumed, injected, pending);
4194
+ if (nextState.done) {
4195
+ return { injected, pending };
4196
+ }
4197
+ return consumeNextIslandChunk(nextState.injected, nextState.pending);
4198
+ };
4199
+ return consumeNextIslandChunk(false, "");
4200
+ };
4201
+ return new ReadableStream({
4202
+ async start(controller) {
4203
+ const reader = stream.getReader();
4204
+ try {
4205
+ const { pending } = await runIslandMarkerLoop(controller, reader);
4206
+ finishIslandMarkerStream(controller, pending);
4207
+ } catch (error) {
4208
+ controller.error(error);
4209
+ }
4210
+ }
4211
+ });
4212
+ };
4213
+ var htmlContainsIslands = (html) => html.includes(ISLAND_MARKER);
4214
+ var injectIslandPageContext = (html, options) => {
4215
+ const manifest = globalThis.__absoluteManifest;
4216
+ const hasIslands = options?.hasIslands ?? htmlContainsIslands(html);
4217
+ if (!manifest || !hasIslands) {
4218
+ return html;
4219
+ }
4220
+ if (html.includes(MANIFEST_MARKER) || html.includes(ISLAND_STATE_MARKER)) {
4221
+ return html;
4222
+ }
4223
+ return injectHeadMarkup(html, buildIslandsHeadMarkup(manifest));
4224
+ };
4225
+ var injectIslandPageContextStream = (stream, options) => {
4226
+ const manifest = globalThis.__absoluteManifest;
4227
+ if (!manifest)
4228
+ return stream;
4229
+ const markup = buildIslandsHeadMarkup(manifest);
4230
+ if (options?.hasIslands === true) {
4231
+ return pipeStreamWithHeadInjection(stream, markup);
4232
+ }
4233
+ if (options?.hasIslands === false) {
4234
+ return stream;
4235
+ }
4236
+ return pipeStreamWithIslandMarkerDetection(stream, markup);
4237
+ };
4238
+ var setCurrentIslandManifest = (manifest) => {
4239
+ globalThis.__absoluteManifest = manifest;
4240
+ };
4241
+
4242
+ // src/utils/ssrErrorPage.ts
4243
+ var ssrErrorPage = (framework, error) => {
4244
+ const frameworkColors = {
4245
+ angular: "#dd0031",
4246
+ html: "#e34c26",
4247
+ htmx: "#1a365d",
4248
+ react: "#61dafb",
4249
+ svelte: "#ff3e00",
4250
+ vue: "#42b883"
4251
+ };
4252
+ const accent = frameworkColors[framework] ?? "#94a3b8";
4253
+ const label = framework.charAt(0).toUpperCase() + framework.slice(1);
4254
+ const message = error instanceof Error ? error.message : String(error);
4255
+ return `<!DOCTYPE html>
4256
+ <html>
4257
+ <head>
4258
+ <meta charset="utf-8">
4259
+ <meta name="viewport" content="width=device-width, initial-scale=1">
4260
+ <title>SSR Error - AbsoluteJS</title>
4261
+ <style>
4262
+ *{margin:0;padding:0;box-sizing:border-box}
4263
+ 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}
4264
+ .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}
4265
+ .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)}
4266
+ .brand{font-weight:700;font-size:20px;color:#fff;letter-spacing:-0.02em}
4267
+ .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)}
4268
+ .kind{color:#94a3b8;font-size:13px;font-weight:500}
4269
+ .content{padding:24px}
4270
+ .label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px}
4271
+ .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}
4272
+ .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}
4273
+ </style>
4274
+ </head>
4275
+ <body>
4276
+ <div class="card">
4277
+ <div class="header">
4278
+ <div style="display:flex;align-items:center;gap:12px">
4279
+ <span class="brand">AbsoluteJS</span>
4280
+ <span class="badge">${label}</span>
4281
+ </div>
4282
+ <span class="kind">Server Render Error</span>
4283
+ </div>
4284
+ <div class="content">
4285
+ <div class="label">What went wrong</div>
4286
+ <pre class="message">${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>
4287
+ <div class="hint">A component threw during server-side rendering. Check the terminal for the full stack trace.</div>
4288
+ </div>
4289
+ </div>
4290
+ </body>
4291
+ </html>`;
4292
+ };
4293
+
4294
+ // src/utils/resolveConvention.ts
4295
+ import { basename } from "path";
4296
+ var CONVENTIONS_KEY = "__absoluteConventions";
4297
+ var isConventionsMap = (value) => Boolean(value) && typeof value === "object";
4298
+ var getMap = () => {
4299
+ const value = Reflect.get(globalThis, CONVENTIONS_KEY);
4300
+ if (isConventionsMap(value))
4301
+ return value;
4302
+ const empty = {};
4303
+ return empty;
4304
+ };
4305
+ var derivePageName = (pagePath) => {
4306
+ const base = basename(pagePath);
4307
+ const dotIndex = base.indexOf(".");
4308
+ const name = dotIndex > 0 ? base.slice(0, dotIndex) : base;
4309
+ return toPascal(name);
4310
+ };
4311
+ var resolveErrorConventionPath = (framework, pageName) => {
4312
+ const conventions = getMap()[framework];
4313
+ if (!conventions)
4314
+ return;
4315
+ return conventions.pages?.[pageName]?.error ?? conventions.defaults?.error;
4316
+ };
4317
+ var resolveNotFoundConventionPath = (framework) => getMap()[framework]?.defaults?.notFound;
4318
+ var setConventions = (map) => {
4319
+ Reflect.set(globalThis, CONVENTIONS_KEY, map);
4320
+ };
4321
+ var isDev = () => true;
4322
+ var buildErrorProps = (error) => {
4323
+ const message = error instanceof Error ? error.message : String(error);
4324
+ const stack = isDev() && error instanceof Error ? error.stack : undefined;
4325
+ return { error: { message, stack } };
4326
+ };
4327
+ var renderReactError = async (conventionPath, errorProps) => {
4328
+ const { createElement } = await import("react");
4329
+ const { renderToReadableStream } = await import("react-dom/server");
4330
+ const mod = await import(conventionPath);
4331
+ const [firstKey] = Object.keys(mod);
4332
+ const ErrorComponent = mod.default ?? (firstKey ? mod[firstKey] : undefined);
4333
+ const element = createElement(ErrorComponent, errorProps);
4334
+ const stream = await renderToReadableStream(element);
4335
+ return new Response(stream, {
4336
+ headers: { "Content-Type": "text/html" },
4337
+ status: 500
4338
+ });
4339
+ };
4340
+ var renderSvelteError = async (conventionPath, errorProps) => {
4341
+ const { render } = await import("svelte/server");
4342
+ const mod = await import(conventionPath);
4343
+ const ErrorComponent = mod.default;
4344
+ const { head, body } = render(ErrorComponent, {
4345
+ props: errorProps
4346
+ });
4347
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
4348
+ return new Response(html, {
4349
+ headers: { "Content-Type": "text/html" },
4350
+ status: 500
4351
+ });
4352
+ };
4353
+ var unescapeVueStyles = (ssrBody) => {
4354
+ let styles = "";
4355
+ const body = ssrBody.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => {
4356
+ styles += `<style>${css.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")}</style>`;
4357
+ return "";
4358
+ });
4359
+ return { body, styles };
4360
+ };
4361
+ var renderVueError = async (conventionPath, errorProps) => {
4362
+ const { createSSRApp, h } = await import("vue");
4363
+ const { renderToString } = await import("vue/server-renderer");
4364
+ const mod = await import(conventionPath);
4365
+ const ErrorComponent = mod.default;
4366
+ const app = createSSRApp({
4367
+ render: () => h(ErrorComponent, errorProps)
4368
+ });
4369
+ const rawBody = await renderToString(app);
4370
+ const { styles, body } = unescapeVueStyles(rawBody);
4371
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
4372
+ return new Response(html, {
4373
+ headers: { "Content-Type": "text/html" },
4374
+ status: 500
4375
+ });
4376
+ };
4377
+ var renderAngularError = async (conventionPath, errorProps) => {
4378
+ const mod = await import(conventionPath);
4379
+ const renderError = mod.default ?? mod.renderError;
4380
+ if (typeof renderError !== "function")
4381
+ return null;
4382
+ const html = renderError(errorProps);
4383
+ return new Response(html, {
4384
+ headers: { "Content-Type": "text/html" },
4385
+ status: 500
4386
+ });
4387
+ };
4388
+ var logConventionRenderError = (framework, label, renderError) => {
4389
+ const message = renderError instanceof Error ? renderError.message : "";
4390
+ if (message.includes("Cannot find module") || message.includes("Cannot find package") || message.includes("not found in module")) {
4391
+ 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}).`);
4392
+ return;
4393
+ }
4394
+ console.error(`[SSR] Failed to render ${framework} convention ${label} page:`, renderError);
4395
+ };
4396
+ var ERROR_RENDERERS = {
4397
+ angular: renderAngularError,
4398
+ react: renderReactError,
4399
+ svelte: renderSvelteError,
4400
+ vue: renderVueError
4401
+ };
4402
+ var renderConventionError = async (framework, pageName, error) => {
4403
+ const conventionPath = resolveErrorConventionPath(framework, pageName);
4404
+ if (!conventionPath)
4405
+ return null;
4406
+ const errorProps = buildErrorProps(error);
4407
+ const renderer = ERROR_RENDERERS[framework];
4408
+ if (!renderer)
4409
+ return null;
4410
+ try {
4411
+ return await renderer(conventionPath, errorProps);
4412
+ } catch (renderError) {
4413
+ logConventionRenderError(framework, "error", renderError);
4414
+ }
4415
+ return null;
4416
+ };
4417
+ var renderReactNotFound = async (conventionPath) => {
4418
+ const { createElement } = await import("react");
4419
+ const { renderToReadableStream } = await import("react-dom/server");
4420
+ const mod = await import(conventionPath);
4421
+ const [nfKey] = Object.keys(mod);
4422
+ const NotFoundComponent = mod.default ?? (nfKey ? mod[nfKey] : undefined);
4423
+ const element = createElement(NotFoundComponent);
4424
+ const stream = await renderToReadableStream(element);
4425
+ return new Response(stream, {
4426
+ headers: { "Content-Type": "text/html" },
4427
+ status: 404
4428
+ });
4429
+ };
4430
+ var renderSvelteNotFound = async (conventionPath) => {
4431
+ const { render } = await import("svelte/server");
4432
+ const mod = await import(conventionPath);
4433
+ const NotFoundComponent = mod.default;
4434
+ const { head, body } = render(NotFoundComponent);
4435
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
4436
+ return new Response(html, {
4437
+ headers: { "Content-Type": "text/html" },
4438
+ status: 404
4439
+ });
4440
+ };
4441
+ var renderVueNotFound = async (conventionPath) => {
4442
+ const { createSSRApp, h } = await import("vue");
4443
+ const { renderToString } = await import("vue/server-renderer");
4444
+ const mod = await import(conventionPath);
4445
+ const NotFoundComponent = mod.default;
4446
+ const app = createSSRApp({
4447
+ render: () => h(NotFoundComponent)
4448
+ });
4449
+ const rawBody = await renderToString(app);
4450
+ const { styles, body } = unescapeVueStyles(rawBody);
4451
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
4452
+ return new Response(html, {
4453
+ headers: { "Content-Type": "text/html" },
4454
+ status: 404
4455
+ });
4456
+ };
4457
+ var renderAngularNotFound = async (conventionPath) => {
4458
+ const mod = await import(conventionPath);
4459
+ const renderNotFound = mod.default ?? mod.renderNotFound;
4460
+ if (typeof renderNotFound !== "function")
4461
+ return null;
4462
+ const html = renderNotFound();
4463
+ return new Response(html, {
4464
+ headers: { "Content-Type": "text/html" },
4465
+ status: 404
4466
+ });
4467
+ };
4468
+ var NOT_FOUND_RENDERERS = {
4469
+ angular: renderAngularNotFound,
4470
+ react: renderReactNotFound,
4471
+ svelte: renderSvelteNotFound,
4472
+ vue: renderVueNotFound
4473
+ };
4474
+ var renderConventionNotFound = async (framework) => {
4475
+ const conventionPath = resolveNotFoundConventionPath(framework);
4476
+ if (!conventionPath)
4477
+ return null;
4478
+ const renderer = NOT_FOUND_RENDERERS[framework];
4479
+ if (!renderer)
4480
+ return null;
4481
+ try {
4482
+ return await renderer(conventionPath);
4483
+ } catch (renderError) {
4484
+ logConventionRenderError(framework, "not-found", renderError);
4485
+ }
4486
+ return null;
4487
+ };
4488
+ var NOT_FOUND_PRIORITY = [
4489
+ "react",
4490
+ "svelte",
4491
+ "vue",
4492
+ "angular"
4493
+ ];
4494
+ var renderFirstNotFound = async () => {
4495
+ for (const framework of NOT_FOUND_PRIORITY) {
4496
+ if (!getMap()[framework]?.defaults?.notFound)
4497
+ continue;
4498
+ const response = await renderConventionNotFound(framework);
4499
+ if (response)
4500
+ return response;
4501
+ }
4502
+ return null;
4503
+ };
4504
+
4505
+ // src/angular/pageHandler.ts
4506
+ init_registerClientScript();
4507
+ init_angularDeps();
4508
+
4509
+ // src/angular/lowerServerIslands.ts
4510
+ init_renderIslandMarkup();
4511
+ var ANGULAR_ISLAND_TAG_RE = /<absolute-island\b([^>]*)>[\s\S]*?<\/absolute-island>/gi;
4512
+ var ATTRIBUTE_RE = /([A-Za-z_:][-A-Za-z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
4513
+ var islandFrameworks = [
4514
+ "react",
4515
+ "svelte",
4516
+ "vue",
4517
+ "angular"
4518
+ ];
4519
+ var islandHydrationModes = [
4520
+ "load",
4521
+ "idle",
4522
+ "visible",
4523
+ "none"
4524
+ ];
4525
+ var decodeHtmlAttribute = (value) => value.replaceAll("&quot;", '"').replaceAll("&#34;", '"').replaceAll("&apos;", "'").replaceAll("&#39;", "'").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">");
4526
+ var isRecord3 = (value) => typeof value === "object" && value !== null;
4527
+ var isIslandFramework = (value) => islandFrameworks.some((framework) => framework === value);
4528
+ var isIslandHydrate = (value) => islandHydrationModes.some((mode) => mode === value);
4529
+ var parseAttributes = (attributeString) => {
4530
+ const attributes = new Map;
4531
+ let match = ATTRIBUTE_RE.exec(attributeString);
4532
+ while (match) {
4533
+ const [, key, doubleQuotedValue, singleQuotedValue] = match;
4534
+ match = ATTRIBUTE_RE.exec(attributeString);
4535
+ if (!key)
4536
+ continue;
4537
+ attributes.set(key, decodeHtmlAttribute(doubleQuotedValue ?? singleQuotedValue ?? ""));
4538
+ }
4539
+ ATTRIBUTE_RE.lastIndex = 0;
4540
+ return attributes;
4541
+ };
4542
+ var parseAngularIslandProps = (attributeString) => {
4543
+ const attributes = parseAttributes(attributeString);
4544
+ const component = attributes.get("component");
4545
+ const framework = attributes.get("framework");
4546
+ const hydrate = attributes.get("hydrate") ?? "load";
4547
+ const serializedProps = attributes.get("data-abs-props") ?? "{}";
4548
+ if (!component || !framework) {
4549
+ return null;
4550
+ }
4551
+ if (!isIslandFramework(framework) || !isIslandHydrate(hydrate)) {
4552
+ return null;
4553
+ }
4554
+ let parsedProps = {};
4555
+ try {
4556
+ const candidate = JSON.parse(serializedProps);
4557
+ parsedProps = isRecord3(candidate) ? candidate : {};
4558
+ } catch {}
4559
+ return {
4560
+ component,
4561
+ framework,
4562
+ hydrate,
4563
+ props: parsedProps
4564
+ };
4565
+ };
4566
+ var lowerAngularServerIslands = async (html) => {
4567
+ if (!ANGULAR_ISLAND_TAG_RE.test(html)) {
4568
+ return html;
4569
+ }
4570
+ const registry = requireCurrentIslandRegistry();
4571
+ ANGULAR_ISLAND_TAG_RE.lastIndex = 0;
4572
+ const segments = [];
4573
+ let lastIndex = 0;
4574
+ let match = ANGULAR_ISLAND_TAG_RE.exec(html);
4575
+ while (match) {
4576
+ const [fullMatch, rawAttributeString] = match;
4577
+ const attributeString = rawAttributeString ?? "";
4578
+ segments.push({
4579
+ before: html.slice(lastIndex, match.index),
4580
+ fullMatch,
4581
+ props: parseAngularIslandProps(attributeString)
4582
+ });
4583
+ lastIndex = match.index + fullMatch.length;
4584
+ match = ANGULAR_ISLAND_TAG_RE.exec(html);
4585
+ }
4586
+ ANGULAR_ISLAND_TAG_RE.lastIndex = 0;
4587
+ const renderedSegments = await Promise.all(segments.map(async (segment) => segment.before + (segment.props ? await renderIslandMarkup(registry, segment.props) : segment.fullMatch)));
4588
+ return renderedSegments.join("") + html.slice(lastIndex);
4589
+ };
4590
+
4591
+ // src/angular/pageHandler.ts
4592
+ init_devRouteRegistrationCallsite();
4567
4593
 
4568
- if (pageHasRawStreamingSlots) {
4569
- window.__ABS_SLOT_HYDRATION_PENDING__ = false;
4570
- if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
4571
- requestAnimationFrame(function() {
4572
- window.__ABS_SLOT_FLUSH__();
4573
- });
4574
- }
4575
- } else {
4576
- bootstrapApplication(${componentClassName}, {
4577
- providers: providers
4578
- }).then(function (appRef) {
4579
- window.__ANGULAR_APP__ = appRef;
4580
- window.__ABS_SLOT_HYDRATION_PENDING__ = false;
4581
- if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
4582
- requestAnimationFrame(function() {
4583
- window.__ABS_SLOT_FLUSH__();
4584
- });
4594
+ // src/angular/ssrSanitizer.ts
4595
+ var escapeHtml = (str) => String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
4596
+ var bypassValue = (value) => ({
4597
+ changingThisBreaksApplicationSecurity: value
4598
+ });
4599
+ var ssrSanitizer = null;
4600
+ var getSsrSanitizer = (deps) => {
4601
+ if (ssrSanitizer)
4602
+ return ssrSanitizer;
4603
+ const SsrSanitizerClass = class extends deps.DomSanitizer {
4604
+ sanitize(ctx, value) {
4605
+ if (value === null)
4606
+ return null;
4607
+ let strValue;
4608
+ let isTrustedHtml = false;
4609
+ if (typeof value === "string") {
4610
+ strValue = value;
4611
+ } else if (typeof value === "object" && "changingThisBreaksApplicationSecurity" in value) {
4612
+ strValue = String(value.changingThisBreaksApplicationSecurity);
4613
+ isTrustedHtml = true;
4614
+ } else {
4615
+ strValue = String(value);
4616
+ }
4617
+ if (ctx === deps.SecurityContext.HTML) {
4618
+ if (isTrustedHtml) {
4619
+ return strValue;
4585
4620
  }
4586
- });
4587
- }
4588
- `.trim() : `
4589
- import '@angular/compiler';
4590
- import { bootstrapApplication } from '@angular/platform-browser';
4591
- import { provideClientHydration } from '@angular/platform-browser';
4592
- import { enableProdMode, provideZonelessChangeDetection } from '@angular/core';
4593
- import * as pageModule from '${normalizedImportPath}';
4594
-
4595
- var ${componentClassName} = pageModule.default;
4596
- var toScreamingSnake = function(str) {
4597
- return str.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();
4621
+ return escapeHtml(strValue);
4622
+ }
4623
+ return strValue;
4624
+ }
4625
+ bypassSecurityTrustHtml(value) {
4626
+ return bypassValue(value);
4627
+ }
4628
+ bypassSecurityTrustStyle(value) {
4629
+ return bypassValue(value);
4630
+ }
4631
+ bypassSecurityTrustScript(value) {
4632
+ return bypassValue(value);
4633
+ }
4634
+ bypassSecurityTrustUrl(value) {
4635
+ return bypassValue(value);
4636
+ }
4637
+ bypassSecurityTrustResourceUrl(value) {
4638
+ return bypassValue(value);
4639
+ }
4640
+ };
4641
+ ssrSanitizer = new SsrSanitizerClass;
4642
+ return ssrSanitizer;
4598
4643
  };
4599
- var isInjectionToken = function(value) {
4600
- return Boolean(value) && typeof value === 'object' && value.ngMetadataName === 'InjectionToken';
4644
+ var resetSsrSanitizer = () => {
4645
+ ssrSanitizer = null;
4601
4646
  };
4602
- var pageProps = window.__ABS_ANGULAR_PAGE_PROPS__ || {};
4603
- var pageHasIslands = Boolean(pageModule.__ABSOLUTE_PAGE_HAS_ISLANDS__) || Boolean(document.querySelector('[data-island="true"]'));
4604
- var pageHasRawStreamingSlots = Boolean(document.querySelector('[data-absolute-raw-slot="true"]'));
4605
- var pageHasStreamingSlots = Boolean(document.querySelector('[data-absolute-slot="true"]'));
4606
- var propProviders = Object.entries(pageProps).map(function(entry) {
4607
- var propName = entry[0];
4608
- var propValue = entry[1];
4609
- var token = pageModule[toScreamingSnake(propName)];
4610
- return isInjectionToken(token) ? { provide: token, useValue: propValue } : null;
4611
- }).filter(Boolean);
4612
-
4613
- enableProdMode();
4614
4647
 
4615
- var providers = [provideZonelessChangeDetection()].concat(propProviders);
4616
- if (!pageHasIslands) {
4617
- providers.unshift(provideClientHydration());
4618
- }
4619
- window.__ABS_SLOT_HYDRATION_PENDING__ = pageHasRawStreamingSlots;
4648
+ // src/core/responseEnhancers.ts
4649
+ init_streamingSlots();
4650
+ var toResponse = async (responseLike) => responseLike;
4651
+ var cloneHeaders = (response) => {
4652
+ const headers = new Headers(response.headers);
4653
+ return headers;
4654
+ };
4655
+ var enhanceHtmlResponseWithStreamingSlots = (response, {
4656
+ nonce,
4657
+ onError,
4658
+ runtimePlacement,
4659
+ runtimePreludeScript,
4660
+ streamingSlots = [],
4661
+ policy
4662
+ } = {}) => {
4663
+ if (!response.body || streamingSlots.length === 0) {
4664
+ return response;
4665
+ }
4666
+ const body = appendStreamingSlotPatchesToStream(response.body, streamingSlots, {
4667
+ nonce,
4668
+ onError,
4669
+ policy,
4670
+ runtimePlacement,
4671
+ runtimePreludeScript
4672
+ });
4673
+ return new Response(body, {
4674
+ headers: cloneHeaders(response),
4675
+ status: response.status,
4676
+ statusText: response.statusText
4677
+ });
4678
+ };
4679
+ var withStreamingSlots = async (responseLike, options = {}) => enhanceHtmlResponseWithStreamingSlots(await toResponse(responseLike), options);
4680
+ var mergeStreamingSlots = (registered, explicit) => {
4681
+ const merged = new Map;
4682
+ for (const slot of registered)
4683
+ merged.set(slot.id, slot);
4684
+ for (const slot of explicit)
4685
+ merged.set(slot.id, slot);
4686
+ return [...merged.values()];
4687
+ };
4688
+ var withRegisteredStreamingSlots = async (renderResponse, options = {}) => {
4689
+ const { result, slots } = await runWithStreamingSlotRegistry(renderResponse);
4690
+ const explicit = options.streamingSlots ?? [];
4691
+ return withStreamingSlots(result, {
4692
+ ...options,
4693
+ streamingSlots: mergeStreamingSlots(slots, explicit)
4694
+ });
4695
+ };
4620
4696
 
4621
- if (pageHasRawStreamingSlots) {
4622
- window.__ABS_SLOT_HYDRATION_PENDING__ = false;
4623
- if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
4624
- requestAnimationFrame(function() {
4625
- window.__ABS_SLOT_FLUSH__();
4626
- });
4697
+ // src/core/streamingSlotWarningScope.ts
4698
+ init_logger();
4699
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4700
+ var STREAMING_SLOT_WARNING_STORAGE_KEY2 = Symbol.for("absolutejs.streamingSlotWarningAsyncLocalStorage");
4701
+ var isObjectRecord4 = (value) => Boolean(value) && typeof value === "object";
4702
+ var isAsyncLocalStorage3 = (value) => isObjectRecord4(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
4703
+ var getWarningStorage = () => {
4704
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2);
4705
+ if (value === null || typeof value === "undefined") {
4706
+ return;
4707
+ }
4708
+ return isAsyncLocalStorage3(value) ? value : undefined;
4709
+ };
4710
+ var ensureWarningStorage = () => {
4711
+ const existing = getWarningStorage();
4712
+ if (existing) {
4713
+ return existing;
4714
+ }
4715
+ const storage = new AsyncLocalStorage2;
4716
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2, storage);
4717
+ return storage;
4718
+ };
4719
+ var normalizeCallsitePath2 = (value) => value.replace(`${process.cwd()}/`, "").replace(process.cwd(), "").replace(/^\.\/+/, "");
4720
+ var formatWarningCallsite = (callsite) => {
4721
+ const match = callsite.match(/^(.*?)(:\d+:\d+)$/);
4722
+ if (!match) {
4723
+ return `\x1B[36m${callsite}\x1B[0m`;
4724
+ }
4725
+ return `\x1B[36m${match[1]}\x1B[33m${match[2]}\x1B[0m`;
4726
+ };
4727
+ var extractCallsiteFromStack = (stack) => {
4728
+ const frames = stack.split(`
4729
+ `).slice(1).map((line) => line.trim());
4730
+ for (const frame of frames) {
4731
+ if (frame.includes("/node_modules/") || frame.includes("/dist/") || frame.includes("/src/react/pageHandler.") || frame.includes("/src/vue/pageHandler.") || frame.includes("/src/svelte/pageHandler.") || frame.includes("/src/angular/pageHandler.") || frame.includes("/src/core/streamingSlotWarningScope.")) {
4732
+ continue;
4627
4733
  }
4628
- } else {
4629
- bootstrapApplication(${componentClassName}, {
4630
- providers: providers
4631
- }).then(function (appRef) {
4632
- window.__ANGULAR_APP__ = appRef;
4633
- window.__ABS_SLOT_HYDRATION_PENDING__ = false;
4634
- if (typeof window.__ABS_SLOT_FLUSH__ === 'function') {
4635
- requestAnimationFrame(function() {
4636
- window.__ABS_SLOT_FLUSH__();
4637
- });
4638
- }
4639
- });
4640
- }
4641
- `.trim();
4642
- const indexHash = Bun.hash(hydration).toString(BASE_36_RADIX);
4643
- const indexUnchanged = cachedWrapper?.indexHash === indexHash;
4644
- await fs.writeFile(clientFile, hydration, "utf-8");
4645
- wrapperOutputCache.set(resolvedEntry, {
4646
- indexHash,
4647
- serverHash: serverContentHash
4648
- });
4649
- return {
4650
- clientPath: clientFile,
4651
- indexUnchanged,
4652
- serverPath: rawServerFile
4653
- };
4654
- });
4655
- const results = await Promise.all(compileTasks);
4656
- const serverPaths = results.map((r) => r.serverPath);
4657
- const clientPaths = results.map((r) => r.clientPath);
4658
- return {
4659
- allIndexesUnchanged: hmr && results.every((r) => r.indexUnchanged),
4660
- clientPaths,
4661
- serverPaths
4662
- };
4734
+ const locationMatch = frame.match(/\((\/[^)]+:\d+:\d+)\)$/) ?? frame.match(/at (\/[^ ]+:\d+:\d+)$/);
4735
+ if (locationMatch?.[1]) {
4736
+ return normalizeCallsitePath2(locationMatch[1]);
4737
+ }
4738
+ }
4739
+ return;
4663
4740
  };
4664
- var init_compileAngular = __esm(() => {
4665
- init_constants();
4666
- init_sourceMetadata();
4667
- init_lowerDeferSyntax();
4668
- init_stylePreprocessor();
4669
- devClientDir = resolveDevClientDir();
4670
- hmrClientPath = join5(devClientDir, "hmrClient.ts").replace(/\\/g, "/");
4671
- hmrRuntimePath = join5(devClientDir, "handlers", "angularRuntime.ts").replace(/\\/g, "/");
4672
- jitContentCache = new Map;
4673
- wrapperOutputCache = new Map;
4741
+ var buildMissingCollectorWarning = (primitiveName, handlerCallsite) => `${primitiveName} rendered during SSR without streaming slot collection enabled. Add { collectStreamingSlots: true } to this page handler to enable out-of-order streaming for this route.${handlerCallsite ? ` Update ${formatWarningCallsite(handlerCallsite)}.` : ""}`;
4742
+ setStreamingSlotWarningController({
4743
+ maybeWarn: (primitiveName) => {
4744
+ const store = getWarningStorage()?.getStore();
4745
+ if (!store || store.hasWarned) {
4746
+ return;
4747
+ }
4748
+ store.hasWarned = true;
4749
+ logWarn(buildMissingCollectorWarning(primitiveName, store.handlerCallsite));
4750
+ }
4674
4751
  });
4752
+ var captureStreamingSlotWarningCallsite = () => {
4753
+ if (false) {}
4754
+ const { stack } = new Error;
4755
+ if (!stack) {
4756
+ return;
4757
+ }
4758
+ return extractCallsiteFromStack(stack);
4759
+ };
4760
+ var runWithStreamingSlotWarningScope = (task, metadata) => ensureWarningStorage().run({ handlerCallsite: metadata?.handlerCallsite, hasWarned: false }, task);
4675
4761
 
4676
4762
  // src/angular/pageHandler.ts
4677
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
4678
- import { mkdir as mkdir2, symlink } from "fs/promises";
4679
- import { tmpdir } from "os";
4680
- import { basename as basename4, dirname as dirname5, join as join6, resolve as resolve7 } from "path";
4681
- var ssrDirty = false, lastSelector = "angular-page", isRecord5 = (value) => typeof value === "object" && value !== null, isAngularComponent = (value) => typeof value === "function", compilerImportPromise = null, ensureAngularCompiler = () => {
4763
+ init_ssrCache();
4764
+ init_ssrRender();
4765
+ var lastSelector = "angular-page";
4766
+ var isRecord5 = (value) => typeof value === "object" && value !== null;
4767
+ var isAngularComponent = (value) => typeof value === "function";
4768
+ var compilerImportPromise = null;
4769
+ var ensureAngularCompiler = () => {
4682
4770
  if (!compilerImportPromise) {
4683
4771
  compilerImportPromise = import("@angular/compiler");
4684
4772
  }
4685
4773
  return compilerImportPromise;
4686
- }, readAngularPageModule = (value) => isRecord5(value) ? value : null, resolveAngularSsrOutDir = () => process.env.ABSOLUTE_ANGULAR_SSR_OUTDIR ?? join6(tmpdir(), "absolutejs", "generated", "angular-ssr"), ensureAngularSsrNodeModules = async (outDir) => {
4774
+ };
4775
+ var readAngularPageModule = (value) => isRecord5(value) ? value : null;
4776
+ var resolveAngularSsrOutDir = () => process.env.ABSOLUTE_ANGULAR_SSR_OUTDIR ?? join6(tmpdir(), "absolutejs", "generated", "angular-ssr");
4777
+ var ensureAngularSsrNodeModules = async (outDir) => {
4687
4778
  const outRoot = resolve7(dirname5(dirname5(outDir)));
4688
4779
  const nodeModulesLink = join6(outRoot, "node_modules");
4689
4780
  if (process.env.ABSOLUTE_ANGULAR_SSR_OUTDIR) {
@@ -4703,7 +4794,8 @@ var ssrDirty = false, lastSelector = "angular-page", isRecord5 = (value) => type
4703
4794
  throw error;
4704
4795
  }
4705
4796
  }
4706
- }, resolveRuntimeAngularModulePath = async (pagePath) => {
4797
+ };
4798
+ var resolveRuntimeAngularModulePath = async (pagePath) => {
4707
4799
  if (!pagePath.endsWith(".ts")) {
4708
4800
  return pagePath;
4709
4801
  }
@@ -4713,10 +4805,10 @@ var ssrDirty = false, lastSelector = "angular-page", isRecord5 = (value) => type
4713
4805
  const outputs = await compileAngularFileJIT2(pagePath, outDir, process.cwd());
4714
4806
  const expectedFileName = basename4(pagePath).replace(/\.ts$/, ".js");
4715
4807
  return outputs.find((output) => output.endsWith(`/${expectedFileName}`)) ?? outputs.find((output) => output.endsWith(`\\${expectedFileName}`)) ?? outputs[0] ?? pagePath;
4716
- }, invalidateAngularSsrCache = () => {
4717
- ssrDirty = true;
4718
- clearSelectorCache();
4719
- }, angularSsrContext, handleAngularPageRequest = async (PageOrInput, pagePath, indexPath, headTag = "<head></head>", ...args) => {
4808
+ };
4809
+ var angularSsrContext = new AsyncLocalStorage3;
4810
+ setSsrContextGetter(() => angularSsrContext.getStore());
4811
+ var handleAngularPageRequest = async (PageOrInput, pagePath, indexPath, headTag = "<head></head>", ...args) => {
4720
4812
  const requestId = `angular_${Date.now()}_${Math.random().toString(BASE_36_RADIX).substring(2, RANDOM_ID_END_INDEX)}`;
4721
4813
  return angularSsrContext.run(requestId, async () => {
4722
4814
  await ensureAngularCompiler();
@@ -4743,7 +4835,8 @@ var ssrDirty = false, lastSelector = "angular-page", isRecord5 = (value) => type
4743
4835
  headTag: resolvedHeadTag,
4744
4836
  props: maybeProps
4745
4837
  });
4746
- if (ssrDirty) {
4838
+ if (isSsrCacheDirty("angular")) {
4839
+ clearSelectorCache();
4747
4840
  const script = resolvedIndexPath ? `<script>import(${JSON.stringify(resolvedIndexPath)});</script>` : "";
4748
4841
  const html = `<!DOCTYPE html><html>${resolvedHeadTag}<body><${lastSelector}></${lastSelector}>${script}</body></html>`;
4749
4842
  return new Response(html, {
@@ -4797,26 +4890,9 @@ var ssrDirty = false, lastSelector = "angular-page", isRecord5 = (value) => type
4797
4890
  }
4798
4891
  });
4799
4892
  };
4800
- var init_pageHandler = __esm(() => {
4801
- init_constants();
4802
- init_islandPageContext();
4803
- init_resolveConvention();
4804
- init_registerClientScript();
4805
- init_angularDeps();
4806
- init_lowerServerIslands();
4807
- init_devRouteRegistrationCallsite();
4808
- init_responseEnhancers();
4809
- init_streamingSlotWarningScope();
4810
- init_ssrRender();
4811
- angularSsrContext = new AsyncLocalStorage3;
4812
- setSsrContextGetter(() => angularSsrContext.getStore());
4813
- });
4814
-
4815
- // src/angular/server.ts
4816
- init_pageHandler();
4817
4893
  export {
4818
4894
  handleAngularPageRequest
4819
4895
  };
4820
4896
 
4821
- //# debugId=A6CB146D0384C6DC64756E2164756E21
4897
+ //# debugId=4F6B5E16C1BC6DAC64756E2164756E21
4822
4898
  //# sourceMappingURL=server.js.map