@fluwa-tool/sdk 1.0.32 → 1.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -77,72 +77,151 @@ class XMLHttpRequestInterceptor {
77
77
  appName: self.appName,
78
78
  source: types_1.RequestSource.REAL,
79
79
  };
80
- // Logar início imediatamente (não esperar mockResolver)
80
+ // Logar início imediatamente
81
81
  self.requestLogger.logStart(requestMetadata).catch(() => { });
82
- // Verificar se mock (não afeta logging)
82
+ // Interceptar mudanças de estado (para request real)
83
+ const originalOnReadyStateChange = xhr.onreadystatechange;
84
+ // Verificar se há mock ANTES de enviar a requisição
83
85
  self.mockResolver.resolve(method, url)
84
86
  .then((mockResponse) => {
85
87
  if (mockResponse) {
86
- // mock disponível
88
+ // Mock encontrado - simular resposta ao invés de fazer request real
87
89
  requestMetadata.source = types_1.RequestSource.MOCK;
88
90
  requestMetadata.status = mockResponse.status || 200;
89
91
  requestMetadata.response = mockResponse.response;
92
+ // Guardar no xhr para depois extrair no handler
93
+ xhr._fluwaMockResponse = mockResponse;
94
+ xhr._fluwaMockStatus = mockResponse.status || 200;
90
95
  // Aplicar delay se configurado
91
- if (mockResponse.delay) {
92
- return new Promise(resolve => setTimeout(resolve, mockResponse.delay));
93
- }
96
+ const delay = mockResponse.delay || 0;
97
+ // Simular a resposta mockada assincronamente
98
+ setTimeout(() => {
99
+ try {
100
+ // Simular readyState = 4 (completo)
101
+ // Criar um evento fake que faz parecer que a resposta chegou
102
+ const mockEvent = new Event('readystatechange');
103
+ // Injetar dados fake no xhr para simular resposta
104
+ Object.defineProperty(xhr, 'readyState', {
105
+ value: 4,
106
+ configurable: true
107
+ });
108
+ Object.defineProperty(xhr, 'status', {
109
+ value: mockResponse.status || 200,
110
+ configurable: true
111
+ });
112
+ Object.defineProperty(xhr, 'statusText', {
113
+ value: 'OK',
114
+ configurable: true
115
+ });
116
+ Object.defineProperty(xhr, 'responseText', {
117
+ value: JSON.stringify(mockResponse.response),
118
+ configurable: true
119
+ });
120
+ Object.defineProperty(xhr, 'response', {
121
+ value: mockResponse.response,
122
+ configurable: true
123
+ });
124
+ const duration = Date.now() - (xhr._fluwaStartTime || 0);
125
+ requestMetadata.duration = duration;
126
+ // Registrar completamento do mock
127
+ self.requestLogger.logComplete(requestMetadata).catch(() => { });
128
+ // Chamar handler original para processar a "resposta"
129
+ if (originalOnReadyStateChange) {
130
+ originalOnReadyStateChange.call(xhr, mockEvent);
131
+ }
132
+ }
133
+ catch (error) {
134
+ self.logger.debug('Erro ao simular mock response:', error);
135
+ }
136
+ }, delay);
137
+ // Não chamar send original para requisições mockadas
138
+ return;
94
139
  }
95
- })
96
- .catch(() => {
97
- // Erro ao verificar mock, continua com request real
98
- });
99
- // Interceptar mudanças de estado
100
- const originalOnReadyStateChange = xhr.onreadystatechange;
101
- xhr.onreadystatechange = function () {
102
- if (xhr.readyState === 4) {
103
- // Requisição completou
104
- requestMetadata.status = xhr.status;
105
- // Tentar extrair response
106
- try {
107
- // responseText só está disponível para responseType 'text' ou '' (padrão)
108
- if (xhr.responseType === '' || xhr.responseType === 'text') {
109
- if (xhr.responseText) {
110
- requestMetadata.response = self.safeParseBody(xhr.responseText);
140
+ // NÃO há mock - fazer request real normalmente
141
+ xhr.onreadystatechange = function (event) {
142
+ if (xhr.readyState === 4) {
143
+ // Requisição completou
144
+ requestMetadata.status = xhr.status;
145
+ // Tentar extrair response
146
+ try {
147
+ if (xhr.responseType === '' || xhr.responseType === 'text') {
148
+ if (xhr.responseText) {
149
+ requestMetadata.response = self.safeParseBody(xhr.responseText);
150
+ }
151
+ }
152
+ else if (xhr.response) {
153
+ if (typeof xhr.response === 'string') {
154
+ requestMetadata.response = self.safeParseBody(xhr.response);
155
+ }
156
+ else {
157
+ requestMetadata.response = `[${xhr.responseType}]`;
158
+ }
111
159
  }
112
160
  }
113
- else if (xhr.response) {
114
- // Para blob, arraybuffer, document, etc., usar xhr.response
115
- if (typeof xhr.response === 'string') {
116
- requestMetadata.response = self.safeParseBody(xhr.response);
161
+ catch (e) {
162
+ try {
163
+ if (xhr.responseText) {
164
+ requestMetadata.response = xhr.responseText;
165
+ }
117
166
  }
118
- else {
119
- // Não consegue serializar blob/arraybuffer, apenas registra tipo
120
- requestMetadata.response = `[${xhr.responseType}]`;
167
+ catch {
168
+ requestMetadata.response = undefined;
121
169
  }
122
170
  }
171
+ const duration = Date.now() - (xhr._fluwaStartTime || 0);
172
+ requestMetadata.duration = duration;
173
+ self.requestLogger.logComplete(requestMetadata).catch(() => { });
123
174
  }
124
- catch (e) {
125
- // Em caso de erro, tenta responseText como fallback
175
+ // Chamar handler original
176
+ if (originalOnReadyStateChange) {
177
+ originalOnReadyStateChange.call(xhr, event);
178
+ }
179
+ };
180
+ // Chamar send original para requisições reais
181
+ return self.originalSend.apply(xhr, [body]);
182
+ })
183
+ .catch(() => {
184
+ // Erro ao verificar mock, continua com request real
185
+ xhr.onreadystatechange = function (event) {
186
+ if (xhr.readyState === 4) {
187
+ requestMetadata.status = xhr.status;
126
188
  try {
127
- if (xhr.responseText) {
128
- requestMetadata.response = xhr.responseText;
189
+ if (xhr.responseType === '' || xhr.responseType === 'text') {
190
+ if (xhr.responseText) {
191
+ requestMetadata.response = self.safeParseBody(xhr.responseText);
192
+ }
193
+ }
194
+ else if (xhr.response) {
195
+ if (typeof xhr.response === 'string') {
196
+ requestMetadata.response = self.safeParseBody(xhr.response);
197
+ }
198
+ else {
199
+ requestMetadata.response = `[${xhr.responseType}]`;
200
+ }
129
201
  }
130
202
  }
131
- catch {
132
- requestMetadata.response = undefined;
203
+ catch (e) {
204
+ try {
205
+ if (xhr.responseText) {
206
+ requestMetadata.response = xhr.responseText;
207
+ }
208
+ }
209
+ catch {
210
+ requestMetadata.response = undefined;
211
+ }
133
212
  }
213
+ const duration = Date.now() - (xhr._fluwaStartTime || 0);
214
+ requestMetadata.duration = duration;
215
+ self.requestLogger.logComplete(requestMetadata).catch(() => { });
134
216
  }
135
- const duration = Date.now() - (xhr._fluwaStartTime || 0);
136
- requestMetadata.duration = duration;
137
- self.requestLogger.logComplete(requestMetadata).catch(() => { });
138
- }
139
- // Chamar handler original
140
- if (originalOnReadyStateChange) {
141
- originalOnReadyStateChange.call(this);
142
- }
143
- };
144
- // Chamar send original
145
- return self.originalSend.apply(this, [body]);
217
+ if (originalOnReadyStateChange) {
218
+ originalOnReadyStateChange.call(xhr, event);
219
+ }
220
+ };
221
+ return self.originalSend.apply(xhr, [body]);
222
+ });
223
+ // Retornar undefined (send é síncrono mas processamento é async)
224
+ return;
146
225
  };
147
226
  this.isInstalled = true;
148
227
  this.logger.success('XMLHttpRequest interceptor instalado');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluwa-tool/sdk",
3
- "version": "1.0.32",
3
+ "version": "1.0.34",
4
4
  "description": "Fluwa DevTools SDK for network interception and mocking",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",