progressively-enhance-web-components 2.0.1 → 2.1.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/CHANGELOG.md CHANGED
@@ -1,3 +1,26 @@
1
+ ## 2.1.0
2
+
3
+ - Breaking: Changed attribute values to be escaped when they are written into a component's markup. Previously a value was pasted into the markup as it was, so one holding a quote or an angle bracket broke the attribute or element it landed in, and an entity such as `&lt;b&gt;` came out as a real `<b>` element. Pass markup as slotted children rather than through an attribute.
4
+ - Related: Fixed a value holding `$&`, `$1` or similar being expanded as a replacement pattern, and an attribute name holding a character such as `.` filling in other template literals as well as its own (`${a.b}` matched `${axb}`). The browser example in USAGE.md and the sample app had the same problems and have been fixed the same way.
5
+ - Breaking: Changed component definitions to only be recognized on a `<template>` whose `id` is a valid custom element name. Previously a `<template id="header">` used for something else caused every `<header>` element to be "enhanced" with its contents.
6
+ - Changed jsdom's CSS parsing complaints to be silenced through a jsdom virtual console rather than by temporarily replacing `console.error`, which could also throw when something logged `null` or `undefined`.
7
+ - Changed files to be read in alphabetical order on every platform. When the same template `id` is defined more than once, which one is used no longer depends on the filesystem, and a warning is now logged.
8
+ - Changed hidden directories, such as `.git`, to be skipped like hidden files. Symbolic links are now followed, with protection against loops.
9
+ - Changed the module to throw a clear error when `templatesDir` is not given, rather than throwing an unhelpful `TypeError` when called with no params at all, or silently doing nothing when called without it.
10
+ - Fixed every file holding a non-ASCII character, such as an accented letter, a curly quote or an emoji, being treated as binary and silently skipped. A file is now treated as binary only when it has a null byte near its start or is not valid UTF-8.
11
+ - Fixed invocations inside HTML comments, inside `<script>`, `<style>`, `<textarea>` and `<title>` elements, and inside plain `<template>` elements being enhanced. Expanding one inside a `<script>` string broke the script.
12
+ - Fixed a component whose template invokes another component only having the inner one enhanced when it happened to be defined first. Nested components are now always enhanced. A component that invokes itself, directly or through another, is expanded one level and then left for its JavaScript to render, with a warning, rather than expanding forever.
13
+ - Fixed an invocation nested inside another of the same kind never being enhanced in `shadow` and `both` modes, the search for invocations stepping over everything the outer one held.
14
+ - Fixed one invocation that is never closed stopping every invocation after it in the same file from being enhanced.
15
+ - Fixed an element whose name only begins the same way as the one being enhanced, such as `</my-thing-two>` inside `<my-thing>`, being taken as its closing tag.
16
+ - Fixed a self-closing invocation nested inside another of the same kind leaving the outer one unclosed.
17
+ - Fixed an apostrophe in an unquoted attribute, such as `<my-thing don't>`, being read as the start of a quoted value.
18
+ - Fixed a character that becomes longer when lowercased, such as `İ`, shifting every position after it and corrupting the output.
19
+ - Fixed `light` mode moving a slotted child that belongs to a nested custom element, or that sits inside another slotted child, to the top level of the component.
20
+ - Fixed the `data-enhanced=""` cleanup also rewriting matching text anywhere inside the enhanced element, not just on the element itself.
21
+ - Improved performance: each file is now scanned once for all components rather than once per component, one jsdom document is reused for every invocation, and a file is parsed as a document only if it contains a `<template>`.
22
+ - Updated dependencies.
23
+
1
24
  ## 2.0.1
2
25
 
3
26
  - Altered the npm package to not include unnecessary files.
package/USAGE.md CHANGED
@@ -214,7 +214,29 @@ Apply a `data-enhanced` attribute:
214
214
 
215
215
  Alternatively, if a `<template shadowrootmode>` exists in your custom element invocation, that will also cause this library to ignore it.
216
216
 
