@stencil/core 5.0.0-alpha.27 → 5.0.0-alpha.29

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 (44) hide show
  1. package/dist/app-data/index.d.ts +1 -1
  2. package/dist/{client-CvcvHKz4.mjs → client-D1MsT-Rp.mjs} +373 -238
  3. package/dist/compiler/index.d.mts +2 -3
  4. package/dist/compiler/index.mjs +3 -3
  5. package/dist/compiler/utils/index.d.mts +272 -2
  6. package/dist/compiler/utils/index.mjs +4 -3
  7. package/dist/{compiler-D43Ied7R.mjs → compiler-BbS9TDF_.mjs} +1845 -1118
  8. package/dist/declarations/stencil-ext-modules.d.ts +5 -5
  9. package/dist/declarations/stencil-public-compiler.d.ts +108 -40
  10. package/dist/declarations/stencil-public-docs.d.ts +9 -0
  11. package/dist/declarations/stencil-public-runtime.d.ts +81 -6
  12. package/dist/fragment-Di1hWOC8.mjs +4 -0
  13. package/dist/{index-F3IidHM1.d.mts → index-BHj3EBl2.d.mts} +395 -312
  14. package/dist/{index-xAkMgLX_.d.ts → index-D2PAsXxx.d.ts} +133 -9
  15. package/dist/index-VK8okIiF.d.mts +108 -0
  16. package/dist/index.d.mts +4 -0
  17. package/dist/index.mjs +91 -2
  18. package/dist/jsx-runtime.mjs +2 -1
  19. package/dist/{node-DKVq_Ud0.mjs → node-BQR4L-TG.mjs} +60 -58
  20. package/dist/reactive-controller-BdCpSAQP.d.mts +13 -0
  21. package/dist/{regular-expression-CFVJOTUh.mjs → regular-expression-XqU5zmPp.mjs} +20 -3
  22. package/dist/{chunk-z9aeyW2b.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  23. package/dist/runtime/client/lazy.js +411 -165
  24. package/dist/runtime/client/runtime.d.ts +136 -9
  25. package/dist/runtime/client/runtime.js +411 -165
  26. package/dist/runtime/index.d.ts +5 -3
  27. package/dist/runtime/index.js +410 -163
  28. package/dist/runtime/server/index.d.mts +80 -8
  29. package/dist/runtime/server/index.mjs +333 -158
  30. package/dist/runtime/server/runner.d.mts +3 -0
  31. package/dist/runtime/server/runner.mjs +232 -308
  32. package/dist/signals/index.d.ts +2 -0
  33. package/dist/sys/node/index.d.mts +1 -2
  34. package/dist/sys/node/index.mjs +1 -1
  35. package/dist/sys/node/worker.d.mts +1 -1
  36. package/dist/sys/node/worker.mjs +6 -3
  37. package/dist/testing/index.d.mts +4 -9
  38. package/dist/testing/index.mjs +74 -56
  39. package/dist/util-BIa-iHnt.mjs +724 -0
  40. package/dist/validation-Dd3g77T5.mjs +778 -0
  41. package/package.json +27 -27
  42. package/dist/index-3fu7WQs4.d.mts +0 -205
  43. package/dist/validation-ByxKj8bC.mjs +0 -1458
  44. /package/{LICENSE.md → LICENSE} +0 -0
@@ -0,0 +1,778 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { G as MEMBER_FLAGS, U as LISTENER_FLAGS, b as toTitleCase, p as isString, tt as WATCH_FLAGS, u as isIterable, w as CMP_FLAGS } from "./regular-expression-XqU5zmPp.mjs";
3
+ import { K as normalizePath, Q as buildWarn } from "./util-BIa-iHnt.mjs";
4
+ //#region src/utils/byte-size.ts
5
+ /**
6
+ * Used to learn the size of a string in bytes.
7
+ *
8
+ * @param str The string to measure
9
+ * @returns number
10
+ */
11
+ const byteSize = (str) => Buffer.byteLength(str, "utf8");
12
+ //#endregion
13
+ //#region src/utils/format-component-runtime-meta.ts
14
+ const formatLazyBundleRuntimeMeta = (bundleId, cmps) => {
15
+ return [bundleId, cmps.map((cmp) => formatComponentRuntimeMeta(cmp, true))];
16
+ };
17
+ /**
18
+ * Transform metadata about a component from the compiler to a compact form for
19
+ * use at runtime.
20
+ *
21
+ * @param compilerMeta component metadata gathered during compilation
22
+ * @param includeMethods include methods in the component's members or not
23
+ * @returns a compact format for component metadata, intended for runtime use
24
+ */
25
+ const formatComponentRuntimeMeta = (compilerMeta, includeMethods) => {
26
+ let flags = 0;
27
+ if (compilerMeta.encapsulation === "shadow") {
28
+ flags |= CMP_FLAGS.shadowDomEncapsulation;
29
+ if (compilerMeta.shadowDelegatesFocus) flags |= CMP_FLAGS.shadowDelegatesFocus;
30
+ if (compilerMeta.slotAssignment === "manual") flags |= CMP_FLAGS.shadowSlotAssignmentManual;
31
+ if (compilerMeta.shadowMode === "closed") flags |= CMP_FLAGS.shadowModeClosed;
32
+ } else if (compilerMeta.encapsulation === "scoped") flags |= CMP_FLAGS.scopedCssEncapsulation;
33
+ if (compilerMeta.formAssociated) flags |= CMP_FLAGS.formAssociated;
34
+ if (compilerMeta.encapsulation !== "shadow" && compilerMeta.htmlTagNames.includes("slot")) flags |= CMP_FLAGS.hasSlotRelocation;
35
+ if (compilerMeta.hasSlot) flags |= CMP_FLAGS.hasSlot;
36
+ if (compilerMeta.hasMode) flags |= CMP_FLAGS.hasMode;
37
+ if (compilerMeta.hasModernPropertyDecls) flags |= CMP_FLAGS.hasModernPropertyDecls;
38
+ if (compilerMeta.patches) {
39
+ if (compilerMeta.patches.all) flags |= CMP_FLAGS.patchAll;
40
+ if (compilerMeta.patches.children) flags |= CMP_FLAGS.patchChildren;
41
+ if (compilerMeta.patches.clone) flags |= CMP_FLAGS.patchClone;
42
+ if (compilerMeta.patches.insert) flags |= CMP_FLAGS.patchInsert;
43
+ }
44
+ const members = formatComponentRuntimeMembers(compilerMeta, includeMethods);
45
+ const hostListeners = formatHostListeners(compilerMeta);
46
+ const watchers = formatComponentRuntimeReactiveHandlers(compilerMeta, "watchers");
47
+ const serializers = formatComponentRuntimeReactiveHandlers(compilerMeta, "serializers");
48
+ const deserializers = formatComponentRuntimeReactiveHandlers(compilerMeta, "deserializers");
49
+ return trimFalsy([
50
+ flags,
51
+ compilerMeta.tagName,
52
+ Object.keys(members).length > 0 ? members : void 0,
53
+ hostListeners.length > 0 ? hostListeners : void 0,
54
+ Object.keys(watchers).length > 0 ? watchers : void 0,
55
+ Object.keys(serializers).length > 0 ? serializers : void 0,
56
+ Object.keys(deserializers).length > 0 ? deserializers : void 0
57
+ ]);
58
+ };
59
+ const stringifyRuntimeData = (data) => {
60
+ const json = JSON.stringify(data);
61
+ if (json.length > 1e4) return `JSON.parse(${JSON.stringify(json)})`;
62
+ return json;
63
+ };
64
+ /**
65
+ * Transforms Stencil compiler metadata into a {@link d.ComponentCompilerMeta} object.
66
+ * This handles processing any compiler metadata transformed from components' uses of `@Watch()`, `@PropSerialize()`, and `@AttrDeserialize()`.
67
+ * The map of watched properties to their callback(s) will be immediately available
68
+ * to the runtime at bootstrap.
69
+ *
70
+ * @param compilerMeta Component metadata gathered during compilation
71
+ * @param decorator The decorator type to be processed: 'watchers', 'serializers', or 'deserializers'
72
+ * @returns An object mapping watched properties to their respective callback(s)
73
+ */
74
+ const formatComponentRuntimeReactiveHandlers = (compilerMeta, decorator) => {
75
+ const handlers = {};
76
+ compilerMeta[decorator]?.forEach(({ propName, methodName, handlerOptions }) => {
77
+ let watcherFlags = 0;
78
+ if (handlerOptions?.immediate) watcherFlags |= WATCH_FLAGS.Immediate;
79
+ handlers[propName] = [...handlers[propName] ?? [], { [methodName]: watcherFlags }];
80
+ });
81
+ return handlers;
82
+ };
83
+ const formatComponentRuntimeMembers = (compilerMeta, includeMethods = true) => {
84
+ return {
85
+ ...formatPropertiesRuntimeMember(compilerMeta.properties),
86
+ ...formatStatesRuntimeMember(compilerMeta.states),
87
+ ...includeMethods ? formatMethodsRuntimeMember(compilerMeta.methods) : {}
88
+ };
89
+ };
90
+ const formatPropertiesRuntimeMember = (properties) => {
91
+ const runtimeMembers = {};
92
+ properties.forEach((member) => {
93
+ runtimeMembers[member.name] = trimFalsy([formatFlags(member), formatAttrName(member)]);
94
+ });
95
+ return runtimeMembers;
96
+ };
97
+ const formatFlags = (compilerProperty) => {
98
+ let type = formatPropType(compilerProperty.type);
99
+ if (compilerProperty.mutable) type |= MEMBER_FLAGS.Mutable;
100
+ if (compilerProperty.reflect) type |= MEMBER_FLAGS.ReflectAttr;
101
+ if (compilerProperty.getter) type |= MEMBER_FLAGS.Getter;
102
+ if (compilerProperty.setter) type |= MEMBER_FLAGS.Setter;
103
+ return type;
104
+ };
105
+ /**
106
+ * We mainly add the alternative kebab-case attribute name because it might
107
+ * be used in an HTML environment (non JSX). Since we support hydration of
108
+ * complex types we provide a kebab-case attribute name for properties with
109
+ * these types.
110
+ */
111
+ const kebabCaseSupportForTypes = ["string", "unknown"];
112
+ const formatAttrName = (compilerProperty) => {
113
+ if (kebabCaseSupportForTypes.includes(typeof compilerProperty.attribute)) {
114
+ if (compilerProperty.name === compilerProperty.attribute) return;
115
+ return compilerProperty.attribute;
116
+ }
117
+ };
118
+ const formatPropType = (type) => {
119
+ if (type === "string") return MEMBER_FLAGS.String;
120
+ if (type === "number") return MEMBER_FLAGS.Number;
121
+ if (type === "boolean") return MEMBER_FLAGS.Boolean;
122
+ if (type === "any") return MEMBER_FLAGS.Any;
123
+ return MEMBER_FLAGS.Unknown;
124
+ };
125
+ const formatStatesRuntimeMember = (states) => {
126
+ const runtimeMembers = {};
127
+ states.forEach((member) => {
128
+ runtimeMembers[member.name] = [MEMBER_FLAGS.State];
129
+ });
130
+ return runtimeMembers;
131
+ };
132
+ const formatMethodsRuntimeMember = (methods) => {
133
+ const runtimeMembers = {};
134
+ methods.forEach((member) => {
135
+ runtimeMembers[member.name] = [MEMBER_FLAGS.Method];
136
+ });
137
+ return runtimeMembers;
138
+ };
139
+ const formatHostListeners = (compilerMeta) => {
140
+ return compilerMeta.listeners.map((compilerListener) => {
141
+ return [
142
+ computeListenerFlags(compilerListener),
143
+ compilerListener.name,
144
+ compilerListener.method
145
+ ];
146
+ });
147
+ };
148
+ const computeListenerFlags = (listener) => {
149
+ let flags = 0;
150
+ if (listener.capture) flags |= LISTENER_FLAGS.Capture;
151
+ if (listener.passive) flags |= LISTENER_FLAGS.Passive;
152
+ switch (listener.target) {
153
+ case "document":
154
+ flags |= LISTENER_FLAGS.TargetDocument;
155
+ break;
156
+ case "window":
157
+ flags |= LISTENER_FLAGS.TargetWindow;
158
+ break;
159
+ case "body": flags |= LISTENER_FLAGS.TargetBody;
160
+ }
161
+ return flags;
162
+ };
163
+ const trimFalsy = (data) => {
164
+ const arr = data;
165
+ for (let i = arr.length - 1; i >= 0; i--) {
166
+ if (arr[i]) break;
167
+ arr.pop();
168
+ }
169
+ return arr;
170
+ };
171
+ //#endregion
172
+ //#region src/utils/is-root-path.ts
173
+ /**
174
+ * Checks if the path is the Operating System (OS) root path, such as "/" or "C:\". This function does not take the OS
175
+ * the code is running on into account when performing this evaluation.
176
+ * @param p the path to check
177
+ * @returns `true` if the path is an OS root path, `false` otherwise
178
+ */
179
+ const isRootPath = (p) => p === "/" || windowsPathRegex.test(p);
180
+ const windowsPathRegex = /^(?:[a-zA-Z]:|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)?[\\/]$/;
181
+ //#endregion
182
+ //#region src/utils/logger/logger-utils.ts
183
+ /**
184
+ * Iterate through a series of diagnostics to provide minor fix-ups for various edge cases, deduplicate messages, etc.
185
+ * @param compilerCtx the current compiler context
186
+ * @param diagnostics the diagnostics to normalize
187
+ * @returns the normalize documents
188
+ */
189
+ const normalizeDiagnostics = (compilerCtx, diagnostics) => {
190
+ const maxErrorsToNormalize = 25;
191
+ const normalizedErrors = [];
192
+ const normalizedOthers = [];
193
+ const dups = /* @__PURE__ */ new Set();
194
+ for (let i = 0; i < diagnostics.length; i++) {
195
+ const diagnostic = normalizeDiagnostic(compilerCtx, diagnostics[i]);
196
+ const key = (diagnostic.absFilePath ?? "") + (diagnostic.code ?? "") + diagnostic.messageText + diagnostic.type;
197
+ if (dups.has(key)) continue;
198
+ dups.add(key);
199
+ const total = normalizedErrors.length + normalizedOthers.length;
200
+ if (diagnostic.level === "error") normalizedErrors.push(diagnostic);
201
+ else if (total < maxErrorsToNormalize) normalizedOthers.push(diagnostic);
202
+ }
203
+ return [...normalizedErrors, ...normalizedOthers];
204
+ };
205
+ /**
206
+ * Perform post-processing on a `Diagnostic` to handle a few message edge cases, massaging error message text and
207
+ * updating build failure contexts
208
+ * @param compilerCtx the current compiler
209
+ * @param diagnostic the diagnostic to normalize
210
+ * @returns the altered diagnostic
211
+ */
212
+ const normalizeDiagnostic = (compilerCtx, diagnostic) => {
213
+ if (diagnostic.messageText) {
214
+ if (typeof diagnostic.messageText.message === "string") diagnostic.messageText = diagnostic.messageText.message;
215
+ else if (typeof diagnostic.messageText === "string" && diagnostic.messageText.indexOf("Error: ") === 0) diagnostic.messageText = diagnostic.messageText.slice(7);
216
+ }
217
+ if (diagnostic.messageText) {
218
+ if (diagnostic.messageText.includes(`Cannot find name 'h'`)) {
219
+ diagnostic.header = `Missing "h" import for JSX types`;
220
+ diagnostic.messageText = `In order to load accurate JSX types for components, the "h" function must be imported from "@stencil/core" by each component using JSX. For example: import { Component, h } from '@stencil/core';`;
221
+ if (diagnostic.absFilePath) try {
222
+ const sourceText = compilerCtx.fs.readFileSync(diagnostic.absFilePath);
223
+ const srcLines = splitLineBreaks(sourceText);
224
+ for (let i = 0; i < srcLines.length; i++) {
225
+ const srcLine = srcLines[i];
226
+ if (srcLine.includes("@stencil/core")) {
227
+ const msgLines = [];
228
+ const beforeLineIndex = i - 1;
229
+ if (beforeLineIndex > -1) {
230
+ const beforeLine = {
231
+ lineIndex: beforeLineIndex,
232
+ lineNumber: beforeLineIndex + 1,
233
+ text: srcLines[beforeLineIndex],
234
+ errorCharStart: -1,
235
+ errorLength: -1
236
+ };
237
+ msgLines.push(beforeLine);
238
+ }
239
+ const errorLine = {
240
+ lineIndex: i,
241
+ lineNumber: i + 1,
242
+ text: srcLine,
243
+ errorCharStart: 0,
244
+ errorLength: -1
245
+ };
246
+ msgLines.push(errorLine);
247
+ diagnostic.lineNumber = errorLine.lineNumber;
248
+ diagnostic.columnNumber = srcLine.indexOf("}");
249
+ const afterLineIndex = i + 1;
250
+ if (afterLineIndex < srcLines.length) {
251
+ const afterLine = {
252
+ lineIndex: afterLineIndex,
253
+ lineNumber: afterLineIndex + 1,
254
+ text: srcLines[afterLineIndex],
255
+ errorCharStart: -1,
256
+ errorLength: -1
257
+ };
258
+ msgLines.push(afterLine);
259
+ }
260
+ diagnostic.lines = msgLines;
261
+ break;
262
+ }
263
+ }
264
+ } catch {}
265
+ }
266
+ }
267
+ return diagnostic;
268
+ };
269
+ /**
270
+ * Split a corpus by newlines. Carriage returns are treated a newlines.
271
+ * @param sourceText the corpus to split
272
+ * @returns the split text
273
+ */
274
+ const splitLineBreaks = (sourceText) => {
275
+ if (typeof sourceText !== "string") return [];
276
+ sourceText = sourceText.replace(/\\r/g, "\n");
277
+ return sourceText.split("\n");
278
+ };
279
+ const escapeHtml = (unsafe) => {
280
+ if (unsafe === void 0) return "undefined";
281
+ if (unsafe === null) return "null";
282
+ if (typeof unsafe !== "string") unsafe = unsafe.toString();
283
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
284
+ };
285
+ //#endregion
286
+ //#region src/utils/logger/logger-rolldown.ts
287
+ const isRolldownError = (e) => typeof e === "object" && e !== null && "message" in e;
288
+ const loadRolldownDiagnostics = (config, compilerCtx, buildCtx, rolldownError) => {
289
+ const formattedCode = formatErrorCode(rolldownError.code);
290
+ const diagnostic = {
291
+ level: "error",
292
+ type: "bundling",
293
+ language: "javascript",
294
+ code: rolldownError.code,
295
+ header: `Rolldown${formattedCode.length > 0 ? ": " + formattedCode : ""}`,
296
+ messageText: formattedCode,
297
+ relFilePath: void 0,
298
+ absFilePath: void 0,
299
+ lines: []
300
+ };
301
+ if (config.logLevel === "debug" && rolldownError.stack) diagnostic.messageText = rolldownError.stack;
302
+ else if (rolldownError.message) diagnostic.messageText = rolldownError.message;
303
+ if (rolldownError.plugin) diagnostic.messageText += ` (plugin: ${rolldownError.plugin}${rolldownError.hook ? `, ${rolldownError.hook}` : ""})`;
304
+ const loc = rolldownError.loc;
305
+ if (loc != null) {
306
+ const srcFile = loc.file || rolldownError.id;
307
+ if (isString(srcFile)) try {
308
+ const sourceText = compilerCtx.fs.readFileSync(srcFile);
309
+ if (sourceText) {
310
+ diagnostic.absFilePath = srcFile;
311
+ try {
312
+ const srcLines = splitLineBreaks(sourceText);
313
+ const errorLine = {
314
+ lineIndex: loc.line - 1,
315
+ lineNumber: loc.line,
316
+ text: srcLines[loc.line - 1],
317
+ errorCharStart: loc.column,
318
+ errorLength: 0
319
+ };
320
+ diagnostic.lineNumber = errorLine.lineNumber;
321
+ diagnostic.columnNumber = errorLine.errorCharStart;
322
+ const highlightLine = errorLine.text?.slice(loc.column) ?? "";
323
+ for (let i = 0; i < highlightLine.length; i++) {
324
+ if (charBreak.has(highlightLine.charAt(i))) break;
325
+ errorLine.errorLength++;
326
+ }
327
+ diagnostic.lines.push(errorLine);
328
+ if (errorLine.errorLength === 0 && errorLine.errorCharStart > 0) {
329
+ errorLine.errorLength = 1;
330
+ errorLine.errorCharStart--;
331
+ }
332
+ if (errorLine.lineIndex > 0) {
333
+ const previousLine = {
334
+ lineIndex: errorLine.lineIndex - 1,
335
+ lineNumber: errorLine.lineNumber - 1,
336
+ text: srcLines[errorLine.lineIndex - 1],
337
+ errorCharStart: -1,
338
+ errorLength: -1
339
+ };
340
+ diagnostic.lines.unshift(previousLine);
341
+ }
342
+ if (errorLine.lineIndex + 1 < srcLines.length) {
343
+ const nextLine = {
344
+ lineIndex: errorLine.lineIndex + 1,
345
+ lineNumber: errorLine.lineNumber + 1,
346
+ text: srcLines[errorLine.lineIndex + 1],
347
+ errorCharStart: -1,
348
+ errorLength: -1
349
+ };
350
+ diagnostic.lines.push(nextLine);
351
+ }
352
+ } catch {
353
+ diagnostic.messageText += `\nError parsing: ${diagnostic.absFilePath}, line: ${loc.line}, column: ${loc.column}`;
354
+ diagnostic.debugText = sourceText;
355
+ }
356
+ } else if (typeof rolldownError.frame === "string") diagnostic.messageText += "\n" + rolldownError.frame;
357
+ } catch {}
358
+ }
359
+ buildCtx.diagnostics.push(diagnostic);
360
+ };
361
+ const createOnWarnFn = (diagnostics, bundleModulesFiles) => {
362
+ const previousWarns = /* @__PURE__ */ new Set();
363
+ return function onWarningMessage(warning) {
364
+ if (warning == null || warning.code && ignoreWarnCodes.has(warning.code) || warning.message && previousWarns.has(warning.message)) return;
365
+ if (warning.message) previousWarns.add(warning.message);
366
+ let label = "";
367
+ if (bundleModulesFiles) {
368
+ label = bundleModulesFiles.reduce((cmps, m) => {
369
+ cmps.push(...m.cmps);
370
+ return cmps;
371
+ }, []).join(", ").trim();
372
+ if (label.length) label += ": ";
373
+ }
374
+ const diagnostic = buildWarn(diagnostics);
375
+ diagnostic.header = `Bundling Warning ${warning.code}`;
376
+ diagnostic.messageText = label + (warning.message || warning);
377
+ };
378
+ };
379
+ const ignoreWarnCodes = /* @__PURE__ */ new Set([
380
+ "THIS_IS_UNDEFINED",
381
+ "NON_EXISTENT_EXPORT",
382
+ "CIRCULAR_DEPENDENCY",
383
+ "EMPTY_BUNDLE",
384
+ "UNUSED_EXTERNAL_IMPORT",
385
+ "EMPTY_IMPORT_META"
386
+ ]);
387
+ const charBreak = /* @__PURE__ */ new Set([
388
+ " ",
389
+ "=",
390
+ ".",
391
+ ",",
392
+ "?",
393
+ ":",
394
+ ";",
395
+ "(",
396
+ ")",
397
+ "{",
398
+ "}",
399
+ "[",
400
+ "]",
401
+ "|",
402
+ `'`,
403
+ `"`,
404
+ "`"
405
+ ]);
406
+ const formatErrorCode = (errorCode) => {
407
+ if (typeof errorCode === "string") return errorCode.split("_").map((c) => {
408
+ return toTitleCase(c.toLowerCase());
409
+ }).join(" ");
410
+ return (errorCode || "").trim();
411
+ };
412
+ //#endregion
413
+ //#region src/utils/logger/logger-typescript.ts
414
+ /**
415
+ * Augment a `Diagnostic` with information from a `Node` in the AST to provide richer error information
416
+ * @param d the diagnostic to augment
417
+ * @param node the node to augment with additional information
418
+ * @returns the augmented diagnostic
419
+ */
420
+ const augmentDiagnosticWithNode = (d, node) => {
421
+ if (!node) return d;
422
+ const sourceFile = node.getSourceFile();
423
+ if (!sourceFile) return d;
424
+ d.absFilePath = normalizePath(sourceFile.fileName);
425
+ const sourceText = sourceFile.text;
426
+ const srcLines = splitLineBreaks(sourceText);
427
+ const start = node.getStart();
428
+ const end = node.getEnd();
429
+ const posStart = sourceFile.getLineAndCharacterOfPosition(start);
430
+ const errorLine = {
431
+ lineIndex: posStart.line,
432
+ lineNumber: posStart.line + 1,
433
+ text: srcLines[posStart.line],
434
+ errorCharStart: posStart.character,
435
+ errorLength: Math.max(end - start, 1)
436
+ };
437
+ d.lineNumber = errorLine.lineNumber;
438
+ d.columnNumber = errorLine.errorCharStart + 1;
439
+ d.lines.push(errorLine);
440
+ if (errorLine.errorLength === 0 && errorLine.errorCharStart > 0) {
441
+ errorLine.errorLength = 1;
442
+ errorLine.errorCharStart--;
443
+ }
444
+ if (errorLine.lineIndex > 0) {
445
+ const previousLine = {
446
+ lineIndex: errorLine.lineIndex - 1,
447
+ lineNumber: errorLine.lineNumber - 1,
448
+ text: srcLines[errorLine.lineIndex - 1],
449
+ errorCharStart: -1,
450
+ errorLength: -1
451
+ };
452
+ d.lines.unshift(previousLine);
453
+ }
454
+ if (errorLine.lineIndex + 1 < srcLines.length) {
455
+ const nextLine = {
456
+ lineIndex: errorLine.lineIndex + 1,
457
+ lineNumber: errorLine.lineNumber + 1,
458
+ text: srcLines[errorLine.lineIndex + 1],
459
+ errorCharStart: -1,
460
+ errorLength: -1
461
+ };
462
+ d.lines.push(nextLine);
463
+ }
464
+ return d;
465
+ };
466
+ /**
467
+ * Ok, so formatting overkill, we know. But whatever, it makes for great
468
+ * error reporting within a terminal. So, yeah, let's code it up, shall we?
469
+ */
470
+ /**
471
+ * Convert an array of TypeScript diagnostics to Stencil diagnostic format.
472
+ *
473
+ * @param tsDiagnostics - array of TypeScript diagnostic objects
474
+ * @returns array of Stencil diagnostic objects
475
+ */
476
+ const loadTypeScriptDiagnostics = (tsDiagnostics) => {
477
+ const diagnostics = [];
478
+ const maxErrors = Math.min(tsDiagnostics.length, 50);
479
+ for (let i = 0; i < maxErrors; i++) diagnostics.push(loadTypeScriptDiagnostic(tsDiagnostics[i]));
480
+ return diagnostics;
481
+ };
482
+ /**
483
+ * Convert a TypeScript diagnostic object into our internal, Stencil-specific
484
+ * diagnostic format
485
+ *
486
+ * @param tsDiagnostic a TypeScript diagnostic message record
487
+ * @returns a Stencil diagnostic, suitable for showing an error to the user
488
+ */
489
+ const loadTypeScriptDiagnostic = (tsDiagnostic) => {
490
+ const d = {
491
+ absFilePath: void 0,
492
+ code: tsDiagnostic.code.toString(),
493
+ columnNumber: void 0,
494
+ header: "TypeScript",
495
+ language: "typescript",
496
+ level: "warn",
497
+ lineNumber: void 0,
498
+ lines: [],
499
+ messageText: flattenDiagnosticMessageText(tsDiagnostic, tsDiagnostic.messageText),
500
+ relFilePath: void 0,
501
+ type: "typescript"
502
+ };
503
+ if (tsDiagnostic.category === 1) d.level = "error";
504
+ if (tsDiagnostic.file && typeof tsDiagnostic.start === "number") {
505
+ d.absFilePath = tsDiagnostic.file.fileName;
506
+ const sourceText = tsDiagnostic.file.text;
507
+ const srcLines = splitLineBreaks(sourceText);
508
+ const posData = tsDiagnostic.file.getLineAndCharacterOfPosition(tsDiagnostic.start);
509
+ const errorLine = {
510
+ lineIndex: posData.line,
511
+ lineNumber: posData.line + 1,
512
+ text: srcLines[posData.line],
513
+ errorCharStart: posData.character,
514
+ errorLength: Math.max(tsDiagnostic.length ?? 0, 1)
515
+ };
516
+ d.lineNumber = errorLine.lineNumber;
517
+ d.columnNumber = errorLine.errorCharStart + 1;
518
+ d.lines.push(errorLine);
519
+ if (errorLine.errorLength === 0 && errorLine.errorCharStart > 0) {
520
+ errorLine.errorLength = 1;
521
+ errorLine.errorCharStart--;
522
+ }
523
+ if (errorLine.lineIndex > 0) {
524
+ const previousLine = {
525
+ lineIndex: errorLine.lineIndex - 1,
526
+ lineNumber: errorLine.lineNumber - 1,
527
+ text: srcLines[errorLine.lineIndex - 1],
528
+ errorCharStart: -1,
529
+ errorLength: -1
530
+ };
531
+ d.lines.unshift(previousLine);
532
+ }
533
+ if (errorLine.lineIndex + 1 < srcLines.length) {
534
+ const nextLine = {
535
+ lineIndex: errorLine.lineIndex + 1,
536
+ lineNumber: errorLine.lineNumber + 1,
537
+ text: srcLines[errorLine.lineIndex + 1],
538
+ errorCharStart: -1,
539
+ errorLength: -1
540
+ };
541
+ d.lines.push(nextLine);
542
+ }
543
+ }
544
+ return d;
545
+ };
546
+ /**
547
+ * Flatten a TypeScript diagnostic object into a string which can be easily
548
+ * included in a Stencil diagnostic record.
549
+ *
550
+ * @param tsDiagnostic a TypeScript diagnostic record
551
+ * @param diag a {@link DiagnosticMessageChain} or a string with further info
552
+ * @returns a string with the relevant error message
553
+ */
554
+ const flattenDiagnosticMessageText = (tsDiagnostic, diag) => {
555
+ if (typeof diag === "string") return diag;
556
+ else if (diag === void 0) return "";
557
+ const ignoreCodes = [];
558
+ const isStencilConfig = (tsDiagnostic.file?.fileName ?? "").includes("stencil.config");
559
+ if (isStencilConfig) ignoreCodes.push(2322);
560
+ let result = "";
561
+ if (!ignoreCodes.includes(diag.code)) {
562
+ result = diag.messageText;
563
+ if (isIterable(diag.next)) for (const kid of diag.next) result += flattenDiagnosticMessageText(tsDiagnostic, kid);
564
+ }
565
+ if (isStencilConfig) {
566
+ result = result.replace(`type 'StencilConfig'`, `Stencil Config`);
567
+ result = result.replace(`Object literal may only specify known properties, but `, ``);
568
+ result = result.replace(`Object literal may only specify known properties, and `, ``);
569
+ }
570
+ return result.trim();
571
+ };
572
+ //#endregion
573
+ //#region src/utils/result.ts
574
+ var result_exports = /* @__PURE__ */ __exportAll({
575
+ err: () => err,
576
+ map: () => map,
577
+ ok: () => ok,
578
+ unwrap: () => unwrap,
579
+ unwrapErr: () => unwrapErr
580
+ });
581
+ /**
582
+ * Create an `Ok` given a value. This doesn't do any checking that the value is
583
+ * 'ok-ish' since doing so would make an undue assumption about what is 'ok'.
584
+ * Instead, this trusts the user to determine, at the call site, whether
585
+ * something is `ok()` or `err()`.
586
+ *
587
+ * @param value the value to wrap up in an `Ok`
588
+ * @returns an Ok wrapping the value
589
+ */
590
+ const ok = (value) => ({
591
+ isOk: true,
592
+ isErr: false,
593
+ value
594
+ });
595
+ /**
596
+ * Create an `Err` given a value.
597
+ *
598
+ * @param value the value to wrap up in an `Err`
599
+ * @returns an Ok wrapping the value
600
+ */
601
+ const err = (value) => ({
602
+ isOk: false,
603
+ isErr: true,
604
+ value
605
+ });
606
+ function map(result, fn) {
607
+ if (result.isOk) {
608
+ const val = fn(result.value);
609
+ if (val instanceof Promise) return val.then((newVal) => ok(newVal));
610
+ else return ok(val);
611
+ }
612
+ if (result.isErr) {
613
+ const value = result.value;
614
+ return err(value);
615
+ }
616
+ throw "should never get here";
617
+ }
618
+ /**
619
+ * Unwrap a {@link Result}, return the value inside if it is an `Ok` and
620
+ * throw with the wrapped value if it is an `Err`.
621
+ *
622
+ * @throws with the wrapped value if it is an `Err`.
623
+ * @param result a result to peer inside of
624
+ * @returns the wrapped value, if `Ok`
625
+ */
626
+ const unwrap = (result) => {
627
+ if (result.isOk) return result.value;
628
+ else throw result.value;
629
+ };
630
+ /**
631
+ * Unwrap a {@link Result}, return the value inside if it is an `Err` and
632
+ * throw with the wrapped value if it is an `Ok`.
633
+ *
634
+ * @throws with the wrapped value if it is an `Ok`.
635
+ * @param result a result to peer inside of
636
+ * @returns the wrapped value, if `Err`
637
+ */
638
+ const unwrapErr = (result) => {
639
+ if (result.isErr) return result.value;
640
+ else throw result.value;
641
+ };
642
+ //#endregion
643
+ //#region src/utils/sourcemaps.ts
644
+ function rolldownToStencilSourceMap(rolldownSourceMap) {
645
+ if (!rolldownSourceMap || !rolldownSourceMap.file) return null;
646
+ return {
647
+ file: rolldownSourceMap.file,
648
+ mappings: rolldownSourceMap.mappings,
649
+ names: rolldownSourceMap.names,
650
+ sources: rolldownSourceMap.sources,
651
+ sourcesContent: rolldownSourceMap.sourcesContent,
652
+ version: rolldownSourceMap.version
653
+ };
654
+ }
655
+ /**
656
+ * A JavaScript formatted string used to link generated code back to the original. This string follows the guidelines
657
+ * found in the [Linking generated code to source maps](https://sourcemaps.info/spec.html#h.lmz475t4mvbx) section of
658
+ * the Sourcemaps V3 specification proposal.
659
+ */
660
+ const JS_SOURCE_MAPPING_URL_LINKER = "//# sourceMappingURL=";
661
+ /**
662
+ * Generates an RFC-3986 compliant string for the given input.
663
+ * More information about RFC-3986 can be found [here](https://datatracker.ietf.org/doc/html/rfc3986)
664
+ * This function's original source is derived from
665
+ * [MDN's encodeURIComponent documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#description)
666
+ * @param filename the filename to encode
667
+ * @returns the encoded URI
668
+ */
669
+ const encodeToRfc3986 = (filename) => {
670
+ return encodeURIComponent(filename).replace(/[!'()*]/g, (matchedCharacter) => {
671
+ return "%" + matchedCharacter.charCodeAt(0).toString(16);
672
+ });
673
+ };
674
+ /**
675
+ * Generates a string used to link generated code with the original source, to be placed at the end of the generated
676
+ * code.
677
+ * @param url the url of the source map
678
+ * @returns a linker string, of the format {@link JS_SOURCE_MAPPING_URL_LINKER}=<url>
679
+ */
680
+ const getSourceMappingUrlLinker = (url) => {
681
+ return `${JS_SOURCE_MAPPING_URL_LINKER}${encodeToRfc3986(url)}`;
682
+ };
683
+ /**
684
+ * Generates a string used to link generated code with the original source, to be placed at the end of the generated
685
+ * code as an inline source map.
686
+ * @param sourceMapContents the sourceMapContents of the source map
687
+ * @returns a linker string, of the format {@link JS_SOURCE_MAPPING_URL_LINKER}<dataUriPrefixAndMime><sourceMapContents>
688
+ */
689
+ const getInlineSourceMappingUrlLinker = (sourceMapContents) => {
690
+ const mapBase64 = Buffer.from(sourceMapContents, "utf8").toString("base64");
691
+ return `${JS_SOURCE_MAPPING_URL_LINKER}data:application/json;charset=utf-8;base64,${mapBase64}`;
692
+ };
693
+ /**
694
+ * Generates a string used to link generated code with the original source, to be placed at the end of the generated
695
+ * code. This function prepends a newline to the string.
696
+ * @param url the url of the source map
697
+ * @returns a linker string, of the format {@link JS_SOURCE_MAPPING_URL_LINKER}=<url>.map, prepended with a newline
698
+ */
699
+ const getSourceMappingUrlForEndOfFile = (url) => {
700
+ return `\n${getSourceMappingUrlLinker(url)}.map`;
701
+ };
702
+ //#endregion
703
+ //#region src/utils/url-paths.ts
704
+ /**
705
+ * Determines whether a string should be considered a remote url or not.
706
+ *
707
+ * This helper only checks the provided string to evaluate is one of a few pre-defined schemes, and should not be
708
+ * considered all-encompassing
709
+ *
710
+ * @param p the string to evaluate
711
+ * @returns `true` if the provided string is a remote url, `false` otherwise
712
+ */
713
+ const isRemoteUrl = (p) => {
714
+ if (isString(p)) {
715
+ p = p.toLowerCase();
716
+ return p.startsWith("https://") || p.startsWith("http://");
717
+ }
718
+ return false;
719
+ };
720
+ //#endregion
721
+ //#region src/utils/validation.ts
722
+ const getModeKeys = (value) => {
723
+ if (value == null || typeof value !== "object" || Array.isArray(value) || value.__identifier) return [];
724
+ return Object.keys(value);
725
+ };
726
+ /**
727
+ * Validates the mode keys used in a component's `styleUrls`/`styles` against a
728
+ * `config.modes` allowlist, if one is declared.
729
+ * @param configModes the `config.modes` allowlist (mixed string/{@link d.ModeConfig} entries)
730
+ * @param componentOptions the `@Component()` decorator options for a single component
731
+ * @returns a validation error if a used mode is unknown or a required mode is missing, undefined otherwise
732
+ */
733
+ const validateComponentModes = (configModes, componentOptions) => {
734
+ if (!configModes || configModes.length === 0) return;
735
+ const allowedModes = /* @__PURE__ */ new Map();
736
+ for (const entry of configModes) if (typeof entry === "string") allowedModes.set(entry, false);
737
+ else allowedModes.set(entry.mode, !!entry.required);
738
+ const fields = [{
739
+ propName: "styleUrls",
740
+ keys: getModeKeys(componentOptions.styleUrls)
741
+ }, {
742
+ propName: "styles",
743
+ keys: getModeKeys(componentOptions.styles)
744
+ }];
745
+ for (const field of fields) for (const key of field.keys) if (!allowedModes.has(key)) return {
746
+ propName: field.propName,
747
+ message: `Invalid mode "${key}" in "${field.propName}". Valid modes are: ${[...allowedModes.keys()].join(", ")}.`
748
+ };
749
+ const usedModes = /* @__PURE__ */ new Set([...fields[0].keys, ...fields[1].keys]);
750
+ if (usedModes.size > 0) {
751
+ const missingRequired = [...allowedModes.entries()].filter(([mode, required]) => required && !usedModes.has(mode)).map(([mode]) => mode);
752
+ if (missingRequired.length > 0) return {
753
+ propName: fields[0].keys.length > 0 ? "styleUrls" : "styles",
754
+ message: `Missing required mode${missingRequired.length > 1 ? "s" : ""}: ${missingRequired.join(", ")}.`
755
+ };
756
+ }
757
+ };
758
+ /**
759
+ * Validates that a component tag meets required naming conventions to be used for a web component
760
+ * @param tag the tag to validate
761
+ * @returns an error message if the tag has an invalid name, undefined if the tag name passes all checks
762
+ */
763
+ const validateComponentTag = (tag) => {
764
+ if (typeof tag !== "string") return `Tag "${tag}" must be a string type`;
765
+ if (tag !== tag.trim()) return `Tag can not contain white spaces`;
766
+ if (tag !== tag.toLowerCase()) return `Tag can not contain upper case characters`;
767
+ if (tag.length === 0) return `Received empty tag value`;
768
+ if (tag.indexOf(" ") > -1) return `"${tag}" tag cannot contain a space`;
769
+ if (tag.indexOf(",") > -1) return `"${tag}" tag cannot be used for multiple tags`;
770
+ const invalidChars = tag.replace(/\w|-/g, "");
771
+ if (invalidChars !== "") return `"${tag}" tag contains invalid characters: ${invalidChars}`;
772
+ if (tag.indexOf("-") === -1) return `"${tag}" tag must contain a dash (-) to work as a valid web component`;
773
+ if (tag.indexOf("--") > -1) return `"${tag}" tag cannot contain multiple dashes (--) next to each other`;
774
+ if (tag.indexOf("-") === 0) return `"${tag}" tag cannot start with a dash (-)`;
775
+ if (tag.lastIndexOf("-") === tag.length - 1) return `"${tag}" tag cannot end with a dash (-)`;
776
+ };
777
+ //#endregion
778
+ export { formatLazyBundleRuntimeMeta as C, formatComponentRuntimeMeta as S, byteSize as T, loadRolldownDiagnostics as _, getSourceMappingUrlForEndOfFile as a, splitLineBreaks as b, err as c, result_exports as d, augmentDiagnosticWithNode as f, isRolldownError as g, createOnWarnFn as h, getInlineSourceMappingUrlLinker as i, map as l, loadTypeScriptDiagnostics as m, validateComponentTag as n, getSourceMappingUrlLinker as o, loadTypeScriptDiagnostic as p, isRemoteUrl as r, rolldownToStencilSourceMap as s, validateComponentModes as t, ok as u, escapeHtml as v, stringifyRuntimeData as w, isRootPath as x, normalizeDiagnostics as y };