-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresolve.mm
455 lines (362 loc) · 14.6 KB
/
resolve.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
//
// resolve.mm
// paq
//
// Created by Ben on 3/25/15.
// Copyright (c) 2015 Ben Ng. All rights reserved.
//
#import "resolve.h"
Resolve::Resolve(NSDictionary* options)
{
_pathCache = nil;
_realPathCache = nil;
_packageMainCache = nil;
_nativeModules = nil;
_modulePaths = nil;
_cwd = nil;
_pathCache = [[NSMutableDictionary alloc] initWithCapacity:1000];
_realPathCache = [[NSMutableDictionary alloc] initWithCapacity:1000];
_packageMainCache = [[NSMutableDictionary alloc] initWithCapacity:1000];
_packageBrowserCache = [[NSMutableDictionary alloc] initWithCapacity:1000];
_nativeModules = Script::getNativeBuiltins();
if (options != nil && options[@"cwd"]) {
_cwd = options[@"cwd"];
}
else {
_cwd = [NSURL fileURLWithPath:[[NSFileManager defaultManager] currentDirectoryPath] isDirectory:YES];
}
NSDictionary* process_env = [[NSProcessInfo processInfo] environment];
NSString* homeDir = process_env[@"HOME"];
NSMutableArray* paths = [[NSMutableArray alloc] initWithCapacity:10];
NSString* process_execPath = NSProcessInfo.processInfo.arguments[0];
[paths addObject:path_resolve(@[ process_execPath, @"..", @"..", @"lib", @"node" ])];
if (homeDir) {
[paths insertObject:path_resolve(@[ homeDir, @".node_libraries" ]) atIndex:0];
[paths insertObject:path_resolve(@[ homeDir, @".node_modules" ]) atIndex:0];
}
NSString* nodePath = process_env[@"NODE_PATH"];
if (nodePath) {
NSArray* components = [nodePath componentsSeparatedByString:@"/"];
for (long i = 0, ii = [components count]; i < ii; ++i) {
[paths insertObject:components[i] atIndex:i];
}
}
_modulePaths = paths;
}
NSString* Resolve::_resolveFilename(NSString* request, NSMutableDictionary* parent, NSError** error)
{
if (_nativeModuleExists(request)) {
return request;
}
NSArray* resolvedModule = _resolveLookupPaths(request, parent);
NSString* fileId = resolvedModule[0];
NSArray* paths = resolvedModule[1];
NSString* filename = _findPath(request, paths);
if (!filename) {
NSMutableString* errString = [[NSMutableString alloc] init];
[errString appendFormat:@"Cannot resolve module \"%@\"\n", request];
[errString appendFormat:@"from: %@\n", fileId];
if (parent && parent[@"filename"]) {
[errString appendFormat:@"required from: \"%@\"\n", parent[@"filename"]];
}
for (NSUInteger i = 0, ii = [paths count]; i < ii; ++i) {
[errString appendFormat:@"tried: %@\n", paths[i]];
}
if (error != nil) {
*error = [NSError errorWithDomain:@"com.benng.paq" code:15 userInfo:@{ NSLocalizedDescriptionKey : errString }];
}
return nil;
}
return filename;
}
NSArray* Resolve::_nodeModulePaths(NSString* from)
{
NSString* sep = @"/";
NSMutableArray* paths = [[NSMutableArray alloc] initWithCapacity:20];
// guarantee that 'from' is absolute
/* This is in the node.js source. In paq, everything is absolute, so no worries here.
if (![from isAbsolutePath]) {
NSString* absstr = [[NSURL URLWithString:from relativeToURL:_cwd] absoluteString];
from = pathWithoutFileScheme(absstr);
}
*/
// Posix only. I doubt this project will ever run on windows anyway.
NSArray* parts = [from componentsSeparatedByString:sep];
for (long tip = [parts count] - 1; tip >= 0; tip--) {
if ([parts[tip] isEqualToString:@"node_modules"]) {
continue;
}
else {
NSString* dir = [[[parts subarrayWithRange:NSMakeRange(0, tip + 1)] componentsJoinedByString:sep] stringByAppendingPathComponent:@"node_modules"];
[paths addObject:dir];
}
}
return paths;
}
NSArray* Resolve::_resolveLookupPaths(NSString* request, NSMutableDictionary* parent)
{
if (_nativeModuleExists(request)) {
return @[ request, @[] ];
}
if (![request hasPrefix:@"./"] && ![request hasPrefix:@".."]) {
NSArray* paths = _modulePaths;
if (parent != nil) {
if (parent[@"paths"] == nil) {
parent[@"paths"] = @[];
}
paths = [parent[@"paths"] arrayByAddingObjectsFromArray:paths];
}
return @[ request, paths ];
}
// with --eval, parent.id is not set and parent.filename is null
if (parent == nil || parent[@"id"] == nil || parent[@"filename"] == nil) {
// make require('./path/to/foo') work - normally the path is taken
// from realpath(__filename) but with eval there is no filename
NSArray* mainpaths = [@[ @"." ] arrayByAddingObjectsFromArray:_modulePaths];
mainpaths = [_nodeModulePaths(@".") arrayByAddingObjectsFromArray:mainpaths];
return @[ request, mainpaths ];
}
// Is the parent an index module?
// We can assume the parent has a valid extension,
// as it already has been accepted as a module.
/*
* This is in the actual node source, but I don't think it works when the entry file is an index module
* because in node, there is a root module, and that makes this behave differently
NSPredicate* isIndexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^index\\.\\w+?$"];
BOOL isIndex = [isIndexTest evaluateWithObject:[parent[@"filename"] lastPathComponent]];
NSString* parentIdPath = isIndex ? parent[@"id"] : [parent[@"id"] stringByDeletingLastPathComponent];
*/
// We basically just want the directory, so just do this.
NSString* fileId = path_resolve(@[ [parent[@"filename"] stringByDeletingLastPathComponent], request ]);
// Root module?
if ([parent[@"id"] isEqualToString:@"."] && [fileId rangeOfString:@"/"].location == NSNotFound) {
fileId = [@"./" stringByAppendingString:fileId];
}
return @[ fileId, @[ [parent[@"filename"] stringByDeletingLastPathComponent] ] ];
}
NSString* Resolve::_findPath(NSString* request, NSArray* paths)
{
NSArray* exts = @[ @".js", @".json" ];
if ([request characterAtIndex:0] == '/') {
paths = @[ @"" ];
}
BOOL trailingSlash = [request hasSuffix:@"/"];
NSString* cacheKey = [[@[ request ] arrayByAddingObjectsFromArray:paths] componentsJoinedByString:@"\0"];
if (_pathCache[cacheKey] != nil) {
return _pathCache[cacheKey];
}
for (NSUInteger i = 0, PL = [paths count]; i < PL; i++) {
NSString* basePath = path_resolve(@[ paths[i], request ]);
NSString* filename;
if (!trailingSlash) {
// try to join the request to the path
filename = tryFile(basePath);
if (!filename && !trailingSlash) {
// try it with each of the extensions
filename = tryExtensions(basePath, exts);
}
}
if (!filename) {
filename = tryPackage(basePath, exts);
}
if (!filename) {
// try it with each of the extensions at "index"
filename = tryExtensions(path_resolve(@[ basePath, @"index" ]), exts);
}
if (filename) {
_pathCache[cacheKey] = filename;
return filename;
}
}
return nil;
}
BOOL Resolve::_nativeModuleExists(NSString* request)
{
return _nativeModules[request] != nil;
}
NSString* Resolve::path_resolve(NSArray* args)
{
NSString* resolvedPath = @"";
BOOL resolvedAbsolute = NO;
for (long i = [args count] - 1; i >= -1 && !resolvedAbsolute; i--) {
NSString* path = (i >= 0) ? args[i] : pathWithoutFileScheme(_cwd.absoluteString);
// Skip empty and invalid entries
if (path == nil || [path length] == 0) {
continue;
}
resolvedPath = [NSString stringWithFormat:@"%@/%@", path, resolvedPath];
resolvedAbsolute = [resolvedPath characterAtIndex:0] == '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = [resolvedPath stringByStandardizingPath];
if ([resolvedPath isNotEqualTo:@""]) {
return resolvedPath;
}
else {
return @".";
}
}
NSMutableDictionary* Resolve::makeModuleStub(NSString* filename)
{
if (_nativeModuleExists(filename)) {
filename = _nativeModules[filename];
}
else {
filename = path_resolve(@[ filename ]);
}
return [[NSMutableDictionary alloc] initWithDictionary:@{
@"id" : filename,
@"filename" : filename,
@"paths" : _nodeModulePaths([filename stringByDeletingLastPathComponent])
}];
}
NSString* Resolve::tryFile(NSString* requestPath)
{
// Preload the browser field replacement dictionary, if there is one
readPackage(requestPath);
requestPath = [requestPath stringByStandardizingPath];
// Replace with browser version if there is one
if (_packageBrowserCache[requestPath] != nil) {
// This package wants us to ignore bundling this file
if ([_packageBrowserCache[requestPath] isKindOfClass:NSNumber.class] && [_packageBrowserCache[requestPath] boolValue] == NO) {
return @"\0";
}
else {
requestPath = _packageBrowserCache[requestPath];
}
}
BOOL isDirectory;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:requestPath isDirectory:&isDirectory];
if (exists && !isDirectory) {
char* _realPath = realpath([requestPath cStringUsingEncoding:NSUTF8StringEncoding], NULL);
if (_realPath == NULL) {
NSLog(@"Warning: realpath returned NULL for %@", requestPath);
return nil;
}
else {
NSString* realPath = [NSString stringWithCString:_realPath encoding:NSUTF8StringEncoding];
free(_realPath);
_realPathCache[requestPath] = realPath;
return realPath;
}
}
return nil;
}
NSString* Resolve::tryExtensions(NSString* p, NSArray* exts)
{
for (NSUInteger i = 0, EL = [exts count]; i < EL; i++) {
NSString* filename = tryFile([p stringByAppendingString:exts[i]]);
if (filename != nil) {
return filename;
}
}
return nil;
}
NSString* Resolve::tryPackage(NSString* requestPath, NSArray* exts)
{
NSString* pkg = readPackage(requestPath);
if (pkg == nil) {
return nil;
}
NSString* filename = path_resolve(@[ requestPath, pkg ]);
NSString* temp;
temp = tryFile(filename);
if (temp != nil) {
return temp;
}
temp = tryExtensions(filename, exts);
if (temp != nil) {
return temp;
}
temp = tryExtensions(path_resolve(@[ filename, @"index" ]), exts);
return temp;
}
NSString* Resolve::readPackage(NSString* requestPath)
{
if (_packageMainCache[requestPath] != nil) {
NSString* mainFile = _packageMainCache[requestPath];
return [mainFile length] == 0 ? nil : mainFile;
}
NSString* jsonPath = path_resolve(@[ requestPath, @"package.json" ]);
NSError* error = nil;
NSString* jsonString = [[NSString stringWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:&error] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (jsonString == nil) {
return nil;
}
NSData* json = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id object = [NSJSONSerialization JSONObjectWithData:json options:0 error:&error];
if (object == nil) {
NSLog(@"Could not parse package.json as json: %@ (%@)\n%@", jsonPath, error.localizedDescription, jsonString);
return nil;
}
if ([object isKindOfClass:[NSDictionary class]]) {
NSObject* browserFile = ((NSDictionary*)object)[@"browser"];
NSString* mainFile = ((NSDictionary*)object)[@"main"];
NSDictionary* browserDict = nil;
if (browserFile != nil) {
// If dictionary, write the aliases now
if ([browserFile isKindOfClass:NSDictionary.class]) {
browserDict = (NSDictionary*)browserFile;
[browserDict enumerateKeysAndObjectsUsingBlock:^(NSString* needle, NSObject* replacement, BOOL* stop) {
// Absolute paths are way easier to work with!
NSString* absNeedPath = [[requestPath stringByAppendingPathComponent:needle] stringByStandardizingPath];
if ([replacement isKindOfClass:NSString.class]) {
NSString* absReplPath = [[requestPath stringByAppendingPathComponent:(NSString *) replacement] stringByStandardizingPath];
// Make sure that modules can't overwite other modules by traversing upwards
if (![absNeedPath hasPrefix:requestPath] || ![absReplPath hasPrefix:requestPath]) {
[NSException raise:@"Malicious package.json" format:@"%@ is trying to alter settings beyond its allowed scope", requestPath];
}
_packageBrowserCache[absNeedPath] = absReplPath;
}
else {
_packageBrowserCache[absNeedPath] = [NSNumber numberWithBool:NO];
}
}];
}
else {
_packageMainCache[requestPath] = (NSString*)browserFile;
}
}
// Second condition is because a string browser field overrides the main field
if (mainFile != nil && !_packageMainCache[requestPath]) {
// Use the browser alias if provided
if (browserDict && browserDict[mainFile] != nil) {
_packageMainCache[requestPath] = browserDict[mainFile];
}
else {
_packageMainCache[requestPath] = mainFile;
}
}
if (_packageMainCache[requestPath] == nil) {
_packageMainCache[requestPath] = @"";
}
return _packageMainCache[requestPath];
}
else {
NSLog(@"Parsed %@ but did not get a dictionary: %@", jsonPath, [error localizedDescription]);
return nil;
}
}
NSString* Resolve::pathWithoutFileScheme(NSString* path)
{
unsigned long proto = [@"file://" length];
NSString* substr = [path substringWithRange:NSMakeRange(proto, [path length] - proto)];
if ([substr hasPrefix:@"//"]) {
return [substr substringWithRange:NSMakeRange(1, [substr length] - 1)];
}
else {
return substr;
}
}
Resolve::~Resolve()
{
_pathCache = nil;
_realPathCache = nil;
_packageMainCache = nil;
_packageBrowserCache = nil;
_nativeModules = nil;
_modulePaths = nil;
_cwd = nil;
}