@atlaspack/utils 2.14.5-canary.36 → 2.14.5-canary.360

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.
Files changed (197) hide show
  1. package/CHANGELOG.md +462 -0
  2. package/benchmark.js +23 -0
  3. package/dist/DefaultMap.js +41 -0
  4. package/dist/Deferred.js +16 -0
  5. package/dist/PromiseQueue.js +107 -0
  6. package/dist/TapStream.js +23 -0
  7. package/dist/alternatives.js +97 -0
  8. package/dist/ansi-html.js +12 -0
  9. package/dist/blob.js +29 -0
  10. package/dist/bundle-url.js +32 -0
  11. package/dist/collection.js +106 -0
  12. package/dist/config.js +138 -0
  13. package/dist/countLines.js +12 -0
  14. package/dist/debounce.js +15 -0
  15. package/dist/debug-tools.js +39 -0
  16. package/dist/dependency-location.js +22 -0
  17. package/dist/escape-html.js +19 -0
  18. package/dist/generateBuildMetrics.js +111 -0
  19. package/dist/generateCertificate.js +124 -0
  20. package/dist/getCertificate.js +13 -0
  21. package/dist/getExisting.js +20 -0
  22. package/dist/getModuleParts.js +27 -0
  23. package/dist/getRootDir.js +46 -0
  24. package/dist/getTimeId.js +13 -0
  25. package/dist/glob.js +129 -0
  26. package/dist/hash.js +45 -0
  27. package/dist/http-server.js +55 -0
  28. package/dist/index.js +148 -0
  29. package/dist/is-url.js +15 -0
  30. package/dist/isDirectoryInside.js +11 -0
  31. package/dist/objectHash.js +20 -0
  32. package/dist/openInBrowser.js +61 -0
  33. package/dist/parseCSSImport.js +14 -0
  34. package/dist/path.js +36 -0
  35. package/dist/prettifyTime.js +6 -0
  36. package/dist/prettyDiagnostic.js +108 -0
  37. package/dist/progress-message.js +31 -0
  38. package/dist/relativeBundlePath.js +13 -0
  39. package/dist/relativeUrl.js +11 -0
  40. package/dist/replaceBundleReferences.js +131 -0
  41. package/dist/schema.js +404 -0
  42. package/dist/shared-buffer.js +24 -0
  43. package/dist/sourcemap.js +121 -0
  44. package/dist/stream.js +69 -0
  45. package/dist/throttle.js +12 -0
  46. package/dist/urlJoin.js +22 -0
  47. package/lib/DefaultMap.js +42 -0
  48. package/lib/Deferred.js +30 -0
  49. package/lib/PromiseQueue.js +112 -0
  50. package/lib/TapStream.js +34 -0
  51. package/lib/alternatives.js +116 -0
  52. package/lib/ansi-html.js +20 -0
  53. package/lib/blob.js +40 -0
  54. package/lib/bundle-url.js +34 -0
  55. package/lib/collection.js +111 -0
  56. package/lib/config.js +174 -0
  57. package/lib/countLines.js +15 -0
  58. package/lib/debounce.js +18 -0
  59. package/lib/debug-tools.js +40 -0
  60. package/lib/dependency-location.js +21 -0
  61. package/lib/escape-html.js +22 -0
  62. package/lib/generateBuildMetrics.js +121 -0
  63. package/lib/generateCertificate.js +129 -0
  64. package/lib/getCertificate.js +18 -0
  65. package/lib/getExisting.js +25 -0
  66. package/lib/getModuleParts.js +30 -0
  67. package/lib/getRootDir.js +52 -0
  68. package/lib/getTimeId.js +10 -0
  69. package/lib/glob.js +110 -0
  70. package/lib/hash.js +50 -0
  71. package/lib/http-server.js +85 -0
  72. package/lib/index.js +643 -37310
  73. package/lib/is-url.js +24 -0
  74. package/lib/isDirectoryInside.js +18 -0
  75. package/lib/objectHash.js +26 -0
  76. package/lib/openInBrowser.js +74 -0
  77. package/lib/parseCSSImport.js +15 -0
  78. package/lib/path.js +39 -0
  79. package/lib/prettifyTime.js +9 -0
  80. package/lib/prettyDiagnostic.js +154 -0
  81. package/lib/progress-message.js +39 -0
  82. package/lib/relativeBundlePath.js +22 -0
  83. package/lib/relativeUrl.js +24 -0
  84. package/lib/replaceBundleReferences.js +182 -0
  85. package/lib/schema.js +353 -0
  86. package/lib/shared-buffer.js +31 -0
  87. package/lib/sourcemap.js +138 -0
  88. package/lib/stream.js +76 -0
  89. package/lib/throttle.js +15 -0
  90. package/lib/types/DefaultMap.d.ts +13 -0
  91. package/lib/types/Deferred.d.ts +8 -0
  92. package/lib/types/PromiseQueue.d.ts +25 -0
  93. package/lib/types/TapStream.d.ts +6 -0
  94. package/lib/types/alternatives.d.ts +3 -0
  95. package/lib/types/ansi-html.d.ts +1 -0
  96. package/lib/types/blob.d.ts +4 -0
  97. package/lib/types/bundle-url.d.ts +4 -0
  98. package/lib/types/collection.d.ts +33 -0
  99. package/lib/types/config.d.ts +17 -0
  100. package/lib/types/countLines.d.ts +1 -0
  101. package/lib/types/debounce.d.ts +1 -0
  102. package/lib/types/debug-tools.d.ts +8 -0
  103. package/lib/types/dependency-location.d.ts +14 -0
  104. package/lib/types/escape-html.d.ts +1 -0
  105. package/lib/types/generateBuildMetrics.d.ts +18 -0
  106. package/lib/types/generateCertificate.d.ts +5 -0
  107. package/lib/types/getCertificate.d.ts +5 -0
  108. package/lib/types/getExisting.d.ts +8 -0
  109. package/lib/types/getModuleParts.d.ts +4 -0
  110. package/lib/types/getRootDir.d.ts +2 -0
  111. package/lib/types/getTimeId.d.ts +1 -0
  112. package/lib/types/glob.d.ts +9 -0
  113. package/lib/types/hash.d.ts +7 -0
  114. package/lib/types/http-server.d.ts +19 -0
  115. package/lib/types/index.d.ts +49 -0
  116. package/lib/types/is-url.d.ts +1 -0
  117. package/lib/types/isDirectoryInside.d.ts +2 -0
  118. package/lib/types/objectHash.d.ts +3 -0
  119. package/lib/types/openInBrowser.d.ts +1 -0
  120. package/lib/types/parseCSSImport.d.ts +1 -0
  121. package/lib/types/path.d.ts +8 -0
  122. package/lib/types/prettifyTime.d.ts +1 -0
  123. package/lib/types/prettyDiagnostic.d.ts +18 -0
  124. package/lib/types/progress-message.d.ts +3 -0
  125. package/lib/types/relativeBundlePath.d.ts +4 -0
  126. package/lib/types/relativeUrl.d.ts +1 -0
  127. package/lib/types/replaceBundleReferences.d.ts +39 -0
  128. package/lib/types/schema.d.ts +107 -0
  129. package/lib/types/shared-buffer.d.ts +2 -0
  130. package/lib/types/sourcemap.d.ts +15 -0
  131. package/lib/types/stream.d.ts +8 -0
  132. package/lib/types/throttle.d.ts +1 -0
  133. package/lib/types/urlJoin.d.ts +5 -0
  134. package/lib/urlJoin.js +35 -0
  135. package/package.json +27 -18
  136. package/src/{DefaultMap.js → DefaultMap.ts} +8 -12
  137. package/src/Deferred.ts +26 -0
  138. package/src/{PromiseQueue.js → PromiseQueue.ts} +40 -35
  139. package/src/{TapStream.js → TapStream.ts} +8 -7
  140. package/src/{alternatives.js → alternatives.ts} +15 -16
  141. package/src/{ansi-html.js → ansi-html.ts} +1 -1
  142. package/src/{blob.js → blob.ts} +3 -5
  143. package/src/{bundle-url.js → bundle-url.ts} +3 -5
  144. package/src/{collection.js → collection.ts} +23 -20
  145. package/src/{config.js → config.ts} +20 -21
  146. package/src/{countLines.js → countLines.ts} +0 -2
  147. package/src/{debounce.js → debounce.ts} +3 -5
  148. package/src/debug-tools.ts +48 -0
  149. package/src/{dependency-location.js → dependency-location.ts} +15 -11
  150. package/src/{escape-html.js → escape-html.ts} +5 -3
  151. package/src/{generateBuildMetrics.js → generateBuildMetrics.ts} +19 -21
  152. package/src/{generateCertificate.js → generateCertificate.ts} +8 -6
  153. package/src/{getCertificate.js → getCertificate.ts} +6 -5
  154. package/src/{getExisting.js → getExisting.ts} +4 -3
  155. package/src/{getModuleParts.js → getModuleParts.ts} +3 -2
  156. package/src/{getRootDir.js → getRootDir.ts} +1 -3
  157. package/src/getTimeId.ts +12 -0
  158. package/src/{glob.js → glob.ts} +13 -14
  159. package/src/{hash.js → hash.ts} +23 -18
  160. package/src/{http-server.js → http-server.ts} +34 -40
  161. package/src/{index.js → index.ts} +14 -10
  162. package/src/{is-url.js → is-url.ts} +1 -2
  163. package/src/{isDirectoryInside.js → isDirectoryInside.ts} +1 -2
  164. package/src/{objectHash.js → objectHash.ts} +1 -4
  165. package/src/{openInBrowser.js → openInBrowser.ts} +2 -4
  166. package/src/{parseCSSImport.js → parseCSSImport.ts} +0 -2
  167. package/src/{path.js → path.ts} +2 -4
  168. package/src/{prettifyTime.js → prettifyTime.ts} +0 -2
  169. package/src/{prettyDiagnostic.js → prettyDiagnostic.ts} +47 -24
  170. package/src/progress-message.ts +43 -0
  171. package/src/{relativeBundlePath.js → relativeBundlePath.ts} +4 -4
  172. package/src/{relativeUrl.js → relativeUrl.ts} +0 -1
  173. package/src/{replaceBundleReferences.js → replaceBundleReferences.ts} +67 -51
  174. package/src/schema.ts +552 -0
  175. package/src/{shared-buffer.js → shared-buffer.ts} +5 -3
  176. package/src/{sourcemap.js → sourcemap.ts} +28 -10
  177. package/src/{stream.js → stream.ts} +30 -22
  178. package/src/throttle.ts +13 -0
  179. package/src/{urlJoin.js → urlJoin.ts} +1 -3
  180. package/test/{DefaultMap.test.js → DefaultMap.test.ts} +4 -6
  181. package/test/{PromiseQueue.test.js → PromiseQueue.test.ts} +5 -6
  182. package/test/{collection.test.js → collection.test.ts} +0 -2
  183. package/test/{config.test.js → config.test.ts} +0 -3
  184. package/test/{objectHash.test.js → objectHash.test.ts} +4 -5
  185. package/test/{prettifyTime.test.js → prettifyTime.test.ts} +0 -1
  186. package/test/{replaceBundleReferences.test.js → replaceBundleReferences.test.ts} +0 -32
  187. package/test/schema.test.ts +748 -0
  188. package/test/{sourcemap.test.js → sourcemap.test.ts} +0 -1
  189. package/test/{throttle.test.js → throttle.test.ts} +1 -3
  190. package/test/{urlJoin.test.js → urlJoin.test.ts} +0 -2
  191. package/tsconfig.json +36 -0
  192. package/tsconfig.tsbuildinfo +1 -0
  193. package/lib/index.js.map +0 -1
  194. package/src/Deferred.js +0 -23
  195. package/src/progress-message.js +0 -22
  196. package/src/schema.js +0 -504
  197. package/src/throttle.js +0 -15
