partial-react 0.0.0 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,465 @@
1
+ export type RendererImportMap = { imports?: Record<string, string>; scopes?: Record<string, Record<string, string>>; styles?: string[] };
2
+
3
+ // A provider contributes import-map entries. `base` providers always run; `fallback` providers only run when earlier
4
+ // providers left some required specifier unresolved, and only see (and should answer for) those `missing` specifiers.
5
+ export type ImportMapProviderContext = { code: string; missing: string[] };
6
+ export type ImportMapProvider = { kind?: "base" | "fallback"; prefetch?: () => Promise<unknown> | void; resolve: (context: ImportMapProviderContext) => RendererImportMap | Promise<RendererImportMap> };
7
+
8
+ const ESM_SH_VERSION_OVERRIDES = { "@number-flow/react": "0.6.0" } as const;
9
+ const DEFAULT_ESM_SH_EXTERNALS = ["react", "react-dom", "scheduler"] as const;
10
+ export const RUNTIME_SINGLETON_SPECIFIERS = ["react", "react-dom", "react-dom/client", "react/jsx-runtime", "react/jsx-dev-runtime", "scheduler"] as const;
11
+ export type RuntimeSingletonSpecifier = (typeof RUNTIME_SINGLETON_SPECIFIERS)[number];
12
+ export const isRuntimeSingletonSpecifier = (specifier: string): specifier is RuntimeSingletonSpecifier => RUNTIME_SINGLETON_SPECIFIERS.includes(specifier as RuntimeSingletonSpecifier);
13
+ // A trailing-slash import-map key also owns matching singleton subpaths.
14
+ export const isRuntimeSingletonImportMapKey = (specifier: string) => isRuntimeSingletonSpecifier(specifier) || (specifier.endsWith("/") && RUNTIME_SINGLETON_SPECIFIERS.some((runtimeSpecifier) => runtimeSpecifier.startsWith(specifier)));
15
+ const IDENTIFIER_CHAR_PATTERN = /[\w$]/;
16
+ const REGEX_PREFIX_WORDS = new Set(["return", "throw", "case", "delete", "typeof", "void", "new", "in", "of", "await", "yield"]);
17
+ const LOCAL_EXPORT_KEYWORDS = ["abstract", "async", "class", "const", "declare", "default", "enum", "function", "interface", "let", "namespace", "var"];
18
+
19
+ export const isBareModuleSpecifier = (specifier: string) => !specifier.startsWith(".") && !specifier.startsWith("/") && !/^(?:[a-z][a-z\d+.-]*:|#)/i.test(specifier);
20
+ export const getBarePackageName = (specifier: string) => (specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0] || specifier);
21
+ // Shared #1178 contract: /src/… and /node_modules/… targets are root-relative disk paths each engine rebases against
22
+ // its own root (dev: Vite's resolved root; build: cwd). Single-sourced so a new local prefix lands in both engines.
23
+ export const isLocalRootRelativeTarget = (target: string) => target.startsWith("/src/") || target.startsWith("/node_modules/");
24
+ const canUseEsmShFallback = (specifier: string) => isBareModuleSpecifier(specifier) && !specifier.startsWith("@/");
25
+
26
+ const isKeywordAt = (code: string, index: number, keyword: string) => code.startsWith(keyword, index) && !IDENTIFIER_CHAR_PATTERN.test(code[index - 1] ?? "") && !IDENTIFIER_CHAR_PATTERN.test(code[index + keyword.length] ?? "");
27
+
28
+ const skipLineComment = (code: string, index: number) => {
29
+ const newlineIndex = code.indexOf("\n", index + 2);
30
+ return newlineIndex === -1 ? code.length : newlineIndex;
31
+ };
32
+
33
+ const skipBlockComment = (code: string, index: number) => {
34
+ const closeIndex = code.indexOf("*/", index + 2);
35
+ return closeIndex === -1 ? code.length : closeIndex + 2;
36
+ };
37
+
38
+ const skipWhitespaceAndComments = (code: string, index: number) => {
39
+ while (index < code.length) {
40
+ if (/\s/.test(code[index])) {
41
+ index += 1;
42
+ continue;
43
+ }
44
+ if (code[index] === "/" && code[index + 1] === "/") {
45
+ index = skipLineComment(code, index);
46
+ continue;
47
+ }
48
+ if (code[index] === "/" && code[index + 1] === "*") {
49
+ index = skipBlockComment(code, index);
50
+ continue;
51
+ }
52
+ break;
53
+ }
54
+ return index;
55
+ };
56
+
57
+ const readStringLiteral = (code: string, index: number) => {
58
+ const quote = code[index];
59
+ if (quote !== '"' && quote !== "'") return null;
60
+ let value = "";
61
+ index += 1;
62
+ while (index < code.length) {
63
+ const char = code[index];
64
+ if (char === "\\") {
65
+ value += code.slice(index, index + 2);
66
+ index += 2;
67
+ continue;
68
+ }
69
+ if (char === quote) return { value, end: index + 1, terminated: true };
70
+ value += char;
71
+ index += 1;
72
+ }
73
+ // Unterminated literal (a streamed import mid-chunk, e.g. `import X from "https://x/Foo.ts`). Report end so scanning
74
+ // still advances past it, but flag it so callers don't treat a half-typed specifier as a real import to fetch.
75
+ return { value, end: code.length, terminated: false };
76
+ };
77
+
78
+ const skipTemplateLiteral = (code: string, index: number, onExpression?: (start: number, end: number) => void) => {
79
+ index += 1;
80
+ while (index < code.length) {
81
+ if (code[index] === "\\") {
82
+ index += 2;
83
+ continue;
84
+ }
85
+ if (code[index] === "`") return index + 1;
86
+ if (code[index] === "$" && code[index + 1] === "{") {
87
+ const expressionStart = index + 2;
88
+ const expressionEnd = findBalancedBlockEnd(code, index + 1, "{", "}");
89
+ onExpression?.(expressionStart, Math.max(expressionStart, expressionEnd - 1));
90
+ index = expressionEnd;
91
+ continue;
92
+ }
93
+ index += 1;
94
+ }
95
+ return code.length;
96
+ };
97
+
98
+ const findBalancedBlockEnd = (code: string, index: number, opener: string, closer: string) => {
99
+ let depth = 0;
100
+ while (index < code.length) {
101
+ const char = code[index];
102
+ if (char === "/" && code[index + 1] === "/") {
103
+ index = skipLineComment(code, index);
104
+ continue;
105
+ }
106
+ if (char === "/" && code[index + 1] === "*") {
107
+ index = skipBlockComment(code, index);
108
+ continue;
109
+ }
110
+ if (isLikelyRegexLiteralStart(code, index)) {
111
+ index = skipRegexLiteral(code, index);
112
+ continue;
113
+ }
114
+ if (char === '"' || char === "'") {
115
+ index = readStringLiteral(code, index)?.end ?? index + 1;
116
+ continue;
117
+ }
118
+ if (char === "`") {
119
+ index = skipTemplateLiteral(code, index);
120
+ continue;
121
+ }
122
+ if (char === opener) depth += 1;
123
+ if (char === closer) {
124
+ depth -= 1;
125
+ if (depth === 0) return index + 1;
126
+ }
127
+ index += 1;
128
+ }
129
+ return code.length;
130
+ };
131
+
132
+ const isLikelyRegexLiteralStart = (code: string, index: number) => {
133
+ if (code[index] !== "/" || code[index + 1] === "/" || code[index + 1] === "*") return false;
134
+ let previous = index - 1;
135
+ while (previous >= 0 && /\s/.test(code[previous])) previous -= 1;
136
+ if (previous < 0) return true;
137
+ const previousChar = code[previous];
138
+ if ("([{=,:;!&|?+-*~^<>".includes(previousChar)) return true;
139
+ if (!/[A-Za-z_$]/.test(previousChar)) return false;
140
+ let word = "";
141
+ for (let cursor = previous; cursor >= 0 && /[A-Za-z0-9_$]/.test(code[cursor]); cursor -= 1) word = code[cursor] + word;
142
+ return REGEX_PREFIX_WORDS.has(word);
143
+ };
144
+
145
+ const skipRegexLiteral = (code: string, index: number) => {
146
+ index += 1;
147
+ let inClass = false;
148
+ while (index < code.length) {
149
+ const char = code[index];
150
+ if (char === "\\") {
151
+ index += 2;
152
+ continue;
153
+ }
154
+ index += 1;
155
+ if (char === "[" && !inClass) inClass = true;
156
+ else if (char === "]" && inClass) inClass = false;
157
+ else if (char === "/" && !inClass) {
158
+ while (index < code.length && /[A-Za-z]/.test(code[index])) index += 1;
159
+ return index;
160
+ }
161
+ }
162
+ return code.length;
163
+ };
164
+
165
+ const readFromSpecifier = (code: string, index: number) => {
166
+ while (index < code.length) {
167
+ const char = code[index];
168
+ if (char === ";") return null;
169
+ if (char === "/" && code[index + 1] === "/") {
170
+ index = skipLineComment(code, index);
171
+ continue;
172
+ }
173
+ if (char === "/" && code[index + 1] === "*") {
174
+ index = skipBlockComment(code, index);
175
+ continue;
176
+ }
177
+ if (isLikelyRegexLiteralStart(code, index)) {
178
+ index = skipRegexLiteral(code, index);
179
+ continue;
180
+ }
181
+ if (char === '"' || char === "'") {
182
+ index = readStringLiteral(code, index)?.end ?? index + 1;
183
+ continue;
184
+ }
185
+ if (char === "`") {
186
+ index = skipTemplateLiteral(code, index);
187
+ continue;
188
+ }
189
+ if (isKeywordAt(code, index, "from")) {
190
+ const literal = readStringLiteral(code, skipWhitespaceAndComments(code, index + "from".length));
191
+ if (literal) return { specifier: literal.value, end: literal.end, terminated: literal.terminated };
192
+ index += "from".length;
193
+ continue;
194
+ }
195
+ index += 1;
196
+ }
197
+ return null;
198
+ };
199
+
200
+ const readExportFromSpecifier = (code: string, index: number) => {
201
+ let next = skipWhitespaceAndComments(code, index);
202
+ if (isKeywordAt(code, next, "type")) next = skipWhitespaceAndComments(code, next + "type".length);
203
+ if (code[next] === "*" || code[next] === "{") return readFromSpecifier(code, next);
204
+ for (const keyword of LOCAL_EXPORT_KEYWORDS) if (isKeywordAt(code, next, keyword)) return null;
205
+ return readFromSpecifier(code, next);
206
+ };
207
+
208
+ const collectModuleSpecifiers = (code: string, specifiers: Set<string>, includeSpecifier: (specifier: string) => boolean, start = 0, end = code.length) => {
209
+ for (let index = start; index < end; index += 1) {
210
+ const char = code[index];
211
+ if (char === "/" && code[index + 1] === "/") {
212
+ index = skipLineComment(code, index);
213
+ continue;
214
+ }
215
+ if (char === "/" && code[index + 1] === "*") {
216
+ index = skipBlockComment(code, index);
217
+ continue;
218
+ }
219
+ if (isLikelyRegexLiteralStart(code, index)) {
220
+ index = skipRegexLiteral(code, index);
221
+ continue;
222
+ }
223
+ if (char === '"' || char === "'") {
224
+ index = readStringLiteral(code, index)?.end ?? index;
225
+ continue;
226
+ }
227
+ if (char === "`") {
228
+ index = skipTemplateLiteral(code, index, (expressionStart, expressionEnd) => collectModuleSpecifiers(code, specifiers, includeSpecifier, expressionStart, expressionEnd));
229
+ continue;
230
+ }
231
+ if (isKeywordAt(code, index, "import")) {
232
+ const afterImport = skipWhitespaceAndComments(code, index + "import".length);
233
+ if (code[afterImport] === ".") {
234
+ index = afterImport;
235
+ continue;
236
+ }
237
+ if (code[afterImport] === "(") {
238
+ const literal = readStringLiteral(code, skipWhitespaceAndComments(code, afterImport + 1));
239
+ if (literal?.terminated && literal.value && includeSpecifier(literal.value)) specifiers.add(literal.value);
240
+ index = literal?.end ?? afterImport;
241
+ continue;
242
+ }
243
+ const sideEffect = readStringLiteral(code, afterImport);
244
+ const from = sideEffect ? { specifier: sideEffect.value, end: sideEffect.end, terminated: sideEffect.terminated } : readFromSpecifier(code, afterImport);
245
+ if (from?.terminated && from.specifier && includeSpecifier(from.specifier)) specifiers.add(from.specifier);
246
+ index = from?.end ?? afterImport;
247
+ continue;
248
+ }
249
+ if (isKeywordAt(code, index, "export")) {
250
+ const from = readExportFromSpecifier(code, index + "export".length);
251
+ if (from?.terminated && from.specifier && includeSpecifier(from.specifier)) specifiers.add(from.specifier);
252
+ index = from?.end ?? index;
253
+ }
254
+ }
255
+ };
256
+
257
+ export function extractBareModuleSpecifiers(code: string) {
258
+ const specifiers = new Set<string>();
259
+ collectModuleSpecifiers(code, specifiers, isBareModuleSpecifier);
260
+ return specifiers;
261
+ }
262
+
263
+ export function extractModuleSpecifiers(code: string) {
264
+ const specifiers = new Set<string>();
265
+ collectModuleSpecifiers(code, specifiers, () => true);
266
+ return specifiers;
267
+ }
268
+
269
+ export function hasImportMapEntry(imports: Record<string, string> | Set<string> | Map<string, string>, specifier: string) {
270
+ const keys = imports instanceof Set ? imports : imports instanceof Map ? new Set(imports.keys()) : new Set(Object.keys(imports));
271
+ if (keys.has(specifier)) return true;
272
+ for (const key of keys) if (key.endsWith("/") && specifier.startsWith(key)) return true;
273
+ return false;
274
+ }
275
+
276
+ export function toEsmShImportUrl(specifier: string, external: readonly string[] = DEFAULT_ESM_SH_EXTERNALS) {
277
+ if (!canUseEsmShFallback(specifier)) throw new Error(`Cannot create an esm.sh fallback for ${specifier}`);
278
+ const packageName = getBarePackageName(specifier);
279
+ const version = ESM_SH_VERSION_OVERRIDES[packageName as keyof typeof ESM_SH_VERSION_OVERRIDES];
280
+ const versionedSpecifier = version ? `${packageName}@${version}${specifier.slice(packageName.length)}` : specifier;
281
+ const separator = versionedSpecifier.includes("?") ? "&" : "?";
282
+ const externalParam = external.length ? `&external=${external.join(",")}` : "";
283
+ return `https://esm.sh/${versionedSpecifier}${separator}bundle&target=es2022${externalParam}`;
284
+ }
285
+
286
+ export type EsmShProbe = { alive: true } | { alive: false; detail: string };
287
+ type EsmShProbeFetch = (url: string) => Promise<Pick<Response, "ok" | "status" | "text" | "json">>;
288
+ // esm.sh 404/2xx verdicts are deterministic per specifier, so they're cached for the process lifetime; transient
289
+ // fail-open verdicts (5xx/rate-limit/network) are evicted on resolve so they don't pin. Tests inject a fetcher and
290
+ // must use per-test specifiers to dodge the shared cache.
291
+ const esmShProbeCache = new Map<string, Promise<EsmShProbe | null>>();
292
+
293
+ // A dead entry usually means the model hallucinated the package or its layout; the registry's real subpaths are the
294
+ // heal signal that lets it rewrite the import in one shot.
295
+ const MAX_HINT_SUBPATHS = 8; // enough real subpaths for the model to spot the right one without bloating the diagnostic
296
+ const registryExportsHint = async (packageName: string, fetcher: EsmShProbeFetch) => {
297
+ const response = await fetcher(`https://registry.npmjs.org/${packageName}/latest`);
298
+ if (!response.ok) return response.status === 404 ? "the package does not exist on npm" : "";
299
+ const { exports: exportsMap } = (await response.json()) as { exports?: Record<string, unknown> };
300
+ const subpaths = Object.keys(exportsMap ?? {}).filter((key) => key.startsWith("./"));
301
+ return subpaths.length ? `its real exports subpaths are ${subpaths.slice(0, MAX_HINT_SUBPATHS).join(", ")}${subpaths.length > MAX_HINT_SUBPATHS ? `, … (${subpaths.length} total)` : ""}` : "";
302
+ };
303
+
304
+ // Would the esm.sh fallback actually answer this specifier at render time? Null means the fallback never applies
305
+ // (relative path, `@/` alias) — the caller should leave its own resolution verdict alone. Only a deterministic 404
306
+ // condemns an import: network failures and 5xx must not fail checks that run offline or during an esm.sh incident. #1372
307
+ export const probeEsmShSpecifier = (specifier: string, fetcher: EsmShProbeFetch = fetch): Promise<EsmShProbe | null> => {
308
+ let probe = esmShProbeCache.get(specifier);
309
+ if (!probe) {
310
+ probe = (async (): Promise<EsmShProbe | null> => {
311
+ let url: string;
312
+ try {
313
+ url = toEsmShImportUrl(specifier);
314
+ } catch {
315
+ return null;
316
+ }
317
+ // A non-404 status esm.sh can't build deterministically (5xx incident, 429/403 npm rate-limit) or a network
318
+ // failure fails open so offline `check` still passes, but that verdict isn't deterministic; evict it so a
319
+ // genuinely-dead import isn't pinned `alive` for the host's lifetime.
320
+ const failOpenTransiently = (): EsmShProbe => {
321
+ esmShProbeCache.delete(specifier);
322
+ return { alive: true };
323
+ };
324
+ try {
325
+ const response = await fetcher(url);
326
+ if (response.status === 404) {
327
+ const body = (await response.text()).trim().split("\n")[0];
328
+ const hint = await registryExportsHint(getBarePackageName(specifier), fetcher).catch(() => "");
329
+ return { alive: false, detail: `The renderer's esm.sh fallback fails too (404: ${body})${hint ? `; ${hint}` : ""}.` };
330
+ }
331
+ // Only a 2xx means esm.sh actually resolved the build; anything else joins the fail-open path above.
332
+ return response.ok ? { alive: true } : failOpenTransiently();
333
+ } catch {
334
+ return failOpenTransiently();
335
+ }
336
+ })();
337
+ esmShProbeCache.set(specifier, probe);
338
+ }
339
+ return probe;
340
+ };
341
+
342
+ // `build` fetch-bundles remote http(s) module imports and dev/the runtime import them directly, so the URL itself is
343
+ // the authority to consult before condemning a remote specifier's TS2307 (#1468). Same doctrine as the esm.sh probe:
344
+ // only a deterministic 404 condemns; transient verdicts (5xx/rate-limit/network) fail open and are evicted so they don't pin.
345
+ const remoteModuleProbeCache = new Map<string, Promise<EsmShProbe>>();
346
+ export const probeRemoteModuleUrl = (url: string, fetcher: EsmShProbeFetch = fetch): Promise<EsmShProbe> => {
347
+ let probe = remoteModuleProbeCache.get(url);
348
+ if (!probe) {
349
+ probe = (async (): Promise<EsmShProbe> => {
350
+ const failOpenTransiently = (): EsmShProbe => {
351
+ remoteModuleProbeCache.delete(url);
352
+ return { alive: true };
353
+ };
354
+ try {
355
+ const response = await fetcher(url);
356
+ if (response.status === 404) return { alive: false, detail: `The renderer's remote module fetch fails too (404: ${(await response.text()).trim().split("\n")[0]}).` };
357
+ return response.ok ? { alive: true } : failOpenTransiently();
358
+ } catch {
359
+ return failOpenTransiently();
360
+ }
361
+ })();
362
+ remoteModuleProbeCache.set(url, probe);
363
+ }
364
+ return probe;
365
+ };
366
+
367
+ // One probe for every specifier `check`'s local TS resolution can't see: remote http(s) URLs consult the origin itself,
368
+ // bare specifiers consult the esm.sh fallback, anything else (relative path, `@/` alias) keeps the caller's own verdict.
369
+ export const probeImportSpecifier = (specifier: string, fetcher: EsmShProbeFetch = fetch): Promise<EsmShProbe | null> => (/^https?:\/\//i.test(specifier) ? probeRemoteModuleUrl(specifier, fetcher) : probeEsmShSpecifier(specifier, fetcher));
370
+
371
+ export function prepareRendererImportMap(map: RendererImportMap | null | undefined, baseUrl = typeof location === "undefined" ? undefined : location.href) {
372
+ const resolveTarget = (target: string) => (baseUrl ? new URL(target, baseUrl).href : target);
373
+ const resolveEntries = (entries: Record<string, string>) => Object.fromEntries(Object.entries(entries).map(([specifier, target]) => [specifier, resolveTarget(target)]));
374
+ const imports = resolveEntries(map?.imports ?? {});
375
+ const styles = map?.styles?.map(resolveTarget);
376
+ const scopes = map?.scopes && Object.fromEntries(Object.entries(map.scopes).map(([scope, entries]) => [scope, resolveEntries(entries)]));
377
+ return { imports, ...(scopes ? { scopes } : {}), ...(styles?.length ? { styles } : {}) };
378
+ }
379
+
380
+ export function literalImportMap(map: RendererImportMap): ImportMapProvider {
381
+ return { resolve: () => map };
382
+ }
383
+
384
+ // Loads a remote/JSON import map once. `prefetch()` and `resolve()` share the in-flight promise so an idle-time
385
+ // prefetch and a later render both reuse the same fetch instead of hitting the network twice.
386
+ export function urlImportMap(source: string, options?: { kind?: ImportMapProvider["kind"]; fetch?: (source: string) => Promise<Pick<Response, "ok" | "status" | "statusText" | "json">> }): ImportMapProvider {
387
+ const fetcher = options?.fetch ?? fetch;
388
+ let loadPromise: Promise<RendererImportMap> | undefined;
389
+ const load = () =>
390
+ (loadPromise ??= (async () => {
391
+ const response = await fetcher(source);
392
+ if (!response.ok) throw new Error(`Failed to load import map ${source}: ${response.status} ${response.statusText}`);
393
+ const baseUrl = typeof location === "undefined" ? source : new URL(source, location.href).href;
394
+ return prepareRendererImportMap((await response.json()) as RendererImportMap, baseUrl);
395
+ })());
396
+ return { kind: options?.kind ?? "base", prefetch: load, resolve: load };
397
+ }
398
+
399
+ // Node-only: resolve `packageName`'s package.json#genui.importMap into a provider. Relative targets (./dist/…) are
400
+ // rebased to absolute disk paths so Vite/Rollup can load them; absolute paths and URLs pass through. Throws if the
401
+ // package declares no genui.importMap. Resolution is from the caller's cwd (where the user installed the package),
402
+ // not this file's location — so `bunx @genui/cli -i @macaron/ui` finds the user's package, not the CLI's. node:
403
+ // imports stay inside resolve() so this module remains browser-bundleable.
404
+ export function packageImportMap(packageName: string, options?: { resolve?: (name: string) => string }): ImportMapProvider {
405
+ return {
406
+ resolve: async () => {
407
+ const [{ createRequire }, { readFile }, { dirname, resolve: resolvePath }] = await Promise.all([import("node:module"), import("node:fs/promises"), import("node:path")]);
408
+ const resolveName = options?.resolve ?? createRequire(resolvePath("package.json")).resolve;
409
+ const manifestPath = resolveName(`${packageName}/package.json`);
410
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as { genui?: { importMap?: RendererImportMap } };
411
+ const importMap = manifest.genui?.importMap;
412
+ if (!importMap) throw new Error(`${packageName} has no package.json#genui.importMap — add it to declare the GenUI importmap contract`);
413
+ const packageDir = dirname(manifestPath);
414
+ const rebase = (target: string) => (target.startsWith(".") ? resolvePath(packageDir, target) : target);
415
+ return { imports: Object.fromEntries(Object.entries(importMap.imports ?? {}).map(([specifier, target]) => [specifier, rebase(target)])), styles: importMap.styles?.map(rebase) };
416
+ },
417
+ };
418
+ }
419
+
420
+ // esm.sh fallback only answers for `missing` specifiers, so the resolver can merge its output without re-checking
421
+ // coverage. In dev, locally installed packages are preferred so peer deps like React stay on the preview's runtime.
422
+ export function esmShFallback(options?: { external?: readonly string[]; hasLocalPackage?: (packageName: string) => Promise<boolean> }): ImportMapProvider {
423
+ return {
424
+ kind: "fallback",
425
+ resolve: async ({ missing }) => {
426
+ const entries = await Promise.all(
427
+ missing.filter(canUseEsmShFallback).map(async (specifier) => {
428
+ const isLocal = await options?.hasLocalPackage?.(getBarePackageName(specifier));
429
+ return [specifier, isLocal ? `/node_modules/${specifier}` : toEsmShImportUrl(specifier, options?.external)] as const;
430
+ }),
431
+ );
432
+ return { imports: Object.fromEntries(entries) };
433
+ },
434
+ };
435
+ }
436
+
437
+ export function createImportMapResolver(providers: ImportMapProvider[]) {
438
+ return {
439
+ // Idle/build-time warmup only touches base providers. Fallback providers stay lazy until resolve() has scanned the
440
+ // TSX for missing specifiers, so prefetching them would fetch remote maps the rendered code may never reference.
441
+ prefetch: () => Promise.all(providers.filter((provider) => provider.kind !== "fallback").map((provider) => provider.prefetch?.())).then(() => undefined),
442
+ async resolve({ code = "" }: { code?: string } = {}) {
443
+ const required = [...extractBareModuleSpecifiers(code)];
444
+ let imports: Record<string, string> = {};
445
+ let scopes: RendererImportMap["scopes"];
446
+ let styles: string[] | undefined;
447
+ for (const provider of providers) {
448
+ const covered = new Set(Object.keys(imports));
449
+ const missing = required.filter((specifier) => !hasImportMapEntry(covered, specifier));
450
+ if (provider.kind === "fallback" && missing.length === 0) continue;
451
+ const next = await provider.resolve({ code, missing });
452
+ imports = { ...imports, ...next.imports };
453
+ // scopes is an advanced compat field with no producer today, so a later provider replaces an earlier one's
454
+ // entries for the same scope key rather than deep-merging them. Revisit if two providers ever both emit scopes.
455
+ if (next.scopes) scopes = { ...scopes, ...next.scopes };
456
+ if (next.styles?.length) styles = [...(styles ?? []), ...next.styles];
457
+ }
458
+ return { imports, ...(scopes ? { scopes } : {}), ...(styles?.length ? { styles: [...new Set(styles)] } : {}) };
459
+ },
460
+ };
461
+ }
462
+
463
+ export async function mergeFallbackImports(imports: Record<string, string>, code: string, options?: { hasLocalPackage?: (packageName: string) => Promise<boolean> }) {
464
+ return (await createImportMapResolver([literalImportMap({ imports }), esmShFallback(options)]).resolve({ code })).imports;
465
+ }
@@ -0,0 +1,120 @@
1
+ import { createTsxCompiler, type TsxCompiler } from "./compiler";
2
+ import { esmShFallback, extractModuleSpecifiers, isBareModuleSpecifier, isRuntimeSingletonSpecifier, type ImportMapProvider, type RendererImportMap } from "./importMap";
3
+
4
+ // A remote https module worth compiling is one that ships source the browser can't `import` directly. Already-JS URLs
5
+ // (esm.sh builds, .mjs) import natively, so they pass through; only these source extensions need a transpile pass.
6
+ // Only the path decides — a source extension inside a query/hash (`?path=lib/index.ts`) belongs to a native URL that must
7
+ // pass through, not a source module to compile. Splitting off `[?#]` keeps `a.tsx?v=1` matching while dropping that case.
8
+ const REMOTE_SOURCE_EXTENSION = /\.(?:tsx|ts|jsx|mts|cts)$/;
9
+ export const isRemoteSourceModuleSpecifier = (specifier: string) => /^https?:\/\//.test(specifier) && REMOTE_SOURCE_EXTENSION.test(specifier.split(/[?#]/, 1)[0]);
10
+ // The compiler picks its parser from the filename extension, but `filename` must be the post-redirect URL (to rebase
11
+ // relative imports) which a CDN often strips to a signed, extension-less path — so JSX/TS in a redirected module would
12
+ // parse as plain JS and fail. Derive `lang` from the REQUEST URL, which always carries a real source extension, and pass
13
+ // it explicitly so the parser is fixed regardless of where the fetch redirected to.
14
+ const langFromRemoteUrl = (url: string): "ts" | "tsx" | "jsx" => {
15
+ const ext = REMOTE_SOURCE_EXTENSION.exec(url.split(/[?#]/, 1)[0])?.[0];
16
+ return ext === ".tsx" ? "tsx" : ext === ".jsx" ? "jsx" : "ts"; // .mts/.cts/.ts all parse as ts; only .tsx/.jsx enable JSX
17
+ };
18
+
19
+ // Fetches remote https TSX/TS/JSX components, compiles each to a blob: module, and hands back `{ [httpsUrl]: blobUrl }`
20
+ // so the transform's importMap rewrites the original specifiers. Recurses into a remote module's own remote imports
21
+ // (a global import graph breaks cycles even across concurrent entry branches; a per-provider cache dedupes DAGs and
22
+ // survives across renders). React runtime singletons stay bare and resolve through the page's importmap, exactly like
23
+ // the esm.sh fallback path.
24
+ export function remoteModuleImportMap(options?: { compiler?: TsxCompiler; fetch?: typeof fetch }): ImportMapProvider {
25
+ const compiler = options?.compiler ?? createTsxCompiler();
26
+ const fetcher = options?.fetch ?? fetch;
27
+ const blobByUrl = new Map<string, Promise<string>>();
28
+ // No `hasLocalPackage`: a remote module's own bare deps deliberately don't bind to the host's local /node_modules —
29
+ // third-party remote code resolves through esm.sh in every env, unlike the top-level chain's dev local-package preference.
30
+ const esmSh = esmShFallback();
31
+
32
+ // module → the remote modules it directly imports, recorded synchronously as each edge is discovered. A per-branch
33
+ // `visited` set can't catch a cycle reached through two separate entry branches (a↔b where the entry imports both) —
34
+ // each branch caches an in-flight promise before the other's traversal sees the loop, so they await each other and
35
+ // hang. This global graph makes the cross-branch cycle observable regardless of which branch discovers the edge first.
36
+ const importsOf = new Map<string, Set<string>>();
37
+ const reaches = (from: string, target: string): boolean => {
38
+ const seen = new Set<string>();
39
+ const stack = [from];
40
+ while (stack.length) {
41
+ const url = stack.pop()!;
42
+ if (url === target) return true;
43
+ if (seen.has(url)) continue;
44
+ seen.add(url);
45
+ const deps = importsOf.get(url);
46
+ if (deps) stack.push(...deps);
47
+ }
48
+ return false;
49
+ };
50
+
51
+ // Resolve a remote module's own imports to a self-contained import map, keyed by ABSOLUTE URL so the transform (given
52
+ // the module's URL as `filename`) matches them after rebasing relatives: nested remote source → blob, bare npm dep →
53
+ // esm.sh. Relative browser-native deps (./x.mjs, ./x.css) need no entry — the transform rebases them to absolute URLs
54
+ // against `filename` on its own. Runtime singletons stay bare for the page importmap; esm.sh builds pass through.
55
+ // `identityUrl` is how importers reference this module (its request URL — the key for blobByUrl, the cycle graph, and
56
+ // eviction). `rebaseUrl` is the post-redirect `response.url`, used ONLY to resolve the module's relative imports. They
57
+ // must stay separate: keying edges by `rebaseUrl` would disconnect the graph at every redirect (a redirected node's
58
+ // own edges land under its final URL while every importer refers to it by its request URL → missed cross-branch cycle).
59
+ const collect = async (code: string, identityUrl: string, rebaseUrl: string): Promise<Record<string, string>> => {
60
+ const specifiers = [...extractModuleSpecifiers(code)];
61
+ // Two passes on purpose. Pass 1 records every edge and checks cycles synchronously (no await) so a concurrent sibling
62
+ // branch sees the edges — but it starts NO async work, so a mid-loop cyclic throw can't strand an already-launched
63
+ // resolveModule() as an unhandled rejection. Pass 2 launches the fetches once the whole edge set is known valid.
64
+ let deps = importsOf.get(identityUrl);
65
+ if (!deps) importsOf.set(identityUrl, (deps = new Set()));
66
+ const bareMissing: string[] = [];
67
+ for (const specifier of specifiers) {
68
+ // Rebase only relative/absolute paths against the module URL. A bare specifier whose subpath happens to end in a
69
+ // source extension (`@acme/ui/Button.tsx`, `pkg/foo.ts`) must stay bare for esm.sh — rebasing it first would turn
70
+ // it into a bogus `https://…/pkg/foo.ts` remote fetch that 404s before the fallback can map the package.
71
+ if (isBareModuleSpecifier(specifier)) {
72
+ if (!isRuntimeSingletonSpecifier(specifier)) bareMissing.push(specifier);
73
+ continue;
74
+ }
75
+ const absolute = new URL(specifier, rebaseUrl).href;
76
+ if (!isRemoteSourceModuleSpecifier(absolute)) continue;
77
+ // A cycle exists iff the dependency can already reach this module (reaches() returns true for a direct self-import too).
78
+ if (reaches(absolute, identityUrl)) throw new Error(`Cyclic remote module import: ${absolute}`);
79
+ deps.add(absolute);
80
+ }
81
+ const [remote, bare] = await Promise.all([Promise.all([...deps].map((absolute) => resolveModule(absolute).then((blob) => [absolute, blob] as const))), esmSh.resolve({ code, missing: bareMissing })]);
82
+ return { ...bare.imports, ...Object.fromEntries(remote) };
83
+ };
84
+
85
+ const resolveModule = (url: string): Promise<string> => {
86
+ let blob = blobByUrl.get(url);
87
+ if (!blob) {
88
+ blob = (async () => {
89
+ const response = await fetcher(url);
90
+ if (!response.ok) throw new Error(`Failed to fetch remote module ${url}: ${response.status} ${response.statusText}`);
91
+ const source = await response.text();
92
+ // A CDN/raw endpoint may redirect to a versioned/storage URL; rebase the module's relative imports against the
93
+ // final `response.url` (falling back to the request URL) so `./Leaf.tsx` resolves from the right directory.
94
+ const finalUrl = response.url || url;
95
+ const imports = await collect(source, url, finalUrl);
96
+ // filename = the module's own URL so the transform rebases its relative imports against it (matching the
97
+ // absolute-keyed entries above, and turning relative browser-native imports into absolute URLs natively).
98
+ const { code } = await compiler.compile(source, { filename: finalUrl, lang: langFromRemoteUrl(url), importMap: { imports } });
99
+ return URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
100
+ })();
101
+ // A failed fetch/compile must not pin this URL for the provider's lifetime — evict the rejected promise so a
102
+ // later render retries, mirroring probeEsmShSpecifier's fail-open eviction.
103
+ blob.catch(() => {
104
+ blobByUrl.delete(url);
105
+ importsOf.delete(url);
106
+ });
107
+ blobByUrl.set(url, blob);
108
+ }
109
+ return blob;
110
+ };
111
+
112
+ // The entry code isn't fetched or compiled here — the outer resolver chain compiles it and maps its bare specifiers,
113
+ // so this provider only surfaces its remote-source imports as blob: entries (keyed by their already-absolute URL).
114
+ return {
115
+ resolve: async ({ code }): Promise<RendererImportMap> => {
116
+ const entries = await Promise.all([...extractModuleSpecifiers(code)].flatMap((specifier) => (isRemoteSourceModuleSpecifier(specifier) ? [resolveModule(specifier).then((blob) => [specifier, blob] as const)] : [])));
117
+ return { imports: Object.fromEntries(entries) };
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,25 @@
1
+ import { createContext, useContext, type Context } from "react";
2
+
3
+ export type GenUIRenderContextValue = { rendererScope: string; streamingPartialFrame: boolean; nextStreamingRenderKey?: () => string };
4
+ const defaultRendererScope = "default";
5
+ const renderContextValues = new Map<string, { complete: GenUIRenderContextValue; streaming: GenUIRenderContextValue }>();
6
+ const getRenderContextValues = (rendererScope: string) => {
7
+ const cached = renderContextValues.get(rendererScope);
8
+ if (cached) return cached;
9
+ const values = { complete: Object.freeze({ rendererScope, streamingPartialFrame: false }), streaming: Object.freeze({ rendererScope, streamingPartialFrame: true }) };
10
+ renderContextValues.set(rendererScope, values);
11
+ return values;
12
+ };
13
+ const completeRenderContextValue = getRenderContextValues(defaultRendererScope).complete;
14
+
15
+ const renderContextKey = Symbol.for("@macaron/genui-runtime:render-context");
16
+ const globalRenderContext = globalThis as typeof globalThis & { [renderContextKey]?: Context<GenUIRenderContextValue> };
17
+
18
+ export const getGenUIRenderContextValue = (streamingPartialFrame: boolean, rendererScope = defaultRendererScope, nextStreamingRenderKey?: () => string): GenUIRenderContextValue => {
19
+ if (nextStreamingRenderKey) return { rendererScope, streamingPartialFrame, nextStreamingRenderKey };
20
+ const values = getRenderContextValues(rendererScope);
21
+ return streamingPartialFrame ? values.streaming : values.complete;
22
+ };
23
+ // Production chunks can load separate copies of this module; the global symbol keeps charts and the renderer on one Context.
24
+ export const GenUIRenderContext = (globalRenderContext[renderContextKey] ??= createContext<GenUIRenderContextValue>(completeRenderContextValue));
25
+ export const useGenUIRenderContext = () => useContext(GenUIRenderContext);