{"bugs":{"url":"https://github.com/ampproject/amp-toolbox/issues"},"dist":{"shasum":"ca2fc9bb88ca0d37a6e2db498b4a53ff98c0f227","tarball":"https://registry.npmjs.org/@ampproject/toolbox-optimizer/-/toolbox-optimizer-2.4.0-alpha.2.tgz","fileCount":42,"integrity":"sha512-r80SdhPtTocKLWG7q/F0wGXWTirAiZ4tkETozmbDU/ZyBZ9Sa77xGbjT3c1QJPu5LpuLuvAGl63uQ6NiE5QEhw==","signatures":[{"sig":"MEQCIEdPE/wHk4+hKpl7kHCJVVYdf8RgT02azEGhD8PhCGVgAiB0nqKrnTtZATxg0ZASy3Rv4/0vxBetpwMUI/U1oPr8lg==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":181185,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJetWAXCRA9TVsSAnZWagAAOTkP/0kAgtK75LFpQ8Uke95B\nfrYIka3dGxt4WCUgBhRJOvJeQt6qh7mM+bqFKg0HJy0WZA+uqBPH7xL+HcID\nTX5JOuuWUpuqOa7mSiEKnHGKTTTCb4n52wr6uW0bDwNEtVg0dno5Z9pOeXsZ\nhdzVUatM794Dj5oPURuqDpAzU4jXUDD9uOdB5WYS4hicxexnTvCxrbQHetau\nvGE9CbPOtrg4Az/9Y3nXWmh/LCRJwsryfXHVH8zBM6NIrc6NXaVCeIiYhfLm\n8Gyf1hbZ9jXveXYAl3a4QCPD7ysCfLF/H1KFi8cjvONkiqcuubr7EYrGOF/G\nefrS45XT4tsJqGWaSUnbfdisKFumpGUWGJ/6VpamgEG43nVPC1S5cjYHHmRY\ntK6p749RJ6A58W2FqS/87bUVV5IKWYwpmw0iU29JhKDQ+NtO+EJLSNbazY33\nPqv/QV+aR6TPqM8MPMeRuEUVsMl4IZ1TYoFuO1/AzbZ4j9RK9nJnDKVKI46I\nSSQuCh69BgMhV3sTt4ZuBsse1PODH2amf+o/GxLlrskWUEM+sHPBMp77IgJa\nxySjwieKvnfeY7B/Fe70/KFdE8sJjiOiLX8gLAPhtfgCdUtQFXgsqed8xplL\np+OUhEOfI6cLfllx1x1P1shgalIheaQu3dIYfnG57DZ1Sla/Kr2btvf/Okzy\nKtkK\r\n=s4pT\r\n-----END PGP SIGNATURE-----\r\n"},"main":"index.js","name":"@ampproject/toolbox-optimizer","author":{"name":"AMPHTML Team"},"readme":"# AMP Optimizer\n\n[![npm version](https://badge.fury.io/js/%40ampproject%2Ftoolbox-optimizer.svg)](https://badge.fury.io/js/%40ampproject%2Ftoolbox-optimizer)\n\nAMP Optimizer is a tool to simplify creating AMP pages and improve AMP rendering performance. AMP Optimizer implements [AMP performance best practices](https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/optimize_amp?format=websites) and supports [AMP server-side-rendering](https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/server-side-rendering?format=websites). By default, it will perform the following optimizations:\n\n* Server-side render AMP layouts.\n* **Automatically import all missing AMP component scripts**.\n* **Automaticallly add any missing mandatory AMP tags**.\n* Remove the AMP boilerplate (when possible).\n* Remove not needed whitespace.\n* Extract and move CSS keyframe animations to the bottom of the page.\n* Optimize AMP framework and custom font loading\n* Generate CSP for inlined [`amp-script`](https://amp.dev/documentation/components/amp-script/) code.\n\nThe performance optimizations can improve page rendering times by up to 50%. You can read more about the potential performance gains in this [blog post](https://blog.amp.dev/2018/10/08/how-to-make-amp-even-faster/). To give it a try, check out [the online playground](https://toolbox-optimizer.glitch.me/).\n\n**Good to know:**\n\n* AMP Optimizer will produce valid AMP.\n* AMP Optimizer can be used in combination with [AMP Packager](https://github.com/ampproject/amppackager) to create SXGs.\n\n## Usage\n\nInstall via:\n\n```\nnpm install @ampproject/toolbox-optimizer\n```\n\nMinimal usage:\n\n```js\nconst AmpOptimizer = require('@ampproject/toolbox-optimizer');\n\nconst ampOptimizer = AmpOptimizer.create();\n\nconst originalHtml = `\n<!doctype html>\n<html ⚡>\n  ...\n</html>`;\n\nampOptimizer.transformHtml(originalHtml).then((optimizedHtml) => {\n  console.log(optimizedHtml);\n});\n```\n\nYou can find a sample implementation [here](/packages/optimizer/demo/simple). If you're using express to serve your site, you can use the [AMP Optimizer Middleware](/packages/optimizer-express).\n\n### Incomplete markup\n\nIt's possible to pass incomplete documents and AMP Optimizer will add any \nmissing tags and extension imports required by a valid AMP document. \n\n```\nconst originalHtml = `\n  <h1>Hello World!</h1>\n  <amp-twitter width=\"375\" \n               height=\"472\" \n               layout=\"responsive\" \n               data-tweetid=\"1182321926473162752\">\n  </amp-twitter>\n`;\n\n// you can pass the canonical URL, default is `.`\nconst opts = {\n  canonical: '/example.html'\n}\nampOptimizer.transformHtml(originalHtml, params).then((optimizedHtml) => {\n  // optimizedHtml will be a valid AMP document\n  console.log(optimizedHtml);\n});\n```\n\n### Markup support\n\nAMP Optimizer supports converting Markdown to AMPHTML. A typical conversion flow would be:\n\n```\nREADME.md => HTML => AMP Optimizer => valid AMP\n```\n\nThe AMP Optimizer converts `<img>` tags into `<amp-img>` or `<amp-anim>` tags when in Markdown mode. Enable Markdown mode via `markdown : true`. AMP Optimizer will try to resolve image dimensions from the actual files. Images wider than 320px will automatically get an `intrinsic` layout.\n\nAll other Markdown features are already supported by AMP.\n\nYou can pass an additional option `imageBasePath` to specify a base path used to resolve an image during build, this can be a file system path or URL prefix.\n\n**Important:** for image size detection to work, an optional dependency\n`probe-image-size` needs to be installed via NPM.\n\n```\nnpm install probe-image-size --save-dev\n```\n\nExample:\n\n```\nconst AmpOptimizer = require('@ampproject/toolbox-optimizer');\nconst md = require('markdown-it')({\n  // don't sanitize html if you want to support AMP components in Markdown\n  html: true,\n});\n\n// enable markdown mode\nconst ampOptimizer = AmpOptimizer.create({\n  markdown: true,\n});\n\nconst markdown = `\n# Markdown 🤯\n\nHere is an image declared in Markdown syntax: \n\n![A random image](https://unsplash.it/800/600).\n\nYou can directly declare AMP components:\n\n<amp-twitter width=\"375\" \n             height=\"472\" \n             layout=\"responsive\" \n             data-tweetid=\"1182321926473162752\">\n</amp-twitter>\n\nAny missing extensions will be automatically imported.\n`;\n\nconst html = md.render(markdown);\n\nconst amphtml = await ampOptimizer.transformHtml(html, {\n  canonical: filePath,\n});\n```\n\nYou can find a working sample [here](/packages/optimizer/demo/markdown).\n\n### Custom transformations\n\nAMP Optimizer supports custom HTML transformations:\n\n```\nconst AmpOptimizer = require('@ampproject/toolbox-optimizer');\nconst {createElement, firstChildByTag, appendChild} = AmpOptimizer.NodeUtils;\n\nclass CustomTransformer {\n  constructor(config) {\n    this.log_ = config.log.tag('CUSTOM');\n  }\n  transform(tree, params) {\n    this.log_.info('Running custom transformation for ', params.filePath);\n    const html = firstChildByTag(tree, 'html');\n    if (!html) return;\n    const head = firstChildByTag(html, 'head');\n    if (!head) return;\n    const desc = createElement('meta', {\n      name: 'description',\n      content: 'this is just a demo',\n    });\n    appendChild(head, desc);\n  }\n}\n\n// it's best to run custom transformers first\nconst customTransformations = [CustomTransformer, ...AmpOptimizer.TRANSFORMATIONS_AMP_FIRST];\n\n// pass custom transformers when creating the optimizer\nconst optimizer = AmpOptimizer.create({\n  transformations: customTransformations,\n});\n// you can add custom parameters on a per document basis\nconst transformedHtml = await optimizer.transformHtml(html, {\n  filePath,\n});\n```\n\nCheckout [the samples](/packages/optimizer/demo/simple/index.js) to learn how to customize AMP Optimizer.\n\n### CLI\n\nThere's also a [command line version](/packages/cli/README.md) available:\n\n```shell\n$ npx @ampproject/toolbox-cli optimize myFile.html\n```\n\n## Why doesn't my AMP page render faster?\n\nThe biggest performance gain results from [removing the AMP boilerplate code](https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/server-side-rendering/#why-is-it-faster?). However, under some circumstances it's not possible to remove the boilerplate code:\n\n* if the`amp-experiment`, `amp-story` or `amp-dynamic-css-classes` components are used ([code](https://github.com/ampproject/amphtml/blob/62a9eab084ccd800d80a371e2cb29cd4f9e8576a/src/render-delaying-services.js#L39-L43)).\n* if an AMP component uses the `media`, `sizes` or `heights` attribute ([documentation](https://amp.dev/documentation/guides-and-tutorials/learn/common_attributes/?format=websites#heights)). A simple workaround is to replace the `media`, `sizes` or `heights` attributes with normal CSS media queries.\n\nTo find out, why the AMP boilerplate could not be removed, enable `verbose` mode:\n\n```\n// globally\nconst optimizer = ampOptimizer.create({\n  verbose: true\n} );\n```\n\n... or for individual pages:\n\n```\n// per transformation\nampOptimizer.transformHtml(originalHtml, {\n  verbose: true\n})\n```\n\n## Best Practices\n\n### Transform AMP pages at build time if possible\n\nApplying the transformations to an AMP file consumes additional server resources. Also, since the entire file is needed to apply the transformations, it also becomes impossible to stream the response while applying it. In order to avoid server overhead, if the set of AMP files to be transformed is known in advance, transformations should be run at build time.\n\n### Cache transformed AMPs at runtime\n\nMost websites have a more dynamic nature though and are not able to apply the transformations statically. For such cases it is possible to run the transformations after AMP pages are rendered, e.g. in an Express middleware. In that case, to achieve best performance, it's best to cache transformed pages for subsequent requests. Caching can take place on the CDN level, on the site's internal infrastructure (eg: Memcached), or even on the server itself, if the set of pages is small enough to fit in memory.\n\n### Regenerate pages at least once a week\n\nAMP Optimizer inlines CSS styles required by AMP. To make sure, that the inlined CSS stays in sync with the latest AMP release, we recommend to re-generate pages at least once a weekOut-of-sync CSS will not break your page, but it could theoretically cause AMP components to briefly appear with the \"wrong\" styles, such as being visible when they should be hidden. The good news is that these glitches will only be temporary, because as soon as the AMP JS starts, it will check the inlined CSS and update it if required.\n\n## Experimental Features\n\n**Warning: these features are experimental and might result in invalid AMP pages.**\n\n### Paired AMP\n\nWhen using experimental features resulting in invalid AMP it's best to setup paired AMP mode. Paired AMP mode will add `<link rel=amphtml href=${ampUrl}>` to the transformed page, were `ampUrl` needs to point to the valid version of this page.\n\nExample:\n\n```\nconst optimizer = AmpOptimizer.create({\n  transformations: AmpOptimizer.TRANSFORMATIONS_PAIRED_AMP,\n});\nconst ampFilePath = filePath.substring(1, filePath.length)\n    .replace('.html', '.amp.html');\nconst transformedHtml = await optimizer.transformHtml(html, {\n  // needed to calculate the `<link rel=amphtml href=${ampUrl}>`\n  ampUrl: ampFilePath,\n});\n```\n\n### Versioned AMP Runtime\n\nThe `ampRuntimeVersion` parameter will rewrite all AMP runtime and extension imports to the specified version. For example:\n\n```\nhttps://cdn.ampproject.org/v0.js\n```\n\nwill be replaced with:\n\n```\nhttps://cdn.ampproject.org/rtv/001515617716922/v0.js\n```\n\nVersioning the AMP runtime URLs has one main benefit: versioned AMP runtime URLs are served with a longer max-age than the unversioned ones. This means AMP pages served with versioned AMP runtime benefit from better browser caching.\n\n**Important:** when using versioned AMP runtime URLs make sure to invalidate all caches whenever a new AMP runtime is released. This is to ensure that your AMP pages always use the latest version of the AMP runtime.\n\nYou can use [@ampproject/toolbox-runtime-version](/packages/runtime-version) to retrieve the latest version of the AMP runtime. Here is a sample to apply the optimizations including versioning the URLs:\n\n```\nconst ampOptimizer = require('@ampproject/toolbox-optimizer');\nconst ampRuntimeVersion = await runtimeVersion.currentVersion();\n\n// The input string\nconst originalHtml = `\n<!doctype html>\n<html ⚡>\n...\n`\n\n// Additional options can be passed as the second argument\nconst optimizedHtml = await ampOptimizer.transformHtml(originalHtml, {\n  ampUrl: 'canonical.amp.html',\n  ampRuntimeVersion: ampRuntimeVersion\n});\n\nconsole.log(optimizedHtml);\n```\n\n### Blurry image placeholders\n\nAdd placeholders for `amp-img` and `amp-video` posters. The placeholders are blurry versions of the corresponding original source. The blur will be displayed as the `<amp-img>` is rendering, and will fade out once the element is loaded. The current requirements of appending a blurry placeholder is for the element is to be a JPEG that is either responsive or a poster for an `amp-video`.\n\n**Important: blurry image placeholder computation is computationally expensive. Make sure to only use it for static or cached pages.**\n\nThis transformer supports the following options:\n\n* `blurredPlaceholders`: Enables blurry image placeholder generation. Default is `false`.\n* `imageBasePath`: specifies a base path used to resolve an image during build.\n* `maxBlurredPlaceholders`: Specifies the max number of blurred images. Defaults to 5.\n* `blurredPlaceholdersCacheSize`: Specifies the max number of blurred images to be cached\n  to avoid expensive recalculation. Set to 0 if caching should be disabled. Set to -1 if\n  all placeholders should be cached (good for static sites). Defaults to 30.\n\nUsage:\n\n```\nconst optimizer = AmpOptimizer.create({\n  // blurry image placeholders are currently not considered valid AMP\n  // hence it's recommended to setup paired AMP mode when enabling this feature.\n  transformations: AmpOptimizer.TRANSFORMATIONS_PAIRED_AMP,\n  blurredPlaceholders: true,\n});\n```\n\n### Self-hosted AMP components\n\nIt's possible to rewrite the AMP framework and component imports to a different domain than `cdn.ampproject.org`.\n\nExample:\n```\nconst ampOptimizer = require('@ampproject/toolbox-optimizer');\n\n// The input string\nconst originalHtml = `\n<!doctype html>\n<html ⚡>\n...\n`\n\n// Additional options can be passed as the second argument\nconst optimizedHtml = await ampOptimizer.transformHtml(originalHtml, {\n  ampUrl: 'canonical.amp.html',\n  // this will rewrite https://cdn.ampproject.org/v0.js to /amp/v0.js\n  ampUrlPrefix: '/amp'\n});\n\nconsole.log(optimizedHtml);\n```\n\n### Fallback API for amp-geo\n\nIdeally, when self-hosting the AMP framework, `amp-geo-0.1.js` should be patched at delivery time to replace `{{AMP_ISO_COUNTRY_HOTPATCH}}` with the ISO 3166-1 alpha-2 country code where the request originated ([reference](https://github.com/ampproject/amphtml/blob/master/spec/amp-cache-guidelines.md#guidelines-adding-a-new-cache-to-the-amp-ecosystem)). If your host does not have this capability, you can instead rely on a web API to return the country at runtime. The web API must be secure (HTTPS), adhere to [AMP CORS guidelines](https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cors-requests/), and return JSON in the following format:\n\n```\n{\"country\": \"de\"}\n```\n\nwhere in this example, `de` is the ISO 3166-1 alpha-2 country code for Germany.\n\nExample:\n```\nconst ampOptimizer = require('@ampproject/toolbox-optimizer');\n\n// The input string\nconst originalHtml = `\n<!doctype html>\n<html ⚡>\n...\n`;\n\nconst optimizedHtml = await ampOptimizer.transformHtml(originalHtml, {\n  // this will instruct amp-geo to fetch the user's country from an API\n  // which returns JSON in format: {\"country\": \"de\"}\n  geoApiUrl: 'https://example.com/geo'\n});\n\nconsole.log(optimizedHtml);\n```\n\n## Development & Testing\n\nAMP Optimizer uses a snapshot based testing approach. To execute the tests, run in the project root:\n\n```\n$ npm run test:node\n```\n\nTransformer tests are located in:\n\n```\n- spec/transformers/valid/TransformerName/test-name/\n    expected_output.html\n    input.html\n```\n\nThe transformation input is defined in `input.html`, whereas `expected_output.html` contains the expected\noutcome of the transformation. Don't edit `expected_output.html` manually, instead, after changing \na transformer implementation, run: \n\n```\n$ npm run test:optimizer:snapshot\n```\n\nto store a new snapshot version in `expected_output.html`. \n\n\n","gitHead":"c2105027e95afd110e9f3b8c3e252492e3db5149","license":"Apache-2.0","scripts":{"postinstall":"scripts/init.js"},"_npmUser":{"name":"amp-toolbox","email":"amp-toolbox-eng@google.com"},"homepage":"https://github.com/ampproject/amp-toolbox/tree/master/packages/optimizer","keywords":["amp"],"repository":{"url":"git+https://github.com/ampproject/amp-toolbox.git","type":"git","directory":"packages/optimizer"},"_npmVersion":"lerna/3.20.2/node@v12.16.1+x64 (darwin)","description":"Server-side rendering for AMPs.","directories":{},"maintainers":[{"name":"amp-toolbox","email":"amp-toolbox-eng@google.com"},{"name":"ampproject-admin","email":"admin@ampproject.org"},{"name":"choumx","email":"willchou@google.com"},{"name":"erwinmombay","email":"erwin.mombay@gmail.com"},{"name":"fstanis","email":"filip@stanis.me"},{"name":"jridgewell","email":"justin+npm@ridgewell.name"},{"name":"kristoferbaxter","email":"kbax@me.com"}],"_nodeVersion":"12.16.1","dependencies":{"terser":"4.6.13","cssnano":"4.1.10","domutils":"2.0.0","lru-cache":"5.1.1","domhandler":"3.0.0","htmlparser2":"4.1.0","postcss-safe-parser":"4.0.2","@ampproject/toolbox-core":"^2.4.0-alpha.1","normalize-html-whitespace":"1.0.0","@ampproject/toolbox-script-csp":"^2.3.0","@ampproject/toolbox-runtime-version":"^2.4.0-alpha.1","@ampproject/toolbox-validator-rules":"^2.3.0"},"_hasShrinkwrap":false,"readmeFilename":"README.md","peerDependenciesMeta":{"jimp":{"optional":true},"probe-image-size":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/toolbox-optimizer_2.4.0-alpha.2_1588944918950_0.8887560898710563","host":"s3://npm-registry-packages"},"_id":"@ampproject/toolbox-optimizer@2.4.0-alpha.2","version":"2.4.0-alpha.2"}