File size: 6,877 Bytes
d4b85c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/node/index.ts
var node_exports = {};
__export(node_exports, {
  SetupServerApi: () => SetupServerApi,
  setupServer: () => setupServer
});
module.exports = __toCommonJS(node_exports);

// src/node/SetupServerApi.ts
var import_node_async_hooks = require("async_hooks");
var import_ClientRequest = require("@mswjs/interceptors/ClientRequest");
var import_XMLHttpRequest = require("@mswjs/interceptors/XMLHttpRequest");
var import_fetch = require("@mswjs/interceptors/fetch");

// src/node/SetupServerCommonApi.ts
var import_outvariant = require("outvariant");
var import_interceptors = require("@mswjs/interceptors");
var import_SetupApi = require("../core/SetupApi.js");
var import_handleRequest = require("../core/utils/handleRequest.js");
var import_mergeRight = require("../core/utils/internal/mergeRight.js");
var import_devUtils = require("../core/utils/internal/devUtils.js");
var import_handleWebSocketEvent = require("../core/ws/handleWebSocketEvent.js");
var import_webSocketInterceptor = require("../core/ws/webSocketInterceptor.js");
var import_isHandlerKind = require("../core/utils/internal/isHandlerKind.js");
var DEFAULT_LISTEN_OPTIONS = {
  onUnhandledRequest: "warn"
};
var SetupServerCommonApi = class extends import_SetupApi.SetupApi {
  interceptor;
  resolvedOptions;
  constructor(interceptors, handlers) {
    super(...handlers);
    this.interceptor = new import_interceptors.BatchInterceptor({
      name: "setup-server",
      interceptors: interceptors.map((Interceptor) => new Interceptor())
    });
    this.resolvedOptions = {};
  }
  /**
   * Subscribe to all requests that are using the interceptor object
   */
  init() {
    this.interceptor.on(
      "request",
      async ({ request, requestId, controller }) => {
        const response = await (0, import_handleRequest.handleRequest)(
          request,
          requestId,
          this.handlersController.currentHandlers().filter((0, import_isHandlerKind.isHandlerKind)("RequestHandler")),
          this.resolvedOptions,
          this.emitter,
          {
            onPassthroughResponse(request2) {
              const acceptHeader = request2.headers.get("accept");
              if (acceptHeader) {
                const nextAcceptHeader = acceptHeader.replace(
                  /(,\s+)?msw\/passthrough/,
                  ""
                );
                if (nextAcceptHeader) {
                  request2.headers.set("accept", nextAcceptHeader);
                } else {
                  request2.headers.delete("accept");
                }
              }
            }
          }
        );
        if (response) {
          controller.respondWith(response);
        }
        return;
      }
    );
    this.interceptor.on("unhandledException", ({ error }) => {
      if (error instanceof import_devUtils.InternalError) {
        throw error;
      }
    });
    this.interceptor.on(
      "response",
      ({ response, isMockedResponse, request, requestId }) => {
        this.emitter.emit(
          isMockedResponse ? "response:mocked" : "response:bypass",
          {
            response,
            request,
            requestId
          }
        );
      }
    );
    (0, import_handleWebSocketEvent.handleWebSocketEvent)({
      getUnhandledRequestStrategy: () => {
        return this.resolvedOptions.onUnhandledRequest;
      },
      getHandlers: () => {
        return this.handlersController.currentHandlers();
      },
      onMockedConnection: () => {
      },
      onPassthroughConnection: () => {
      }
    });
  }
  listen(options = {}) {
    this.resolvedOptions = (0, import_mergeRight.mergeRight)(
      DEFAULT_LISTEN_OPTIONS,
      options
    );
    this.interceptor.apply();
    this.init();
    this.subscriptions.push(() => this.interceptor.dispose());
    import_webSocketInterceptor.webSocketInterceptor.apply();
    this.subscriptions.push(() => import_webSocketInterceptor.webSocketInterceptor.dispose());
    (0, import_outvariant.invariant)(
      [import_interceptors.InterceptorReadyState.APPLYING, import_interceptors.InterceptorReadyState.APPLIED].includes(
        this.interceptor.readyState
      ),
      import_devUtils.devUtils.formatMessage(
        'Failed to start "setupServer": the interceptor failed to apply. This is likely an issue with the library and you should report it at "%s".'
      ),
      "https://github.com/mswjs/msw/issues/new/choose"
    );
  }
  close() {
    this.dispose();
  }
};

// src/node/SetupServerApi.ts
var store = new import_node_async_hooks.AsyncLocalStorage();
var AsyncHandlersController = class {
  rootContext;
  constructor(initialHandlers) {
    this.rootContext = { initialHandlers, handlers: [] };
  }
  get context() {
    return store.getStore() || this.rootContext;
  }
  prepend(runtimeHandlers) {
    this.context.handlers.unshift(...runtimeHandlers);
  }
  reset(nextHandlers) {
    const context = this.context;
    context.handlers = [];
    context.initialHandlers = nextHandlers.length > 0 ? nextHandlers : context.initialHandlers;
  }
  currentHandlers() {
    const { initialHandlers, handlers } = this.context;
    return handlers.concat(initialHandlers);
  }
};
var SetupServerApi = class extends SetupServerCommonApi {
  constructor(handlers) {
    super(
      [import_ClientRequest.ClientRequestInterceptor, import_XMLHttpRequest.XMLHttpRequestInterceptor, import_fetch.FetchInterceptor],
      handlers
    );
    this.handlersController = new AsyncHandlersController(handlers);
  }
  boundary(callback) {
    return (...args) => {
      return store.run(
        {
          initialHandlers: this.handlersController.currentHandlers(),
          handlers: []
        },
        callback,
        ...args
      );
    };
  }
  close() {
    super.close();
    store.disable();
  }
};

// src/node/setupServer.ts
var setupServer = (...handlers) => {
  return new SetupServerApi(handlers);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SetupServerApi,
  setupServer
});
//# sourceMappingURL=index.js.map