MCPcopy
hub / github.com/unpkg/unpkg / rewriteEsmImports

Function rewriteEsmImports

packages/unpkg-files/src/lib/esm-build-service.ts:312–352  ·  view source on GitHub ↗
(
  code: string,
  registry: string,
  origin: string,
  dependencies: Record<string, string>,
  options: NormalizedBuildOptions
)

Source from the content-addressed store, hash-verified

310}
311
312export async function rewriteEsmImports(
313 code: string,
314 registry: string,
315 origin: string,
316 dependencies: Record<string, string>,
317 options: NormalizedBuildOptions
318): Promise<string> {
319 let [imports] = parse(code);
320 let rewrites: { start: number; end: number; value: string }[] = [];
321
322 for (let imp of imports) {
323 if (imp.n === undefined) {
324 continue;
325 }
326
327 let specifier = code.slice(imp.s, imp.e);
328 let rewriteValue: string;
329
330 if (imp.t === 2) {
331 let match = /^(["'])([^"']*)\1$/.exec(specifier);
332 if (match === null) continue;
333
334 rewriteValue = match[1] + await rewriteEsmSpecifier(match[2], registry, origin, dependencies, options) + match[1];
335 } else {
336 rewriteValue = await rewriteEsmSpecifier(specifier, registry, origin, dependencies, options);
337 }
338
339 if (rewriteValue !== specifier) {
340 rewrites.push({ start: imp.s, end: imp.e, value: rewriteValue });
341 }
342 }
343
344 rewrites.sort((a, b) => b.start - a.start);
345
346 let result = code;
347 for (let { start, end, value } of rewrites) {
348 result = result.slice(0, start) + value + result.slice(end);
349 }
350
351 return result;
352}
353
354export async function bundleSource(
355 packageDirectory: string,

Callers 3

buildEsmModuleFunction · 0.85
transformInlineEsmModuleFunction · 0.85

Calls 1

rewriteEsmSpecifierFunction · 0.85

Tested by

no test coverage detected