aboutsummaryrefslogtreecommitdiff
path: root/packages/bun-npm/src/util.ts
blob: c36bda2b7c71e3cd800eb878a499b024cfdb1b90 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import fs from "fs";
import path, { dirname } from "path";
import { tmpdir } from "os";
import child_process from "child_process";

if (process.env["DEBUG"] !== "1") {
  console.debug = () => {};
}

export function join(...paths: (string | string[])[]): string {
  return path.join(...paths.flat(2));
}

export function tmp(): string {
  const path = fs.mkdtempSync(join(tmpdir(), "bun-"));
  console.debug("tmp", path);
  return path;
}

export function rm(path: string): void {
  console.debug("rm", path);
  try {
    fs.rmSync(path, { recursive: true });
    return;
  } catch (error) {
    console.debug("rmSync failed", error);
    // Did not exist before Node.js v14.
    // Attempt again with older, slower implementation.
  }
  let stats: fs.Stats;
  try {
    stats = fs.lstatSync(path);
  } catch (error) {
    console.debug("lstatSync failed", error);
    // The file was likely deleted, so return early.
    return;
  }
  if (!stats.isDirectory()) {
    fs.unlinkSync(path);
    return;
  }
  try {
    fs.rmdirSync(path, { recursive: true });
    return;
  } catch (error) {
    console.debug("rmdirSync failed", error);
    // Recursive flag did not exist before Node.js X.
    // Attempt again with older, slower implementation.
  }
  for (const filename of fs.readdirSync(path)) {
    rm(join(path, filename));
  }
  fs.rmdirSync(path);
}

export function rename(path: string, newPath: string): void {
  console.debug("rename", path, newPath);
  try {
    fs.renameSync(path, newPath);
    return;
  } catch (error) {
    console.debug("renameSync failed", error);
    // If there is an error, delete the new path and try again.
  }
  try {
    rm(newPath);
  } catch (error) {
    console.debug("rm failed", error);
    // The path could have been deleted already.
  }
  fs.renameSync(path, newPath);
}

export function write(
  path: string,
  content: string | ArrayBuffer | ArrayBufferView,
): void {
  console.debug("write", path);
  try {
    fs.writeFileSync(path, content);
    return;
  } catch (error) {
    console.debug("writeFileSync failed", error);
    // If there is an error, ensure the parent directory
    // exists and try again.
    try {
      fs.mkdirSync(dirname(path), { recursive: true });
    } catch (error) {
      console.debug("mkdirSync failed", error);
      // The directory could have been created already.
    }
    fs.writeFileSync(path, content);
  }
}

export function read(path: string): string {
  console.debug("read", path);
  return fs.readFileSync(path, "utf-8");
}

export function chmod(path: string, mode: fs.Mode): void {
  console.debug("chmod", path, mode);
  fs.chmodSync(path, mode);
}

export function spawn(
  cmd: string,
  args: string[],
  options: child_process.SpawnOptions = {},
): {
  exitCode: number;
  stdout: string;
  stderr: string;
} {
  console.debug("spawn", [cmd, ...args].join(" "));
  const { status, stdout, stderr } = child_process.spawnSync(cmd, args, {
    stdio: "pipe",
    encoding: "utf-8",
    ...options,
  });
  return {
    exitCode: status ?? 1,
    stdout,
    stderr,
  };
}

export type Response = {
  readonly status: number;
  arrayBuffer(): Promise<ArrayBuffer>;
  json<T>(): Promise<T>;
};

export const fetch = "fetch" in globalThis ? webFetch : nodeFetch;

async function webFetch(url: string, assert?: boolean): Promise<Response> {
  const response = await globalThis.fetch(url);
  console.debug("fetch", url, response.status);
  if (assert !== false && !isOk(response.status)) {
    throw new Error(`${response.status}: ${url}`);
  }
  return response;
}

async function nodeFetch(url: string, assert?: boolean): Promise<Response> {
  const { get } = await import("node:http");
  return new Promise((resolve, reject) => {
    get(url, (response) => {
      console.debug("get", url, response.statusCode);
      const status = response.statusCode ?? 501;
      if (response.headers.location && isRedirect(status)) {
        return nodeFetch(url).then(resolve, reject);
      }
      if (assert !== false && !isOk(status)) {
        return reject(new Error(`${status}: ${url}`));
      }
      const body: Buffer[] = [];
      response.on("data", (chunk) => {
        body.push(chunk);
      });
      response.on("end", () => {
        resolve({
          status,
          async arrayBuffer() {
            return Buffer.concat(body).buffer as ArrayBuffer;
          },
          async json() {
            const text = Buffer.concat(body).toString("utf-8");
            return JSON.parse(text);
          },
        });
      });
    }).on("error", reject);
  });
}

function isOk(status: number): boolean {
  return status === 200;
}

function isRedirect(status: number): boolean {
  switch (status) {
    case 301: // Moved Permanently
    case 308: // Permanent Redirect
    case 302: // Found
    case 307: // Temporary Redirect
    case 303: // See Other
      return true;
  }
  return false;
}