package/dist/schema.js ADDED
@@ -0,0 +1,404 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.fuzzySearch = fuzzySearch;
40
+ const diagnostic_1 = __importStar(require("@atlaspack/diagnostic"));
41
+ const nullthrows_1 = __importDefault(require("nullthrows"));
42
+ const levenshtein = __importStar(require("fastest-levenshtein"));
43
+ function validateSchema(schema, data) {
44
+ function walk(schemaAncestors, dataNode, dataPath) {
45
+ let [schemaNode] = schemaAncestors;
46
+ if ('type' in schemaNode && schemaNode.type) {
47
+ let type = Array.isArray(dataNode) ? 'array' : typeof dataNode;
48
+ if (schemaNode.type !== type) {
49
+ return {
50
+ type: 'type',
51
+ dataType: 'value',
52
+ dataPath,
53
+ expectedTypes: [schemaNode.type],
54
+ ancestors: schemaAncestors,
55
+ prettyType: '__type' in schemaNode ? schemaNode.__type : undefined,
56
+ };
57
+ }
58
+ else {
59
+ switch (schemaNode.type) {
60
+ case 'array': {
61
+ if ('items' in schemaNode &&
62
+ schemaNode.items &&
63
+ Array.isArray(dataNode)) {
64
+ let results = [];
65
+ for (let i = 0; i < dataNode.length; i++) {
66
+ let result = walk([schemaNode.items].concat(schemaAncestors), dataNode[i], dataPath + '/' + i);
67
+ if (result)
68
+ results.push(result);
69
+ }
70
+ if (results.length)
71
+ return results.reduce((acc, v) => acc.concat(v), []);
72
+ }
73
+ break;
74
+ }
75
+ case 'string': {
76
+ if (typeof dataNode === 'string') {
77
+ let value = dataNode;
78
+ if ('enum' in schemaNode && schemaNode.enum) {
79
+ if (!schemaNode.enum.includes(value)) {
80
+ return {
81
+ type: 'enum',
82
+ dataType: 'value',
83
+ dataPath,
84
+ expectedValues: schemaNode.enum,
85
+ actualValue: value,
86
+ ancestors: schemaAncestors,
87
+ };
88
+ }
89
+ }
90
+ else if ('__validate' in schemaNode && schemaNode.__validate) {
91
+ let validationError = schemaNode.__validate(value);
92
+ if (typeof validationError == 'string') {
93
+ return {
94
+ type: 'other',
95
+ dataType: 'value',
96
+ dataPath,
97
+ message: validationError,
98
+ actualValue: value,
99
+ ancestors: schemaAncestors,
100
+ };
101
+ }
102
+ }
103
+ }
104
+ break;
105
+ }
106
+ case 'number': {
107
+ if (typeof dataNode === 'number') {
108
+ let value = dataNode;
109
+ if ('enum' in schemaNode && schemaNode.enum) {
110
+ if (!schemaNode.enum.includes(value)) {
111
+ return {
112
+ type: 'enum',
113
+ dataType: 'value',
114
+ dataPath,
115
+ expectedValues: schemaNode.enum,
116
+ actualValue: value,
117
+ ancestors: schemaAncestors,
118
+ };
119
+ }
120
+ }
121
+ }
122
+ break;
123
+ }
124
+ case 'object': {
125
+ if (typeof dataNode === 'object' &&
126
+ dataNode !== null &&
127
+ !Array.isArray(dataNode)) {
128
+ let results = [];
129
+ let invalidProps;
130
+ if ('__forbiddenProperties' in schemaNode &&
131
+ schemaNode.__forbiddenProperties) {
132
+ let keys = Object.keys(dataNode);
133
+ invalidProps = schemaNode.__forbiddenProperties.filter((val) => keys.includes(val));
134
+ results.push(...invalidProps.map((k) => ({
135
+ type: 'forbidden-prop',
136
+ dataPath: dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k),
137
+ dataType: 'key',
138
+ prop: k,
139
+ expectedProps: Object.keys(schemaNode.properties),
140
+ actualProps: keys,
141
+ ancestors: schemaAncestors,
142
+ })));
143
+ }
144
+ if ('required' in schemaNode && schemaNode.required) {
145
+ let keys = Object.keys(dataNode);
146
+ let missingKeys = schemaNode.required.filter((val) => !keys.includes(val));
147
+ results.push(...missingKeys.map((k) => ({
148
+ type: 'missing-prop',
149
+ dataPath,
150
+ dataType: 'value',
151
+ prop: k,
152
+ expectedProps: schemaNode.required,
153
+ actualProps: keys,
154
+ ancestors: schemaAncestors,
155
+ })));
156
+ }
157
+ if ('properties' in schemaNode && schemaNode.properties) {
158
+ let { additionalProperties = true } = schemaNode;
159
+ for (let k in dataNode) {
160
+ if (invalidProps && invalidProps.includes(k)) {
161
+ // Don't check type on forbidden props
162
+ continue;
163
+ }
164
+ else if (k in schemaNode.properties) {
165
+ let result = walk([schemaNode.properties[k]].concat(schemaAncestors), dataNode[k], dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k));
166
+ if (result)
167
+ results.push(result);
168
+ }
169
+ else {
170
+ if (typeof additionalProperties === 'boolean') {
171
+ if (!additionalProperties) {
172
+ results.push({
173
+ type: 'enum',
174
+ dataType: 'key',
175
+ dataPath: dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k),
176
+ expectedValues: Object.keys(schemaNode.properties).filter((p) => !(p in dataNode)),
177
+ actualValue: k,
178
+ ancestors: schemaAncestors,
179
+ prettyType: schemaNode.__type,
180
+ });
181
+ }
182
+ }
183
+ else {
184
+ let result = walk([additionalProperties].concat(schemaAncestors), dataNode[k], dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k));
185
+ if (result)
186
+ results.push(result);
187
+ }
188
+ }
189
+ }
190
+ }
191
+ if (results.length)
192
+ return results.reduce((acc, v) => acc.concat(v), []);
193
+ }
194
+ break;
195
+ }
196
+ case 'boolean':
197
+ // NOOP, type was checked already
198
+ break;
199
+ default:
200
+ throw new Error(`Unimplemented schema type ${type}?`);
201
+ }
202
+ }
203
+ }
204
+ else {
205
+ if ('enum' in schemaNode &&
206
+ schemaNode.enum &&
207
+ !schemaNode.enum.includes(dataNode)) {
208
+ return {
209
+ type: 'enum',
210
+ dataType: 'value',
211
+ dataPath: dataPath,
212
+ expectedValues: schemaNode.enum,
213
+ actualValue: schemaNode,
214
+ ancestors: schemaAncestors,
215
+ };
216
+ }
217
+ if ('oneOf' in schemaNode || 'allOf' in schemaNode) {
218
+ let list = 'oneOf' in schemaNode
219
+ ? schemaNode.oneOf
220
+ : 'allOf' in schemaNode
221
+ ? schemaNode.allOf
222
+ : [];
223
+ let results = [];
224
+ for (let f of list) {
225
+ let result = walk([f].concat(schemaAncestors), dataNode, dataPath);
226
+ if (result)
227
+ results.push(result);
228
+ }
229
+ if ('oneOf' in schemaNode
230
+ ? results.length == schemaNode.oneOf.length
231
+ : results.length > 0) {
232
+ // return the result with more values / longer key
233
+ results.sort((a, b) => Array.isArray(a) || Array.isArray(b)
234
+ ? Array.isArray(a) && !Array.isArray(b)
235
+ ? -1
236
+ : !Array.isArray(a) && Array.isArray(b)
237
+ ? 1
238
+ : Array.isArray(a) && Array.isArray(b)
239
+ ? b.length - a.length
240
+ : 0
241
+ : b.dataPath.length - a.dataPath.length);
242
+ return results[0];
243
+ }
244
+ }
245
+ else if ('not' in schemaNode && schemaNode.not) {
246
+ let result = walk([schemaNode.not].concat(schemaAncestors), dataNode, dataPath);
247
+ if (!result || (Array.isArray(result) && result.length == 0)) {
248
+ return {
249
+ type: 'other',
250
+ dataPath,
251
+ dataType: null,
252
+ message: schemaNode.__message,
253
+ actualValue: dataNode,
254
+ ancestors: schemaAncestors,
255
+ };
256
+ }
257
+ }
258
+ }
259
+ return undefined;
260
+ }
261
+ let result = walk([schema], data, '');
262
+ return Array.isArray(result) ? result : result ? [result] : [];
263
+ }
264
+ exports.default = validateSchema;
265
+ function fuzzySearch(expectedValues, actualValue) {
266
+ let result = expectedValues
267
+ .map((exp) => [exp, levenshtein.distance(exp, actualValue)])
268
+ .filter(
269
+ // Remove if more than half of the string would need to be changed
270
+ ([, d]) => d * 2 < actualValue.length);
271
+ result.sort(([, a], [, b]) => a - b);
272
+ return result.map(([v]) => v);
273
+ }
274
+ validateSchema.diagnostic = function (schema, data, origin, message) {
275
+ if (!('map' in data) && !('source' in data || 'data' in data)) {
276
+ throw new Error('At least one of data.source, data.data, or data.map must be defined!');
277
+ }
278
+ let loadedSource;
279
+ function loadSource(loader) {
280
+ if (loadedSource !== undefined) {
281
+ return loadedSource;
282
+ }
283
+ else if (typeof loader === 'function') {
284
+ loadedSource = loader();
285
+ return loadedSource;
286
+ }
287
+ else if (typeof loader === 'string') {
288
+ loadedSource = loader;
289
+ return loadedSource;
290
+ }
291
+ return loadedSource;
292
+ }
293
+ let object;
294
+ if ('map' in data && data.map) {
295
+ object = data.map.data;
296
+ }
297
+ else if ('data' in data && data.data !== undefined) {
298
+ object = data.data;
299
+ }
300
+ else if ('source' in data && data.source) {
301
+ object = JSON.parse(loadSource(data.source) || '');
302
+ }
303
+ else {
304
+ throw new Error('Unable to get object from data');
305
+ }
306
+ let errors = validateSchema(schema, object);
307
+ if (errors.length) {
308
+ let keys = errors.map((e) => {
309
+ let message;
310
+ if (e.type === 'enum') {
311
+ let { actualValue } = e;
312
+ let expectedValues = e.expectedValues.map(String);
313
+ let likely = actualValue != null
314
+ ? fuzzySearch(expectedValues, String(actualValue))
315
+ : [];
316
+ if (likely.length > 0) {
317
+ message = `Did you mean ${likely
318
+ .map((v) => JSON.stringify(v))
319
+ .join(', ')}?`;
320
+ }
321
+ else if (expectedValues.length > 0) {
322
+ message = `Possible values: ${expectedValues
323
+ .map((v) => JSON.stringify(v))
324
+ .join(', ')}`;
325
+ }
326
+ else {
327
+ message = 'Unexpected value';
328
+ }
329
+ }
330
+ else if (e.type === 'forbidden-prop') {
331
+ let { prop, expectedProps, actualProps } = e;
332
+ let likely = fuzzySearch(expectedProps, prop).filter((v) => !actualProps.includes(v));
333
+ if (likely.length > 0) {
334
+ message = `Did you mean ${likely
335
+ .map((v) => JSON.stringify(v))
336
+ .join(', ')}?`;
337
+ }
338
+ else {
339
+ message = 'Unexpected property';
340
+ }
341
+ }
342
+ else if (e.type === 'missing-prop') {
343
+ let { prop, actualProps } = e;
344
+ let likely = fuzzySearch(actualProps, prop);
345
+ if (likely.length > 0) {
346
+ message = `Did you mean ${JSON.stringify(prop)}?`;
347
+ e.dataPath += '/' + likely[0];
348
+ e.dataType = 'key';
349
+ }
350
+ else {
351
+ message = `Missing property ${prop}`;
352
+ }
353
+ }
354
+ else if (e.type === 'type') {
355
+ if (e.prettyType != null) {
356
+ message = `Expected ${e.prettyType}`;
357
+ }
358
+ else {
359
+ message = `Expected type ${e.expectedTypes.join(', ')}`;
360
+ }
361
+ }
362
+ else {
363
+ message = e.message;
364
+ }
365
+ return { key: e.dataPath, type: e.dataType, message };
366
+ });
367
+ let map, code;
368
+ if ('map' in data && data.map) {
369
+ map = data.map;
370
+ code = loadSource(data.source) ?? '';
371
+ }
372
+ else {
373
+ if ('source' in data && data.source) {
374
+ map = loadSource(data.source) ?? '';
375
+ }
376
+ else if ('data' in data && data.data !== undefined) {
377
+ map = JSON.stringify((0, nullthrows_1.default)(data.data), null, '\t');
378
+ }
379
+ else {
380
+ map = '';
381
+ }
382
+ code = map;
383
+ }
384
+ let codeFrames = [
385
+ {
386
+ filePath: data.filePath ?? undefined,
387
+ language: 'json',
388
+ code: code ?? '',
389
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(map, keys.map(({ key, type, message }) => ({
390
+ key: (data.prependKey ?? '') + key,
391
+ type: type,
392
+ message: message != null ? (0, diagnostic_1.escapeMarkdown)(message) : message,
393
+ }))),
394
+ },
395
+ ];
396
+ throw new diagnostic_1.default({
397
+ diagnostic: {
398
+ message: message,
399
+ origin,
400
+ codeFrames,
401
+ },
402
+ });
403
+ }
404
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SharedBuffer = void 0;
4
+ // @ts-expect-error process.browser is a browser-specific property
5
+ if (process.browser) {
6
+ exports.SharedBuffer = ArrayBuffer;
7
+ // Safari has removed the constructor
8
+ if (typeof SharedArrayBuffer !== 'undefined') {
9
+ let channel = new MessageChannel();
10
+ try {
11
+ // Firefox might throw when sending the Buffer over a MessagePort
12
+ channel.port1.postMessage(new SharedArrayBuffer(0));
13
+ exports.SharedBuffer = SharedArrayBuffer;
14
+ }
15
+ catch (_) {
16
+ // NOOP
17
+ }
18
+ channel.port1.close();
19
+ channel.port2.close();
20
+ }
21
+ }
22
+ else {
23
+ exports.SharedBuffer = SharedArrayBuffer;
24
+ }
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SOURCEMAP_EXTENSIONS = exports.SOURCEMAP_RE = void 0;
7
+ exports.matchSourceMappingURL = matchSourceMappingURL;
8
+ exports.loadSourceMapUrl = loadSourceMapUrl;
9
+ exports.loadSourceMap = loadSourceMap;
10
+ exports.remapSourceLocation = remapSourceLocation;
11
+ const feature_flags_1 = require("@atlaspack/feature-flags");
12
+ const source_map_1 = __importDefault(require("@atlaspack/source-map"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const path_2 = require("./path");
15
+ exports.SOURCEMAP_RE = /(?:\/\*|\/\/)\s*[@#]\s*sourceMappingURL\s*=\s*([^\s*]+)(?:\s*\*\/)?\s*$/;
16
+ const DATA_URL_RE = /^data:[^;]+(?:;charset=[^;]+)?;base64,(.*)/;
17
+ exports.SOURCEMAP_EXTENSIONS = new Set([
18
+ 'css',
19
+ 'es',
20
+ 'es6',
21
+ 'js',
22
+ 'jsx',
23
+ 'mjs',
24
+ 'ts',
25
+ 'tsx',
26
+ ]);
27
+ function matchSourceMappingURL(contents) {
28
+ return contents.match(exports.SOURCEMAP_RE);
29
+ }
30
+ async function loadSourceMapUrl(fs, filename, contents) {
31
+ let match = matchSourceMappingURL(contents);
32
+ if (match) {
33
+ let url = match[1].trim();
34
+ let dataURLMatch = url.match(DATA_URL_RE);
35
+ let mapFilePath;
36
+ if (dataURLMatch) {
37
+ mapFilePath = filename;
38
+ }
39
+ else {
40
+ mapFilePath = url.replace(/^file:\/\//, '');
41
+ mapFilePath = (0, path_2.isAbsolute)(mapFilePath)
42
+ ? mapFilePath
43
+ : path_1.default.join(path_1.default.dirname(filename), mapFilePath);
44
+ }
45
+ return {
46
+ url,
47
+ filename: mapFilePath,
48
+ map: JSON.parse(dataURLMatch
49
+ ? Buffer.from(dataURLMatch[1], 'base64').toString()
50
+ : await fs.readFile(mapFilePath, 'utf8')),
51
+ };
52
+ }
53
+ }
54
+ async function loadSourceMap(filename, contents, options) {
55
+ let foundMap = await loadSourceMapUrl(options.fs, filename, contents);
56
+ if (foundMap) {
57
+ let mapSourceRoot = path_1.default.dirname(filename);
58
+ if (foundMap.map.sourceRoot &&
59
+ !(0, path_2.normalizeSeparators)(foundMap.map.sourceRoot).startsWith('/')) {
60
+ mapSourceRoot = path_1.default.join(mapSourceRoot, foundMap.map.sourceRoot);
61
+ }
62
+ let sourcemapInstance = new source_map_1.default(options.projectRoot);
63
+ sourcemapInstance.addVLQMap({
64
+ ...foundMap.map,
65
+ sources: foundMap.map.sources.map((s) => {
66
+ return path_1.default.join(mapSourceRoot, s);
67
+ }),
68
+ });
69
+ return sourcemapInstance;
70
+ }
71
+ }
72
+ function remapSourceLocation(loc, originalMap, projectRoot) {
73
+ let { filePath, start: { line: startLine, column: startCol }, end: { line: endLine, column: endCol }, } = loc;
74
+ let lineDiff = endLine - startLine;
75
+ let colDiff = endCol - startCol;
76
+ let start = originalMap.findClosestMapping(startLine, startCol - 1);
77
+ let end = originalMap.findClosestMapping(endLine, endCol - 1);
78
+ if (start?.original) {
79
+ if (start.source) {
80
+ if ((0, feature_flags_1.getFeatureFlag)('symbolLocationFix') &&
81
+ !path_1.default.isAbsolute(start.source)) {
82
+ filePath = path_1.default.join(projectRoot, start.source);
83
+ }
84
+ else {
85
+ filePath = start.source;
86
+ }
87
+ }
88
+ ({ line: startLine, column: startCol } = start.original);
89
+ startCol++; // source map columns are 0-based
90
+ }
91
+ if (end?.original) {
92
+ ({ line: endLine, column: endCol } = end.original);
93
+ endCol++; // source map columns are 0-based
94
+ if (endLine < startLine) {
95
+ endLine = startLine;
96
+ endCol = startCol;
97
+ }
98
+ else if (endLine === startLine && endCol < startCol && lineDiff === 0) {
99
+ endCol = startCol + colDiff;
100
+ }
101
+ else if (endLine === startLine && startCol === endCol && lineDiff === 0) {
102
+ // Prevent 0-length ranges
103
+ endCol = startCol + 1;
104
+ }
105
+ }
106
+ else {
107
+ endLine = startLine;
108
+ endCol = startCol;
109
+ }
110
+ return {
111
+ filePath,
112
+ start: {
113
+ line: startLine,
114
+ column: startCol,
115
+ },
116
+ end: {
117
+ line: endLine,
118
+ column: endCol,
119
+ },
120
+ };
121
+ }
package/dist/stream.js ADDED
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.measureStreamLength = measureStreamLength;
4
+ exports.readableFromStringOrBuffer = readableFromStringOrBuffer;
5
+ exports.bufferStream = bufferStream;
6
+ exports.blobToStream = blobToStream;
7
+ exports.streamFromPromise = streamFromPromise;
8
+ exports.fallbackStream = fallbackStream;
9
+ const stream_1 = require("stream");
10
+ function measureStreamLength(stream) {
11
+ return new Promise((resolve, reject) => {
12
+ let length = 0;
13
+ stream.on('data', (chunk) => {
14
+ length += chunk;
15
+ });
16
+ stream.on('end', () => resolve(length));
17
+ stream.on('error', reject);
18
+ });
19
+ }
20
+ function readableFromStringOrBuffer(str) {
21
+ // https://stackoverflow.com/questions/12755997/how-to-create-streams-from-string-in-node-js
22
+ const stream = new stream_1.Readable();
23
+ stream.push(str);
24
+ stream.push(null);
25
+ return stream;
26
+ }
27
+ function bufferStream(stream) {
28
+ return new Promise((resolve, reject) => {
29
+ let buf = Buffer.from([]);
30
+ stream.on('data', (data) => {
31
+ buf = Buffer.concat([buf, data]);
32
+ });
33
+ stream.on('end', () => {
34
+ resolve(buf);
35
+ });
36
+ stream.on('error', reject);
37
+ });
38
+ }
39
+ function blobToStream(blob) {
40
+ if (blob instanceof stream_1.Readable) {
41
+ return blob;
42
+ }
43
+ return readableFromStringOrBuffer(blob);
44
+ }
45
+ function streamFromPromise(promise) {
46
+ const stream = new stream_1.PassThrough();
47
+ promise.then((blob) => {
48
+ if (blob instanceof stream_1.Readable) {
49
+ blob.pipe(stream);
50
+ }
51
+ else {
52
+ stream.end(blob);
53
+ }
54
+ });
55
+ return stream;
56
+ }
57
+ function fallbackStream(stream, fallback) {
58
+ const res = new stream_1.PassThrough();
59
+ stream.on('error', (err) => {
60
+ if (err.code === 'ENOENT') {
61
+ fallback().pipe(res);
62
+ }
63
+ else {
64
+ res.emit('error', err);
65
+ }
66
+ });
67
+ stream.pipe(res);
68
+ return res;
69
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = throttle;
4
+ function throttle(fn, delay) {
5
+ let lastCalled;
6
+ return function throttled(...args) {
7
+ if (lastCalled == null || lastCalled + delay <= Date.now()) {
8
+ fn.call(this, ...args);
9
+ lastCalled = Date.now();
10
+ }
11
+ };
12
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = urlJoin;
7
+ const url_1 = __importDefault(require("url"));
8
+ const path_1 = __importDefault(require("path"));
9
+ /**
10
+ * Joins a path onto a URL, and normalizes Windows paths
11
+ * e.g. from \path\to\res.js to /path/to/res.js.
12
+ */
13
+ function urlJoin(publicURL, assetPath) {
14
+ const url = url_1.default.parse(publicURL, false, true);
15
+ // Leading / ensures that paths with colons are not parsed as a protocol.
16
+ let p = assetPath.startsWith('/') ? assetPath : '/' + assetPath;
17
+ const assetUrl = url_1.default.parse(p);
18
+ url.pathname = path_1.default.posix.join(url.pathname ?? '', assetUrl.pathname ?? '');
19
+ url.search = assetUrl.search;
20
+ url.hash = assetUrl.hash;
21
+ return url_1.default.format(url);
22
+ }