217
- This library will also apply the `data-enhanced` attribute to any custom element it enhances to prevent re-enhancing on a second pass.
217
+ This library will also apply the `data-enhanced` attribute to any custom element it enhances to prevent re-enhancing on a second pass.
218
+
219
+ The element itself is left exactly as written, but other invocations nested inside it that are not marked are still enhanced.
220
+
221
+ An invocation is also left alone wherever a browser would not render it as an element: inside an HTML comment, inside a `<script>`, `<style>`, `<textarea>` or `<title>`, and inside a plain `<template>` (including the `<template>` that defines a component, which your component's JavaScript clones as it was written). An invocation inside a `<template shadowrootmode>` is rendered by the browser, so it is enhanced.
222
+
223
+ ### What counts as a component definition
224
+
225
+ Only a `<template>` whose `id` is a valid custom element name is treated as a component: it must start with a lowercase letter, contain a hyphen, and contain no uppercase letters, the same rules `customElements.define` enforces. So `<template id="word-count">` defines `<word-count>`, while a `<template id="header">` or `<template id="row">` used for some other purpose is ignored rather than being applied to every `<header>` or `<row>`.
226
+
227
+ If the same `id` is defined in more than one file, the one in the file that comes last alphabetically by path is used, and a warning is logged.
228
+
229
+ A component's template can invoke other components, and each of those is enhanced as part of it. A component that invokes itself, directly or through another component, would expand forever, so the inner invocation is left for the component's JavaScript to render (and marked `data-enhanced`), and a warning is logged.
230
+
231
+ ### Attribute values are escaped
232
+
233
+ The value of an attribute is written into the component's markup as text, so `label="Tom &amp; Jerry"` or `label="say &quot;hi&quot;"` comes out as that text rather than as broken markup. If you need markup inside a component, pass it as slotted child content instead of through an attribute.
234
+
235
+ Values are not escaped for CSS or JavaScript, so avoid putting a `${templateLiteral}` inside a `<style>` or `<script>` element unless you control the attribute's value.
236
+
237
+ ### Template language syntax inside an invocation's opening tag
238
+
239
+ Each invocation is read by an HTML parser, so template language syntax written *between the attributes* of an invocation's opening tag will not survive. For example, `<word-count {if hidden}hidden{/if}>` is read as attributes named `{if`, `hidden}hidden{` and `if}`. Template syntax inside an attribute value (`text="{story}"`) or in the element's children is fine. If you need a conditional attribute, put the condition around the whole element instead.
218
240
 
219
241
  ### Writing the frontend JavaScript
220
242
 
@@ -230,13 +252,20 @@ class WordCount extends window.HTMLElement {
230
252
 
231
253
  // add the markup of the component if it is not already populated
232
254
  if (!this.shadow.childElementCount) {
233
- const markup = document.createElement('div')
234
- markup.appendChild(document.getElementById('word-count').content.cloneNode(true))
255
+ const markup = document.getElementById('word-count').content.cloneNode(true)
235
256
 
236
257
  // fill in its ${templateLiterals} from this element's attributes
237
- for (const attrib of this.attributes) markup.innerHTML = markup.innerHTML.replace(new RegExp(`\\$\\{${attrib.name}\\}`, 'gi'), attrib.value)
258
+ //
259
+ // the text and attribute values are set directly rather than by editing markup, so that a value holding a quote or an angle bracket is written as text instead of being parsed as html
260
+ const fill = text => text.replace(/\$\{([^}]+)\}/g, (literal, name) => this.getAttribute(name) ?? literal)
261
+ const walker = document.createTreeWalker(markup, window.NodeFilter.SHOW_ELEMENT | window.NodeFilter.SHOW_TEXT)
262
+ while (walker.nextNode()) {
263
+ const node = walker.currentNode
264
+ if (node.nodeType === window.Node.TEXT_NODE) node.data = fill(node.data)
265
+ else for (const attrib of node.attributes) attrib.value = fill(attrib.value)
266
+ }
238
267
 
239
- this.shadow.append(...markup.childNodes)
268
+ this.shadow.append(markup)
240
269
  }
241
270
 
242
271
  const textarea = this.shadow.querySelector('textarea')
package/package.json CHANGED
@@ -8,7 +8,7 @@
8
8
  "url": "https://github.com/rooseveltframework/progressively-enhance-web-components/graphs/contributors"
9
9
  }
10
10
  ],
11
- "version": "2.0.1",
11
+ "version": "2.1.0",
12
12
  "homepage": "https://rooseveltframework.org/docs/progressively-enhance-web-components/latest",
13
13
  "license": "CC-BY-4.0",
14
14
  "main": "progressively-enhance-web-components.js",
@@ -23,10 +23,10 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "js-beautify": "2.0.3",
26
- "jsdom": "30.1.0"
26
+ "jsdom": "31.0.1"
27
27
  },
28
28
  "devDependencies": {
29
- "@playwright/test": "^1.63.0",
29
+ "@playwright/test": "1.65.1",
30
30
  "standard": "17.1.2"
31
31
  },
