summaryrefslogtreecommitdiffstats
path: root/test/server.js
blob: 720f4a0755799f6c703043fe899ccd735ba49c9d (plain)
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
/**
 * A fake cep.is, stood up with `Bun.serve` so the browser tests never touch the
 * network. Same shapes and status codes as the real API, plus the counters the
 * tests assert on.
 *
 * @module
 */

const ADDRESSES = {
  "01001000": {
    cep: "01001000",
    logradouro: "Praça da Sé",
    complemento: "lado ímpar",
    unidade: "",
    bairro: "Sé",
    localidade: "São Paulo",
    uf: "SP",
    estado: "São Paulo",
    regiao: "Sudeste",
    ibge: "3550308",
    gia: "1004",
    ddd: "11",
    siafi: "7107",
    geo: { lat: -23.567202, lon: -46.649659, raio_m: 1084, precisao: "logradouro" },
  },
  20040020: {
    cep: "20040020",
    logradouro: "Avenida Rio Branco",
    complemento: "até 0999 - lado ímpar",
    unidade: "",
    bairro: "Centro",
    localidade: "Rio de Janeiro",
    uf: "RJ",
    estado: "Rio de Janeiro",
    regiao: "Sudeste",
    ibge: "3304557",
    gia: "",
    ddd: "21",
    siafi: "6001",
  },
};

const CORS = {
  "Access-Control-Allow-Origin": "*",
  "Content-Type": "application/json; charset=utf-8",
};

/**
 * Start the fake API on an ephemeral port.
 *
 * The returned `state` is live: set `state.delays[cep]` to hold a response
 * back, or `state.force` to `{status}` to make every route fail. `requests`
 * lists every CEP asked for, and `aborted` counts the requests the browser
 * dropped mid-flight.
 *
 * @returns {{url: string, state: {requests: string[], aborted: number, delays: Record<string, number>, force: {status: number}|null}, reset: () => void, stop: () => void}}
 */
export function startApi() {
  const state = { requests: [], aborted: 0, delays: {}, force: null };

  const server = Bun.serve({
    port: 0,
    hostname: "127.0.0.1",
    async fetch(request) {
      const path = new URL(request.url).pathname.slice(1);
      state.requests.push(path);
      request.signal.addEventListener("abort", () => {
        state.aborted += 1;
      });

      const delay = state.delays[path] ?? 0;
      if (delay > 0) {
        await Bun.sleep(delay);
      }
      if (request.signal.aborted) {
        return new Response(null, { status: 499 });
      }

      if (state.force) {
        return new Response(JSON.stringify({ erro: "interno", mensagem: "falha interna" }), {
          status: state.force.status,
          headers: {
            ...CORS,
            ...(state.force.status === 429 ? { "Retry-After": "3" } : {}),
          },
        });
      }
      if (!/^\d{8}$/.test(path)) {
        return new Response(
          JSON.stringify({ erro: "cep_invalido", mensagem: "CEP deve ter 8 dígitos" }),
          { status: 400, headers: CORS },
        );
      }
      if (path === "88888888") {
        return new Response(JSON.stringify({ erro: "interno", mensagem: "falha interna" }), {
          status: 500,
          headers: CORS,
        });
      }
      if (path === "77777777") {
        return new Response(JSON.stringify({ erro: "limite", mensagem: "muitas consultas" }), {
          status: 429,
          headers: { ...CORS, "Retry-After": "3" },
        });
      }
      const address = ADDRESSES[path];
      if (!address) {
        return new Response(
          JSON.stringify({ erro: "cep_nao_encontrado", mensagem: "CEP não existe na base do DNE" }),
          { status: 404, headers: CORS },
        );
      }
      return new Response(JSON.stringify(address), { status: 200, headers: CORS });
    },
  });

  return {
    url: `http://127.0.0.1:${server.port}`,
    state,
    reset() {
      state.requests.length = 0;
      state.aborted = 0;
      state.delays = {};
      state.force = null;
    },
    stop() {
      server.stop(true);
    },
  };
}

/**
 * Serve the checkout fixture page together with a freshly built `<script>`
 * bundle of the widget, so the tests exercise the file consumers actually
 * drop into a page.
 *
 * @returns {Promise<{url: string, stop: () => void}>}
 */
export async function startPage() {
  const build = await Bun.build({
    entrypoints: [new URL("../src/global.js", import.meta.url).pathname],
    target: "browser",
    format: "iife",
  });
  if (!build.success) {
    throw new AggregateError(build.logs, "could not build the widget");
  }
  const bundle = await build.outputs[0].text();
  const fixture = await Bun.file(new URL("./fixture.html", import.meta.url).pathname).text();

  const server = Bun.serve({
    port: 0,
    hostname: "127.0.0.1",
    fetch(request) {
      const path = new URL(request.url).pathname;
      if (path === "/cepis-autofill.js") {
        return new Response(bundle, {
          headers: { "Content-Type": "text/javascript; charset=utf-8" },
        });
      }
      return new Response(fixture, { headers: { "Content-Type": "text/html; charset=utf-8" } });
    },
  });

  return {
    url: `http://127.0.0.1:${server.port}/`,
    stop() {
      server.stop(true);
    },
  };
}