color-name-list 9.32.0 → 10.0.0

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.
package/scripts/server.js DELETED
@@ -1,289 +0,0 @@
1
- const http = require('http');
2
- const url = require('url');
3
- const fs = require('fs');
4
- const zlib = require('zlib');
5
- const colorNameLists = require('color-name-lists');
6
- const colors = JSON.parse(
7
- fs.readFileSync(__dirname + '/../dist/colornames.json', 'utf8')
8
- );
9
- const colorsBestOf = JSON.parse(
10
- fs.readFileSync(__dirname + '/../dist/colornames.bestof.json', 'utf8')
11
- );
12
- const FindColors = require('./findColors.js');
13
- const getPaletteTitle = require('./generatePaletteName.js');
14
- const port = process.env.PORT || 8080;
15
- const currentVersion = 'v1';
16
- const urlNameSubpath = 'names';
17
- const APIurl = ''; // subfolder for the API
18
- const baseUrl = `${APIurl}${currentVersion}/`;
19
- const baseUrlNames = `${baseUrl}${urlNameSubpath}/`;
20
- const urlColorSeparator = ',';
21
- const responseHeaderObj = {
22
- 'Access-Control-Allow-Origin': '*',
23
- 'Access-Control-Allow-Methods': 'GET',
24
- 'Access-Control-Allow-Credentials': false,
25
- 'Access-Control-Max-Age': '86400',
26
- 'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept',
27
- 'Content-Type': 'application/json; charset=utf-8',
28
- };
29
-
30
- // accepts encoding
31
-
32
- // [{name: 'red', value: '#f00'}, ...]
33
- const colorsLists = {
34
- default: colors,
35
- colors: colors,
36
- bestOf: colorsBestOf,
37
- };
38
-
39
- Object.assign(colorsLists, colorNameLists.lists);
40
-
41
- const avalibleColorNameLists = Object.keys(colorsLists);
42
-
43
- const findColors = new FindColors(colorsLists);
44
-
45
- /**
46
- * validates a hex color
47
- * @param {string} color hex representation of color
48
- * @return {boolen}
49
- */
50
- const validateColor = (color) => (
51
- /^[0-9A-F]{3}([0-9A-F]{3})?$/i.test(color)
52
- );
53
-
54
- /**
55
- * responds to the client
56
- * @param {object} response server response object
57
- * @param {object} responseObj the actual response object
58
- * @param {*} statusCode HTTP status code
59
- */
60
- const httpRespond = (
61
- response,
62
- responseObj = {},
63
- statusCode = 200,
64
- responseHeader = responseHeaderObj
65
- ) => {
66
- response.writeHead(statusCode, responseHeader);
67
- const stringifiedResponse = JSON.stringify(responseObj);
68
-
69
- if (responseHeader['Content-Encoding'] === 'gzip') {
70
- // ends the response with the gziped API answer
71
- zlib.gzip(stringifiedResponse, (_, result) => {
72
- response.end(result);
73
- });
74
- } else {
75
- response.end(stringifiedResponse);
76
- }
77
- };
78
-
79
- const respondNameSearch = (
80
- searchParams = new URLSearchParams(''),
81
- listKey = 'default',
82
- requestUrl,
83
- request,
84
- response,
85
- responseHeader,
86
- ) => {
87
- const nameQuery = request.url.replace(requestUrl.search, '')
88
- // splits the base url from everything
89
- // after the API URL
90
- .split(baseUrlNames)[1] || '';
91
-
92
- // gets the name
93
- const nameString = searchParams.has('name')
94
- ? searchParams.get('name') : '';
95
-
96
- const searchString = decodeURI(nameString || nameQuery);
97
-
98
- if (searchString.length < 3) {
99
- return httpRespond(
100
- response,
101
- {error: {
102
- status: 404,
103
- message: `the color name your are looking for must be at least 3 characters long.`,
104
- }},
105
- 404,
106
- responseHeader
107
- );
108
- }
109
-
110
- return httpRespond(response, {
111
- colors: findColors.searchNames(searchString, listKey),
112
- }, 200, responseHeader);
113
- };
114
-
115
- const respondValueSearch = (
116
- searchParams = new URLSearchParams(''),
117
- listKey = 'default',
118
- requestUrl,
119
- request,
120
- response,
121
- responseHeader
122
- ) => {
123
- const uniqueMode = searchParams.has('noduplicates')
124
- && searchParams.get('noduplicates') === 'true';
125
-
126
- const colorQuery = request.url.replace(requestUrl.search, '')
127
- // splits the base url from everything
128
- // after the API URL
129
- .split(baseUrl)[1] || '';
130
-
131
- const colorListString = searchParams.has('values')
132
- ? searchParams.get('values') : '';
133
-
134
- // gets all the colors after
135
- const urlColorList = (colorQuery || colorListString).toLowerCase()
136
- .split(urlColorSeparator)
137
- .filter((hex) => hex);
138
-
139
- // creates a list of invalid colors
140
- const invalidColors = urlColorList.filter((hex) => (
141
- !validateColor(hex) && hex
142
- ));
143
-
144
- if (invalidColors.length) {
145
- return httpRespond(
146
- response,
147
- {
148
- error: {
149
- status: 404,
150
- message: `'${invalidColors.join(', ')}' is not a valid HEX color`,
151
- }
152
- },
153
- 404,
154
- responseHeader
155
- );
156
- }
157
-
158
- let paletteTitle;
159
- let colorsResponse;
160
-
161
- if (urlColorList[0]) {
162
- colorsResponse = findColors.getNamesForValues(
163
- urlColorList, uniqueMode, listKey
164
- );
165
- } else {
166
- colorsResponse = colorsLists[listKey];
167
- }
168
-
169
- if (urlColorList.length === 1) {
170
- // if there is only one color, just return its name as palette title
171
- paletteTitle = colorsResponse[0].name;
172
- } else if (urlColorList.length > 1) {
173
- // get a palette title for the returned colors
174
- paletteTitle = getPaletteTitle(colorsResponse.map((color) => color.name));
175
- } else {
176
- // return all colors if no colors were given
177
- paletteTitle = `All the ${listKey} names`;
178
- }
179
-
180
- // actual http response
181
- return httpRespond(response, {
182
- paletteTitle,
183
- colors: colorsResponse,
184
- }, 200, responseHeader);
185
- };
186
-
187
- /**
188
- * Paths:
189
- *
190
- * / => Error
191
- * /v1/ => all colors
192
- * /v1/212121 => array with one color
193
- * /v1/212121,222,f02f123 => array with 3 color
194
- * /v1/names/ => all colors
195
- * /v1/names/red => all colors containing the word red
196
- */
197
-
198
- const requestHandler = (request, response) => {
199
- const requestUrl = url.parse(request.url);
200
- const isAPI = requestUrl.pathname.includes(baseUrl);
201
- const isNamesAPI = requestUrl.pathname.includes(urlNameSubpath + '/');
202
- const responseHeader = {...responseHeaderObj};
203
-
204
- // understanding where requests come from
205
- console.info(
206
- 'request from',
207
- request.headers.origin
208
- );
209
-
210
- if (request.headers['accept-encoding']) {
211
- const accepts = request.headers['accept-encoding'];
212
- if (accepts.toLowerCase().includes("gzip")) {
213
- responseHeader['Content-Encoding'] = 'gzip';
214
- }
215
- }
216
-
217
- let accpets = request.headers['accept-encoding'];
218
-
219
- // makes sure the API is beeing requested
220
- if (!isAPI) {
221
- return httpRespond(
222
- response,
223
- {
224
- error: {
225
- status: 404,
226
- message: 'invalid URL: make sure to provide the API version',
227
- }
228
- },
229
- 404,
230
- responseHeader
231
- );
232
- }
233
-
234
- // const search = requestUrl.search || '';
235
- const searchParams = new URLSearchParams(requestUrl.search);
236
-
237
- const goodNamesMode = searchParams.has('goodnamesonly')
238
- && searchParams.get('goodnamesonly') === 'true';
239
-
240
- let listKey = searchParams.has('list')
241
- && searchParams.get('list');
242
-
243
- listKey = goodNamesMode ? 'bestOf' : listKey;
244
- listKey = listKey || 'default';
245
-
246
- const isValidListKey = listKey && avalibleColorNameLists.includes(listKey);
247
-
248
- if (!isValidListKey) {
249
- return httpRespond(
250
- response,
251
- {
252
- error: {
253
- status: 404,
254
- message: `invalid list key: '${listKey}, available keys are: ${avalibleColorNameLists.join(', ')}`,
255
- }
256
- },
257
- 404
258
- );
259
- }
260
-
261
- if (!isNamesAPI) {
262
- return respondValueSearch(
263
- searchParams,
264
- listKey,
265
- requestUrl,
266
- request,
267
- response,
268
- responseHeader,
269
- );
270
- } else {
271
- return respondNameSearch(
272
- searchParams,
273
- listKey,
274
- requestUrl,
275
- request,
276
- response,
277
- responseHeader,
278
- );
279
- }
280
- };
281
-
282
- const server = http.createServer(requestHandler);
283
- server.listen(port, '0.0.0.0', (error) => {
284
- if (error) {
285
- return console.log(`something terrible happened: ${error}`);
286
- }
287
- console.log(`Server running and listening on port ${port}`);
288
- console.log(`http://localhost:${port}/${baseUrl}`);
289
- });