codekingpro/portable-devtools
114k
1'use strict'
2const builtins = require('./builtin-modules.json')
3
4var scopedPackagePattern = new RegExp('^(?:@([^/]+?)[/])?([^/]+?)$')
5var exclusionList = [
6 'node_modules',
7 'favicon.ico',
8]
9
10function validate (name) {
11 var warnings = []
12 var errors = []
13
14 if (name === null) {
15 errors.push('name cannot be null')
16 return done(warnings, errors)
17 }
18
19 if (name === undefined) {
20 errors.push('name cannot be undefined')
21 return done(warnings, errors)
22 }
23
24 if (typeof name !== 'string') {
25 errors.push('name must be a string')
26 return done(warnings, errors)
27 }
28
29 if (!name.length) {
30 errors.push('name length must be greater than zero')
31 }
32
33 if (name.startsWith('.')) {
34 errors.push('name cannot start with a period')
35 }
36
37 if (name.startsWith('-')) {
38 errors.push('name cannot start with a hyphen')
39 }
40
41 if (name.match(/^_/)) {
42 errors.push('name cannot start with an underscore')
43 }
44
45 if (name.trim() !== name) {
46 errors.push('name cannot contain leading or trailing spaces')
47 }
48
49 // No funny business
50 exclusionList.forEach(function (excludedName) {
51 if (name.toLowerCase() === excludedName) {
52 errors.push(excludedName + ' is not a valid package name')
53 }
54 })
55
56 // Generate warnings for stuff that used to be allowed
57
58 // core module names like http, events, util, etc
59 if (builtins.includes(name.toLowerCase())) {
60 warnings.push(name + ' is a core module name')
61 }
62
63 if (name.length > 214) {
64 warnings.push('name can no longer contain more than 214 characters')
65 }
66
67 // mIxeD CaSe nAMEs
68 if (name.toLowerCase() !== name) {
69 warnings.push('name can no longer contain capital letters')
70 }
71
72 if (/[~'!()*]/.test(name.split('/').slice(-1)[0])) {
73 warnings.push('name can no longer contain special characters ("~\'!()*")')
74 }
75
76 if (encodeURIComponent(name) !== name) {
77 // Maybe it's a scoped package name, like @user/package
78 var nameMatch = name.match(scopedPackagePattern)
79 if (nameMatch) {
80 var user = nameMatch[1]
81 var pkg = nameMatch[2]
82
83 if (pkg.startsWith('.')) {
84 errors.push('name cannot start with a period')
85 }
86
87 if (encodeURIComponent(user) === user && encodeURIComponent(pkg) === pkg) {
88 return done(warnings, errors)
89 }
90 }
91
92 errors.push('name can only contain URL-friendly characters')
93 }
94
95 return done(warnings, errors)
96}
97
98var done = function (warnings, errors) {
99 var result = {
100 validForNewPackages: errors.length === 0 && warnings.length === 0,
101 validForOldPackages: errors.length === 0,
102 warnings: warnings,
103 errors: errors,
104 }
105 if (!result.warnings.length) {
106 delete result.warnings
107 }
108 if (!result.errors.length) {
109 delete result.errors
110 }
111 return result
112}
113
114module.exports = validate
115 