{"bugs":{"url":"https://github.com/ampproject/amp-toolbox/issues"},"dist":{"shasum":"ab77cd5a44c6c736aedacb770106b01faa81d2f0","tarball":"https://registry.npmjs.org/@ampproject/toolbox-optimizer/-/toolbox-optimizer-2.8.0-canary.6.tgz","fileCount":48,"integrity":"sha512-NXmdDRUD9I1Z/l2MRzbdZuUWvLOdFpJpLFyhkkmoKVoYf0ZxBF0EgHWgtDpv4BfjgIh5KNcxHwzmFFMLJcTUHg==","signatures":[{"sig":"MEUCIQDzKYs3l7oQ0og0mc59vcZAKaaHxvaItTcSkT4Lu+OPZAIgBjqonX6dkNulw7n8ScPXNdlnbKZJcGqziTu4Ieax8/Y=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":218573,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgU40HCRA9TVsSAnZWagAAd4gP/3Zwa3owEW0PCczOGycW\nHfmODZNqXzSWX+5dO1opaic38V0wFCooTbLG5VT0fJMg+k2aOh2/j0lussoY\nvW1uV1DgUxlMf1+N6LIye7lOqGiJm22nLlSM+stqDT6kUjhdNB8bjUBVEyGg\nacjGOt1mIma0RUw1LjX1tBIqVX+7vW7OD6dCwsqPbtqZFe916+kQx8rrjux6\nNQLImKyrCv6JxCmwEPsPqIgOBbWVnZnhxRkEelcBlChRRtEO7AmQTqE1LZ7U\nA2tJ6KdKK0srahWAvvqYDIhNMewsFxFMb6GSO2oQcoQljWgzDRoNqgCteM+h\n14JT7HHJGGUTwXq2kz155mYWYO13azmWXczxjBkjVJ7xnLiJPEyMLUjfNPUn\nk46KHXS5fHGaepMQU263u8fmIbKnLs5UWcMhFR8OlgjrJobHcnh8IS2T2RVq\nkuniAXOX4mKxV7ih+Ff1Xa6o3ug61zbQ7lW6mnE9wWTH/IJx8QBsdhH6LGpC\nVOErowkpXldp/ZOKe8bZx+cXH0vD07BKS0FdNYC1l7AN9V6DRyag7XEFZP71\n4iQpHznQiLNAXdquNS7F2cgHQyB5d5CmkF1cYSzr5PNqrINTAy7CK3AlnfEJ\nolZL9rmMI+ubB0g/r8OHlSkfHJp9O45/sm2lytqvZDzMM883vhcgyvpw/wll\nLlDi\r\n=ri8a\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](https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/server-side-rendering/).\n- **Automatically import all missing AMP component scripts**.\n- **Automatically add any missing mandatory AMP tags**.\n- Auto detects and preloads hero images from amp-img, amp-iframe, amp-video, or amp-video-iframe.\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\n### API\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### CLI\n\nAMP Optimizer can be used via the [AMP Toolbox CLI](/packages/cli/README.md):\n\n```shell\nnpm install @ampproject/toolbox-cli -g\namp optimize myFile.html\n```\n\nor run without installation via `npx`:\n\n```shell\nnpx @ampproject/toolbox-cli optimize myFile.html\n```\n\n### Options\n\nOptions are passed when creating a new AMP Optimizer instance:\n\n```js\nconst ampOptimizer = AmpOptimizer.create({\n  verbose: true\n});\n...\n```\n\nAvailable options are:\n\n- [autoAddMandatoryTags](#autoaddmandatorytags)\n- [autoExtensionImport](#autoextensionimport)\n- [esmModulesEnabled](#esmmodulesenabled)\n- [extensionVersions](#extensionversions)\n- [fetch](#fetch)\n- [format](#format)\n- [imageBasePath](#imagebasePath)\n- [imageOptimizer](#imageoptimizer)\n- [lts](#lts)\n- [markdown](#markdown)\n- [minify](#minify)\n- [optimizeAmpBind](#optimizeampbind)\n- [optimizeHeroImages](#optimizeheroimages)\n- [preloadHeroImage](#preloadheroimage)\n- [verbose](#verbose)\n\n#### `autoAddMandatoryTags`\n\nAutomatically inject any missing markup required by AMP.\n\n- name: `autoAddMandatoryTags`\n- valid options: `[true|false]`\n- default: `true`\n- used by: [AddMandatoryTags](lib/transformers/AddMandatoryTags.js)\n\n#### `autoExtensionImport`\n\nAutomatically import any missing AMP Extensions (e.g. amp-carousel).\n\n- name: `autoExtensionImport`\n- valid options: `[true|false]`\n- default: `true`\n- used by: [AutoExtensionImport](lib/transformers/AutoExtensionImporter.js)\n\n#### `esmModulesEnabled`\n\nEnables the smaller ESM module version of AMP runtime and components:\n\n```\n<script async nomodule src=\"https://cdn.ampproject.org/v0.js\"></script>\n<script async src=\"https://cdn.ampproject.org/v0.mjs\" type=\"module\" crossorigin=\"anonymous\"></script>\n```\n\n**Warning: This is incompatible with AMP Packager unless using a prerelease version containing [this commit](https://github.com/ampproject/amppackager/commit/92387ecf97e420eec10b378282383c59f95ab45f).**\n\n- name: `esmModulesEnabled`\n- valid options: `[true|false]`\n- default: `true`\n- used by: [RewriteAmpUrls](lib/transformers/RewriteAmpUrls.js)\n\n#### `extensionVersions`\n\nSpecify version numbers to use for automatically imported Extensions. If not defined, default to latest.\n\nExample:\n\n```js\nconst ampOptimizer = AmpOptimizer.create({\n  extensionVersions: {\n    'amp-twitter': '0.1',\n  },\n});\n```\n\n- name: `extensionVersions`\n- valid options: `OBJECT`\n- default: `{}`\n- used by: [AutoExtensionImport](lib/transformers/AutoExtensionImporter.js)\n\n#### `format`\n\nSpecifies the AMP format of the input file. Defaults to `AMP`.\n\n- name: `format`\n- valid options: `[AMP|AMP4EMAIL|AMP4ADS]`\n- default: `AMP`\n- used by: [AutoExtensionImport](lib/transformers/AutoExtensionImporter.js), [AddMandatoryTags](lib/transformers/AddMandatoryTags.js)\n\n#### `experimentEsm`\n\nEnable [JavaScript Module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) support for AMP runtime and components. AMP Optimizer will generate module/nonmodule script imports for AMP runtime and components:\n\n```\n<script async nomodule src=\"https://cdn.ampproject.org/v0.js\"></script>\n<script async src=\"https://cdn.ampproject.org/v0.mjs\" type=\"module\" crossorigin=\"anonymous\"></script>\n```\n\n**Warning: this will result in invalid AMP pages.**\n\n- name: `experimentEsm`\n- valid options: `[true|false]`\n- default: `false`\n- used by: [RewriteAmpUrls](lib/transformers/RewriteAmpUrls.js)\n\n#### `imageBasePath`\n\nSpecifies a base path used to resolve an image during build,\nthis can be a file system path or URL prefix. You can also pass a function\n`(imgSrc, params) => '../img/' + imgSrc` for dynamically calculating the image path.\n\n- name: `imageBasePath`\n- valid options: `STRING|FUNCTION`\n- default: undefined\n- used by: [Markdown](lib/transformers/Markdown.js)\n\n#### `imageOptimizer`\n\nEnable automated image `srcset` generation by providing a function for calculating `srcset` URLs for a given image `src`. The function should return a URL pointing to a version of the `src` image with the given `width`. If no image is available, it should return a falsy value.\n\nExample:\n\n```js\nconst ampOptimizer = AmpOptimizer.create({\n  imageOptimizer: (src, width) => `${src}?width=${width}`,\n});\n```\n\n- name: `imageOptimizer`\n- valid options: `FUNCTION`\n- default: undefined\n- used by: [OptimizeImages](lib/transformers/OptimizeImages.js)\n\n#### `lts`\n\nUse [long-term stable URLs](https://github.com/ampproject/amphtml/blob/main/contributing/lts-release.md) for downloading the AMP runtime and components.\n\n- name: `lts`\n- valid options: `[true|false]`\n- default: `false`\n- used by: [RewriteAmpUrls](lib/transformers/RewriteAmpUrls.js)\n\n#### `markdown`\n\nThis transformer adds out-of-the-box markdown support. This allows\nusing AMP Optimizer to convert HTML documents created from Markdown\nfiles into valid AMP. A typical conversion flow would be:\n\nREADME.md => HTML => AMP Optimizer => valid AMP\n\nThe only thing this transformer does is converting `<img>` tags into\neither `amp-img` or `amp-anim` tags. All other Markdown features are\nalready supported by AMP. The transformer will try to resolve image\ndimensions from the actual files. Images larger than 320px will automatically\nget an intrinsic layout. For image detection to work, an optional dependency\n`probe-image-size` needs to be installed via NPM.\n\n- name: `markdown`\n- valid options: `[true|false]`\n- default: `false`\n- used by: [Markdown](lib/transformers/Markdown.js)\n\n#### `minify`\n\nMinifies the generated HTML output and inlined CSS.\n\n- name: `minify`\n- valid options: `[true|false]`\n- default: `true`\n- used by: [MinifyHtml](lib/transformers/MinifyHtml.js), [SeparateKeyframes](lib/transformers/SeparateKeyframes.js)\n\n**Warning:** this setting is not recommended when running AMP Optimizer in your backend on every request as execution time can increase by up to 7x.\n\n#### `optimizeAmpBind`\n\nEnables a considerably faster scanning method in `amp-bind`, by injecting a `i-amphtml-binding` attribute on all elements with a bound attribute.\n\n- name: `optimizeAmpBind`\n- valid options: `[true|false]`\n- default: `false`\n- used by: [OptimizeAmpBind](lib/transformers/OptimizeAmpBind.js)\n\n#### `optimizeHeroImages`\n\nEnables hero image optimization. Hero images will either be auto detected or you can explicitly mark these by adding the `data-hero` attribute:\n\n```\n<amp-img data-hero src=\"foo.jpg\" ...>\n```\n\nThe maximum number of hero images that can be marked up using `data-hero` is `2`. This number can be increased using the `maxHeroImageCount` parameter.\n\nHero images are optimized by server-side rendering the `img` element inside the `amp-img` element. This can siginificantly improve image rendering performance and reduce the [largest contentful paint](https://web.dev/lcp/) (LCP) metric from [Core Web Vitals](https://web.dev/vitals/).\n\n- name: `optimizeHeroImages`\n- valid options: `[true|false]`\n- default: `true`\n- used by: [OptimizeHeroImages](lib/transformers/OptimizeHeroImages.js)\n\n#### `preloadHeroImage`\n\nDeprecated, use [optimizeHeroImages](#optimizeheroimages) instead. \n\n#### `verbose`\n\nEnable verbose mode with more detailed logging output.\n\n- name: `verbose`\n- valid options: `[true|false]`\n- default: `false`\n\n## Features\n\n### Image optimization\n\nAMP Optimizer helps you serve optimized images. For this to work, you need to provide a function that maps an image `src` to a resized `srcset` source value. The image resizing needs to either happen at build time (e.g. for static sites) or via a image hosting service such as [thumbor](https://github.com/thumbor/thumbor).\n\nHere is an example implementation that appends the image width to the `src`:\n\n```js\nconst ampOptimizer = AmpOptimizer.create({\n  // parameters are the amp-img `src` and the `width` of the to be generated srcset source value\n  imageOptimizer: (src, width) => {\n    // we cannot rename if the image does not have a file extension\n    const index = src.lastIndexOf('.');\n    if (index === -1) {\n      // return null means we won't generate a srcset source value for this width\n      return null;\n    }\n    const prefix = src.substring(0, index);\n    const postfix = src.substring(index, src.length);\n    return `${prefix}.${width}w${postfix}`;\n  };\n})\n```\n\nUsing this implementation, AMP Optimizer will transform the following `amp-img` declarations:\n\n```html\n<!-- Injects srcset for responsive layout -->\n<amp-img src=\"image1.png\" width=\"400\" height=\"800\" layout=\"responsive\"></amp-img>\n<!-- Ignores existing srcset -->\n<amp-img\n  layout=\"fill\"\n  srcset=\"image-1x.png 1x,\n                             image-2x.png 2x\"\n></amp-img>\n```\n\ninto:\n\n```html\n<!-- Injects srcset for responsive layout -->\n<amp-img\n  src=\"image1.png\"\n  width=\"400\"\n  height=\"800\"\n  layout=\"responsive\"\n  srcset=\"image1.470w.png 470w, image1.820w.png 820w, image1.1440w.png 1440w\"\n></amp-img>\n<!-- Ignores existing srcset -->\n<amp-img\n  layout=\"fill\"\n  srcset=\"image-1x.png 1x,\n                               image-2x.png 2x\"\n></amp-img>\n```\n\n**Important** when using `layout=responsive` use the `width` and `height` attribute to specify the minimum image dimensions. For example, for a full-bleed hero image on mobile, specify the width as`width=320`.\n\n### Auto add 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```js\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, opts).then((optimizedHtml) => {\n  // optimizedHtml will be a valid AMP document\n  console.log(optimizedHtml);\n});\n```\n\n### Automated Markdown conversion\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```shell\nnpm install probe-image-size --save-dev\n```\n\nExample:\n\n```js\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## Extending AMP Optimizer with custom transformations\n\nAMP Optimizer supports custom HTML transformations:\n\n```js\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## Best Practices\n\n### Make sure to enable AMP Boilerplate removal\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\nTo find out, why the AMP boilerplate could not be removed, enable `verbose` mode:\n\n```js\n// globally\nconst optimizer = ampOptimizer.create({\n  verbose: true,\n});\n```\n\n... or for individual pages:\n\n```js\n// per transformation\nampOptimizer.transformHtml(originalHtml, {\n  verbose: true,\n});\n```\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```js\nconst optimizer = AmpOptimizer.create({\n  transformations: AmpOptimizer.TRANSFORMATIONS_PAIRED_AMP,\n});\nconst ampFilePath = filePath.substring(1, filePath.length).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```js\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```js\nconst optimizer = AmpOptimizer.create({\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\n```js\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/main/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```js\n{\"country\": \"de\"}\n```\n\nwhere in this example, `de` is the ISO 3166-1 alpha-2 country code for Germany.\n\nExample:\n\n```js\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```shell\nnpm 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```shell\nnpm run test:optimizer:snapshot\n```\n\nto store a new snapshot version in `expected_output.html`.\n","gitHead":"69468eb65804e741db4bfbd129c7c4dbfb4b7561","license":"Apache-2.0","scripts":{"postinstall":"node lib/warmup.js"},"_npmUser":{"name":"amp-toolbox","email":"amp-toolbox-eng@google.com"},"homepage":"https://github.com/ampproject/amp-toolbox/tree/main/packages/optimizer","keywords":["amp"],"repository":{"url":"git+https://github.com/ampproject/amp-toolbox.git","type":"git","directory":"packages/optimizer"},"_npmVersion":"lerna/4.0.0/node@v14.15.4+x64 (darwin)","description":"Server-side rendering for AMPs.","directories":{},"maintainers":[{"name":"ampproject-admin","email":"admin@ampproject.org"},{"name":"kristoferbaxter","email":"kbax@me.com"},{"name":"jridgewell","email":"justin+npm@ridgewell.name"},{"name":"choumx","email":"willchou@google.com"},{"name":"amp-toolbox","email":"amp-toolbox-eng@google.com"},{"name":"fstanis","email":"filip@stanis.me"},{"name":"erwinmombay","email":"erwin.mombay@gmail.com"},{"name":"samouri","email":"jzfisgreat@gmail.com"},{"name":"caroqliu","email":"carolineliu@google.com"},{"name":"rsimha","email":"rsimha@amp.dev"},{"name":"dvoytenko","email":"dvoytenko@gmail.com"},{"name":"patrickkettner","email":"patrickkettner@gmail.com"},{"name":"alanorozco","email":"orozcoalan@gmail.com"}],"_nodeVersion":"14.15.4","dependencies":{"terser":"5.6.0","postcss":"8.2.8","domutils":"2.5.0","lru-cache":"6.0.0","domhandler":"4.0.0","cross-fetch":"3.0.6","htmlparser2":"6.0.1","cssnano-simple":"1.2.2","dom-serializer":"1.2.0","abort-controller":"3.0.0","https-proxy-agent":"5.0.0","postcss-safe-parser":"5.0.2","@ampproject/toolbox-core":"^2.8.0-canary.0","normalize-html-whitespace":"1.0.0","@ampproject/toolbox-script-csp":"^2.8.0-canary.0","@ampproject/toolbox-runtime-version":"^2.8.0-canary.0","@ampproject/toolbox-validator-rules":"^2.8.0-canary.0"},"_hasShrinkwrap":false,"readmeFilename":"README.md","peerDependenciesMeta":{"jimp":{"optional":true},"probe-image-size":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/toolbox-optimizer_2.8.0-canary.6_1616088327307_0.21422016328306137","host":"s3://npm-registry-packages"},"_id":"@ampproject/toolbox-optimizer@2.8.0-canary.6","version":"2.8.0-canary.6"}