Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 /// Transfomer that inlines polymer-element definitions from html imports. | 5 /// Transfomer that inlines polymer-element definitions from html imports. |
| 6 library polymer.src.build.import_inliner; | 6 library polymer.src.build.import_inliner; |
| 7 | 7 |
| 8 import 'dart:async'; | 8 import 'dart:async'; |
| 9 import 'dart:convert'; | 9 import 'dart:convert'; |
| 10 | 10 |
| 11 import 'package:analyzer/src/generated/ast.dart'; | |
| 11 import 'package:barback/barback.dart'; | 12 import 'package:barback/barback.dart'; |
| 12 import 'package:path/path.dart' as path; | 13 import 'package:path/path.dart' as path; |
| 13 import 'package:html5lib/dom.dart' show | 14 import 'package:html5lib/dom.dart' show |
| 14 Document, DocumentFragment, Element, Node; | 15 Document, DocumentFragment, Element, Node; |
| 15 import 'package:html5lib/dom_parsing.dart' show TreeVisitor; | 16 import 'package:html5lib/dom_parsing.dart' show TreeVisitor; |
| 17 import 'package:source_maps/refactor.dart' show TextEditTransaction; | |
| 16 import 'package:source_maps/span.dart'; | 18 import 'package:source_maps/span.dart'; |
| 17 | 19 |
| 18 import 'code_extractor.dart'; // import just for documentation. | |
| 19 import 'common.dart'; | 20 import 'common.dart'; |
| 20 | 21 |
| 21 class _HtmlInliner extends PolymerTransformer { | 22 class _HtmlInliner extends PolymerTransformer { |
| 22 final TransformOptions options; | 23 final TransformOptions options; |
| 23 final Transform transform; | 24 final Transform transform; |
| 24 final TransformLogger logger; | 25 final TransformLogger logger; |
| 25 final AssetId docId; | 26 final AssetId docId; |
| 26 final seen = new Set<AssetId>(); | 27 final seen = new Set<AssetId>(); |
| 27 final scriptIds = <AssetId>[]; | 28 final scriptIds = <AssetId>[]; |
| 28 | 29 |
| 29 static const TYPE_DART = 'application/dart'; | |
| 30 static const TYPE_JS = 'text/javascript'; | |
| 31 | |
| 32 _HtmlInliner(this.options, Transform transform) | 30 _HtmlInliner(this.options, Transform transform) |
| 33 : transform = transform, | 31 : transform = transform, |
| 34 logger = transform.logger, | 32 logger = transform.logger, |
| 35 docId = transform.primaryInput.id; | 33 docId = transform.primaryInput.id; |
| 36 | 34 |
| 37 Future apply() { | 35 Future apply() { |
| 38 seen.add(docId); | 36 seen.add(docId); |
| 39 | 37 |
| 40 Document document; | 38 Document document; |
| 39 bool changed; | |
| 41 | 40 |
| 42 return readPrimaryAsHtml(transform).then((document) => | 41 return readPrimaryAsHtml(transform).then((doc) { |
| 43 _visitImports(document, docId).then((importsFound) { | 42 document = doc; |
| 43 // Add the main script's ID, or null if none is present. | |
| 44 // This will be used by ScriptCompactor. | |
| 45 changed = _extractScripts(document.querySelectorAll('script')); | |
| 46 return _visitImports(document, docId); | |
| 47 }).then((importsFound) { | |
| 48 changed = changed || importsFound; | |
| 44 | 49 |
| 45 var output = transform.primaryInput; | 50 var output = transform.primaryInput; |
| 46 if (importsFound) { | 51 if (changed) output = new Asset.fromString(docId, document.outerHtml); |
| 47 output = new Asset.fromString(docId, document.outerHtml); | |
| 48 } | |
| 49 transform.addOutput(output); | 52 transform.addOutput(output); |
| 50 | 53 |
| 51 // We produce a secondary asset with extra information for later phases. | 54 // We produce a secondary asset with extra information for later phases. |
| 52 transform.addOutput(new Asset.fromString( | 55 transform.addOutput(new Asset.fromString( |
| 53 docId.addExtension('.scriptUrls'), | 56 docId.addExtension('.scriptUrls'), |
| 54 JSON.encode(scriptIds, toEncodable: (id) => id.serialize()))); | 57 JSON.encode(scriptIds, toEncodable: (id) => id.serialize()))); |
| 55 })); | 58 }); |
| 56 } | 59 } |
| 57 | 60 |
| 58 /// Visits imports in [document] and add the imported documents to documents. | 61 /// Visits imports in [document] and add the imported documents to documents. |
| 59 /// Documents are added in the order they appear, transitive imports are added | 62 /// Documents are added in the order they appear, transitive imports are added |
| 60 /// first. | 63 /// first. |
| 61 /// | 64 /// |
| 62 /// Returns `true` if and only if the document was changed and should be | 65 /// Returns `true` if and only if the document was changed and should be |
| 63 /// written out. | 66 /// written out. |
| 64 Future<bool> _visitImports(Document document, AssetId sourceId) { | 67 Future<bool> _visitImports(Document document, AssetId sourceId) { |
| 65 bool changed = false; | 68 bool changed = false; |
| (...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 100 /// respect to eachother, because stylesheets can be pulled in transitively | 103 /// respect to eachother, because stylesheets can be pulled in transitively |
| 101 /// from imports. | 104 /// from imports. |
| 102 // TODO(jmesserly): vulcanizer doesn't need this because they inline JS | 105 // TODO(jmesserly): vulcanizer doesn't need this because they inline JS |
| 103 // scripts, causing them to be naturally moved as part of the inlining. | 106 // scripts, causing them to be naturally moved as part of the inlining. |
| 104 // Should we do the same? Alternatively could we inline head into head and | 107 // Should we do the same? Alternatively could we inline head into head and |
| 105 // body into body and avoid this whole thing? | 108 // body into body and avoid this whole thing? |
| 106 void _moveHeadToBody(Document doc) { | 109 void _moveHeadToBody(Document doc) { |
| 107 var insertionPoint = doc.body.firstChild; | 110 var insertionPoint = doc.body.firstChild; |
| 108 for (var node in doc.head.nodes.toList(growable: false)) { | 111 for (var node in doc.head.nodes.toList(growable: false)) { |
| 109 if (node is! Element) continue; | 112 if (node is! Element) continue; |
| 110 var tag = node.tagName; | 113 var tag = node.localName; |
| 111 var type = node.attributes['type']; | 114 var type = node.attributes['type']; |
| 112 var rel = node.attributes['rel']; | 115 var rel = node.attributes['rel']; |
| 113 if (tag == 'style' || tag == 'script' && | 116 if (tag == 'style' || tag == 'script' && |
| 114 (type == null || type == TYPE_JS || type == TYPE_DART) || | 117 (type == null || type == TYPE_JS || type == TYPE_DART) || |
| 115 tag == 'link' && (rel == 'stylesheet' || rel == 'import')) { | 118 tag == 'link' && (rel == 'stylesheet' || rel == 'import')) { |
| 116 // Move the node into the body, where its contents will be placed. | 119 // Move the node into the body, where its contents will be placed. |
| 117 doc.body.insertBefore(node, insertionPoint); | 120 doc.body.insertBefore(node, insertionPoint); |
| 118 } | 121 } |
| 119 } | 122 } |
| 120 } | 123 } |
| 121 | 124 |
| 122 // Loads an asset identified by [id], visits its imports and collects its | 125 // Loads an asset identified by [id], visits its imports and collects its |
| 123 // html imports. Then inlines it into the main document. | 126 // html imports. Then inlines it into the main document. |
| 124 Future _inlineImport(AssetId id, Element link) => | 127 Future _inlineImport(AssetId id, Element link) => |
| 125 readAsHtml(id, transform).then((doc) => _visitImports(doc, id).then((_) { | 128 readAsHtml(id, transform).then((doc) => _visitImports(doc, id).then((_) { |
| 126 | 129 |
| 127 new _UrlNormalizer(transform, id).visit(doc); | 130 new _UrlNormalizer(transform, id).visit(doc); |
| 128 _extractScripts(doc); | 131 |
| 132 var scripts = doc.querySelectorAll('script'); | |
| 133 _extractScripts(scripts); | |
| 134 _removeScripts(scripts); | |
| 129 | 135 |
| 130 // TODO(jmesserly): figure out how this is working in vulcanizer. | 136 // TODO(jmesserly): figure out how this is working in vulcanizer. |
| 131 // Do they produce a <body> tag with a <head> and <body> inside? | 137 // Do they produce a <body> tag with a <head> and <body> inside? |
| 132 var imported = new DocumentFragment(); | 138 var imported = new DocumentFragment(); |
| 133 imported.nodes..addAll(doc.head.nodes)..addAll(doc.body.nodes); | 139 imported.nodes..addAll(doc.head.nodes)..addAll(doc.body.nodes); |
| 134 link.replaceWith(imported); | 140 link.replaceWith(imported); |
| 135 })); | 141 })); |
| 136 | 142 |
| 137 Future _inlineStylesheet(AssetId id, Element link) { | 143 Future _inlineStylesheet(AssetId id, Element link) { |
| 138 return transform.readInputAsString(id).then((css) { | 144 return transform.readInputAsString(id).then((css) { |
| 139 var url = spanUrlFor(id, transform); | 145 css = new _UrlNormalizer(transform, id).visitCss(css); |
| 140 css = new _UrlNormalizer(transform, id).visitCss(css, url); | |
| 141 link.replaceWith(new Element.tag('style')..text = css); | 146 link.replaceWith(new Element.tag('style')..text = css); |
| 142 }); | 147 }); |
| 143 } | 148 } |
| 144 | 149 |
| 145 /// Split Dart script tags from all the other elements. Now that Dartium | 150 /// Remove scripts from HTML imports, and remember their [AssetId]s for later |
| 146 /// only allows a single script tag per page, we can't inline script | 151 /// use. |
| 147 /// tags. Instead, we collect the urls of each script tag so we import | 152 /// |
| 148 /// them directly from the Dart bootstrap code. | 153 /// Dartium only allows a single script tag per page, so we can't inline |
| 149 void _extractScripts(Document document) { | 154 /// the script tags. Instead we remove them entirely. |
| 150 bool first = true; | 155 void _removeScripts(List<Element> scripts) { |
| 151 for (var script in document.querySelectorAll('script')) { | 156 for (var script in scripts) { |
| 152 if (script.attributes['type'] == TYPE_DART) { | 157 if (script.attributes['type'] == TYPE_DART) { |
| 153 script.remove(); | 158 script.remove(); |
| 159 var src = script.attributes['src']; | |
| 160 scriptIds.add(resolve(docId, src, logger, script.sourceSpan)); | |
| 154 | 161 |
| 155 // only one Dart script per document is supported in Dartium. | 162 // only the first script needs to be added. |
| 156 if (first) { | 163 // others are already removed by _extractInlineScripts |
|
Siggi Cherem (dart-lang)
2014/02/26 22:27:09
_extarctInlineScripts => _extractScripts
Jennifer Messerly
2014/02/27 22:31:40
Done.
| |
| 157 first = false; | 164 return; |
| 158 | |
| 159 var src = script.attributes['src']; | |
| 160 if (src == null) { | |
| 161 logger.warning('unexpected script without a src url. The ' | |
| 162 'ImportInliner transformer should run after running the ' | |
| 163 'InlineCodeExtractor', span: script.sourceSpan); | |
| 164 continue; | |
| 165 } | |
| 166 scriptIds.add(resolve(docId, src, logger, script.sourceSpan)); | |
| 167 | |
| 168 } else { | |
| 169 // TODO(jmesserly): remove this when we are running linter. | |
| 170 logger.warning('more than one Dart script per HTML ' | |
| 171 'document is not supported. Script will be ignored.', | |
| 172 span: script.sourceSpan); | |
| 173 } | |
| 174 } | 165 } |
| 175 } | 166 } |
| 176 } | 167 } |
| 168 | |
| 169 /// Split inline scripts into their own files. We need to do this for dart2js | |
| 170 /// to be able to compile them. | |
| 171 /// | |
| 172 /// This also validates that there weren't any duplicate scripts. | |
| 173 bool _extractScripts(List<Element> scripts) { | |
|
Jennifer Messerly
2014/02/26 03:04:45
the refactored version
| |
| 174 bool changed = false; | |
| 175 bool first = true; | |
| 176 int count = 0; | |
| 177 for (var script in scripts) { | |
| 178 if (script.attributes['type'] != TYPE_DART) continue; | |
| 179 | |
| 180 // only one Dart script per document is supported in Dartium. | |
| 181 if (!first) { | |
| 182 // Remove the script. It's invalid to have more than one in Dartium. | |
| 183 script.remove(); | |
| 184 changed = true; | |
| 185 | |
| 186 // TODO(jmesserly): remove this when we are running linter. | |
| 187 logger.warning('more than one Dart script per HTML ' | |
| 188 'document is not supported. Script will be ignored.', | |
| 189 span: script.sourceSpan); | |
| 190 continue; | |
| 191 } | |
| 192 | |
| 193 first = false; | |
| 194 | |
| 195 var src = script.attributes['src']; | |
| 196 if (src != null) continue; | |
| 197 | |
| 198 var filename = path.url.basename(docId.path); | |
| 199 var code = script.text; | |
| 200 // TODO(sigmund): ensure this path is unique (dartbug.com/12618). | |
| 201 script.attributes['src'] = src = '$filename.$count.dart'; | |
|
Siggi Cherem (dart-lang)
2014/02/26 22:27:09
I never bothered fixing this, but since there is o
Jennifer Messerly
2014/02/27 22:31:40
good catch! done.
Siggi Cherem (dart-lang)
2014/02/28 01:26:45
sigh - sorry, now that I reread things I think we
Jennifer Messerly
2014/02/28 02:21:49
hah, yeah. Fixed now.
| |
| 202 script.text = ''; | |
| 203 changed = true; | |
| 204 | |
| 205 var newId = docId.addExtension('.$count.dart'); | |
| 206 if (!_hasLibraryDirective(code)) { | |
| 207 // TODO(jmesserly): consolidate this with our other parsing. | |
| 208 var libname = path.withoutExtension(newId.path) | |
| 209 .replaceAll(new RegExp('[-./]'), '_'); | |
| 210 code = "library $libname;\n$code"; | |
| 211 } | |
| 212 transform.addOutput(new Asset.fromString(newId, code)); | |
| 213 } | |
| 214 return changed; | |
| 215 } | |
| 177 } | 216 } |
| 178 | 217 |
| 218 /// Parse [code] and determine whether it has a library directive. | |
| 219 bool _hasLibraryDirective(String code) => | |
| 220 parseCompilationUnit(code).directives.any((d) => d is LibraryDirective); | |
| 221 | |
| 222 | |
| 179 /// Recursively inlines the contents of HTML imports. Produces as output a | 223 /// Recursively inlines the contents of HTML imports. Produces as output a |
| 180 /// single HTML file that inlines the polymer-element definitions, and a text | 224 /// single HTML file that inlines the polymer-element definitions, and a text |
| 181 /// file that contains, in order, the URIs to each library that sourced in a | 225 /// file that contains, in order, the URIs to each library that sourced in a |
| 182 /// script tag. | 226 /// script tag. |
| 183 /// | 227 /// |
| 184 /// This transformer assumes that all script tags point to external files. To | 228 /// This transformer assumes that all script tags point to external files. To |
| 185 /// support script tags with inlined code, use this transformer after running | 229 /// support script tags with inlined code, use this transformer after running |
| 186 /// [InlineCodeExtractor] on an earlier phase. | 230 /// [InlineCodeExtractor] on an earlier phase. |
| 187 class ImportInliner extends Transformer { | 231 class ImportInliner extends Transformer { |
| 188 final TransformOptions options; | 232 final TransformOptions options; |
| 189 | 233 |
| 190 ImportInliner(this.options); | 234 ImportInliner(this.options); |
| 191 | 235 |
| 192 /// Only run on entry point .html files. | 236 /// Only run on entry point .html files. |
| 193 Future<bool> isPrimary(Asset input) => | 237 Future<bool> isPrimary(Asset input) => |
| 194 new Future.value(options.isHtmlEntryPoint(input.id)); | 238 new Future.value(options.isHtmlEntryPoint(input.id)); |
| 195 | 239 |
| 196 Future apply(Transform transform) => | 240 Future apply(Transform transform) => |
| 197 new _HtmlInliner(options, transform).apply(); | 241 new _HtmlInliner(options, transform).apply(); |
| 198 } | 242 } |
| 199 | 243 |
| 244 const TYPE_DART = 'application/dart'; | |
| 245 const TYPE_JS = 'text/javascript'; | |
| 200 | 246 |
| 201 /// Internally adjusts urls in the html that we are about to inline. | 247 /// Internally adjusts urls in the html that we are about to inline. |
| 202 class _UrlNormalizer extends TreeVisitor { | 248 class _UrlNormalizer extends TreeVisitor { |
| 203 final Transform transform; | 249 final Transform transform; |
| 204 | 250 |
| 205 /// Asset where the original content (and original url) was found. | 251 /// Asset where the original content (and original url) was found. |
| 206 final AssetId sourceId; | 252 final AssetId sourceId; |
| 207 | 253 |
| 208 _UrlNormalizer(this.transform, this.sourceId); | 254 _UrlNormalizer(this.transform, this.sourceId); |
| 209 | 255 |
| 210 visitElement(Element node) { | 256 visitElement(Element node) { |
| 211 for (var key in node.attributes.keys) { | 257 node.attributes.forEach((name, value) { |
| 212 if (_urlAttributes.contains(key)) { | 258 if (_urlAttributes.contains(name)) { |
| 213 var url = node.attributes[key]; | 259 if (value != '' && !value.trim().startsWith('{{')) { |
| 214 if (url != null && url != '' && !url.startsWith('{{')) { | 260 node.attributes[name] = _newUrl(value, node.sourceSpan); |
| 215 node.attributes[key] = _newUrl(url, node.sourceSpan); | |
| 216 } | 261 } |
| 217 } | 262 } |
| 263 }); | |
| 264 if (node.localName == 'style') { | |
| 265 node.text = visitCss(node.text); | |
| 266 } else if (node.localName == 'script' && | |
| 267 node.attributes['type'] == TYPE_DART) { | |
| 268 // TODO(jmesserly): we might need to visit JS too to handle ES Harmony | |
| 269 // modules. | |
| 270 node.text = visitInlineDart(node.text); | |
| 218 } | 271 } |
| 219 super.visitElement(node); | 272 super.visitElement(node); |
| 220 } | 273 } |
| 221 | 274 |
| 222 static final _URL = new RegExp(r'url\(([^)]*)\)', multiLine: true); | 275 static final _URL = new RegExp(r'url\(([^)]*)\)', multiLine: true); |
| 223 static final _QUOTE = new RegExp('["\']', multiLine: true); | 276 static final _QUOTE = new RegExp('["\']', multiLine: true); |
| 224 | 277 |
| 225 /// Visit the CSS text and replace any relative URLs so we can inline it. | 278 /// Visit the CSS text and replace any relative URLs so we can inline it. |
| 226 // Ported from: | 279 // Ported from: |
| 227 // https://github.com/Polymer/vulcanize/blob/c14f63696797cda18dc3d372b78aa3378 acc691f/lib/vulcan.js#L149 | 280 // https://github.com/Polymer/vulcanize/blob/c14f63696797cda18dc3d372b78aa3378 acc691f/lib/vulcan.js#L149 |
| 228 // TODO(jmesserly): use csslib here instead? Parsing with RegEx is sadness. | 281 // TODO(jmesserly): use csslib here instead? Parsing with RegEx is sadness. |
| 229 // Maybe it's reliable enough for finding URLs in CSS? I'm not sure. | 282 // Maybe it's reliable enough for finding URLs in CSS? I'm not sure. |
| 230 String visitCss(String cssText, String url) { | 283 String visitCss(String cssText) { |
| 284 var url = spanUrlFor(sourceId, transform); | |
| 231 var src = new SourceFile.text(url, cssText); | 285 var src = new SourceFile.text(url, cssText); |
| 232 return cssText.replaceAllMapped(_URL, (match) { | 286 return cssText.replaceAllMapped(_URL, (match) { |
| 233 // Extract the URL, without any surrounding quotes. | 287 // Extract the URL, without any surrounding quotes. |
| 234 var span = src.span(match.start, match.end); | 288 var span = src.span(match.start, match.end); |
| 235 var href = match[1].replaceAll(_QUOTE, ''); | 289 var href = match[1].replaceAll(_QUOTE, ''); |
| 236 href = _newUrl(href, span); | 290 href = _newUrl(href, span); |
| 237 return 'url($href)'; | 291 return 'url($href)'; |
| 238 }); | 292 }); |
| 239 } | 293 } |
| 240 | 294 |
| 241 _newUrl(String href, Span span) { | 295 String visitInlineDart(String code) { |
| 296 var unit = parseCompilationUnit(code); | |
| 297 var file = new SourceFile.text(spanUrlFor(sourceId, transform), code); | |
| 298 var output = new TextEditTransaction(code, file); | |
| 299 | |
| 300 for (Directive directive in unit.directives) { | |
| 301 if (directive is UriBasedDirective) { | |
| 302 var uri = directive.uri.stringValue; | |
| 303 var span = _getSpan(file, directive.uri); | |
| 304 | |
| 305 // TODO(jmesserly): _newUrl supports some things we shouldn't allow | |
| 306 // in Dart imports, such as assets/. | |
| 307 var targetUri = _newUrl(uri, span); | |
| 308 if (targetUri != uri) { | |
| 309 output.edit(span.start.offset, span.end.offset, "'$targetUri'"); | |
| 310 } | |
| 311 } | |
| 312 } | |
| 313 | |
| 314 if (!output.hasEdits) return code; | |
| 315 | |
| 316 // TODO(sigmund): emit source maps when barback supports it (see | |
| 317 // dartbug.com/12340) | |
| 318 return (output.commit()..build(file.url)).text; | |
| 319 | |
|
Siggi Cherem (dart-lang)
2014/02/26 22:27:09
nit: remove empty line
Jennifer Messerly
2014/02/27 22:31:40
eeeeeek. that was ugly! fixed.
| |
| 320 } | |
| 321 | |
| 322 String _newUrl(String href, Span span) { | |
| 242 var uri = Uri.parse(href); | 323 var uri = Uri.parse(href); |
| 243 if (uri.isAbsolute) return href; | 324 if (uri.isAbsolute) return href; |
| 244 if (!uri.scheme.isEmpty) return href; | 325 if (!uri.scheme.isEmpty) return href; |
| 245 if (!uri.host.isEmpty) return href; | 326 if (!uri.host.isEmpty) return href; |
| 246 if (uri.path.isEmpty) return href; // Implies standalone ? or # in URI. | 327 if (uri.path.isEmpty) return href; // Implies standalone ? or # in URI. |
| 247 if (path.isAbsolute(href)) return href; | 328 if (path.isAbsolute(href)) return href; |
| 248 | 329 |
| 249 var id = resolve(sourceId, href, transform.logger, span); | 330 var id = resolve(sourceId, href, transform.logger, span); |
| 250 if (id == null) return href; | 331 if (id == null) return href; |
| 251 var primaryId = transform.primaryInput.id; | 332 var primaryId = transform.primaryInput.id; |
| (...skipping 30 matching lines...) Expand all Loading... | |
| 282 'cite', // in blockquote, del, ins, q | 363 'cite', // in blockquote, del, ins, q |
| 283 'data', // in object | 364 'data', // in object |
| 284 'formaction', // in button, input | 365 'formaction', // in button, input |
| 285 'href', // in a, area, link, base, command | 366 'href', // in a, area, link, base, command |
| 286 'icon', // in command | 367 'icon', // in command |
| 287 'manifest', // in html | 368 'manifest', // in html |
| 288 'poster', // in video | 369 'poster', // in video |
| 289 'src', // in audio, embed, iframe, img, input, script, source, track, | 370 'src', // in audio, embed, iframe, img, input, script, source, track, |
| 290 // video | 371 // video |
| 291 ]; | 372 ]; |
| 373 | |
| 374 _getSpan(SourceFile file, ASTNode node) => file.span(node.offset, node.end); | |
| OLD | NEW |