-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.mm
580 lines (453 loc) · 19.5 KB
/
main.mm
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
//
// main.cpp
// paq-tests
//
// Created by Ben on 3/23/15.
// Copyright (c) 2015 Ben Ng. All rights reserved.
//
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#import <Foundation/Foundation.h>
#import "PseudoBrowserJSContext.h"
#import "json.h"
#import "catch.hpp"
#import "parser.h"
#import "require.h"
#import "resolve.h"
#import "pack.h"
#import "paq.h"
/**
* Executes the parser method synchronously and returns the array @[ error, ast, source ]
*/
NSArray* parseSync(NSString* input)
{
Parser* parser = new Parser(nil);
__block NSArray* cbData = nil;
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
parser->parse(input, ^(NSError *error, NSArray *literals, NSArray *expressions, NSString *source) {
cbData = @[error != nil ? error : [NSNull null], literals != nil ? literals : [NSNull null], expressions != nil ? expressions : [NSNull null], source != nil ? source : [NSNull null]];
dispatch_semaphore_signal(sema);
});
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
delete parser;
return cbData;
}
/**
* Executes the require method synchronously and returns the array @[ error, requires ]
*/
NSArray* requireSync(NSString* path, NSArray* expressions)
{
Require* require = new Require(nil);
__block NSArray* cbData = nil;
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
require->evaluateRequireExpressions(path, expressions, ^(NSError *error, NSArray *requires) {
cbData = @[error != nil ? error : [NSNull null], requires != nil ? requires : [NSNull null]];
dispatch_semaphore_signal(sema);
});
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
delete require;
return cbData;
}
NSString* evaluateTransformSync(NSString* transformString, NSString* file, NSString* source)
{
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
__block NSString* cbData = nil;
NSString* wrappedBundle = [NSString stringWithFormat:@"var global = {}, exports = {}, module={exports:exports};%@;", transformString];
JSContext* ctx = [[PseudoBrowserJSContext alloc] init];
ctx.exceptionHandler = ^(JSContext* ctx, JSValue* e) {
NSLog(@"Test Transform JS Error: %@", [e toString]);
};
[ctx evaluateScript:wrappedBundle];
ctx[@"transformCb"] = ^(JSValue* err, JSValue* data) {
cbData = [data toString];
dispatch_semaphore_signal(sema);
};
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[ctx evaluateScript:[NSString stringWithFormat:@"module.exports(%@, %@, transformCb); __PBSJC_drain()", JSONString(file), JSONString(source)]];
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
ctx.exceptionHandler = nil;
ctx[@"transformCb"] = nil;
ctx = nil;
return cbData;
}
/**
* Parser
*/
TEST_CASE("Parser returns require statements for valid code", "[parser]")
{
NSArray* result = parseSync(@"require('taco') && require(path.join(__dirname, 'path'))");
NSError* err = result[0];
NSArray* literals = result[1];
NSArray* expressions = result[2];
REQUIRE([err isKindOfClass:NSNull.class]);
REQUIRE(literals.count == 1);
REQUIRE([literals[0] isEqualToString:@"taco"]);
REQUIRE(expressions.count == 1);
REQUIRE([expressions[0] isEqualToString:@"path.join(__dirname, 'path')"]);
}
TEST_CASE("Parser returns an error for invalid code", "[parser]")
{
// MUST have "require" somewhere in the string because node-detective cheats!
NSArray* result = parseSync(@"var unbalanced = {this [][] is not !! valid @#@#$ code require");
NSError* err = result[0];
NSArray* literals = result[1];
NSArray* expressions = result[2];
NSString* source = result[3];
REQUIRE(![err isKindOfClass:NSNull.class]);
REQUIRE([err.localizedDescription isEqualToString:@"SyntaxError: Unexpected token (1:23)"]);
REQUIRE([literals isKindOfClass:NSNull.class]);
REQUIRE([expressions isKindOfClass:NSNull.class]);
REQUIRE([source isKindOfClass:NSNull.class]);
}
TEST_CASE("Parser works on executable scripts", "[parser]")
{
NSArray* result = parseSync(@"#!/usr/local/bin/node\nrequire(__dirname + 'path')");
NSError* err = result[0];
NSArray* literals = result[1];
NSArray* expressions = result[2];
NSString* source = result[3];
REQUIRE([err isKindOfClass:NSNull.class]);
REQUIRE(literals.count == 0);
REQUIRE(expressions.count == 1);
REQUIRE([expressions[0] isEqualToString:@"__dirname + 'path'"]);
REQUIRE(source.length > 0);
}
TEST_CASE("Extracts literal requires", "[parse]")
{
NSError* err = nil;
NSArray* result = parseSync(@"require('tofu')");
REQUIRE([result[0] isKindOfClass:NSNull.class]);
NSArray* literals = result[1];
err = result[0];
REQUIRE([err isKindOfClass:NSNull.class]);
REQUIRE([literals count] == 1);
REQUIRE([literals[0] isEqualToString:@"tofu"]);
}
/**
* Require
*/
TEST_CASE("Evaluates require expressions with the path module available", "[parse]")
{
NSError* err = nil;
NSArray* result = parseSync(@"'use unstrict'; require(path.join(__dirname, 'compound'));");
err = result[0];
NSArray* expressions = result[2];
REQUIRE([err isKindOfClass:NSNull.class]);
Require* require = new Require(nil);
err = nil;
NSArray* results = requireSync(@"/fakedir/somefile.js", expressions);
err = results[0];
NSArray* requires = results[1];
REQUIRE([err isKindOfClass:NSNull.class]);
REQUIRE([requires count] == 1);
REQUIRE([requires[0] isEqualToString:@"/fakedir/compound"]);
}
TEST_CASE("Fails to resolve expressions with arbitrary variables", "[require]")
{
NSError* err = nil;
NSArray* result = parseSync(@"require(opts.puppy)");
err = result[0];
NSArray* expressions = result[2];
REQUIRE([err isKindOfClass:NSNull.class]);
Require* require = new Require(nil);
err = nil;
NSArray* results = requireSync(@"/fakedir/somefile.js", expressions);
err = results[0];
NSArray* requires = results[1];
REQUIRE(![err isKindOfClass:NSNull.class]);
REQUIRE(err.code == 8);
// Should say what the problem is
REQUIRE([err.localizedDescription rangeOfString:@"Can't find variable: opts"].location != NSNotFound);
// Should give a recovery option
REQUIRE([err.localizedDescription rangeOfString:@"Rerun with --ignoreUnresolvableExpressions to continue"].location != NSNotFound);
}
/**
* Resolve
*/
TEST_CASE("Creates node_module paths", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSArray* paths = resolver->_nodeModulePaths(here);
REQUIRE([paths count] > 1);
REQUIRE([paths[0] hasSuffix:@"node_modules"]);
delete resolver;
}
TEST_CASE("Resolves lookup paths", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/entry.js");
NSArray* paths = resolver->_resolveLookupPaths(@"lodash", parent);
REQUIRE([paths count] == 2);
REQUIRE([paths[1] count] > 6); // This should be pretty long
delete resolver;
}
TEST_CASE("Resolves relative file", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/entry.js");
NSString* resolved = resolver->_resolveFilename(@"./mylib/index.js", parent, nil);
REQUIRE(resolved != nil);
REQUIRE([resolved hasSuffix:@"/fixtures/basic/mylib/index.js"]);
delete resolver;
}
TEST_CASE("Resolves relative directory", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/entry.js");
NSString* resolved = resolver->_resolveFilename(@"./mylib", parent, nil);
REQUIRE(resolved != nil);
REQUIRE([resolved hasSuffix:@"/fixtures/basic/mylib/index.js"]);
delete resolver;
}
TEST_CASE("Resolves dependency with user defined main script", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/entry.js");
NSString* resolved = resolver->_resolveFilename(@"waldo", parent, nil);
REQUIRE(resolved != nil);
REQUIRE([resolved hasSuffix:@"/fixtures/basic/node_modules/waldo/waldo/index.js"]);
delete resolver;
}
TEST_CASE("Resolves dependency by traversing upwards", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/entry.js");
NSString* resolved = resolver->_resolveFilename(@"flamingo", parent, nil);
REQUIRE(resolved != nil);
REQUIRE([resolved hasSuffix:@"/fixtures/node_modules/flamingo/flamingo.js"]);
delete resolver;
}
TEST_CASE("Resolves relative dependency by traversing upwards multiple directories", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/deep/deeper/deepest/bottom.js");
NSString* resolved = resolver->_resolveFilename(@"../../../json", parent, nil);
REQUIRE(resolved != nil);
REQUIRE([resolved hasSuffix:@"/fixtures/basic/json.json"]);
delete resolver;
}
TEST_CASE("Resolves global", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/entry.js");
NSString* resolved = resolver->_resolveFilename(@"http", parent, nil);
REQUIRE(resolved != nil);
REQUIRE([resolved isEqualToString:@"http"]);
delete resolver;
}
TEST_CASE("Should error on missing module", "[resolve]")
{
Resolve* resolver = new Resolve(nil);
NSString* here = [[NSFileManager defaultManager] currentDirectoryPath];
NSMutableDictionary* parent = resolver->makeModuleStub(@"fixtures/basic/entry.js");
NSError* error = nil;
NSString* resolved = resolver->_resolveFilename(@"i-dont-exist!", parent, &error);
REQUIRE(resolved == nil);
REQUIRE(error != nil);
REQUIRE([error.localizedDescription rangeOfString:@"tried:"].location != NSNotFound);
delete resolver;
}
/**
* paq: deps
*/
TEST_CASE("Creates a dependency map", "[deps]")
{
Paq* paq = new Paq(@[ @"fixtures/basic/entry.js" ], nil);
__block NSDictionary* dependencies;
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
paq->deps(@{}, ^(NSDictionary* deps) {
dependencies = deps;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
REQUIRE(dependencies != nil);
REQUIRE([dependencies count] == 7);
[dependencies enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL* stop) {
NSString *sourceFile = (NSString *) key;
NSDictionary *sourceData = (NSDictionary *) obj;
NSDictionary *requirePairs = sourceData[@"deps"];
REQUIRE(sourceData[@"source"] != nil);
if([key hasSuffix:@"/basic/entry.js"]) {
REQUIRE([sourceData[@"entry"] boolValue] == YES);
REQUIRE([requirePairs count] == 5);
[requirePairs enumerateKeysAndObjectsUsingBlock:^(NSString *requireExpr, NSString *resolution, BOOL *stop) {
if([requireExpr isEqualToString:@"./mylib"]) {
REQUIRE([resolution hasSuffix:@"/fixtures/basic/mylib/index.js"]);
}
else if([requireExpr isEqualToString:@"waldo"]) {
REQUIRE([resolution hasSuffix:@"/fixtures/basic/node_modules/waldo/waldo/index.js"]);
}
else if([requireExpr isEqualToString:@"flamingo"]) {
REQUIRE([resolution hasSuffix:@"/fixtures/node_modules/flamingo/flamingo.js"]);
}
else if([requireExpr isEqualToString:@"flamingo/package"]) {
REQUIRE([resolution hasSuffix:@"/fixtures/node_modules/flamingo/package.json"]);
}
else if([requireExpr isEqualToString:@"./deep/deeper/deepest/bottom"]) {
REQUIRE([resolution hasSuffix:@"/fixtures/basic/deep/deeper/deepest/bottom.js"]);
}
}];
}
else if([key hasSuffix:@"/basic/deep/deeper/deepest/bottom.js"]) {
REQUIRE([sourceData[@"entry"] boolValue] == NO);
REQUIRE([requirePairs count] == 1);
REQUIRE([requirePairs[@"../../../json"] hasSuffix:@"/fixtures/basic/json.json"]);
}
else {
REQUIRE([sourceData[@"entry"] boolValue] == NO);
REQUIRE([requirePairs count] == 0);
}
}];
delete paq;
}
/**
* paq: pack errors
*/
TEST_CASE("Eval cannot be used with more than one entry script")
{
Pack::pack(@[ @"a", @"b" ], nil, @{ @"eval" : [NSNumber numberWithBool:YES] },
^(NSError* error, NSString* bundle) {
REQUIRE(error != nil);
});
}
TEST_CASE("Standalone cannot be used with more than one entry script")
{
Pack::pack(@[ @"a", @"b" ], nil, @{ @"standalone" : [NSNumber numberWithBool:YES] },
^(NSError* error, NSString* bundle) {
REQUIRE(error != nil);
});
}
TEST_CASE("ConvertBrowserifyTransform cannot be used with more than one entry script")
{
Pack::pack(@[ @"a", @"b" ], nil, @{ @"standalone" : [NSNumber numberWithBool:YES] },
^(NSError* error, NSString* bundle) {
REQUIRE(error != nil);
});
}
/**
* paq: bundle
*/
TEST_CASE("Creates a basic bundle", "[bundle]")
{
Paq* paq = new Paq(@[ @"fixtures/basic/entry.js" ], nil);
REQUIRE([paq->evalToString() isEqualToString:@"Custom Lib You found waldo! flamingo fishing flamingo.js"]);
delete paq;
}
TEST_CASE("Creates a basic bundle without concurrency", "[bundle]")
{
Paq* paq = new Paq(@[ @"fixtures/basic/entry.js" ], @{ @"parserTasks" : [NSNumber numberWithInt:1],
@"requireTasks" : [NSNumber numberWithInt:1] });
REQUIRE([paq->evalToString() isEqualToString:@"Custom Lib You found waldo! flamingo fishing flamingo.js"]);
delete paq;
}
TEST_CASE("Bundles node core modules", "[bundle]")
{
Paq* paq = new Paq(@[ @"fixtures/node-core/index.js" ], nil);
NSString* evaled = paq->evalToString();
REQUIRE([evaled isEqualToString:@"a/b"]);
delete paq;
}
TEST_CASE("Inserts module globals", "[bundle]")
{
Paq* paq = new Paq(@[ @"fixtures/insert-globals/index.js" ], nil);
NSString* evaled = paq->evalToString();
REQUIRE([evaled hasSuffix:@"insert-globals/browser"]);
delete paq;
}
TEST_CASE("Ignores unevaluated expressions", "[bundle]")
{
// There is something like a require(opts.p || opts.default) in hbsfy. If this test passes, then the option was respected
Paq* paq = new Paq(@[ @"fixtures/node_modules/hbsfy/index.js" ], @{ @"ignoreUnresolvableExpressions" : [NSNumber numberWithBool:YES] });
NSError* err = nil;
NSString* bundle = paq->bundleSync(nil, &err);
REQUIRE(err == nil);
REQUIRE([bundle lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 0);
delete paq;
}
TEST_CASE("Converts the hbsfy transform", "[bundle]")
{
Paq* paq = new Paq(@[ @"fixtures/node_modules/hbsfy/index.js" ], @{ @"ignoreUnresolvableExpressions" : [NSNumber numberWithBool:YES] });
NSError* err = nil;
NSString* bundle = paq->bundleSync(@{ @"convertBrowserifyTransform" : [NSNumber numberWithBool:YES] }, &err);
// Should have the hbsfy runtime somewhere in it
REQUIRE([bundle rangeOfString:@"require('hbsfy/runtime')"].location != NSNotFound);
NSString* evaluated = evaluateTransformSync(bundle, @"hbs", @"My name is {{name}}");
REQUIRE(evaluated != nil);
REQUIRE([evaluated rangeOfString:@"return \"My name is \""].location != NSNotFound);
delete paq;
}
TEST_CASE("Converts the babelify transform", "[bundle]")
{
Paq* paq = new Paq(@[ @"fixtures/node_modules/babelify/index.js" ], @{ @"ignoreUnresolvableExpressions" : [NSNumber numberWithBool:YES] });
NSError* err = nil;
NSString* bundle = paq->bundleSync(@{ @"convertBrowserifyTransform" : [NSNumber numberWithBool:YES] }, &err);
// Should have references to JSX stuff somewhere in it
REQUIRE([bundle rangeOfString:@"JSXElement"].location != NSNotFound);
NSString* evaluated = evaluateTransformSync(bundle, @"hello.jsx", @"<div>Hello {this.props.name}</div>;");
REQUIRE(evaluated != nil);
REQUIRE([evaluated rangeOfString:@"React.createElement("].location != NSNotFound);
delete paq;
}
TEST_CASE("Creates a transform chain", "[transform]")
{
Paq* paq = new Paq(@[ @"fixtures/node_modules/hbsfy/index.js", @"fixtures/node_modules/babelify/index.js" ], @{
@"ignoreUnresolvableExpressions" : [NSNumber numberWithBool:YES]
});
NSError* err = nil;
NSString* bundle = paq->bundleSync(@{ @"chainTransforms" : [NSNumber numberWithBool:YES] }, &err);
// Should have references to JSX stuff somewhere in it
REQUIRE([bundle rangeOfString:@"JSXElement"].location != NSNotFound);
// Should have the hbsfy runtime somewhere in it
REQUIRE([bundle rangeOfString:@"require('hbsfy/runtime')"].location != NSNotFound);
// The same bundle should be able to handle both jsx and hbs
NSString* evaluated = evaluateTransformSync(bundle, @"hello.jsx", @"<div>Hello {this.props.name}</div>;");
REQUIRE(evaluated != nil);
REQUIRE([evaluated rangeOfString:@"React.createElement("].location != NSNotFound);
evaluated = evaluateTransformSync(bundle, @"hbs", @"My name is {{name}}");
REQUIRE(evaluated != nil);
REQUIRE([evaluated rangeOfString:@"return \"My name is \""].location != NSNotFound);
// And it just shouldn't do anything sometimes
evaluated = evaluateTransformSync(bundle, @"index.js", @"var donothing = 4;");
REQUIRE(evaluated != nil);
REQUIRE([evaluated rangeOfString:@"var donothing = 4;"].location != NSNotFound);
delete paq;
}
TEST_CASE("Uses hbsfy transform", "[bundle, transform]")
{
// There is something like a require(opts.p || opts.default) in hbsfy. If this test passes, then the option was respected
// because that kind of require can't be evaluated statically
Paq* paq = new Paq(@[ @"fixtures/hbs-app/index.js" ], @{ @"ignoreUnresolvableExpressions" : [NSNumber numberWithBool:YES],
@"transforms" : @[ @"fixtures/node_modules/hbsfy/index.js" ] });
NSError* err = nil;
NSString* bundle = paq->evalToString();
REQUIRE(err == nil);
REQUIRE([bundle isEqualToString:@"Hello World!"]);
delete paq;
}
/*
TEST_CASE("Wait for instruments to detect leaks", "[instruments]")
{
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
[NSThread sleepForTimeInterval:1.0f];
REQUIRE(1 == 1);
}*/