32
32
  "standard": {
@@ -1,120 +1,233 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
- const { JSDOM } = require('jsdom')
3
+ const { JSDOM, VirtualConsole } = require('jsdom')
4
4
  const beautify = require('js-beautify').html
5
5
 
6
- function loopThroughFilesSync (dir) {
7
- let fileList = []
8
- let files
6
+ const MODULE_NAME = 'progressively-enhance-web-components'
7
+
8
+ // every file under a directory, in an order that is the same on every platform
9
+ //
10
+ // the order matters: when two templates share an id the later one wins, and readdir hands entries back in whatever order the filesystem keeps them. hidden files and hidden directories are both skipped, so a .git or a .preprocessed_views folder kept inside the templates directory is not read as templates. symbolic links are followed, and a directory reached a second time through one is not walked again, so a link pointing back up the tree cannot loop forever
11
+ function loopThroughFilesSync (dir, visited = new Set()) {
12
+ let realDir
13
+ let entries
9
14
  try {
10
- files = fs.readdirSync(dir, { withFileTypes: true })
11
- } catch (err) {
12
- return fileList
15
+ realDir = fs.realpathSync(dir)
16
+ entries = fs.readdirSync(dir, { withFileTypes: true })
17
+ } catch {
18
+ return []
13
19
  }
14
- files.forEach(file => {
15
- const filePath = path.join(dir, file.name)
16
- if (file.isDirectory()) fileList = fileList.concat(loopThroughFilesSync(filePath)) // recurse dirs
17
- else if (file.isFile() && !file.name.startsWith('.')) fileList.push(filePath) // exclude hidden files
18
- })
19
- return fileList
20
- }
21
-
22
- function isBinaryFile (filePath, bytesToCheck = 512) {
23
- const buffer = Buffer.alloc(bytesToCheck)
24
- const fd = fs.openSync(filePath, 'r')
25
- const bytesRead = fs.readSync(fd, buffer, 0, bytesToCheck, 0)
26
- fs.closeSync(fd)
27
- for (let i = 0; i < bytesRead; i++) {
28
- const byte = buffer[i]
29
- if (byte === 0) return true // null byte found, likely a binary file
30
- else if ((byte < 32 || byte > 126) && byte !== 10 && byte !== 13 && byte !== 9) return true // non-printable ascii character found, likely a binary file; allow common control characters: \n (10), \r (13), \t (9)
20
+ if (visited.has(realDir)) return []
21
+ visited.add(realDir)
22
+ const fileList = []
23
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
24
+ for (const entry of entries) {
25
+ if (entry.name.startsWith('.')) continue
26
+ const entryPath = path.join(dir, entry.name)
27
+ let kind = entry
28
+ if (entry.isSymbolicLink()) {
29
+ try {
30
+ kind = fs.statSync(entryPath)
31
+ } catch {
32
+ continue // a link to nothing
33
+ }
34
+ }
35
+ if (kind.isDirectory()) fileList.push(...loopThroughFilesSync(entryPath, visited))
36
+ else if (kind.isFile()) fileList.push(entryPath)
31
37
  }
32
- return false
38
+ return fileList
33
39
  }
34
40
 
35
- // jsdom complains about css it cannot parse, which is not something the caller can do anything about
41
+ // the contents of a file, or null when it is not text this module should read
36
42
  //
37
- // silencing it is done around the parse and undone afterwards, rather than once when this module is loaded: console.error belongs to whatever application is calling this, and it should not lose an error of its own for as long as the process lives because a stylesheet somewhere is unparseable
38
- const jsDomCssError = 'Error: Could not parse CSS stylesheet'
39
- function withoutJsdomCssComplaints (work) {
40
- const originalConsoleError = console.error
41
- console.error = (...params) => {
42
- if (!params.find(p => p.toString().includes(jsDomCssError))) originalConsoleError(...params)
43
- }
43
+ // a null byte near the start is the usual sign of a binary file, and checking only the start means a large image or video is not read in full just to be thrown away. anything else is read as utf-8 and rejected if it is not valid utf-8. testing each byte for printable ascii, as this once did, rejected every template holding an accented letter, a curly quote or an emoji, and so silently enhanced nothing in them
44
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
45
+ function readTextFile (filePath, bytesToCheck = 8000) {
44
46
  try {
45
- return work()
46
- } finally {
47
- console.error = originalConsoleError
47
+ const fd = fs.openSync(filePath, 'r')
48
+ try {
49
+ const head = Buffer.alloc(bytesToCheck)
50
+ const bytesRead = fs.readSync(fd, head, 0, bytesToCheck, 0)
51
+ if (head.subarray(0, bytesRead).includes(0)) return null
52
+ } finally {
53
+ fs.closeSync(fd)
54
+ }
55
+ return utf8.decode(fs.readFileSync(filePath))
56
+ } catch {
57
+ return null
48
58
  }
49
59
  }
50
60
 
61
+ // lower case the ascii letters and nothing else
62
+ //
63
+ // tag names are matched case insensitively by searching a lower cased copy of the markup and using the positions found in it on the original. String.prototype.toLowerCase cannot be used for that: a few characters lower case to more than one code unit, İ becoming i̇ for one, and every position after such a character would then point at the wrong place in the original
64
+ const asciiLowerCase = text => text.replace(/[A-Z]+/g, letters => letters.toLowerCase())
65
+
66
+ // whether the character after a tag name ends it, so that <my-thing> is not mistaken for <my-thing-two>
67
+ const endsTagName = character => /[\s/>]/.test(character || '')
68
+
51
69
  // where the opening tag that begins at `from` ends
52
70
  //
53
- // the quotes are followed so that a greater than sign inside an attribute value does not look like the end of the tag
71
+ // quotes are followed so that a greater than sign inside an attribute value does not look like the end of the tag. a quote only opens a value straight after an equals sign, as it does for the html parser, so an apostrophe in a bare attribute such as <my-thing don't> does not swallow the rest of the file
54
72
  function endOfOpeningTag (markup, from) {
55
73
  let quote = null
56
- for (let i = from; i < markup.length; i++) {
74
+ let valueMayStart = false
75
+ for (let i = from + 1; i < markup.length; i++) {
57
76
  const character = markup[i]
58
77
  if (quote) {
59
78
  if (character === quote) quote = null
60
- } else if (character === '"' || character === "'") quote = character
61
- else if (character === '>') return i
79
+ } else if (valueMayStart && (character === '"' || character === "'")) {
80
+ quote = character
81
+ valueMayStart = false
82
+ } else if (character === '>') return i
83
+ else if (character === '=') valueMayStart = true
84
+ else if (!/\s/.test(character)) valueMayStart = false
85
+ }
86
+ return -1
87
+ }
88
+
89
+ // elements whose contents the html parser reads as text rather than as markup, so that a tag written inside one is not a tag at all
90
+ const RAW_TEXT_ELEMENTS = new Set(['script', 'style', 'textarea', 'title', 'xmp', 'iframe', 'noembed', 'noframes'])
91
+
92
+ // the stretches of markup in which a custom element written there is not one this module should enhance
93
+ //
94
+ // those are comments, the contents of the raw text elements above, and <template> elements other than declarative shadow roots. a comment and a raw text element do not render what is written in them as elements at all: expanding an invocation written inside a <script> string broke the script by writing double quotes into it. a plain <template> is not rendered either, and one that defines a component is cloned by the component's own javascript, so it has to stay as it was written. a declarative shadow root is rendered by the parser, so a custom element inside one is enhanced like any other
95
+ //
96
+ // each range is [start, end), sorted and not overlapping
97
+ function ignoredRanges (markup, lowerMarkup) {
98
+ const ranges = []
99
+ let templateDepth = 0
100
+ let templateStart = -1
101
+ let at = 0
102
+ while (true) {
103
+ const lessThan = lowerMarkup.indexOf('<', at)
104
+ if (lessThan === -1) break
105
+ if (lowerMarkup.startsWith('<!--', lessThan)) {
106
+ const commentEnd = lowerMarkup.indexOf('-->', lessThan + 4)
107
+ const end = commentEnd === -1 ? markup.length : commentEnd + 3
108
+ if (!templateDepth) ranges.push([lessThan, end])
109
+ at = end
110
+ continue
111
+ }
112
+ const tag = /^<(\/?)([a-z][^\s/>]*)/.exec(lowerMarkup.slice(lessThan, lessThan + 256))
113
+ if (!tag) {
114
+ at = lessThan + 1
115
+ continue
116
+ }
117
+ const [, closing, name] = tag
118
+ if (closing) {
119
+ const end = lowerMarkup.indexOf('>', lessThan)
120
+ at = end === -1 ? markup.length : end + 1
121
+ if (name === 'template' && templateDepth && !--templateDepth) ranges.push([templateStart, at])
122
+ continue
123
+ }
124
+ const openingTagEnd = endOfOpeningTag(markup, lessThan)
125
+ if (openingTagEnd === -1) break
126
+ if (name === 'plaintext') { // nothing after it is markup, not even a closing tag
127
+ if (!templateDepth) ranges.push([lessThan, markup.length])
128
+ at = markup.length
129
+ } else if (RAW_TEXT_ELEMENTS.has(name)) {
130
+ let close = lowerMarkup.indexOf(`</${name}`, openingTagEnd)
131
+ while (close !== -1 && !endsTagName(lowerMarkup[close + name.length + 2])) close = lowerMarkup.indexOf(`</${name}`, close + 1)
132
+ const closeEnd = close === -1 ? -1 : lowerMarkup.indexOf('>', close)
133
+ const end = closeEnd === -1 ? markup.length : closeEnd + 1
134
+ if (!templateDepth) ranges.push([lessThan, end])
135
+ at = end
136
+ } else {
137
+ if (name === 'template') {
138
+ // inside a plain template every nested template is counted, a shadow root or not, so that the closing tags pair up
139
+ const isShadowRoot = /\sshadowrootmode\s*=/.test(lowerMarkup.slice(lessThan, openingTagEnd))
140
+ if (templateDepth) templateDepth++
141
+ else if (!isShadowRoot) {
142
+ templateDepth = 1
143
+ templateStart = lessThan
144
+ }
145
+ }
146
+ at = openingTagEnd + 1
147
+ }
148
+ }
149
+ if (templateDepth) ranges.push([templateStart, markup.length]) // a template never closed takes the rest of the file with it
150
+ return ranges
151
+ }
152
+
153
+ // the end of the ignored range holding `position`, or -1 when it is not in one
154
+ function endOfIgnoredRange (ranges, position) {
155
+ let low = 0
156
+ let high = ranges.length - 1
157
+ while (low <= high) {
158
+ const middle = (low + high) >> 1
159
+ const [start, end] = ranges[middle]
160
+ if (position < start) high = middle - 1
161
+ else if (position >= end) low = middle + 1
162
+ else return end
62
163
  }
63
164
  return -1
64
165
  }
65
166
 
167
+ // where the next tag beginning with `opening` (such as `<my-thing` or `</my-thing`) is, skipping the ignored ranges and any longer name that only begins the same way
168
+ function findTag (lowerMarkup, ranges, opening, from) {
169
+ let at = from
170
+ while (true) {
171
+ const found = lowerMarkup.indexOf(opening, at)
172
+ if (found === -1) return -1
173
+ const ignoredUntil = endOfIgnoredRange(ranges, found)
174
+ if (ignoredUntil !== -1) at = ignoredUntil
175
+ else if (!endsTagName(lowerMarkup[found + opening.length])) at = found + opening.length
176
+ else return found
177
+ }
178
+ }
179
+
66
180
  // the span of markup an element occupies, from the < that opens it to the > that closes it
67
181
  //
68
182
  // a regular expression cannot answer this. it has no way to pair an opening tag with the closing tag that belongs to it, so an element holding another of the same name ended at the inner closing tag and left the outer one behind as stray text
69
- function elementSpan (markup, name, start) {
183
+ function elementSpan (markup, lowerMarkup, ranges, name, start) {
70
184
  const openingTagEnd = endOfOpeningTag(markup, start)
71
185
  if (openingTagEnd === -1) return null
72
186
  if (markup[openingTagEnd - 1] === '/') return { start, end: openingTagEnd + 1 } // closed itself, so there is no closing tag to pair it with
73
- const lowerMarkup = markup.toLowerCase()
74
- const opening = `<${name.toLowerCase()}`
75
- const closing = `</${name.toLowerCase()}`
76
187
  let depth = 1
77
188
  let at = openingTagEnd + 1
78
- while (at < markup.length) {
79
- const nextOpening = lowerMarkup.indexOf(opening, at)
80
- const nextClosing = lowerMarkup.indexOf(closing, at)
189
+ while (true) {
190
+ const nextClosing = findTag(lowerMarkup, ranges, `</${name}`, at)
81
191
  if (nextClosing === -1) return null // never closed
192
+ const nextOpening = findTag(lowerMarkup, ranges, `<${name}`, at)
82
193
  if (nextOpening !== -1 && nextOpening < nextClosing) {
83
- // a longer name beginning the same way is a different element: <my-thing> is not <my-thing-two>
84
- if (/[\s/>]/.test(markup[nextOpening + opening.length] || '')) depth++
85
- at = nextOpening + opening.length
194
+ const nestedOpeningTagEnd = endOfOpeningTag(markup, nextOpening)
195
+ if (nestedOpeningTagEnd === -1) return null
196
+ if (markup[nestedOpeningTagEnd - 1] !== '/') depth++ // one that closed itself has no closing tag of its own to wait for
197
+ at = nestedOpeningTagEnd + 1
86
198
  continue
87
199
  }
88
200
  const closingTagEnd = markup.indexOf('>', nextClosing)
89
201
  if (closingTagEnd === -1) return null
90
- depth--
91
- if (depth === 0) return { start, end: closingTagEnd + 1 }
202
+ if (--depth === 0) return { start, end: closingTagEnd + 1 }
92
203
  at = closingTagEnd + 1
93
204
  }
94
- return null
95
205
  }
96
206
 
97
- // every place an element of this name is written, outermost first
98
- function elementSpans (markup, name) {
99
- const spans = []
100
- const lowerMarkup = markup.toLowerCase()
101
- const opening = `<${name.toLowerCase()}`
102
- let at = 0
103
- while (at < markup.length) {
104
- const found = lowerMarkup.indexOf(opening, at)
105
- if (found === -1) break
106
- if (!/[\s/>]/.test(markup[found + opening.length] || '')) { // a different element whose name begins the same way
107
- at = found + opening.length
207
+ // where the next opening tag of any of these custom elements is, and which of them it opens
208
+ function nextInvocation (lowerMarkup, ranges, names, from) {
209
+ let at = from
210
+ while (true) {
211
+ const lessThan = lowerMarkup.indexOf('<', at)
212
+ if (lessThan === -1) return null
213
+ const ignoredUntil = endOfIgnoredRange(ranges, lessThan)
214
+ if (ignoredUntil !== -1) {
215
+ at = ignoredUntil
108
216
  continue
109
217
  }
110
- const span = elementSpan(markup, name, found)
111
- if (!span) break
112
- spans.push(span)
113
- at = span.end // whatever is nested inside this element is replaced along with it
218
+ const tag = /^<([a-z][^\s/>]*)/.exec(lowerMarkup.slice(lessThan, lessThan + 256))
219
+ if (tag && names.has(tag[1])) return { start: lessThan, name: tag[1] }
220
+ at = lessThan + 1
114
221
  }
115
- return spans
116
222
  }
117
223
 
224
+ // whether a template id names a custom element, which is what makes it a component definition rather than any other use of a <template>
225
+ //
226
+ // without this a page holding <template id="header"> for some other script had every <header> on the site treated as an invocation of it. the rule is the one customElements.define enforces: it starts with a lower case ascii letter, holds a hyphen and no ascii upper case letters, and is not one of the hyphenated names svg and mathml already use
227
+ const POTENTIAL_CUSTOM_ELEMENT_NAME = /^[a-z][-.0-9_a-z·À-ÖØ-öø-ͽͿ-῿‌-‍‿-⁀⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\u{10000}-\u{EFFFF}]*$/u
228
+ const RESERVED_NAMES = new Set(['annotation-xml', 'color-profile', 'font-face', 'font-face-src', 'font-face-uri', 'font-face-format', 'font-face-name', 'missing-glyph'])
229
+ const isCustomElementName = name => name.includes('-') && POTENTIAL_CUSTOM_ELEMENT_NAME.test(name) && !RESERVED_NAMES.has(name)
230
+
118
231
  // the ways an invocation can be enhanced
119
232
  //
120
233
  // `light` writes the component's markup into the element as fallback content, which is what this module has always done. `shadow` writes it into a declarative shadow root instead, which keeps the styles and slots a fallback cannot use and needs nothing swapped once the component upgrades. `both` writes each of them, so that a browser which builds the shadow root renders that and one which does not renders the fallback
@@ -152,62 +265,146 @@ function holdOutOfSlots (container) {
152
265
  }
153
266
  }
154
267
 
268
+ // puts the attribute values of an invocation where the ${templateLiterals} of its definition are
269
+ //
270
+ // this works on the dom rather than on serialized markup. replacing text in serialized markup wrote each value in exactly as it was, so a value holding a quote or an angle bracket broke the attribute or the element it landed in, and the value having been decoded from its entities on the way in meant &lt;b&gt; arrived as a real <b>. setting the text of a node lets the serializer escape it for wherever it ended up. it also means each literal is looked up once by name, rather than every attribute name being made into a regular expression, which a name such as a.b or :value is not safe to be, and rather than every value being a replacement pattern, in which $& and $1 mean something
271
+ const TEMPLATE_LITERAL = /\$\{([^}]+)\}/g
272
+ function fillTemplateLiterals (node, values) {
273
+ const fill = text => text.replace(TEMPLATE_LITERAL, (literal, name) => values.get(name.toLowerCase()) ?? literal)
274
+ for (const child of node.childNodes) {
275
+ if (child.nodeType === 1) {
276
+ for (const attribute of child.attributes) attribute.value = fill(attribute.value)
277
+ if (child.tagName === 'TEMPLATE') fillTemplateLiterals(child.content, values)
278
+ fillTemplateLiterals(child, values)
279
+ } else if (child.nodeType === 3 || child.nodeType === 8) child.data = fill(child.data) // text and comments
280
+ }
281
+ }
282
+
155
283
  module.exports = (params) => {
156
- const beautifyOptions = params?.beautifyOptions || {
284
+ if (!params || typeof params.templatesDir !== 'string') throw new TypeError(`${MODULE_NAME}: the templatesDir param is required, and must be the path to the folder holding your templates`)
285
+
286
+ const beautifyOptions = params.beautifyOptions || {
157
287
  indent_size: 2
158
288
  }
159
- const beautifyMarkup = markup => params?.disableBeautify ? markup : beautify(markup, beautifyOptions)
289
+ const beautifyMarkup = markup => params.disableBeautify ? markup : beautify(markup, beautifyOptions)
160
290
 
161
291
  // the dom serializer writes an empty attribute out as data-enhanced="", which says the same thing as the bare form but is not what anyone writing it by hand would write
162
- const bareEnhancedAttribute = markup => markup.replace(new RegExp(`\\s${ENHANCED_ATTRIBUTE}=""`, 'g'), ` ${ENHANCED_ATTRIBUTE}`)
292
+ //
293
+ // only the opening tag of the element just enhanced is touched, so that an attribute written that way somewhere inside it, or text that happens to read the same, is left as it was
294
+ const bareEnhancedAttribute = markup => {
295
+ const start = markup.indexOf('<')
296
+ const end = start === -1 ? -1 : endOfOpeningTag(markup, start)
297
+ if (end === -1) return markup
298
+ return markup.slice(0, start) + markup.slice(start, end + 1).replace(new RegExp(`(\\s)${ENHANCED_ATTRIBUTE}=""`), `$1${ENHANCED_ATTRIBUTE}`) + markup.slice(end + 1)
299
+ }
163
300
 
164
301
  // what to do with an invocation whose definition does not say for itself
165
- const defaultMode = params?.mode || 'both'
166
- if (!MODES.has(defaultMode)) throw new Error(`progressively-enhance-web-components: mode must be one of ${[...MODES].join(', ')}, not ${JSON.stringify(defaultMode)}`)
302
+ const defaultMode = params.mode || 'both'
303
+ if (!MODES.has(defaultMode)) throw new Error(`${MODULE_NAME}: mode must be one of ${[...MODES].join(', ')}, not ${JSON.stringify(defaultMode)}`)
304
+
305
+ // jsdom complains about css it cannot parse, which is not something the caller can do anything about
306
+ //
307
+ // the complaints are dropped by giving jsdom a console of its own rather than by replacing console.error, which belongs to whatever application is calling this. anything else jsdom has to say is still passed on
308
+ const virtualConsole = new VirtualConsole()
309
+ virtualConsole.on('jsdomError', error => {
310
+ if (error.type !== 'css-parsing') console.error(error.message)
311
+ })
167
312
 
168
313
  // every file that could hold a template or an invocation of one, read once
169
314
  //
170
315
  // reading them once is not only quicker: the enhanced markup of one custom element is what the next one is applied to, so a file invoking two of them ends up with both enhanced. re-reading the file for each custom element meant each started again from what was on disk, and only the last one survived into what this returns
171
316
  const files = {}
172
317
  for (const file of loopThroughFilesSync(params.templatesDir)) {
173
- if (!isBinaryFile(file)) files[file] = fs.readFileSync(file, 'utf8')
318
+ const contents = readTextFile(file)
319
+ if (contents !== null) files[file] = contents
174
320
  }
175
321
 
176
- // find all <template> elements with ids that are defined in any of the html templates
322
+ // find all <template> elements whose ids name a custom element in any of the html templates
323
+ //
324
+ // a file without the word <template in it cannot define anything, so it is not handed to jsdom at all, which spares parsing every stylesheet, script and partial in the folder as a document
177
325
  const allTemplateElements = {}
178
- withoutJsdomCssComplaints(() => {
179
- for (const contents of Object.values(files)) {
180
- const { document } = new JSDOM(contents).window
181
- for (const templateElement of document.querySelectorAll('template')) {
182
- if (!templateElement.id) continue
183
- // a definition may say how it wants to be enhanced, which is a property of the component rather than of any one place it is used
184
- const mode = templateElement.getAttribute('mode') || defaultMode
185
- if (!MODES.has(mode)) throw new Error(`progressively-enhance-web-components: <template id="${templateElement.id}"> asks for mode ${JSON.stringify(mode)}, which is not one of ${[...MODES].join(', ')}`)
186
- allTemplateElements[templateElement.id] = { definition: templateElement, mode }
326
+ for (const [file, contents] of Object.entries(files)) {
327
+ if (!asciiLowerCase(contents).includes('<template')) continue
328
+ const { document } = new JSDOM(contents, { virtualConsole }).window
329
+ for (const templateElement of document.querySelectorAll('template')) {
330
+ const id = templateElement.id
331
+ if (!isCustomElementName(id)) continue
332
+ // a definition may say how it wants to be enhanced, which is a property of the component rather than of any one place it is used
333
+ const mode = templateElement.getAttribute('mode') || defaultMode
334
+ if (!MODES.has(mode)) throw new Error(`${MODULE_NAME}: <template id="${id}"> asks for mode ${JSON.stringify(mode)}, which is not one of ${[...MODES].join(', ')}`)
335
+ const previous = allTemplateElements[id]
336
+ if (previous) console.warn(`${MODULE_NAME}: <template id="${id}"> is defined more than once, in ${previous.file} and in ${file}. the one in ${file} is used`)
337
+ allTemplateElements[id] = { definition: templateElement, mode, file }
338
+ }
339
+ }
340
+ const customElementNames = new Set(Object.keys(allTemplateElements))
341
+
342
+ // one document to parse every invocation in, rather than a new one for each
343
+ //
344
+ // it is only used to parse: an element is taken out of it straight away and serialized from where it is, so that enhancing the invocations nested inside one, which parses each of them here in turn, does not disturb it
345
+ const workspace = new JSDOM('<!DOCTYPE html><html><body></body></html>', { virtualConsole }).window.document
346
+
347
+ // every invocation of a known custom element in a stretch of markup, enhanced, with everything around them left as it was
348
+ //
349
+ // `expanding` is the chain of components whose markup this is part of. a component that invokes itself, directly or through another, would expand forever, so an invocation of one already in the chain is left for its javascript to render, marked so that a later pass over the output leaves it alone too
350
+ const warnedAboutRecursion = new Set()
351
+ function enhanceMarkup (markup, expanding) {
352
+ const lowerMarkup = asciiLowerCase(markup)
353
+ const ranges = ignoredRanges(markup, lowerMarkup)
354
+ let output = ''
355
+ let at = 0
356
+ while (true) {
357
+ const found = nextInvocation(lowerMarkup, ranges, customElementNames, at)
358
+ if (!found) break
359
+ const span = elementSpan(markup, lowerMarkup, ranges, found.name, found.start)
360
+ if (!span) { // never closed, which leaves that one alone but not every invocation after it
361
+ output += markup.slice(at, found.start + 1)
362
+ at = found.start + 1
363
+ continue
187
364
  }
365
+ output += markup.slice(at, span.start) + enhance(markup.slice(span.start, span.end), found.name, expanding)
366
+ at = span.end // whatever is nested inside this element is dealt with by enhancing it
188
367
  }
189
- })
368
+ return output + markup.slice(at)
369
+ }
190
370
 
191
371
  // what one invocation of a custom element becomes
192
- function enhance (invocation, customElement) {
193
- // make a dom just for modifying this element
194
- const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')
195
- const document = dom.window.document
196
- document.body.appendChild(JSDOM.fragment(invocation))
197
-
198
- // the element we're modifying
199
- const element = document.body.firstChild
200
- const { definition, mode } = allTemplateElements[customElement]
372
+ function enhance (invocation, customElement, expanding) {
373
+ if (expanding.includes(customElement)) {
374
+ if (!warnedAboutRecursion.has(customElement)) {
375
+ warnedAboutRecursion.add(customElement)
376
+ console.warn(`${MODULE_NAME}: <${customElement}> invokes itself (${[...expanding.slice(expanding.indexOf(customElement)), customElement].join(' > ')}). the inner one is left for its javascript to render`)
377
+ }
378
+ const nameEnd = customElement.length + 1
379
+ return invocation.slice(0, nameEnd) + ` ${ENHANCED_ATTRIBUTE}` + invocation.slice(nameEnd)
380
+ }
201
381
 
202
- // an invocation that has been enhanced already is handed back exactly as it came in, rather than reformatted, so that nothing about it changes
203
- if (alreadyEnhanced(element)) return invocation
382
+ workspace.body.innerHTML = invocation
383
+ const element = workspace.body.firstElementChild
384
+ if (!element) return invocation
385
+ element.remove()
386
+
387
+ // an invocation that has been enhanced already is kept exactly as it came in, rather than reformatted, so that nothing about it changes. it can still hold invocations that have not been, in its light dom or in a shadow root written into it, and only those are enhanced
388
+ if (alreadyEnhanced(element)) {
389
+ const openingTagEnd = endOfOpeningTag(invocation, 0)
390
+ if (invocation[openingTagEnd - 1] === '/') return invocation
391
+ const closingTagStart = invocation.lastIndexOf('</')
392
+ return invocation.slice(0, openingTagEnd + 1) + enhanceMarkup(invocation.slice(openingTagEnd + 1, closingTagStart), expanding) + invocation.slice(closingTagStart)
393
+ }
394
+
395
+ const { definition, mode } = allTemplateElements[customElement]
204
396
 
205
397
  // js-beautify treats <template> as an inline element and so will not break the line before one. the pieces of a component are put on lines of their own here instead, which it then indents. with beautifying turned off they are joined as they were, this module having been asked to leave the markup alone
206
- const gap = params?.disableBeautify ? '' : '\n'
398
+ const gap = params.disableBeautify ? '' : '\n'
207
399
 
208
- // the component's markup, with the attribute values written on this invocation put where its template literals were
400
+ const values = new Map()
401
+ for (const attribute of element.attributes) values.set(attribute.name.toLowerCase(), attribute.value)
402
+
403
+ // the component's markup, with the attribute values written on this invocation put where its template literals were, and any component it invokes enhanced in turn
209
404
  //
210
405
  // a shadow root renders the style, script and slot elements it is given, so it keeps them. light dom fallback markup can use none of them: a style element would leak to the rest of the page, a slot projects nothing when there is no shadow root to project it into, and a script would run a second time once the component upgrades. so they are removed from a fallback
406
+ //
407
+ // what comes back is markup rather than a dom. the enhanced invocations nested in it are serialized already, and parsing them again only to serialize them a second time would undo details such as the bare data-enhanced attribute
211
408
  function componentMarkup (forShadowRoot) {
212
409
  // clone the <template> markup so we can construct a more verbose, progressive enhancement-compatible version of the web component
213
410
  const template = definition.content.cloneNode(true)
@@ -215,66 +412,67 @@ module.exports = (params) => {
215
412
  // remove elements that are not needed in the progressive enhancement context from the <template> markup
216
413
  if (!forShadowRoot) template.querySelectorAll('style, script, slot').forEach(el => el.remove())
217
414
 
218
- // replace template literals with attribute values in the <template> markup
219
- const container = document.createElement('div')
415
+ const container = workspace.createElement('div')
220
416
  container.appendChild(template)
221
- for (const attrib of element.attributes) container.innerHTML = container.innerHTML.replace(new RegExp(`\\$\\{${attrib.name}\\}`, 'gi'), attrib.value)
222
- if (!params?.disableBeautify) {
223
- const componentBeautifyOptions = { ...beautifyOptions }
224
- componentBeautifyOptions.preserve_newlines = false // remove newlines from components in case any style, script, or slot elements have been removed
225
- container.innerHTML = beautify(container.innerHTML, componentBeautifyOptions)
226
- }
227
- return container
417
+ fillTemplateLiterals(container, values)
418
+
419
+ // `both` carries the fallback beside the shadow root, held out of the component's slots so that it shows only where the shadow root was not built
420
+ if (!forShadowRoot && mode === 'both') holdOutOfSlots(container)
421
+
422
+ const markup = enhanceMarkup(container.innerHTML, [...expanding, customElement])
423
+ if (params.disableBeautify) return markup
424
+ const componentBeautifyOptions = { ...beautifyOptions }
425
+ componentBeautifyOptions.preserve_newlines = false // remove newlines from components in case any style, script, or slot elements have been removed
426
+ return beautify(markup, componentBeautifyOptions)
228
427
  }
229
428
 
429
+ // the element with what it now holds, written out around that markup rather than by setting it as the element's contents and serializing the lot, for the same reason
430
+ element.setAttribute(ENHANCED_ATTRIBUTE, '')
431
+ const shell = element.cloneNode(false).outerHTML
432
+ const closingTag = `</${element.localName}>`
433
+ const openingTag = shell.slice(0, shell.length - closingTag.length)
434
+ const wrap = contents => bareEnhancedAttribute(beautifyMarkup(openingTag + contents + closingTag))
435
+
230
436
  if (mode === 'light') {
231
- const fallback = componentMarkup(false)
437
+ let fallback = componentMarkup(false)
232
438
 
233
- // move any component child elements with slot attributs to the root of the component's light dom because such elements always need to be at the root to be accepted by the web component JS
234
- element.querySelectorAll('[slot]').forEach(slot => fallback.appendChild(slot.cloneNode(true)))
439
+ // move any component child elements with slot attributes to the root of the component's light dom because such elements always need to be at the root to be accepted by the web component JS
440
+ //
441
+ // one that belongs to something else is left where it is: a child of an element already being moved goes along with it rather than being moved a second time beside it, and one inside another custom element is that element's slotted content, not this one's
442
+ const belongsToThisElement = slotted => {
443
+ for (let ancestor = slotted.parentElement; ancestor !== element; ancestor = ancestor.parentElement) {
444
+ if (ancestor.hasAttribute('slot') || ancestor.localName.includes('-')) return false
445
+ }
446
+ return true
447
+ }
448
+ for (const slotted of element.querySelectorAll('[slot]')) {
449
+ if (belongsToThisElement(slotted)) fallback += enhanceMarkup(slotted.outerHTML, expanding)
450
+ }
235
451
 
236
452
  // replace the original custom element with the new progressive enhancement-friendly version of the element
237
- element.innerHTML = beautifyMarkup(fallback.innerHTML)
238
- element.setAttribute(ENHANCED_ATTRIBUTE, '')
239
- return bareEnhancedAttribute(beautifyMarkup(document.body.innerHTML))
453
+ return wrap(beautifyMarkup(fallback))
240
454
  }
241
455
 
242
456
  // the other modes build a shadow root, and what the element already holds is the light dom the slots in that shadow root project, so it is kept as it was written rather than replaced
243
457
  //
244
- // nothing is hoisted out of it either: only a direct child of the element can be assigned to a slot, so moving one that is nested deeper would change which content the author had put where in order to make a slot claim it
245
- const light = element.innerHTML
246
- const pieces = [`<template shadowrootmode="open">${componentMarkup(true).innerHTML}</template>`]
247
-
248
- // `both` carries the fallback as well, held out of the component's slots so that it shows only where the shadow root was not built
249
- if (mode === 'both') {
250
- const fallback = componentMarkup(false)
251
- holdOutOfSlots(fallback)
252
- pieces.push(fallback.innerHTML)
253
- }
254
-
458
+ // nothing is hoisted out of it either: only a direct child of the element can be assigned to a slot, so moving one that is nested deeper would change which content the author had put where in order to make a slot claim it. any component invoked in it is enhanced, that being written by the author rather than by this component, so it is not part of the chain being expanded
459
+ const light = enhanceMarkup(element.innerHTML, expanding)
460
+ const pieces = [`<template shadowrootmode="open">${componentMarkup(true)}</template>`]
461
+ if (mode === 'both') pieces.push(componentMarkup(false))
255
462
  if (light.trim()) pieces.push(light)
256
- element.innerHTML = gap + beautifyMarkup(pieces.join(gap))
257
- element.setAttribute(ENHANCED_ATTRIBUTE, '')
258
- return bareEnhancedAttribute(beautifyMarkup(document.body.innerHTML))
463
+ return wrap(gap + beautifyMarkup(pieces.join(gap)))
259
464
  }
260
465
 
261
- // find all invocations of each of the custom elements that are in allTemplateElements
466
+ // enhance every invocation in every file, each file being gone over once for all of the custom elements together
467
+ //
468
+ // a component whose markup invokes another component has that one enhanced as part of it, whichever of the two was defined first. going over a file once for each custom element in turn, as this once did, only reached the inner one when its turn happened to come after the outer one's
262
469
  const editedFiles = {}
263
- withoutJsdomCssComplaints(() => {
470
+ if (customElementNames.size) {
264
471
  for (const file in files) {
265
- const original = files[file]
266
- let markup = original
267
- for (const customElement in allTemplateElements) { // loop through list of known custom elements
268
- // replace all invocations of this custom element with the progressive enhancement-friendly version
269
- //
270
- // the spans are rewritten back to front so that replacing one does not move the next
271
- for (const span of elementSpans(markup, customElement).reverse()) {
272
- markup = markup.slice(0, span.start) + enhance(markup.slice(span.start, span.end), customElement) + markup.slice(span.end)
273
- }
274
- }
275
- if (markup !== original) editedFiles[file] = markup
472
+ const markup = enhanceMarkup(files[file], [])
473
+ if (markup !== files[file]) editedFiles[file] = markup
276
474
  }
277
- })
475
+ }
278
476
 
279
477
  return editedFiles
280
478
  }