for await()

in scripts/utils/postprocess-files.cjs [106:163]


  for await (const file of walk(path.resolve(__dirname, '..', '..', 'dist'))) {
    if (!/\.([cm]?js|(\.d)?[cm]?ts)$/.test(file)) continue;

    const code = await fs.promises.readFile(file, 'utf8');

    let transformed = mapModulePaths(code, (importPath) => {
      if (file.startsWith(distSrcDir)) {
        if (importPath.startsWith(pkgImportPath)) {
          // convert self-references in dist/src to relative paths
          let relativePath = path.relative(
            path.dirname(file),
            path.join(distSrcDir, importPath.substring(pkgImportPath.length)),
          );
          if (!relativePath.startsWith('.')) relativePath = `./${relativePath}`;
          return relativePath;
        }
        return importPath;
      }
      if (importPath.startsWith('.')) {
        // add explicit file extensions to relative imports
        const { dir, name } = path.parse(importPath);
        const ext = /\.mjs$/.test(file) ? '.mjs' : '.js';
        return `${dir}/${name}${ext}`;
      }
      return importPath;
    });

    if (file.startsWith(distSrcDir) && !file.endsWith('_shims/index.d.ts')) {
      // strip out `unknown extends Foo ? never :` shim guards in dist/src
      // to prevent errors from appearing in Go To Source
      transformed = transformed.replace(
        new RegExp('unknown extends (typeof )?\\S+ \\? \\S+ :\\s*'.replace(/\s+/, '\\s+'), 'gm'),
        // replace with same number of characters to avoid breaking source maps
        (match) => ' '.repeat(match.length),
      );
    }

    if (file.endsWith('.d.ts')) {
      // work around bad tsc behavior
      // if we have `import { type Readable } from 'openai/_shims/index'`,
      // tsc sometimes replaces `Readable` with `import("stream").Readable` inline
      // in the output .d.ts
      transformed = transformed.replace(/import\("stream"\).Readable/g, 'Readable');
    }

    // strip out lib="dom" and types="node" references; these are needed at build time,
    // but would pollute the user's TS environment
    transformed = transformed.replace(
      /^ *\/\/\/ *<reference +(lib="dom"|types="node").*?\n/gm,
      // replace with same number of characters to avoid breaking source maps
      (match) => ' '.repeat(match.length - 1) + '\n',
    );

    if (transformed !== code) {
      await fs.promises.writeFile(file, transformed, 'utf8');
      console.error(`wrote ${path.relative(process.cwd(), file)}`);
    }
  }