-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathrequest.ios.ts
More file actions
920 lines (840 loc) · 39.4 KB
/
request.ios.ts
File metadata and controls
920 lines (840 loc) · 39.4 KB
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
import { File, ImageSource, Utils } from '@nativescript/core';
import { CacheOptions, HttpsFormDataParam, HttpsRequest, HttpsRequestOptions, HttpsResponse, HttpsSSLPinningOptions, HttpsResponseLegacy as IHttpsResponseLegacy } from '.';
import { HttpResponseEncoding, getFilenameFromUrl, interceptors, networkInterceptors, parseJSON } from './request.common';
export { addInterceptor, addNetworkInterceptor } from './request.common';
// Error keys used by the Swift wrapper to maintain compatibility with AFNetworking
const AFNetworkingOperationFailingURLResponseErrorKey = 'AFNetworkingOperationFailingURLResponseErrorKey';
const AFNetworkingOperationFailingURLResponseDataErrorKey = 'AFNetworkingOperationFailingURLResponseDataErrorKey';
let cache: NSURLCache;
export function setCache(options?: CacheOptions) {
if (options) {
cache = NSURLCache.alloc().initWithMemoryCapacityDiskCapacityDiskPath(options.memorySize, options.diskSize, options.diskLocation);
} else {
cache = null;
}
NSURLCache.sharedURLCache = cache;
}
export function clearCache() {
NSURLCache.sharedURLCache.removeAllCachedResponses();
}
export function removeCachedResponse(url: string) {
NSURLCache.sharedURLCache.removeCachedResponseForRequest(createNSRequest(url));
}
interface Ipolicies {
def: SecurityPolicyWrapper;
secured: boolean;
secure?: SecurityPolicyWrapper;
}
const policies: Ipolicies = {
def: SecurityPolicyWrapper.defaultPolicy(),
secured: false
};
policies.def.allowInvalidCertificates = true;
policies.def.validatesDomainName = false;
const configuration = NSURLSessionConfiguration.defaultSessionConfiguration;
let manager = AlamofireWrapper.alloc().initWithConfiguration(configuration);
// Note: iOS interceptors must be native Alamofire RequestInterceptor or EventMonitor objects
// They cannot be JavaScript functions like Android OkHttp interceptors
// To use interceptors on iOS, you need to create native Swift wrapper classes
// Apply interceptors from common if they are Alamofire-compatible objects
function applyInterceptors() {
interceptors.forEach((interceptor) => {
if (interceptor && typeof interceptor === 'object' && 'adapt' in interceptor) {
manager.addInterceptor(interceptor);
}
});
networkInterceptors.forEach((monitor) => {
if (monitor && typeof monitor === 'object') {
manager.addEventMonitor(monitor);
}
});
}
// Apply any pre-existing interceptors
applyInterceptors();
export function enableSSLPinning(options: HttpsSSLPinningOptions) {
const url = NSURL.URLWithString(options.host);
manager = AlamofireWrapper.alloc().initWithConfigurationBaseURL(configuration, url);
if (!policies.secure) {
policies.secure = SecurityPolicyWrapper.policyWithPinningMode(AFSSLPinningMode.PublicKey);
policies.secure.allowInvalidCertificates = Utils.isDefined(options.allowInvalidCertificates) ? options.allowInvalidCertificates : false;
policies.secure.validatesDomainName = Utils.isDefined(options.validatesDomainName) ? options.validatesDomainName : true;
const data = NSData.dataWithContentsOfFile(options.certificate);
policies.secure.pinnedCertificates = NSSet.setWithObject(data);
}
policies.secured = true;
}
export function disableSSLPinning() {
policies.secured = false;
}
function nativeToObj(data, encoding?: HttpResponseEncoding) {
let content: any;
if (data instanceof NSDictionary) {
content = {};
data.enumerateKeysAndObjectsUsingBlock((key, value, stop) => {
content[key] = nativeToObj(value, encoding);
});
return content;
} else if (data instanceof NSArray) {
content = [];
data.enumerateObjectsUsingBlock((value, index, stop) => {
content[index] = nativeToObj(value, encoding);
});
return content;
} else if (data instanceof NSData) {
let code = NSUTF8StringEncoding; // long:4
if (encoding === HttpResponseEncoding.GBK) {
code = CFStringEncodings.kCFStringEncodingGB_18030_2000; // long:1586
} else if (encoding === HttpResponseEncoding.ASCII) {
code = NSASCIIStringEncoding;
}
let encodedString = NSString.alloc().initWithDataEncoding(data, code);
// If UTF8 string encoding fails try with ISO-8859-1
if (!encodedString) {
code = NSISOLatin1StringEncoding; // long:5
encodedString = NSString.alloc().initWithDataEncoding(data, code);
}
return encodedString.toString();
} else {
return data;
}
}
function getData(data, encoding?) {
let content: any;
if (data && data.class) {
const nEncoding = encoding === 'ascii' ? NSASCIIStringEncoding : NSUTF8StringEncoding;
if (data.enumerateKeysAndObjectsUsingBlock || data instanceof NSArray) {
const serial = NSJSONSerialization.dataWithJSONObjectOptionsError(data, NSJSONWritingOptions.PrettyPrinted);
content = NSString.alloc().initWithDataEncoding(serial, nEncoding)?.toString();
} else if (data instanceof NSData) {
content = NSString.alloc().initWithDataEncoding(data, nEncoding)?.toString();
} else {
content = data;
}
try {
content = JSON.parse(content);
} catch (ignore) {}
} else if (typeof data === 'object') {
content = JSON.stringify(data);
} else {
content = data;
}
return content;
}
function createNSRequest(url: string): NSMutableURLRequest {
return NSMutableURLRequest.alloc().initWithURL(NSURL.URLWithString(url));
}
class HttpsResponseLegacy implements IHttpsResponseLegacy {
// private callback?: com.nativescript.https.OkhttpResponse.OkHttpResponseAsyncCallback;
private tempFilePath?: string;
private downloadCompletionPromise?: Promise<void>;
private downloadCompleted: boolean = false;
constructor(
private data: NSDictionary<string, any> & NSData & NSArray<any>,
public contentLength,
private url: string,
tempFilePath?: string,
downloadCompletionPromise?: Promise<void>
) {
this.tempFilePath = tempFilePath;
this.downloadCompletionPromise = downloadCompletionPromise;
// If no download promise provided, download is already complete
if (!downloadCompletionPromise) {
this.downloadCompleted = true;
}
}
// Wait for download to complete if needed
private async waitForDownloadCompletion(): Promise<void> {
if (this.downloadCompleted) {
return;
}
if (this.downloadCompletionPromise) {
await this.downloadCompletionPromise;
this.downloadCompleted = true;
}
}
// Helper to ensure data is loaded from temp file if needed
private async ensureDataLoaded(): Promise<boolean> {
// Wait for download to complete first
await this.waitForDownloadCompletion();
// If we have data already, we're good
if (this.data) {
return true;
}
// If we have a temp file, load it into memory
if (this.tempFilePath) {
try {
this.data = NSData.dataWithContentsOfFile(this.tempFilePath) as any;
return this.data != null;
} catch (e) {
console.error('Failed to load data from temp file:', e);
return false;
}
}
return false;
}
// Synchronous version for backward compatibility
private ensureDataLoadedSync(): boolean {
// If we have data already, we're good
if (this.data) {
return true;
}
// If we have a temp file, load it into memory
if (this.tempFilePath) {
try {
this.data = NSData.dataWithContentsOfFile(this.tempFilePath) as any;
return this.data != null;
} catch (e) {
console.error('Failed to load data from temp file:', e);
return false;
}
}
return false;
}
// Helper to get temp file path or create from data
private async getTempFilePath(): Promise<string | null> {
// Wait for download to complete first
await this.waitForDownloadCompletion();
if (this.tempFilePath) {
return this.tempFilePath;
}
// If we have data but no temp file, create a temp file
if (this.data && this.data instanceof NSData) {
const tempDir = NSTemporaryDirectory();
const tempFileName = NSUUID.UUID().UUIDString;
const tempPath = tempDir + tempFileName;
const success = this.data.writeToFileAtomically(tempPath, true);
if (success) {
this.tempFilePath = tempPath;
return tempPath;
}
}
return null;
}
toArrayBufferAsync(): Promise<ArrayBuffer> {
return this.ensureDataLoaded().then(() => this.toArrayBuffer());
}
arrayBuffer: ArrayBuffer;
toArrayBuffer() {
if (!this.ensureDataLoadedSync()) {
return null;
}
if (this.arrayBuffer) {
return this.arrayBuffer;
}
if (this.data instanceof NSData) {
this.arrayBuffer = interop.bufferFromData(this.data);
} else {
this.arrayBuffer = interop.bufferFromData(NSKeyedArchiver.archivedDataWithRootObject(this.data));
}
return this.arrayBuffer;
}
stringResponse: string;
toString(encoding?: HttpResponseEncoding) {
if (!this.ensureDataLoadedSync()) {
return null;
}
if (this.stringResponse) {
return this.stringResponse;
}
if (this.jsonResponse) {
this.stringResponse = JSON.stringify(this.jsonResponse);
return this.stringResponse;
}
if (typeof this.data === 'string') {
this.stringResponse = this.data;
return this.data;
} else {
const data = nativeToObj(this.data, encoding);
if (typeof data === 'string') {
this.stringResponse = data;
} else {
this.jsonResponse = data;
this.stringResponse = JSON.stringify(data);
}
return this.stringResponse;
}
}
toStringAsync(encoding?: HttpResponseEncoding) {
return this.ensureDataLoaded().then(() => this.toString(encoding));
}
jsonResponse: any;
toJSON<T>(encoding?: HttpResponseEncoding) {
if (!this.ensureDataLoadedSync()) {
return null;
}
if (this.jsonResponse) {
return this.jsonResponse;
}
if (this.stringResponse) {
this.jsonResponse = parseJSON(this.stringResponse);
return this.jsonResponse;
}
const data = nativeToObj(this.data, encoding);
if (typeof data === 'object') {
this.jsonResponse = data;
return data;
}
this.stringResponse = data;
this.jsonResponse = data ? parseJSON(data) : null;
return this.jsonResponse as T;
}
toJSONAsync<T>(encoding?: HttpResponseEncoding) {
return this.ensureDataLoaded().then(() => this.toJSON<T>(encoding));
}
imageSource: ImageSource;
async toImage(): Promise<ImageSource> {
if (!(await this.ensureDataLoaded())) {
return Promise.resolve(null);
}
if (this.imageSource) {
return Promise.resolve(this.imageSource);
}
const r = await new Promise<ImageSource>((resolve, reject) => {
(UIImage as any).tns_decodeImageWithDataCompletion(this.data, (image) => {
if (image) {
resolve(new ImageSource(image));
} else {
reject(new Error('Response content may not be converted to an Image'));
}
});
});
this.imageSource = r;
return r;
}
file: File;
async toFile(destinationFilePath?: string): Promise<File> {
// Wait for download to complete before proceeding
await this.waitForDownloadCompletion();
if (this.file) {
return Promise.resolve(this.file);
}
const r = await new Promise<File>((resolve, reject) => {
if (!destinationFilePath) {
destinationFilePath = getFilenameFromUrl(this.url);
}
// If we have a temp file, move it to destination (efficient, no memory copy)
if (this.tempFilePath) {
try {
const fileManager = NSFileManager.defaultManager;
const destURL = NSURL.fileURLWithPath(destinationFilePath);
const tempURL = NSURL.fileURLWithPath(this.tempFilePath);
// Create parent directory if needed
const parentDir = destURL.URLByDeletingLastPathComponent;
fileManager.createDirectoryAtURLWithIntermediateDirectoriesAttributesError(parentDir, true, null);
// Remove destination if it exists
if (fileManager.fileExistsAtPath(destinationFilePath)) {
fileManager.removeItemAtPathError(destinationFilePath);
}
// Move temp file to destination
const success = fileManager.moveItemAtURLToURLError(tempURL, destURL);
if (success) {
// Clear temp path since file has been moved
this.tempFilePath = null;
resolve(File.fromPath(destinationFilePath));
} else {
reject(new Error(`Failed to move temp file to: ${destinationFilePath}`));
}
} catch (e) {
reject(new Error(`Cannot save file with path: ${destinationFilePath}. ${e}`));
}
}
// Fallback: if we have data in memory, write it
else if (this.ensureDataLoadedSync() && this.data instanceof NSData) {
const file = File.fromPath(destinationFilePath);
const result = this.data.writeToFileAtomically(destinationFilePath, true);
if (result) {
resolve(file);
} else {
reject(new Error(`Cannot save file with path: ${destinationFilePath}.`));
}
} else {
reject(new Error(`No data available to save to file: ${destinationFilePath}.`));
}
});
this.file = r;
return r;
}
}
function AFFailure(resolve, reject, httpResponse: NSHTTPURLResponse, error: NSError, url) {
if (error.code === -999) {
return reject(error);
}
let getHeaders = () => ({});
const sendi = {
httpResponse,
contentLength: httpResponse?.expectedContentLength ?? 0,
reason: error.localizedDescription,
get headers() {
return getHeaders();
}
} as any as HttpsResponse;
// Try to get response from error or use the one passed in
const response = httpResponse || (error.userInfo.valueForKey(AFNetworkingOperationFailingURLResponseErrorKey) as NSHTTPURLResponse);
if (!Utils.isNullOrUndefined(response)) {
sendi.statusCode = response.statusCode;
getHeaders = function () {
const dict = response.allHeaderFields;
if (dict) {
const headers = {};
dict.enumerateKeysAndObjectsUsingBlock((k, v) => (headers[k] = v));
return headers;
}
return null;
};
}
const data: NSDictionary<string, any> & NSData & NSArray<any> = error.userInfo.valueForKey(AFNetworkingOperationFailingURLResponseDataErrorKey);
const parsedData = getData(data);
const failingURL = error.userInfo.objectForKey('NSErrorFailingURLKey');
// Always use legacy response
if (!sendi.statusCode) {
return reject(error);
}
const failure: any = {
error,
description: error.description,
reason: error.localizedDescription,
url: failingURL ? failingURL.description : url
};
if (policies.secured === true) {
failure.description = '@nativescript-community/https > Invalid SSL certificate! ' + error.description;
}
sendi.failure = failure;
sendi.content = new HttpsResponseLegacy(data, sendi.contentLength, url);
resolve(sendi);
}
const runningRequests: { [k: string]: string } = {}; // Maps tag to request ID
export function cancelRequest(tag: string) {
const requestId = runningRequests[tag];
if (requestId) {
manager.cancelRequest(requestId);
}
}
export function cancelAllRequests() {
Object.values(runningRequests).forEach((requestId) => {
manager.cancelRequest(requestId);
});
}
export function clearCookies() {
const storage = NSHTTPCookieStorage.sharedHTTPCookieStorage;
const cookies = storage.cookies;
cookies.enumerateObjectsUsingBlock((cookie) => {
storage.deleteCookie(cookie);
});
}
export function createRequest(opts: HttpsRequestOptions): HttpsRequest {
const type = opts.headers?.['Content-Type'] ?? 'application/json';
if (type.startsWith('application/json')) {
manager.requestSerializerWrapper.httpShouldHandleCookies = opts.cookiesEnabled !== false;
manager.responseSerializerWrapper.acceptsJSON = true;
manager.responseSerializerWrapper.readingOptions = NSJSONReadingOptions.AllowFragments;
} else {
manager.requestSerializerWrapper.httpShouldHandleCookies = opts.cookiesEnabled !== false;
manager.responseSerializerWrapper.acceptsJSON = false;
}
manager.requestSerializerWrapper.allowsCellularAccess = true;
manager.securityPolicyWrapper = policies.secured === true ? policies.secure : policies.def;
if (opts.cachePolicy) {
switch (opts.cachePolicy) {
case 'noCache':
manager.setDataTaskWillCacheResponseBlock((session, task, cacheResponse) => null);
manager.requestSerializerWrapper.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData;
break;
case 'onlyCache':
manager.requestSerializerWrapper.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataDontLoad;
break;
case 'ignoreCache':
manager.requestSerializerWrapper.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData;
break;
}
} else {
manager.requestSerializerWrapper.cachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy;
}
const heads = opts.headers ?? {};
let headers: NSMutableDictionary<string, any> = null;
if (heads) {
headers = NSMutableDictionary.dictionary();
Object.keys(heads).forEach(
(key) => {
if (heads[key]) {
headers.setValueForKey(heads[key], key);
}
}
// manager.requestSerializer.setValueForHTTPHeaderField(
// heads[key] as any,
// key
// )
);
}
manager.requestSerializerWrapper.timeoutInterval = opts.timeout ? opts.timeout : 10;
const progress = opts.onProgress
? (progress: NSProgress) => {
if (opts.progressOnMainThread === false || (opts.progressOnMainThread === undefined && opts.responseOnMainThread === false)) {
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
} else {
Utils.dispatchToMainThread(() => {
opts.onProgress(progress.completedUnitCount, progress.totalUnitCount);
});
}
}
: null;
const tag = opts.tag ?? `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
// Generate request ID for tracking
const requestId = tag;
function clearRunningRequest() {
if (tag) {
delete runningRequests[tag];
}
}
return {
get nativeRequest() {
return null; // We no longer expose the task
},
cancel: () => {
const rid = runningRequests[tag];
if (rid) {
manager.cancelRequest(rid);
}
},
run(resolve, reject) {
const success = function (response: NSHTTPURLResponse, data?: any) {
clearRunningRequest();
const contentLength = response?.expectedContentLength ?? 0;
const content = new HttpsResponseLegacy(data, contentLength, opts.url);
let getHeaders = () => ({});
const sendi = {
content,
contentLength,
get headers() {
return getHeaders();
}
} as any as HttpsResponse;
if (!Utils.isNullOrUndefined(response)) {
sendi.statusCode = response.statusCode;
getHeaders = function () {
const dict = response.allHeaderFields;
if (dict) {
const headers = {};
dict.enumerateKeysAndObjectsUsingBlock((k, v) => (headers[k] = v));
return headers;
}
return null;
};
}
resolve(sendi);
// if (AFResponse.reason) {
// sendi.reason = AFResponse.reason;
// }
};
const failure = function (response: NSHTTPURLResponse, error: any) {
clearRunningRequest();
AFFailure(resolve, reject, response, error, opts.url);
};
if (type.startsWith('multipart/form-data')) {
switch (opts.method) {
case 'POST':
// we need to remove the Content-Type or the boundary wont be set correctly
headers.removeObjectForKey('Content-Type');
if (tag) {
runningRequests[tag] = requestId;
}
manager.uploadMultipart(
opts.url,
headers,
requestId,
NSNumber.numberWithBool(opts.responseOnMainThread) as any as NSNumber,
NSNumber.numberWithBool(opts.progressOnMainThread) as any as NSNumber,
(formData) => {
(opts.body as HttpsFormDataParam[]).forEach((param) => {
if (param.fileName && param.contentType) {
if (param.data instanceof NSURL) {
formData.appendPartWithFileURLNameFileNameMimeTypeError(param.data, param.parameterName, param.fileName, param.contentType);
} else if (param.data instanceof File) {
formData.appendPartWithFileURLNameFileNameMimeTypeError(NSURL.fileURLWithPath(param.data.path), param.parameterName, param.fileName, param.contentType);
} else {
let data = param.data;
if (typeof data === 'string') {
data = NSString.stringWithString(data).dataUsingEncoding(NSUTF8StringEncoding);
} else if (data instanceof ArrayBuffer) {
const buffer = new Uint8Array(data);
data = NSData.dataWithData(buffer as any);
} else if (typeof Blob !== 'undefined' && data instanceof Blob) {
// Stolen from core xhr, not sure if we should use InternalAccessor, but it provides fast access.
// @ts-expect-error missing InternalAccessor typings
const buffer = new Uint8Array(Blob.InternalAccessor.getBuffer(data).buffer.slice(0) as ArrayBuffer);
data = NSData.dataWithData(buffer as any);
}
formData.appendPartWithFileDataNameFileNameMimeType(data, param.parameterName, param.fileName, param.contentType);
}
} else {
formData.appendPartWithFormDataName(NSString.stringWithString(param.data).dataUsingEncoding(NSUTF8StringEncoding), param.parameterName);
}
});
},
progress,
success,
failure
);
break;
default:
throw new Error('method_not_supported_multipart');
}
} else if (opts.method === 'PUT') {
if (opts.body instanceof File) {
const request = createNSRequest(opts.url);
request.HTTPMethod = opts.method;
Object.keys(heads).forEach((k) => {
request.setValueForHTTPHeaderField(heads[k], k);
});
if (tag) {
runningRequests[tag] = requestId;
}
manager.uploadFile(
request,
NSURL.fileURLWithPath(opts.body.path),
requestId,
NSNumber.numberWithBool(opts.responseOnMainThread) as any as NSNumber,
NSNumber.numberWithBool(opts.progressOnMainThread) as any as NSNumber,
progress,
success,
failure
);
} else {
let data: NSData;
// TODO: add support for Buffers
if (opts.content instanceof NSData) {
data = opts.content;
} else if (typeof opts.body === 'string') {
data = NSString.stringWithString(opts.body).dataUsingEncoding(NSUTF8StringEncoding);
} else {
data = NSString.stringWithString(JSON.stringify(opts.body)).dataUsingEncoding(NSUTF8StringEncoding);
}
const request = createNSRequest(opts.url);
request.HTTPMethod = opts.method;
Object.keys(heads).forEach((k) => {
request.setValueForHTTPHeaderField(heads[k], k);
});
if (tag) {
runningRequests[tag] = requestId;
}
manager.uploadData(
request,
data,
requestId,
NSNumber.numberWithBool(opts.responseOnMainThread) as any as NSNumber,
NSNumber.numberWithBool(opts.progressOnMainThread) as any as NSNumber,
progress,
success,
failure
);
}
} else {
let dict = null;
if (opts.body) {
if (typeof opts.body === 'string') {
dict = NSJSONSerialization.JSONObjectWithDataOptionsError(NSString.stringWithString(opts.body).dataUsingEncoding(NSUTF8StringEncoding), 0 as any);
} else {
dict = NSJSONSerialization.JSONObjectWithDataOptionsError(NSString.stringWithString(JSON.stringify(opts.body)).dataUsingEncoding(NSUTF8StringEncoding), 0 as any);
}
} else if (typeof opts.content === 'string') {
dict = NSJSONSerialization.JSONObjectWithDataOptionsError(NSString.stringWithString(opts.content).dataUsingEncoding(NSUTF8StringEncoding), 0 as any);
}
// For GET requests, decide between memory and file download
if (opts.method === 'GET') {
// Check if early resolution is requested
const earlyResolve = opts.earlyResolve === true;
const sizeThreshold = opts.downloadSizeThreshold !== undefined ? opts.downloadSizeThreshold : 1024 * 1024 * 10; // Default: always use file download
// Check if conditional download is requested (threshold set and not using early resolve)
const useConditionalDownload = sizeThreshold >= 0 && !earlyResolve;
if (useConditionalDownload) {
// Use conditional download: check size and decide memory vs file
if (tag) {
runningRequests[tag] = requestId;
}
manager.requestWithConditionalDownload(
opts.method,
opts.url,
dict,
headers,
requestId,
NSNumber.numberWithBool(opts.responseOnMainThread) as any as NSNumber,
NSNumber.numberWithBool(opts.progressOnMainThread) as any as NSNumber,
sizeThreshold,
progress,
(httpResponse: NSHTTPURLResponse, responseData: any, tempFilePath: string) => {
clearRunningRequest();
const contentLength = httpResponse?.expectedContentLength || 0;
// If we got a temp file path, response was saved to file (large)
// If we got responseData, response is in memory (small)
const content = tempFilePath ? new HttpsResponseLegacy(null, contentLength, opts.url, tempFilePath) : new HttpsResponseLegacy(responseData, contentLength, opts.url);
let getHeaders = () => ({});
const sendi = {
content,
contentLength,
get headers() {
return getHeaders();
}
} as any as HttpsResponse;
if (!Utils.isNullOrUndefined(httpResponse)) {
sendi.statusCode = httpResponse.statusCode;
getHeaders = function () {
const dict = httpResponse.allHeaderFields;
if (dict) {
const headers = {};
dict.enumerateKeysAndObjectsUsingBlock((k, v) => (headers[k] = v));
return headers;
}
return null;
};
}
resolve(sendi);
},
(httpResponse: NSHTTPURLResponse, error: NSError) => {
clearRunningRequest();
failure(httpResponse, error);
}
);
} else if (earlyResolve) {
// Use early resolution: resolve when headers arrive, continue download in background
let downloadCompletionResolve: () => void;
let downloadCompletionReject: (error: Error) => void;
const downloadCompletionPromise = new Promise<void>((res, rej) => {
downloadCompletionResolve = res;
downloadCompletionReject = rej;
});
// Track the content object so we can update it when download completes
let responseContent: HttpsResponseLegacy | undefined;
if (tag) {
runningRequests[tag] = requestId;
}
manager.downloadToTempWithEarlyHeaders(
opts.method,
opts.url,
dict,
headers,
requestId,
NSNumber.numberWithBool(opts.responseOnMainThread) as any as NSNumber,
NSNumber.numberWithBool(opts.progressOnMainThread) as any as NSNumber,
sizeThreshold,
progress,
(httpResponse: NSHTTPURLResponse, contentLength: number) => {
// Headers callback - resolve request early
clearRunningRequest();
// Create response WITHOUT temp file path (download still in progress)
responseContent = new HttpsResponseLegacy(null, contentLength, opts.url, undefined, downloadCompletionPromise);
const content = responseContent;
let getHeaders = () => ({});
const sendi = {
content,
contentLength,
get headers() {
return getHeaders();
}
} as any as HttpsResponse;
if (!Utils.isNullOrUndefined(httpResponse)) {
sendi.statusCode = httpResponse.statusCode;
getHeaders = function () {
const dict = httpResponse.allHeaderFields;
if (dict) {
const headers = {};
dict.enumerateKeysAndObjectsUsingBlock((k, v) => (headers[k] = v));
return headers;
}
return null;
};
}
// Resolve immediately with headers
resolve(sendi);
},
(httpResponse: NSHTTPURLResponse, tempFilePath: string) => {
// Download completion callback - success
// Update the response content with temp file path
if (responseContent) {
(responseContent as any).tempFilePath = tempFilePath;
}
downloadCompletionResolve();
},
(httpResponse: NSHTTPURLResponse, error: NSError) => {
// Download completion callback - failure
downloadCompletionReject(new Error(error.localizedDescription));
}
);
} else {
// Standard download: wait for full download before resolving
if (tag) {
runningRequests[tag] = requestId;
}
manager.downloadToTemp(
opts.method,
opts.url,
dict,
headers,
requestId,
NSNumber.numberWithBool(opts.responseOnMainThread) as any as NSNumber,
NSNumber.numberWithBool(opts.progressOnMainThread) as any as NSNumber,
progress,
(httpResponse: NSHTTPURLResponse, tempFilePath: string) => {
clearRunningRequest();
const contentLength = httpResponse?.expectedContentLength || 0;
// Create response with temp file path (no data loaded in memory yet)
const content = new HttpsResponseLegacy(null, contentLength, opts.url, tempFilePath);
let getHeaders = () => ({});
const sendi = {
content,
contentLength,
get headers() {
return getHeaders();
}
} as any as HttpsResponse;
if (!Utils.isNullOrUndefined(httpResponse)) {
sendi.statusCode = httpResponse.statusCode;
getHeaders = function () {
const dict = httpResponse.allHeaderFields;
if (dict) {
const headers = {};
dict.enumerateKeysAndObjectsUsingBlock((k, v) => (headers[k] = v));
return headers;
}
return null;
};
}
resolve(sendi);
},
failure
);
}
} else {
// For non-GET requests, use regular request (loads into memory)
if (tag) {
runningRequests[tag] = requestId;
}
manager.request(
opts.method,
opts.url,
dict,
headers,
requestId,
NSNumber.numberWithBool(opts.responseOnMainThread) as any as NSNumber,
NSNumber.numberWithBool(opts.progressOnMainThread) as any as NSNumber,
progress,
progress,
success,
failure
);
}
}
}
};
}
export function request(opts: HttpsRequestOptions) {
return new Promise((resolve, reject) => {
try {
createRequest(opts).run(resolve, reject);
} catch (error) {
reject(error);
}
});
}
// Android only
export function getClient(opts: Partial<HttpsRequestOptions>) {
return undefined;
}