[
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\nindent_style = space\nindent_size = 2\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nend_of_line = lf\n"
  },
  {
    "path": ".gitignore",
    "content": "*.jks\n*.p8\n*.p12\n*.mobileprovision\n*.orig.*\nweb-build/\nnode_modules\n\ndist\n\n**/public/build\n.netlify\n\n.cache\n.next\n.env\nstats.html\n\n*tar.gz\n\n# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/.pnp\n.pnp.js\n\n# testing\ncoverage\n\n# misc\n.DS_Store\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log\nui-debug.log\n\n# Dependencies\njspm_packages\n\n# Serverless\n.serverless\n\n# Dynamodb\n.dynamodb\n\n# Webpack\n.webpack\n\ntest-results\ntest-report\ntests-out\nplaywright-report\n\n# Local folder\nlocal\n\n# Misc\n.DS_Store\n*.pem\nThumbs.db\n\nsize-plugin.json\n"
  },
  {
    "path": ".npmignore",
    "content": "!dist\nexample/\ncoverage/\ndocs/\njest.config.js\ntsconfig.json\nconfig/\n.editorconfig\n.prettierrc\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\",\n  \"semi\": false,\n  \"endOfLine\": \"auto\"\n}\n\n  "
  },
  {
    "path": "CHANGELOG.md",
    "content": "## 1.0.4\n\n- Add subtree checking for prop scripts so that it works well in a React rerender context\n\n## 1.0.5\n\n- Bad publish, oopsie! Use 1.0.6.\n\n## 1.0.6\n\n- Fix peer deps so it correctly resolves.\n\nThanks [@rschristian](https://github.com/rschristian)\n\n## 1.1.0\n\n- 🧩 Experimental web component support including web component portals! This API may change drastically over time so if you use it keep that in mind. If you have ideas on how to improve it file an issue!\n- Migrate examples over to webpack and off of Microbundle + Preact CLI. Now the development server injects the scripts just like you would in production to give you the closest environment to.\n- Internal island lib now ships with support for the shadow dom (even if you don't want to use the build in island web components API)\n- Documentation updates\n\n## 1.1.1\n\n- Fixed bug where rendering a web component multiple times on a page would not function as expected. This was due to the custom element being defined twice causing everything to silently fail.\n\n## 1.1.2\n\n- Fixed bug where data-mount-in did not function with web components\n\n## 1.2.0\n\n- Fix package.json exports field\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright 2022 Marcus Wood\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n  <img src=\"./docs/preact-island.svg\" align=\"center\" />\n</div>\n<div align=\"center\">\n  <h1 align=\"center\">🏝 Preact Island</h1>\n  <p align=\"center\">\n    A 1.3kB module that helps you ship your own slice of paradise to any website. Especially useful for Shopify apps or CMS websites.\n  </p>\n\n[![downloads][downloads-badge]][npmcharts]\n[![version][version-badge]][package]\n[![Supports Preact and React][preact-badge]][preact]\n[![MIT License][license-badge]][license]\n\n</div>\n\n> 🚀 Looking for a zero config starter to build islands fast? Check out [preact-island-starter](https://github.com/mwood23/preact-island-starter)\n\nSometimes you need to embed a component onto someone else's website. This could be a Shopify widget, email sign up form, CMS comment list, social media share icon, etc. Creating these experiences are tedious and difficult because you aren't in control of the website your code will be executed on.\n\nPreact Island helps you build these experiences by adding a lightweight layer on top of Preact. For <5kB, you get a React style workflow (with hooks!), and a framework for rendering your widget with reactive props.\n\n## Features\n\n- 🚀 Render by selector, inline, or by a specific attribute given on the executed script\n- ⚛️ Based on Preact, no special compiler or anything needed to render an island\n- 🙏 5 ways to pass in props to your component\n- 🧩 Experimental support for web components (including web component portals)\n- 🪄 All components are reactive to prop changes causing rerenders (not remounts)\n- 👯‍♀️ Create as many instances of your component as you need with a single island\n- 🧼 Does not mutate the `window`. Use as many islands as you'd like on one page!\n- 🐣 Less than 1.3kB\n- ☠️ Supports replacing the target selector\n- 🏔 React friendly with `preact/compat`\n- 🔧 Manually trigger rerenders with props\n- 🐙 Fully tested with Preact testing library\n- 👔 Fully typed with TypeScript\n\n## Examples\n\n- [Basic element placement with props](https://codesandbox.io/s/preact-island-element-placement-with-props-8kzmj5)\n- [Reactive props](https://codesandbox.io/s/reactive-prop-updates-uqvof7)\n- [Multiple islands](https://codesandbox.io/s/multiple-islands-8xvjqw)\n- [Props script](https://codesandbox.io/s/props-selector-70ks1g)\n- [Replace selector](https://codesandbox.io/s/replace-selector-z2rogw)\n- [Multiple host elements](https://codesandbox.io/s/multiple-host-elements-q6ot5q)\n- [Clean host element](https://codesandbox.io/s/clean-host-element-i35nlt)\n- [Global island](https://codesandbox.io/s/global-island-zqco9p)\n- [Inline script](https://codesandbox.io/s/inline-script-1qm5q8)\n- [Executed script props](https://codesandbox.io/s/preact-island-element-placement-current-script-props-0dwlyo)\n- [Interior script props](https://codesandbox.io/s/interior-script-props-z5rcxg)\n- [Mount In script attribute](https://codesandbox.io/s/mount-in-property-z5rcxg)\n- [React with Props](https://codesandbox.io/s/preact-island-element-placement-with-props-react-49mjrg)\n- [React Portals with Preact Island](https://codesandbox.io/s/preact-island-element-placement-with-props-react-tdss2p)\n\n## Installation\n\n```sh\nnpm install --save preact-island\n```\n\n## Usage\n\n```tsx\nimport { createIsland } from 'preact-island'\n\nconst Widget = () => {\n  return <div>awesome widget!</div>\n}\n\nconst island = createIsland(Widget)\nisland.render({\n  selector: '[data-island=\"widget\"]',\n})\n```\n\n## API\n\n### createIsland\n\nCreates a new island instance with a passed in component. Returns a bag of props/methods to work with your island.\n\n```tsx\nimport { createIsland } from 'preact-island'\n\nconst Widget = () => {\n  return <div>awesome widget!</div>\n}\n\nconst island = createIsland(Widget)\n```\n\n### createIsland().render\n\nRenders an island to the DOM given options.\n\n```ts\nconst island = createIsland(Widget)\nisland.render({...})\n```\n\n#### options\n\n````ts\n  /**\n   * A query selector target to create the widget. This is ignored if inline is passed or if a `data-mount-in` attribute\n   * is appended onto the executed script.\n   *\n   * @example '[data-island=\"widget\"]'\n   */\n  selector?: string\n  /**\n   * If true, removes all children of the element before rendering the component.\n   *\n   * @default false\n   *\n   * @example\n   * ```html\n   * <div data-island=\"widget\">\n   *    <div>some other content</div>\n   *    <div>some other content</div>\n   *    <div>some other content</div>\n   * </div>\n   * ```\n   *\n   * // turns into\n   *\n   * ```html\n   * <div data-island=\"widget\">\n   *    <div>your-widget</div>\n   * </div\n   * ```\n   */\n  clean?: boolean\n  /**\n   * If true, replaces the contents of the selector with the component given. If you use replace,\n   * you will not be able to add props to the host element (since it will be replaced). You will also\n   * not be able to use child props script either (since they will be replaced).\n   *\n   * Use script tag props or a props selector for handling props when in replace mode.\n   *\n   * @default false\n   *\n   * @example\n   * ```html\n   * <div data-island=\"widget\"></div>\n   * ```\n   *\n   * // turns into\n   *\n   * ```html\n   * <div>your-widget</div>\n   * ```\n   */\n  replace?: boolean\n\n  /**\n   * Renders the widget at the current position of the script in the HTML document.\n   *\n   * @default false\n   *\n   * @example\n   * ```html\n   * <div>\n   *    <div>some content here</div>\n   *    <script src=\"https://preact-island.netlify.app/islands/pokemon.inline.island.umd.js\"></script>\n   *    <div>some content here</div>\n   * </div>\n   * ```\n   *\n   * // turns into\n   *\n   * ```html\n   * <div>\n   *    <div>some content here</div>\n   *    <script src=\"https://preact-island.netlify.app/islands/pokemon.inline.island.umd.js\"></script>\n   *    <div>your widget</div>\n   *    <div>some content here</div>\n   * </div>\n   * ```\n   */\n  inline?: boolean\n  /**\n   * Initial props to pass to the component. These props do not cause updates to the island if changed. Use `createIsland().rerender` instead.\n   */\n  initialProps?: P\n  /**\n   * A valid selector to a script tag located in the HTML document with a type of either `text/props` or `application/json`\n   * containing props to pass into the component. If there are multiple scripts found with the selector, all props are merged with\n   * the last script found taking priority.\n   */\n  propsSelector?: string\n````\n\n### createIsland().rerender\n\nTriggers a rerenders of the island with the new props given.\n\n```ts\nconst island = createIsland(Widget)\nisland.render({ selector: '[data-island=\"widget\"]' })\nisland.rerender({ new: 'props' })\n```\n\n### createIsland().destroy\n\nDestroys all instances of the island on the page and disconnects any associated observers.\n\n```ts\nconst island = createIsland(Widget)\nisland.render({ selector: '[data-island=\"widget\"]' })\nisland.destroy()\n```\n\n## Selecting Mount Point from Script\n\nYou can override the `selector` given to render by passing `data-mount-in` to the script.\n\n[Example](https://codesandbox.io/s/mount-in-property-z5rcxg)\n\n```html\n<div data-island=\"pokemon\">\n  <script type=\"text/props\">\n    {\"pokemon\": \"3\"}\n  </script>\n</div>\n<h2>Special mount</h2>\n<!-- This takes priority over the other placement -->\n<!-- Props are scoped to placement so that's why -->\n<!-- Venosaur (pokemon number 3) doesn't appear -->\n<div data-island=\"mount-here-actually\"></div>\n\n<script\n  async\n  data-mount-in='[data-island=\"mount-here-actually\"]'\n  src=\"https://preact-island.netlify.app/islands/pokemon.island.umd.js\"\n></script>\n```\n\n## Passing Props\n\nProps can be passed to your widget various ways. You can choose to pass props multiple different ways to your island where they'll be merged in a defined order.\n\n### Merging Order\n\nProps are merged in the following order (from lowest to highest specificity):\n\n1. Initial props\n2. Element props\n3. Executed script props\n4. Props selector props\n5. Interior script props\n\n### Data Props\n\nAll props located on an HTML element use `data-`. You can name them any of the following ways:\n\n- `data-background-color` => `backgroundColor`\n- `data-prop-background-color` => `backgroundColor`\n- `data-props-background-color` => `backgroundColor`\n\nUnder the hood all of these element will be transformed to `camelCase` and passed to your component.\n\n### Initial Props\n\nDefault props can be passed on render to an island. You can render many islands and give them all different initial props. Initial props\ndo not cause rerenders if updated. Use `createIsland.rerender` instead.\n\n```ts\nimport { createIsland } from 'preact-island'\n\nconst Widget = () => {\n  return <div>awesome widget!</div>\n}\n\nconst island = createIsland(Widget)\n\nisland.render({\n  selector: '[data-island=\"widget\"]',\n  initialProps: {\n    color: '#000000',\n  },\n})\n\nisland.render({\n  selector: '[data-island=\"widget\"]',\n  initialProps: {\n    color: '#ffffff',\n  },\n})\n\n// Will render two instances of the island with different color props\n```\n\n### Element Props\n\nProps can be placed on host elements and passed to your component. These props are reactive and will cause rerenders on changes.\n\n[Example](https://codesandbox.io/s/preact-island-element-placement-with-props-8kzmj5)\n\n```html\n<div data-island=\"pokemon\" data-pokemon=\"130\"></div>\n<script\n  async\n  src=\"https://preact-island.netlify.app/islands/pokemon.island.umd.js\"\n></script>\n```\n\n### Executed Script Props\n\nProps can be placed on the script tag that's evaluated to the create your island. These props are reactive and will cause rerenders on changes.\n\n[Example](https://codesandbox.io/s/preact-island-element-placement-current-script-props-0dwlyo)\n\n```html\n<div data-island=\"pokemon\"></div>\n<script\n  data-pokemon=\"130\"\n  async\n  src=\"https://preact-island.netlify.app/islands/pokemon.island.umd.js\"\n></script>\n```\n\n### Props Selector Props\n\nProps can be placed inside of a `<script>` and targeted with a given selector. These props are reactive and will cause rerenders on changes. If there are multiple scripts found with the selector, all props are merged with the last script found taking priority.\n\n[Example](https://codesandbox.io/s/props-selector-70ks1g)\n\n```tsx\nconst island = createIsland(Pokemon)\nisland.render({\n  selector: '[data-island=\"pokemon\"]',\n  // Make sure you set this in your island's render method!\n  propsSelector: '[data-island-props=\"test-island\"]',\n})\n```\n\n```html\n<div data-island=\"pokemon\"></div>\n\n<!-- Can be located anywhere in the document! -->\n<script data-island-props=\"test-island\" type=\"text/props\">\n  {\"pokemon\": \"3\"}\n</script>\n\n<script\n  async\n  src=\"https://preact-island.netlify.app/islands/pokemon.props-selector.island.umd.js\"\n></script>\n```\n\n### Interior Script Props\n\nProps can be placed inside of a `<script>` and nested instead of a selector. These props are reactive and will cause rerenders on changes. If\nmultiple interior script props are found, all props are merged with the last script found taking priority.\n\n[Example](https://codesandbox.io/s/interior-script-props-z5rcxg)\n\n```html\n<div data-island=\"pokemon\">\n  <script type=\"text/props\">\n    {\"pokemon\": \"3\"}\n  </script>\n</div>\n\n<script\n  async\n  src=\"https://preact-island.netlify.app/islands/pokemon.island.umd.js\"\n></script>\n```\n\n## React Compatibility\n\n- [React with Props](https://codesandbox.io/s/preact-island-element-placement-with-props-react-49mjrg)\n- [React Portals with Preact Island](https://codesandbox.io/s/preact-island-element-placement-with-props-react-tdss2p)\n\nPreact Island fully supports React using [preact/compat](https://preactjs.com/guide/v10/switching-to-preact). This allows you to bring your existing React components over to Preact to get great performance gains without needing to rewrite your components. Check out the `example-react` folder to a demo repo that reproduces some of the Preact islands as React islands.\n\nDepending on what you import from React, using Preact + Preact Island can result in a **15x smaller bundle** for the same functionality and no code changes needed on your end.\n\n### Bundle Sizes\n\n#### React\n\n![react only](./docs/bundle-react-only.png)\n\n#### React + Preact/compat\n\n![react with preact/compat](./docs/bundle-react-with-compat.png)\n\n#### Preact\n\n![preact](./docs/bundle-preact.png)\n\n## Adding Styles\n\nYou can add styles to your island just like any other component. If you're island will be running on someone else's website be mindful of the global CSS scope! Prefix all of your classes with a name `island__` or use CSS modules to make sure those styles don't leak. Do not use element selectors like `p` or `h2`.\n\n### Including Styles\n\nPreact Island takes no opinions on how CSS is included for your islands. There are two main options:\n\n**Inline the CSS into the bundle**\n\nThis is what the `/example` islands do.\n\n```tsx\nimport { createIsland } from 'preact-island'\nimport style from './email-subscribe.island.css'\n\ndocument.head.insertAdjacentHTML('beforeend', `<style>${style}</style>`)\n\nconst Widget = () => {\n  return (\n    <div className=\"email__container\">\n      <p className=\"email__title\">Join our newsletter</p>\n      {/* ... */}\n    </div>\n  )\n}\n\nconst island = createIsland(Widget)\nisland.render({\n  selector: '[data-island=\"email-subscribe\"]',\n})\n```\n\n```html\n<script\n  src=\"https://your-domain/snippets/fancy-widget.island.umd.js\"\n  async\n></script>\n```\n\n**Pros:**\n\n- The consumer of the script doesn't need to include an external stylesheet\n- There's only one request for rendering the entire widget\n\n**Cons:**\n\n- Bloats the bundle\n- The CSS file itself won't be able to be cached\n\n**Use an external stylesheet**\n\n```html\n<!-- Start island -->\n<link\n  href=\"https://your-domain/snippets/fancy-widget.island.css\"\n  rel=\"stylesheet\"\n/>\n<script\n  src=\"https://your-domain/snippets/fancy-widget.island.umd.js\"\n  async\n></script>\n<!-- End island -->\n```\n\n**Pros:**\n\n- The CSS can be cached in the browser\n- Doesn't bloat the JS bundle\n\n**Cons:**\n\n- Unless your script creates an element to automatically request the stylesheet the consumer of your script will need to add two things not one\n\n### CSS Libraries\n\nIt's not recommending to use CSS libraries when developing islands since they're meant to be small and ran everywhere. Some libraries come with opinionated CSS resets and other global CSS styles that could break the consuming website of your island. They are also going to be large.\n\nIf you need a CSS library, use something that has a just in time compilation step like [Tailwind](https://tailwindcss.com/docs/installation) to minimize the excess CSS. Or you can use something like [Vanilla-Extract](https://vanilla-extract.style/) to build your own zero runtime cost Tailwind.\n\n## Building Your Islands\n\nAny modern bundler will work with Preact Island. If you are looking for a script that will run on a webpage you need the `UMD` format. The `/example` project has a demo setup using `webpack`. It works extremely well if you have multiple islands because it can produce multi-entry point bundles.\n\n### Naming Conventions\n\nMake sure to name your bundles `kebab-case` since they'll be served over HTTP. Case sensitive URLs can be fiddly depending on browser!\n\n## Hosting Your Islands\n\nYou can host your files on anywhere you would typically host websites. Vercel, Cloudflare Workers, and Netlify all work great. Netlify recently [changed their prices](https://answers.netlify.com/t/upcoming-changes-to-netlify-plans/52482/158) causing it to be prohibitively expensive depending on your team size.\n\n> Make sure to use your own domain when hosting these assets. If you use their subdomain like `something.mynetlify.com` and embed those onto third party websites you may get locked in.\n\n## The Callsite for Your Island\n\nWhen you are consuming the bundled snippet it's important not to block rendering on a consuming page. When a browser loads a webpage and sees a `script` tag it executes that script immediately blocking render. Islands should be independent of the consuming page so it is safe to use the `async` property. See [async vs defer](https://javascript.info/script-async-defer) for more information.\n\n> The only exception to this is if you are putting the island on the window and want to run a script after it. Check out [global island](https://codesandbox.io/s/global-island-zqco9p) for an example.\n\nDo this:\n\n```html\n<script\n  src=\"https://your-domain/snippets/fancy-widget.island.umd.js\"\n  async\n></script>\n```\n\nNot this:\n\n```html\n<script src=\"https://your-domain/snippets/fancy-widget.island.umd.js\"></script>\n```\n\n## Differences to Preact Habitat\n\nThis library was heavily inspired by [Preact Habitat](https://github.com/zouhir/preact-habitat).\n\nKey differences:\n\n- Components rerender based on prop changes. This can be a `data-prop` attribute change on a host element, inside of a props script tag, or event on the executed script.\n- You can add props to script element itself and they're passed to the component\n- You can add props to a script tag that lives anywhere in the document and sync it up to the component\n- You can replace the target container instead of rendering inside of it if you choose\n- No double loading when mounting the component\n- Calling render multiple times create many components\n- There is a `rerender` method that allows you to manually alter props for the component\n- All dataset attributes (`data-` on an element) are passed as props\n- There is no `clientSpecified` flag. If you declare a `data-mount-in` prop on a script it will take priority over the `selector` given at `render`.\n\n## Alternatives\n\n- [StencilJS](https://stenciljs.com/): A web components toolchain that feels sort of like React and Angular put together. The JSX core is lifted from Preact's internals. It has a lot of nice features like automatic documentation and other nice to haves since it has its own compiler. It feels tailored towards design system and doesn't have the flexibility of prop injection that Preact Island does. It's also another tool to adopt with it's own patterns. All you have to do with Preact Island is bring your component.\n- [Lit](https://lit.dev/docs/): A web components framework by Google. Does not require a compilation step and weights in around 5Kb (roughly the same as Preact Island + Preact). Doesn't use a virtual dom for diffing and feels like a nice layer on top of web components. Does not support JSX or a React style workflow.\n\n## Credits\n\nA huge thank you to [zouhir](https://github.com/zouhir) who is the author of [preact-habitat](https://github.com/zouhir/preact-habitat). This library is heavily inspired by his work on that library.\n\nArtwork by [vik4graphic](https://lottiefiles.com/vik4graphic)\n\n## License\n\n[MIT](LICENSE) - Copyright (c) [Marcus Wood](https://www.marcuswood.io/)\n\n[version-badge]: https://img.shields.io/npm/v/preact-island.svg?style=flat-square\n[package]: https://www.npmjs.com/package/preact-island\n[downloads-badge]: https://img.shields.io/npm/dm/preact-island.svg?style=flat-square\n[npmcharts]: http://npmcharts.com/compare/preact-island\n[license-badge]: https://img.shields.io/npm/l/preact-island.svg?style=flat-square\n[license]: https://github.com/mwood23/preact-island/blob/master/LICENSE\n[preact-badge]: https://img.shields.io/badge/%E2%9A%9B%EF%B8%8F-preact-6F2FBF.svg?style=flat-square\n[preact]: https://preactjs.com\n[module-formats-badge]: https://img.shields.io/badge/module%20formats-umd%2C%20cjs%2C%20es-green.svg?style=flat-square\n[github-star]: https://github.com/mwood23/preact-island/stargazers\n"
  },
  {
    "path": "config/setupTests.js",
    "content": "import 'regenerator-runtime/runtime'\nimport '@testing-library/jest-dom'\n\nimport preact from 'preact'\nimport * as hook from 'preact/hooks'\nglobal.preact = preact\nglobal._hooks = hook\n"
  },
  {
    "path": "example/declaration.d.ts",
    "content": "declare module '*.css'\n"
  },
  {
    "path": "example/package.json",
    "content": "{\n  \"name\": \"preact-island-examples\",\n  \"version\": \"0.1.0\",\n  \"description\": \"\",\n  \"license\": \"MIT\",\n  \"main\": \"dist/index.js\",\n  \"umd:main\": \"dist/index.umd.js\",\n  \"module\": \"dist/index.module.js\",\n  \"source\": \"src/index.tsx\",\n  \"files\": [\n    \"dist\"\n  ],\n  \"scripts\": {\n    \"build\": \"webpack --env prod\",\n    \"dev\": \"webpack serve --env dev\"\n  },\n  \"dependencies\": {\n    \"clsx\": \"^1.2.1\"\n  },\n  \"devDependencies\": {\n    \"@babel/preset-env\": \"^7.18.9\",\n    \"@babel/preset-react\": \"^7.18.6\",\n    \"@babel/preset-typescript\": \"^7.18.6\",\n    \"@types/webpack\": \"^5.28.0\",\n    \"babel-loader\": \"^8.2.5\",\n    \"css-loader\": \"^6.7.1\",\n    \"html-webpack-plugin\": \"^5.5.0\",\n    \"terser-webpack-plugin\": \"^5.3.5\",\n    \"webpack\": \"^5.74.0\",\n    \"webpack-cli\": \"^4.10.0\",\n    \"webpack-dev-server\": \"^4.9.3\"\n  }\n}\n"
  },
  {
    "path": "example/src/call-to-action.island.css",
    "content": ".cta_button {\n  background-color: none;\n  border: none;\n  background-color: #294eab;\n  border-radius: 5px;\n  padding: 10px;\n  font-weight: bold;\n  color: white;\n  cursor: pointer;\n  font-family: inherit;\n}\n\n.cta__modal-dimmer {\n  position: fixed;\n  display: none;\n  z-index: 90;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.6);\n}\n\n.cta__modal-dimmer--visible {\n  display: block;\n  animation: show 0.2s;\n  animation-fill-mode: forwards;\n}\n\n.cta__modal {\n  position: fixed;\n  outline: none;\n  z-index: 100;\n  background-color: white;\n  display: none !important;\n  width: 380px;\n  border-radius: 24px;\n  padding: 34px 21px;\n  left: 50%;\n  top: 50%;\n  transform: translate(-50%, -50%);\n  font-family: inherit;\n  overflow-y: auto;\n  height: 650px;\n  text-align: center;\n}\n\n.cta__modal--visible {\n  display: block !important;\n  animation: show 0.3s;\n  animation-fill-mode: forwards;\n}\n\n.cta__modal img {\n  width: 100%;\n  margin-bottom: 1rem;\n}\n"
  },
  {
    "path": "example/src/call-to-action.island.tsx",
    "content": "import { createIslandWebComponent, WebComponentPortal } from '../../src'\nimport { useState } from 'preact/hooks'\nimport style from './call-to-action.island.css'\nimport cx from 'clsx'\n\nconst Widget = ({ backgroundColor }: { backgroundColor?: string }) => {\n  const [isOpen, setIsOpen] = useState(false)\n\n  return (\n    <div>\n      <button\n        className=\"cta_button\"\n        style={{ backgroundColor: backgroundColor }}\n        onClick={() => setIsOpen(true)}\n      >\n        All expenses paid island vacation. Click to enter!\n      </button>\n\n      {isOpen && (\n        <WebComponentPortal style={style} name=\"bounty-modal\">\n          <div className={cx('cta__modal', isOpen && 'cta__modal--visible')}>\n            <img src=\"https://github.com/mwood23/preact-island/raw/master/docs/preact-island.svg\" />\n            <p>Portals work with web component islands too!</p>\n            <button className=\"cta_button\" onClick={() => setIsOpen(false)}>\n              close\n            </button>\n          </div>\n        </WebComponentPortal>\n      )}\n      {isOpen && (\n        <WebComponentPortal style={style} name=\"bounty-dimmer\">\n          <div\n            className={cx(\n              'cta__modal-dimmer',\n              isOpen && 'cta__modal-dimmer--visible',\n            )}\n            onClick={() => setIsOpen(false)}\n          />\n        </WebComponentPortal>\n      )}\n    </div>\n  )\n}\n\nconst name = 'call-to-action'\nconst island = createIslandWebComponent(name, Widget)\nisland.render({\n  selector: name,\n})\nisland.injectStyles(style)\n"
  },
  {
    "path": "example/src/email-subscribe.island.css",
    "content": ".email__container {\n  border-radius: 5px;\n  border: 1px solid #eae7e7;\n  padding: 1rem;\n}\n\n.email__title {\n  font-family: inherit;\n  display: block;\n  margin-bottom: 1rem;\n  font-weight: bold;\n  color: #333333;\n  font-size: 1.3rem;\n}\n\n.email__input {\n  font-family: inherit;\n  display: block;\n  margin-bottom: 1rem;\n}\n\n.email__input input {\n  display: block;\n  font-family: inherit;\n  background-color: #efefef;\n  padding: 5px 10px;\n  border: none;\n  border-radius: 5px;\n}\n\n.email__submit {\n  background-color: none;\n  border: none;\n  background-color: #2f3a54;\n  border-radius: 5px;\n  padding: 10px;\n  font-weight: bold;\n  color: white;\n  cursor: pointer;\n  font-family: inherit;\n}\n"
  },
  {
    "path": "example/src/email-subscribe.island.tsx",
    "content": "import { createIsland } from '../../src'\nimport { useState } from 'preact/hooks'\nimport { injectCSS } from './utils'\nimport style from './email-subscribe.island.css'\n\ninjectCSS(style)\n\nconst Widget = ({\n  showEmail = true,\n  showName = true,\n  ...rest\n}: {\n  showEmail: boolean\n  showName: boolean\n}) => {\n  const [value, setValue] = useState({ name: '', email: '' })\n  return (\n    <div className=\"email__container\">\n      <p className=\"email__title\">Join our newsletter</p>\n      <form\n        onSubmit={() => {\n          alert(`Submitted with: ${value.name}, ${value.email}`)\n        }}\n      >\n        {showName && (\n          <label className=\"email__input\">\n            Name\n            <input\n              name=\"name\"\n              onInput={(e: any) =>\n                setValue((x) => ({ ...x, name: e.target.value }))\n              }\n            />\n          </label>\n        )}\n\n        {showEmail && (\n          <label className=\"email__input\">\n            Email\n            <input\n              name=\"email\"\n              onInput={(e: any) =>\n                setValue((x) => ({ ...x, email: e.target.value }))\n              }\n            />\n          </label>\n        )}\n        <button className=\"email__submit\">Sign up</button>\n      </form>\n    </div>\n  )\n}\n\nconst island = createIsland(Widget)\nisland.render({\n  selector: '[data-island=\"email-subscribe\"]',\n})\n"
  },
  {
    "path": "example/src/global.d.ts",
    "content": "declare module '*css'\n"
  },
  {
    "path": "example/src/index.ts",
    "content": "// This file is only used for developing the snippet in the sandbox\nimport './call-to-action.island'\nimport './email-subscribe.island'\nimport './pokemon.island'\n"
  },
  {
    "path": "example/src/pokemon.clean.island.tsx",
    "content": "import { createIsland } from '../../dist/index.module'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\nisland.render({\n  selector: '[data-island=\"pokemon\"]',\n  clean: true,\n})\n"
  },
  {
    "path": "example/src/pokemon.component.tsx",
    "content": "import { useEffect, useState } from 'preact/hooks'\n\nexport const Pokemon = ({ pokemon }: { pokemon: string }) => {\n  const [pokemonData, setPokemonData] = useState<null | any>(null)\n  const [loading, setLoading] = useState(false)\n  const [error, setError] = useState('')\n\n  useEffect(() => {\n    if (!pokemon) return\n\n    setLoading(true)\n    fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`)\n      .then((d) => d.json())\n      .then((d) => {\n        setLoading(false)\n        setPokemonData(d)\n        setError('')\n      })\n      .catch((e) => setError(e.message || 'Something went wrong!'))\n  }, [pokemon])\n\n  if (error) {\n    return <div className=\"pokemon__container\">{error}</div>\n  }\n\n  if (loading) {\n    return <div className=\"pokemon__container\">Loading...</div>\n  }\n\n  if (!pokemonData) {\n    return (\n      <div className=\"pokemon__container\">Select a pokemon to see info</div>\n    )\n  }\n\n  return (\n    <div className=\"pokemon__container\">\n      <img\n        className=\"pokemon__image\"\n        src={pokemonData.sprites.front_default}\n        alt={pokemonData.name}\n      />\n      <p className=\"pokemon__info\">\n        <b>Name:</b> {pokemonData.name}\n      </p>\n      <p className=\"pokemon__info\">\n        <b>Number:</b> {pokemonData.id}\n      </p>\n    </div>\n  )\n}\n"
  },
  {
    "path": "example/src/pokemon.global.island.tsx",
    "content": "import { createIsland } from '../../dist/index.module'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\n\n// @ts-expect-error - We're mutating the window to add this\nwindow._pokemon = island\n"
  },
  {
    "path": "example/src/pokemon.initial-props.island.tsx",
    "content": "import { createIsland } from '../../src'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\nisland.render({\n  selector: '[data-island=\"pokemon\"]',\n  initialProps: {\n    pokemon: 3,\n  },\n})\n"
  },
  {
    "path": "example/src/pokemon.inline.island.tsx",
    "content": "import { createIsland } from '../../src'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\nisland.render({\n  inline: true,\n})\n"
  },
  {
    "path": "example/src/pokemon.island.css",
    "content": ".pokemon__container {\n  border-radius: 5px;\n  border: 1px solid #eae7e7;\n  padding: 1rem;\n  display: inline-block;\n}\n\n.pokemon__image {\n  width: 200px;\n  height: 200px;\n  text-align: center;\n}\n\n.pokemon__info {\n  color: #2b2e34;\n  margin-bottom: 5px;\n}\n"
  },
  {
    "path": "example/src/pokemon.island.tsx",
    "content": "import { createIsland } from '../../src'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\nisland.render({\n  selector: '[data-island=\"pokemon\"]',\n})\n"
  },
  {
    "path": "example/src/pokemon.props-selector.island.tsx",
    "content": "import { createIsland } from '../../src'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\nisland.render({\n  selector: '[data-island=\"pokemon\"]',\n  propsSelector: '[data-island-props=\"test-island\"]',\n})\n"
  },
  {
    "path": "example/src/pokemon.replace.island.tsx",
    "content": "import { createIsland } from '../../src'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\nisland.render({\n  selector: '[data-island=\"pokemon\"]',\n  replace: true,\n})\n"
  },
  {
    "path": "example/src/template.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>Widgets</title>\n    <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n    <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n    <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n    <link\n      href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap\"\n      rel=\"stylesheet\"\n    />\n    <style>\n      body {\n        font-family: 'Inter', sans-serif;\n      }\n\n      .preview {\n        width: 100%;\n        max-width: 1100px;\n        margin: 80px auto;\n        border: 1px dashed rgba(0, 0, 0, 0.2);\n        position: relative;\n        padding: 1rem;\n      }\n\n      .preview::before {\n        content: 'WIDGET PREVIEW';\n        position: absolute;\n        display: block;\n        top: -18px;\n        font-size: 11px;\n        color: rgba(0, 0, 0, 0.5);\n      }\n    </style>\n    <script async=\"\" src=\"/call-to-action.island.umd.js\" data-mount-in=\".mount-call-to-action-here\"></script>\n  </head>\n  <body>\n    <div class=\"preview\">\n      <call-to-action></call-to-action>\n    </div>\n    <div data-island=\"email-subscribe\" class=\"preview\"></div>\n    <div data-island=\"pokemon\" class=\"preview\">\n      <script type=\"text/props\">\n        { \"pokemon\": \"122\" }\n      </script>\n    </div>\n    <div class=\"preview\">\n      <div class=\"mount-call-to-action-here\">\n    </div>\n  </body>\n</html>\n"
  },
  {
    "path": "example/src/utils.ts",
    "content": "export const injectCSS = (style: string) => {\n  document.head.insertAdjacentHTML('beforeend', `<style>${style}</style>`)\n}\n"
  },
  {
    "path": "example/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"jsx\": \"react-jsx\",\n    \"jsxImportSource\": \"preact\",\n    \"allowJs\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": true,\n    \"noImplicitOverride\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"sourceMap\": true,\n    \"declaration\": false,\n    \"moduleResolution\": \"node\",\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"importHelpers\": true,\n    \"target\": \"es2015\",\n    \"module\": \"esnext\",\n    \"types\": [\"node\"],\n    \"lib\": [\"es2017\", \"dom\", \"DOM.Iterable\"],\n    \"skipLibCheck\": true,\n    \"skipDefaultLibCheck\": true,\n    \"noPropertyAccessFromIndexSignature\": false,\n    \"baseUrl\": \".\"\n  },\n  \"exclude\": [\n    \"config/setupTests.ts\",\n    \"jest.config.ts\",\n    \"**/*.spec.ts\",\n    \"**/*.test.ts\",\n    \"**/*.spec.tsx\",\n    \"**/*.test.tsx\",\n    \"**/*.spec.js\",\n    \"**/*.test.js\",\n    \"**/*.spec.jsx\",\n    \"**/*.test.jsx\"\n  ],\n  \"include\": [\"src/**/*.js\", \"src/**/*.jsx\", \"src/**/*.ts\", \"src/**/*.tsx\"]\n}\n"
  },
  {
    "path": "example/webpack.config.js",
    "content": "const path = require('path')\nconst HtmlWebpackPlugin = require('html-webpack-plugin')\nconst TerserPlugin = require('terser-webpack-plugin')\n\nmodule.exports = ({ dev, prod }) => {\n  const isDev = dev === true\n  const isProd = prod === true\n\n  /** @type { import('webpack').Configuration } */\n  const config = {\n    mode: isProd ? 'production' : 'development',\n    target: 'web',\n    resolve: {\n      extensions: ['.js', '.json', '.ts', '.tsx'],\n      /**\n       * From the docs to make Webpack compile Preact:\n       * https://preactjs.com/guide/v10/getting-started#aliasing-in-webpack\n       */\n      alias: {\n        react: 'preact/compat',\n        'react-dom/test-utils': 'preact/test-utils',\n        'react-dom': 'preact/compat', // Must be below test-utils\n        'react/jsx-runtime': 'preact/jsx-runtime',\n      },\n    },\n    devServer: {\n      port: 6464,\n      hot: false,\n    },\n    devtool: false,\n    entry: {\n      'call-to-action': './src/call-to-action.island.tsx',\n      'email-subscribe': './src/email-subscribe.island.tsx',\n      pokemon: './src/pokemon.island.tsx',\n    },\n    output: {\n      path: path.join(__dirname, 'dist/islands'),\n      filename: '[name].island.umd.js',\n      libraryTarget: 'umd',\n    },\n    module: {\n      rules: [\n        {\n          test: /\\.(js|ts|tsx)$/,\n          exclude: [/node_modules/],\n          use: [\n            {\n              loader: 'babel-loader',\n              options: {\n                babelrc: false,\n                presets: [\n                  '@babel/preset-typescript',\n                  ['@babel/preset-react', { runtime: 'automatic' }],\n                  [\n                    '@babel/preset-env',\n                    { targets: { node: 16 }, modules: false },\n                  ],\n                ],\n              },\n            },\n          ],\n        },\n        {\n          test: /\\.css$/i,\n          use: ['css-loader'],\n        },\n        {\n          test: /\\.(png|jpe?g|gif)$/i,\n          use: [\n            {\n              loader: 'file-loader',\n            },\n          ],\n        },\n      ],\n    },\n    plugins: [\n      new HtmlWebpackPlugin({\n        template: 'src/template.html',\n        /**\n         * Islands are served from /islands in dist so we don't pollute the root domain since these islands are\n         * embedded into websites we do not control.\n         *\n         * In dev mode, we serve islands and the index.html from the root since it's dev mode. For production,\n         * the index.html file is served from the root.\n         */\n        publicPath: isDev ? '/' : '/islands',\n        filename: isDev ? 'index.html' : '../index.html',\n      }),\n    ],\n    stats: 'errors-warnings',\n    optimization: {\n      minimize: true,\n      minimizer: [new TerserPlugin()],\n    },\n  }\n\n  return config\n}\n"
  },
  {
    "path": "example-react/declaration.d.ts",
    "content": "declare module '*.css'\n"
  },
  {
    "path": "example-react/package.json",
    "content": "{\n  \"name\": \"preact-island-react-examples\",\n  \"version\": \"0.1.0\",\n  \"description\": \"\",\n  \"source\": \"src/index.tsx\",\n  \"main\": \"dist/index.js\",\n  \"module\": \"dist/index.module.js\",\n  \"umd:main\": \"dist/index.umd.js\",\n  \"scripts\": {\n    \"build\": \"NODE_OPTIONS=--max-old-space-size=8192 microbundle src/*.island.tsx build --no-sourcemap --output dist/islands --external none --css inline --tsconfig tsconfig.json --alias react=preact/compat,react-dom=preact/compat,react-dom/test-utils=preact/compat,react/jsx-runtime=preact/compat\"\n  },\n  \"files\": [\n    \"dist\"\n  ],\n  \"license\": \"MIT\",\n  \"devDependencies\": {\n    \"@types/react\": \"^17.0.1\",\n    \"@types/react-dom\": \"^17.0.1\",\n    \"clsx\": \"^1.1.1\",\n    \"microbundle\": \"^0.15.0\",\n    \"react\": \"^17.0.1\",\n    \"react-dom\": \"^17.0.1\"\n  }\n}\n"
  },
  {
    "path": "example-react/src/call-to-action.island.css",
    "content": ".cta_button {\n  background-color: none;\n  border: none;\n  background-color: #294eab;\n  border-radius: 5px;\n  padding: 10px;\n  font-weight: bold;\n  color: white;\n  cursor: pointer;\n  font-family: inherit;\n}\n\n.cta__modal-dimmer {\n  position: fixed;\n  display: none;\n  z-index: 90;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.6);\n}\n\n.cta__modal-dimmer--visible {\n  display: block;\n  animation: show 0.2s;\n  animation-fill-mode: forwards;\n}\n\n.cta__modal {\n  position: fixed;\n  outline: none;\n  z-index: 100;\n  background-color: white;\n  display: none !important;\n  width: 380px;\n  border-radius: 24px;\n  padding: 34px 21px;\n  left: 50%;\n  top: 50%;\n  transform: translate(-50%, -50%);\n  font-family: inherit;\n  overflow-y: auto;\n  height: 650px;\n  text-align: center;\n}\n\n.cta__modal--visible {\n  display: block !important;\n  animation: show 0.3s;\n  animation-fill-mode: forwards;\n}\n\n.cta__modal img {\n  width: 100%;\n  margin-bottom: 1rem;\n}\n"
  },
  {
    "path": "example-react/src/call-to-action.react.island.tsx",
    "content": "import { createIsland } from '../../dist/index.module'\nimport { useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport style from './call-to-action.island.css'\nimport { injectCSS } from './utils'\nimport cx from 'clsx'\n\ninjectCSS(style)\n\nconst Widget = ({ backgroundColor }: { backgroundColor?: string }) => {\n  const [isOpen, setIsOpen] = useState(false)\n\n  return (\n    <div>\n      <button\n        className=\"cta_button\"\n        style={{ backgroundColor: backgroundColor }}\n        onClick={() => setIsOpen(true)}\n      >\n        All expenses paid island vacation. Click to enter!\n      </button>\n\n      {isOpen &&\n        createPortal(\n          <div className={cx('cta__modal', isOpen && 'cta__modal--visible')}>\n            <img src=\"https://github.com/mwood23/preact-island/raw/master/docs/preact-island.svg\" />\n            <p>Portals work with islands too!</p>\n            <button className=\"cta_button\" onClick={() => setIsOpen(false)}>\n              close\n            </button>\n          </div>,\n          document.body,\n        )}\n      {isOpen &&\n        createPortal(\n          <div\n            className={cx(\n              'cta__modal-dimmer',\n              isOpen && 'cta__modal-dimmer--visible',\n            )}\n            onClick={() => setIsOpen(false)}\n          />,\n          document.body,\n        )}\n    </div>\n  )\n}\n\nconst island = createIsland(Widget)\nisland.render({\n  selector: '[data-island=\"call-to-action\"]',\n})\n"
  },
  {
    "path": "example-react/src/pokemon.component.tsx",
    "content": "import { useEffect, useState } from 'react'\n\nexport const Pokemon = ({ pokemon }: { pokemon: string }) => {\n  const [pokemonData, setPokemonData] = useState<null | any>(null)\n  const [loading, setLoading] = useState(false)\n  const [error, setError] = useState('')\n\n  useEffect(() => {\n    if (!pokemon) return\n\n    setLoading(true)\n    fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`)\n      .then((d) => d.json())\n      .then((d) => {\n        setLoading(false)\n        setPokemonData(d)\n        setError('')\n      })\n      .catch((e) => setError(e.message || 'Something went wrong!'))\n  }, [pokemon])\n\n  if (error) {\n    return <div className=\"pokemon__container\">{error}</div>\n  }\n\n  if (loading) {\n    return <div className=\"pokemon__container\">Loading...</div>\n  }\n\n  if (!pokemonData) {\n    return (\n      <div className=\"pokemon__container\">Select a pokemon to see info</div>\n    )\n  }\n\n  return (\n    <div className=\"pokemon__container\">\n      <img\n        className=\"pokemon__image\"\n        src={pokemonData.sprites.front_default}\n        alt={pokemonData.name}\n      />\n      <p className=\"pokemon__info\">\n        <b>Name:</b> {pokemonData.name}\n      </p>\n      <p className=\"pokemon__info\">\n        <b>Number:</b> {pokemonData.id}\n      </p>\n    </div>\n  )\n}\n"
  },
  {
    "path": "example-react/src/pokemon.island.css",
    "content": ".pokemon__container {\n  border-radius: 5px;\n  border: 1px solid #eae7e7;\n  padding: 1rem;\n  display: inline-block;\n}\n\n.pokemon__image {\n  width: 200px;\n  height: 200px;\n  text-align: center;\n}\n\n.pokemon__info {\n  color: #2b2e34;\n  margin-bottom: 5px;\n}\n"
  },
  {
    "path": "example-react/src/pokemon.react.island.tsx",
    "content": "import { createIsland } from '../../dist/index.module'\nimport { Pokemon } from './pokemon.component'\nimport style from './pokemon.island.css'\nimport { injectCSS } from './utils'\n\ninjectCSS(style)\n\nconst island = createIsland(Pokemon)\nisland.render({\n  selector: '[data-island=\"pokemon\"]',\n})\n"
  },
  {
    "path": "example-react/src/utils.ts",
    "content": "export const injectCSS = (style: string) => {\n  document.head.insertAdjacentHTML('beforeend', `<style>${style}</style>`)\n}\n"
  },
  {
    "path": "example-react/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2017\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ES2015\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"declaration\": true,\n    \"preserveWatchOutput\": true,\n    \"jsx\": \"react-jsx\",\n    \"jsxFactory\": \"\",\n    \"jsxFragmentFactory\": \"\",\n    \"noEmit\": true\n  },\n  \"include\": [\"src\", \"declaration.d.ts\"],\n  \"exclude\": [\"**/tests/**\"]\n}\n"
  },
  {
    "path": "jest.config.js",
    "content": "export default {\n  collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}', '!src/**/*.d.ts'],\n  preset: 'jest-preset-preact',\n  setupFilesAfterEnv: ['<rootDir>/config/setupTests.js'],\n  testEnvironment: 'jsdom',\n  globals: {\n    'ts-jest': {\n      isolatedModules: true,\n    },\n  },\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"preact-island\",\n  \"version\": \"1.2.0\",\n  \"type\": \"module\",\n  \"description\": \"🏝 Create your own slice of paradise on any website.\",\n  \"source\": \"src/index.ts\",\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.module.js\",\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.modern.js\",\n      \"require\": \"./dist/index.cjs\",\n      \"umd\": \"./dist/index.umd.js\"\n    }\n  },\n  \"unpkg\": \"./dist/index.umd.js\",\n  \"types\": \"./dist/index.d.ts\",\n  \"scripts\": {\n    \"build:netlify\": \"npm run build && cd ./example && npm install && npm run build\",\n    \"build:netlify:react\": \"npm run build && cd ./example-react && npm install && npm run build\",\n    \"build\": \"microbundle --sourcemap false\",\n    \"dev:lib\": \"microbundle watch\",\n    \"dev:example\": \"cd example && npm run dev\",\n    \"dev\": \"run-p dev:*\",\n    \"test\": \"jest\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/mwood23/preact-island.git\"\n  },\n  \"keywords\": [\n    \"preact\",\n    \"habitat\",\n    \"shopify\",\n    \"cms widgets\"\n  ],\n  \"author\": \"Marcus Wood\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/mwood23/preact-island/issues\"\n  },\n  \"homepage\": \"https://github.com/mwood23/preact-island#readme\",\n  \"eslintConfig\": {\n    \"parser\": \"@typescript-eslint/parser\",\n    \"extends\": [\n      \"preact\",\n      \"plugin:@typescript-eslint/recommended\"\n    ],\n    \"ignorePatterns\": [\n      \"build/\"\n    ]\n  },\n  \"dependencies\": {},\n  \"devDependencies\": {\n    \"@types/jest\": \"^27.5.1\",\n    \"@testing-library/jest-dom\": \"^5.16.4\",\n    \"@testing-library/user-event\": \"^14.2.0\",\n    \"microbundle\": \"^0.15.0\",\n    \"eslint\": \"^8.15.0\",\n    \"eslint-config-preact\": \"^1.3.0\",\n    \"prettier\": \"^2.6.2\",\n    \"jest\": \"^27.2.5\",\n    \"preact\": \"^10.7.2\",\n    \"preact-render-to-string\": \"^5.1.4\",\n    \"npm-run-all\": \"^4.1.5\",\n    \"@testing-library/preact\": \"^2.0.1\",\n    \"jest-preset-preact\": \"^4.0.2\",\n    \"typescript\": \"^4.6.4\"\n  },\n  \"peerDependencies\": {\n    \"preact\": \">=10\"\n  }\n}\n"
  },
  {
    "path": "src/index.ts",
    "content": "export * from './island'\nexport * from './island-web-components'\n"
  },
  {
    "path": "src/island-web-components.tsx",
    "content": "import { ComponentType, VNode } from 'preact'\nimport { createPortal, FC, useEffect, useMemo } from 'preact/compat'\nimport { createIsland, Island } from './island'\n\nexport type InitialPropsWebComponent = { [x: string]: any }\n\nexport const createIslandWebComponent = <P extends InitialPropsWebComponent>(\n  /**\n   * Must be a valid web component element name. See spec for more details:\n   * https://html.spec.whatwg.org/#valid-custom-element-name\n   */\n  elementName: string,\n  /**\n   * Component you would like to render inside of the web component\n   */\n  widget: ComponentType<P>,\n) => {\n  if (customElements.get(elementName) == null) {\n    class Element extends HTMLElement {\n      constructor() {\n        super()\n\n        // Create a shadow root\n        this.attachShadow({ mode: 'open' })\n      }\n    }\n\n    customElements.define(elementName, Element)\n  }\n\n  const island = createIsland(widget)\n\n  return {\n    ...island,\n    render: (\n      args: Omit<\n        Parameters<Island<P>['render']>[0],\n        'replace' | 'clean' | 'inline'\n      >,\n    ) => island.render({ elementName, ...args }),\n    injectStyles: (style: string) => {\n      island._roots.forEach((root) => {\n        const styleElement = document.createElement('style')\n        styleElement.innerHTML = style\n\n        // @ts-ignore\n        root.parentNode.prepend(styleElement)\n      })\n    },\n  }\n}\n\nexport const WebComponentPortal: FC<{\n  name: string\n  container?: Element\n  children: VNode<{}>\n  style?: string | HTMLStyleElement\n}> = ({ name, container = document.body, children, style }) => {\n  const portalTarget = useMemo(() => {\n    if (customElements.get(name) == null) {\n      class Element extends HTMLElement {\n        constructor() {\n          super()\n\n          // Create a shadow root\n          const shadowRoot = this.attachShadow({ mode: 'open' })\n\n          if (!style) return\n\n          if (style instanceof HTMLStyleElement) {\n            shadowRoot.prepend(style)\n          } else {\n            const styleElement = document.createElement('style')\n            styleElement.innerHTML = style\n\n            shadowRoot.prepend(styleElement)\n          }\n        }\n      }\n\n      customElements.define(name, Element)\n    }\n\n    const customElement = document.createElement(name)\n    return container.appendChild(customElement)\n  }, [container, style])\n\n  useEffect(() => {\n    return () => {\n      portalTarget.remove()\n    }\n  }, [portalTarget])\n\n  // @ts-ignore - Internal types wrong\n  return createPortal(children, portalTarget.shadowRoot)\n}\n"
  },
  {
    "path": "src/island.ts",
    "content": "import { getHostElements, mount, RootFragment, renderIsland } from './lib'\nimport { render, ComponentType } from 'preact'\n\nexport type InitialProps = { [x: string]: any }\n\nexport type Island<P extends InitialProps> = {\n  /**\n   * A WeakMap that yields the mutation observers associated with a particular root. Used for cleaning up observers\n   * on destroy.\n   */\n  _rootsToObservers: WeakMap<RootFragment, MutationObserver>\n  /**\n   * An array of the root fragments (a fake DOM element) containing one or more\n   * DOM nodes, which can then be passed as the `parent` argument to Preact's `render()` method.\n   */\n  _roots: RootFragment[]\n  /**\n   * A reference to the executed script that called `createIsland`. This is used for listening to prop\n   * changes on that script and causing rerenders of the island.\n   */\n  _executedScript: HTMLOrSVGScriptElement | null\n  /**\n   * Renders the created island at the given selector. Calling multiple times appends elements at the given selectors.\n   */\n  render: (props: {\n    /**\n     * A query selector target to create the widget. This is ignored if inline is passed or if a `data-mount-in` attribute\n     * is appended onto the executed script.\n     *\n     * @example '[data-island=\"widget\"]'\n     */\n    selector?: string\n    /**\n     * If true, removes all children of the element before rendering the component.\n     *\n     * @default false\n     *\n     * @example\n     * ```html\n     * <div data-island=\"widget\">\n     *    <div>some other content</div>\n     *    <div>some other content</div>\n     *    <div>some other content</div>\n     * </div>\n     * ```\n     *\n     * // turns into\n     *\n     * ```html\n     * <div data-island=\"widget\">\n     *    <div>your-widget</div>\n     * </div\n     * ```\n     */\n    clean?: boolean\n    /**\n     * If true, replaces the contents of the selector with the component given. If you use replace,\n     * you will not be able to add props to the host element (since it will be replaced). You will also\n     * not be able to use child props script either (since they will be replaced).\n     *\n     * Use script tag props or a props selector for handling props when in replace mode.\n     *\n     * @default false\n     *\n     * @example\n     * ```html\n     * <div data-island=\"widget\"></div>\n     * ```\n     *\n     * // turns into\n     *\n     * ```html\n     * <div>your-widget</div>\n     * ```\n     */\n    replace?: boolean\n\n    /**\n     * Renders the widget at the current position of the script in the HTML document.\n     *\n     * @default false\n     *\n     * @example\n     * ```html\n     * <div>\n     *    <div>some content here</div>\n     *    <script src=\"https://preact-island.netlify.app/islands/pokemon.inline.island.umd.js\"></script>\n     *    <div>some content here</div>\n     * </div>\n     * ```\n     *\n     * // turns into\n     *\n     * ```html\n     * <div>\n     *    <div>some content here</div>\n     *    <script src=\"https://preact-island.netlify.app/islands/pokemon.inline.island.umd.js\"></script>\n     *    <div>your widget</div>\n     *    <div>some content here</div>\n     * </div>\n     * ```\n     */\n    inline?: boolean\n    /**\n     * Initial props to pass to the component. These props do not cause updates to the island if changed. Use `createIsland().rerender` instead.\n     */\n    initialProps?: Partial<P>\n    /**\n     * A valid selector to a script tag located in the HTML document with a type of either `text/props` or `application/json`\n     * containing props to pass into the component. If there are multiple scripts found with the selector, all props are merged with\n     * the last script found taking priority.\n     */\n    propsSelector?: string\n\n    /**\n     * Passed in if using for web components\n     */\n    elementName?: string\n  }) => void\n\n  /**\n   * Contains the current props used to render the island.\n   */\n  props: P\n  /**\n   * Triggers a rerenders of the island with the new props given.\n   */\n  rerender: (props: P) => void\n  /**\n   * Destroys all instances of the island on the page and disconnects any associated observers.\n   */\n  destroy: () => void\n}\n\nexport const createIsland = <P extends InitialProps>(\n  widget: ComponentType<P>,\n) => {\n  const island: Island<P> = {\n    _rootsToObservers: new WeakMap(),\n    _roots: [],\n    _executedScript: document.currentScript,\n    // @ts-ignore\n    props: {},\n    render: ({\n      selector,\n      clean = false,\n      replace = false,\n      inline = false,\n      initialProps = {},\n      propsSelector,\n      elementName,\n    }) => {\n      let rendered = false\n\n      const load = () => {\n        /**\n         * We listen for multiple events to render so soon as we do it once\n         * successfully we break early for others.\n         */\n        if (rendered === true) return\n        const hostElements = getHostElements({\n          selector,\n          inline,\n          elementName,\n        })\n\n        // Do nothing if no host elements returned\n        if (hostElements.length === 0) return\n\n        const { rootFragments } = mount<P>({\n          island,\n          widget,\n          clean,\n          hostElements,\n          replace,\n          // @ts-ignore Not sure how to fix this error\n          initialProps,\n          propsSelector,\n        })\n\n        island._roots = island._roots.concat(rootFragments)\n        rendered = true\n      }\n\n      load()\n      document.addEventListener('DOMContentLoaded', load)\n      document.addEventListener('load', load)\n    },\n    rerender: (newProps) => {\n      island._roots.forEach((rootFragment) => {\n        renderIsland({\n          island,\n          widget,\n          rootFragment,\n          props: { ...island.props, ...newProps },\n        })\n      })\n    },\n    destroy: () => {\n      island._roots.forEach((rootFragment) => {\n        island._rootsToObservers.get(rootFragment)?.disconnect()\n        render(null, rootFragment)\n      })\n    },\n  }\n\n  return island\n}\n"
  },
  {
    "path": "src/lib.ts",
    "content": "import { ComponentType, h, render } from 'preact'\nimport { InitialProps, Island } from './island'\n\ntype HostElement = HTMLElement | ShadowRoot\n\nexport const isInShadow = (node: HostElement | HTMLOrSVGScriptElement) => {\n  return node.getRootNode() instanceof ShadowRoot\n}\n\nexport const isShadowRoot = (x: unknown): x is ShadowRoot => {\n  return x instanceof ShadowRoot\n}\n\nexport const formatProp = (str: string) => {\n  return `${str.charAt(0).toLowerCase()}${str.slice(1)}`\n}\n\nexport const getPropsFromElement = (\n  element: HostElement | HTMLOrSVGScriptElement,\n) => {\n  // In a shadow dom we replace the host element because it's within the shadow root. However,\n  // we want the props of the autonomous custom element.\n  const targetElement = isInShadow(element)\n    ? (element.getRootNode() as any).host\n    : element\n\n  const { dataset } = targetElement\n\n  const props: { [x: string]: any } = {}\n\n  for (var d in dataset) {\n    // We don't pull props for inherited attributes\n    if (dataset.hasOwnProperty(d) === false) return\n\n    // data-prop or data-props works!\n    const propName = formatProp(d.split(/(props?)/).pop() || '')\n\n    if (propName) {\n      props[propName] = dataset[d]\n    }\n  }\n\n  return props\n}\n\nexport const isValidPropsScript = (element: Element) => {\n  return (\n    // element.tagName.toLowerCase() === 'script' &&\n    ['text/props', 'application/json'].includes(\n      element.getAttribute('type') || '',\n    )\n  )\n}\n\nexport const getInteriorPropsScriptsForElement = (element: HostElement) => {\n  // getElementsByTagName does not exist on shadow roots and within a shadow root\n  // the caller can't place in props scripts\n  if (isShadowRoot(element)) return []\n\n  return Array.from(element.getElementsByTagName('script')).filter(\n    isValidPropsScript,\n  )\n}\n\nexport const getPropsScriptsBySelector = (selector: string) => {\n  return Array.from(document.querySelectorAll(selector)).filter(\n    isValidPropsScript,\n    // Checked by filter call\n  ) as HTMLOrSVGScriptElement[]\n}\n\nexport const getPropsFromScripts = (scripts: HTMLOrSVGScriptElement[]) => {\n  let interiorScriptProps: any = {}\n  scripts.forEach((script) => {\n    // Swallow any potential errors so we don't throw on someone else's page\n    try {\n      interiorScriptProps = {\n        ...interiorScriptProps,\n        ...JSON.parse(script.innerHTML),\n      }\n    } catch (e: any) {}\n  })\n  return interiorScriptProps\n}\n\n/**\n * Get the props from a host element's data attributes\n * @param  {Element} The host element\n * @return {Object}  props object to be passed to the component\n */\nexport const generateHostElementProps = <P extends InitialProps>(\n  island: Island<P>,\n  element: HostElement,\n  initialProps = {},\n  propsSelector: string | undefined | null,\n): P => {\n  const elementProps = getPropsFromElement(element)\n\n  const currentScriptProps = island._executedScript\n    ? getPropsFromElement(island._executedScript)\n    : {}\n  const interiorScriptProps = getPropsFromScripts(\n    getInteriorPropsScriptsForElement(element),\n  )\n\n  const propsSelectorProps = propsSelector\n    ? getPropsFromScripts(getPropsScriptsBySelector(propsSelector))\n    : {}\n\n  return {\n    ...initialProps,\n    ...elementProps,\n    ...currentScriptProps,\n    ...propsSelectorProps,\n    ...interiorScriptProps,\n  }\n}\n\nexport const getHostElements = ({\n  selector,\n  inline,\n  elementName,\n}: {\n  selector?: string\n  inline: boolean\n  /**\n   * Passed if targeting web components so that mount in can create web components inside of the host elements\n   */\n  elementName?: string\n}): HostElement[] => {\n  const currentScript = document.currentScript\n\n  if (inline && currentScript?.parentNode) {\n    // @ts-ignore Not sure on this one\n    return [currentScript.parentNode]\n  }\n\n  // Next, try to get the selector from the current script\n  const maybeSelector = currentScript?.dataset.mountIn\n\n  if (maybeSelector) {\n    return Array.from(\n      document.querySelectorAll<HTMLElement>(maybeSelector),\n    ).map((n) => {\n      if (elementName != null) {\n        const targetElement = document.createElement(elementName)\n        const node = n.appendChild(targetElement)\n        return node.shadowRoot != null ? node.shadowRoot : node\n      }\n\n      return n\n    })\n  }\n\n  if (selector) {\n    return Array.from(document.querySelectorAll<HTMLElement>(selector)).map(\n      (n) => (n.shadowRoot != null ? n.shadowRoot : n),\n    )\n  }\n\n  return []\n}\n\n/**\n * A Preact 11+ implementation of the `replaceNode` parameter from Preact 10.\n *\n * This creates a \"Persistent Fragment\" (a fake DOM element) containing one or more\n * DOM nodes, which can then be passed as the `parent` argument to Preact's `render()` method.\n *\n * Lifted from: https://gist.github.com/developit/f4c67a2ede71dc2fab7f357f39cff28c\n */\nexport type RootFragment = any\n\nexport function createRootFragment(\n  parent: HostElement,\n  replaceNode: HostElement | HostElement[],\n): RootFragment {\n  replaceNode = ([] as HostElement[]).concat(replaceNode)\n  var s = replaceNode[replaceNode.length - 1].nextSibling\n  function insert(c: HTMLElement, r: HTMLElement) {\n    parent.insertBefore(c, r || s)\n  }\n  // Mutating the parent to add a preact property\n  // @ts-expect-error We're mutating the parent to add these properties for Preact\n  return (parent.__k = {\n    nodeType: 1,\n    parentNode: parent,\n    firstChild: replaceNode[0],\n    childNodes: replaceNode,\n    insertBefore: insert,\n    appendChild: insert,\n    removeChild: function (c: HTMLElement) {\n      parent.removeChild(c)\n    },\n  })\n}\n\nexport const watchForPropChanges = <P extends InitialProps>({\n  island,\n  hostElement,\n  initialProps,\n  onNewProps,\n  propsSelector,\n}: {\n  island: Island<P>\n  hostElement: HostElement\n  initialProps: any\n  onNewProps: (props: P) => void\n  propsSelector: string | undefined | null\n}) => {\n  const observer = new MutationObserver(function (mutations) {\n    mutations.forEach(function () {\n      onNewProps(\n        generateHostElementProps(\n          island,\n          hostElement,\n          initialProps,\n          propsSelector,\n        ),\n      )\n    })\n  })\n\n  const config = { attributes: true, childList: true, characterData: true }\n\n  if (island._executedScript) {\n    observer.observe(island._executedScript, config)\n  }\n\n  getInteriorPropsScriptsForElement(hostElement).forEach((script) => {\n    observer.observe(script, { ...config, subtree: true })\n  })\n\n  if (propsSelector) {\n    getPropsScriptsBySelector(propsSelector).forEach((script) => {\n      observer.observe(script, { ...config, subtree: true })\n    })\n  }\n\n  /**\n   * If the host element is a shadow root we want to observe on the host of it.\n   *\n   * Example:\n   * <preact-element data-prop-foo=\"bar\">\n   *    #shadow-root (open)\n   * </preact-element>\n   *\n   * We want to observe the custom autonomous element, not the shadow root!\n   */\n  observer.observe(\n    isShadowRoot(hostElement) ? hostElement.host! : hostElement,\n    config,\n  )\n\n  return observer\n}\n\nexport const renderIsland = <P extends InitialProps>({\n  island,\n  widget,\n  rootFragment,\n  props,\n}: {\n  island: Island<P>\n  widget: ComponentType<P>\n  rootFragment: RootFragment\n  props: P\n}) => {\n  island.props = props\n  render(h(widget, props), rootFragment)\n}\n\nexport const mount = <P extends InitialProps>({\n  island,\n  widget,\n  hostElements,\n  clean,\n  replace,\n  initialProps,\n  propsSelector,\n}: {\n  island: Island<P>\n  widget: ComponentType<P>\n  hostElements: Array<HostElement>\n  clean: boolean\n  replace: boolean\n  initialProps: P\n  propsSelector?: string\n}) => {\n  const rootFragments: any = []\n\n  hostElements.forEach((hostElement) => {\n    const props = generateHostElementProps<P>(\n      island,\n      hostElement,\n      initialProps,\n      propsSelector,\n    )\n    if (clean) {\n      hostElement.replaceChildren()\n    }\n\n    let rootFragment: any\n    if (replace) {\n      rootFragment = createRootFragment(\n        hostElement.parentElement || document.body,\n        hostElement,\n      )\n    } else {\n      const renderNode = document.createElement('div')\n      hostElement.appendChild(renderNode)\n      rootFragment = createRootFragment(hostElement, renderNode)\n    }\n\n    rootFragments.push(rootFragment)\n\n    renderIsland({ island, widget, rootFragment, props })\n\n    const observer = watchForPropChanges<P>({\n      island,\n      hostElement,\n      initialProps,\n      onNewProps: (newProps) => {\n        renderIsland({ island, widget, rootFragment, props: newProps })\n      },\n      propsSelector,\n    })\n\n    island._rootsToObservers.set(rootFragment, observer)\n  })\n\n  return { rootFragments }\n}\n"
  },
  {
    "path": "src/tests/helpers/getById.ts",
    "content": "export const getById = (x: string) => {\n  const element = document.getElementById(x)\n  if (element == null) {\n    throw new Error(`Could not find element with id: ${x}!`)\n  }\n\n  return element\n}\n"
  },
  {
    "path": "src/tests/helpers/inlineScript.tsx",
    "content": "import { createIsland } from '../../island'\nimport {\n  mount,\n  getHostElements,\n  formatProp,\n  getInteriorPropsScriptsForElement,\n  getPropsFromScripts,\n  generateHostElementProps,\n  getPropsFromElement,\n  createRootFragment,\n  watchForPropChanges,\n  isValidPropsScript,\n  renderIsland,\n  isInShadow,\n  isShadowRoot,\n} from '../../lib'\nimport { h, FunctionComponent } from 'preact'\n\n/**\n * Use this helper when you want to test what it's like to use an inline script to use preact-island. This imports and stubs everything the Babel transforms under\n * the hood for Jest to run the things. I'm not sure a better way to test this unless it's importing the dist files but then that requires a build step every time\n * we run tests.\n */\nexport const InlineScript: FunctionComponent<{\n  widget: any\n  renderCode: string\n  id?: string\n}> = ({ widget, renderCode, ...rest }) => {\n  return (\n    <script\n      {...rest}\n      dangerouslySetInnerHTML={{\n        __html: `\n(function() {\nconst _preact = preact\nconst _objectSpread = Object.assign\nconst _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"]) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); } }; })();\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\n\nconst mount = ${mount};\nconst getHostElements = ${getHostElements};\nconst formatProp = ${formatProp};\nconst getInteriorPropsScriptsForElement = ${getInteriorPropsScriptsForElement};\nconst getPropsFromScripts = ${getPropsFromScripts};\nconst generateHostElementProps = ${generateHostElementProps};\nconst getPropsFromElement = ${getPropsFromElement};\nconst createRootFragment = ${createRootFragment};\nconst watchForPropChanges = ${watchForPropChanges};\nconst isValidPropsScript = ${isValidPropsScript};\nconst renderIsland = ${renderIsland};\nconst isInShadow = ${isInShadow};\nconst isShadowRoot = ${isShadowRoot};\n\nconst _lib = {\n  mount: ${mount},\n  getHostElements: ${getHostElements},\n  formatProp: ${formatProp},\n  getInteriorPropsScriptsForElement: ${getInteriorPropsScriptsForElement},\n  getPropsFromScripts: ${getPropsFromScripts},\n  generateHostElementProps: ${generateHostElementProps},\n  getPropsFromElement: ${getPropsFromElement},\n  createRootFragment: ${createRootFragment},\n  watchForPropChanges: ${watchForPropChanges},\n  isValidPropsScript: ${isValidPropsScript},\n  renderIsland: ${renderIsland}\n}\n\nconst createIsland = ${createIsland}\nconst island = createIsland(${widget})\n${renderCode}\n})()\n`,\n      }}\n    ></script>\n  )\n}\n"
  },
  {
    "path": "src/tests/island.props.test.tsx",
    "content": "import { h } from 'preact'\nimport { createIsland } from '../island'\nimport { useState } from 'preact/hooks'\nimport { render, waitFor } from '@testing-library/preact'\nimport userEvent from '@testing-library/user-event'\nimport { InlineScript } from './helpers/inlineScript'\nimport { getById } from './helpers/getById'\n\nconst Widget = (props: any) => {\n  const [toggle, setToggle] = useState(false)\n\n  return (\n    <div data-testid=\"widget\">\n      <button\n        data-testid=\"toggleButton\"\n        onClick={() => {\n          setToggle((x) => !x)\n        }}\n      >\n        toggle\n      </button>\n      {toggle ? <span data-testid=\"toggled\">toggled</span> : null}\n      <span data-testid=\"widgetProps\">{JSON.stringify(props)}</span>\n    </div>\n  )\n}\n\nit('should render at the given selector and trigger a rerender (not remount) when new props are passed to the host', async () => {\n  const user = userEvent.setup()\n  const r = render(\n    <div\n      data-island=\"island\"\n      data-testid=\"island-host\"\n      data-prop-test=\"bananas\"\n    ></div>,\n  )\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n  })\n\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"bananas\"}',\n    ),\n  )\n\n  /**\n   * We set some local state to the rendered widget to make sure when we update the props that the localized state\n   * continues to exist!\n   */\n  const buttonToggleNode = r.getByTestId('toggleButton')\n  user.click(buttonToggleNode)\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n\n  const islandHost = r.getByTestId('island-host')\n  islandHost.dataset.propTest = 'apples'\n\n  // By asserting that toggled is still in the document it shows we didn't accidentally remount\n  // the component on prop changes\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"apples\"}',\n    ),\n  )\n})\n\nit('should render at the given selector and trigger a rerender (not remount) when rerender is called with new props', async () => {\n  const user = userEvent.setup()\n  const r = render(\n    <div\n      data-island=\"island\"\n      data-testid=\"island-host\"\n      data-prop-test=\"bananas\"\n    ></div>,\n  )\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n  })\n\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"bananas\"}',\n    ),\n  )\n\n  /**\n   * We set some local state to the rendered widget to make sure when we update the props that the localized state\n   * continues to exist!\n   */\n  const buttonToggleNode = r.getByTestId('toggleButton')\n  user.click(buttonToggleNode)\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n\n  island.rerender({ test: 'apples' })\n\n  // By asserting that toggled is still in the document it shows we didn't accidentally remount\n  // the component on prop changes\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"apples\"}',\n    ),\n  )\n})\n\nit('should render at the given selector and trigger a rerender (not remount) when new props are passed to the child script props tag', async () => {\n  const user = userEvent.setup()\n  const r = render(\n    <div data-island=\"island\" data-testid=\"island-host\">\n      <script type=\"application/json\" data-testid=\"script-props\">\n        {'{\"test\": \"bananas\"}'}\n      </script>\n    </div>,\n  )\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n  })\n\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"bananas\"}',\n    ),\n  )\n\n  /**\n   * We set some local state to the rendered widget to make sure when we update the props that the localized state\n   * continues to exist!\n   */\n  const buttonToggleNode = r.getByTestId('toggleButton')\n  user.click(buttonToggleNode)\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n\n  const scriptProps = r.getByTestId('script-props')\n  scriptProps.innerHTML = '{\"test\": \"apples\"}'\n\n  // By asserting that toggled is still in the document it shows we didn't accidentally remount\n  // the component on prop changes\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"apples\"}',\n    ),\n  )\n})\n\nit('should render at the given selector and trigger a rerender (not remount) when new props are passed to the targeted props script', async () => {\n  const user = userEvent.setup()\n  const r = render(\n    <div>\n      <div data-island=\"island\" data-testid=\"island-host\"></div>\n      <script\n        type=\"application/json\"\n        data-island-props=\"test-island\"\n        id=\"inline-script-test\"\n      >\n        {'{\"test\": \"bananas\"}'}\n      </script>\n    </div>,\n  )\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n    propsSelector: '[data-island-props=\"test-island\"]',\n  })\n\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"bananas\"}',\n    ),\n  )\n\n  /**\n   * We set some local state to the rendered widget to make sure when we update the props that the localized state\n   * continues to exist!\n   */\n  const buttonToggleNode = r.getByTestId('toggleButton')\n  user.click(buttonToggleNode)\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n\n  const scriptProps = getById('inline-script-test')\n  scriptProps.innerHTML = '{\"test\": \"apples\"}'\n\n  // By asserting that toggled is still in the document it shows we didn't accidentally remount\n  // the component on prop changes\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"apples\"}',\n    ),\n  )\n})\n\nit('should render at the given selector and trigger a rerender (not remount) when new props are passed to the injected script', async () => {\n  const user = userEvent.setup()\n  const r = render(\n    <div>\n      <div data-island=\"island\" data-testid=\"island-host\"></div>\n      <InlineScript\n        widget={Widget}\n        data-prop-test=\"bananas\"\n        renderCode={`\nisland.render({\n  selector: '[data-island=\"island\"]',\n  })\n        `}\n        id=\"inline-script\"\n      />\n    </div>,\n  )\n\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"bananas\"}',\n    ),\n  )\n\n  /**\n   * We set some local state to the rendered widget to make sure when we update the props that the localized state\n   * continues to exist!\n   */\n  const buttonToggleNode = r.getByTestId('toggleButton')\n  user.click(buttonToggleNode)\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n\n  const scriptProps = getById('inline-script')\n  scriptProps.dataset.test = 'apples'\n\n  // By asserting that toggled is still in the document it shows we didn't accidentally remount\n  // the component on prop changes\n  await waitFor(() => expect(r.getByTestId('toggled')).toBeInTheDocument())\n  await waitFor(() =>\n    expect(r.getByTestId('widgetProps').textContent).toEqual(\n      '{\"island\":\"island\",\"testid\":\"island-host\",\"test\":\"apples\"}',\n    ),\n  )\n})\n"
  },
  {
    "path": "src/tests/island.selector.test.tsx",
    "content": "import { h } from 'preact'\nimport { createIsland } from '../island'\nimport { render, waitFor, within } from '@testing-library/preact'\nimport { InlineScript } from './helpers/inlineScript'\n\nconst Widget = (props: any) => {\n  return <div data-testid=\"widget\">{JSON.stringify(props)}</div>\n}\n\nit('should render at the given selector', async () => {\n  const r = render(<div data-island=\"island\"></div>)\n\n  await waitFor(() => expect(r.queryByTestId('widget')).not.toBeInTheDocument())\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n  })\n\n  await waitFor(() =>\n    expect(r.container).toMatchInlineSnapshot(`\n      <div>\n        <div\n          data-island=\"island\"\n        >\n          <div\n            data-testid=\"widget\"\n          >\n            {\"island\":\"island\"}\n          </div>\n        </div>\n      </div>\n    `),\n  )\n})\n\nit('should render inline if prop is passed and take highest priority', async () => {\n  const r = render(\n    <div data-testid=\"parent-node\">\n      <InlineScript\n        widget={Widget}\n        renderCode={`\nisland.render({\n  inline: true\n})\n  `}\n      />\n    </div>,\n  )\n\n  await waitFor(() =>\n    expect(r.getByTestId('parent-node').lastChild).toMatchInlineSnapshot(`\n      <div\n        data-testid=\"widget\"\n      >\n        {\"testid\":\"parent-node\"}\n      </div>\n    `),\n  )\n})\n\nit('should render using the data-mount-in prop and take priority over a selector if passed', async () => {\n  const r = render(\n    <div data-testid=\"parent-node\">\n      <div data-testid=\"selector\" data-island=\"selector\"></div>\n      <div\n        data-testid=\"inlineScriptMountIn\"\n        data-island=\"inlineScriptMountIn\"\n      ></div>\n      <InlineScript\n        widget={Widget}\n        data-mount-in={`[data-island=\"inlineScriptMountIn\"]`}\n        renderCode={`\nisland.render({\n  selector: '[data-island=\"island\"]'\n})\n  `}\n      />\n    </div>,\n  )\n\n  await waitFor(() =>\n    expect(\n      within(r.getByTestId('selector')).queryByTestId('widget'),\n    ).not.toBeInTheDocument(),\n  )\n\n  await waitFor(() =>\n    expect(\n      within(r.getByTestId('inlineScriptMountIn')).queryByTestId('widget'),\n    ).toBeInTheDocument(),\n  )\n})\n\nit('should pass down default props', async () => {\n  const r = render(<div data-island=\"island\"></div>)\n  const initialProps = {\n    apples: 'yes',\n    bananas: 1,\n    kiwis: true,\n  }\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n    initialProps,\n  })\n\n  await waitFor(() =>\n    expect(r.getByTestId('widget').innerHTML).toEqual(\n      JSON.stringify({ ...initialProps, island: 'island' }),\n    ),\n  )\n})\n\nit('should render twice if multiple nodes are found from the selector', async () => {\n  const r = render(\n    <div>\n      <div data-island=\"island\"></div>\n      <div data-island=\"island\"></div>\n    </div>,\n  )\n  const initialProps = {\n    apples: 'yes',\n    bananas: 1,\n    kiwis: true,\n  }\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n    initialProps,\n  })\n\n  // NOTE: Notice there is a different between this one and the other test.\n  // This one render inside of two data-island elements whereas the other\n  // renders twice inside of the same data widget host element!\n  await waitFor(() =>\n    expect(r.container).toMatchInlineSnapshot(`\n      <div>\n        <div>\n          <div\n            data-island=\"island\"\n          >\n            <div\n              data-testid=\"widget\"\n            >\n              {\"apples\":\"yes\",\"bananas\":1,\"kiwis\":true,\"island\":\"island\"}\n            </div>\n          </div>\n          <div\n            data-island=\"island\"\n          >\n            <div\n              data-testid=\"widget\"\n            >\n              {\"apples\":\"yes\",\"bananas\":1,\"kiwis\":true,\"island\":\"island\"}\n            </div>\n          </div>\n        </div>\n      </div>\n    `),\n  )\n})\n\nit('should render multiple times if render is called twice', async () => {\n  const r = render(<div data-island=\"island\"></div>)\n  const initialProps = {\n    apples: 'yes',\n    bananas: 1,\n    kiwis: true,\n  }\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n    initialProps,\n  })\n  island.render({\n    selector: '[data-island=\"island\"]',\n    initialProps,\n  })\n\n  await waitFor(() =>\n    expect(r.container).toMatchInlineSnapshot(`\n      <div>\n        <div\n          data-island=\"island\"\n        >\n          <div\n            data-testid=\"widget\"\n          >\n            {\"apples\":\"yes\",\"bananas\":1,\"kiwis\":true,\"island\":\"island\"}\n          </div>\n          <div\n            data-testid=\"widget\"\n          >\n            {\"apples\":\"yes\",\"bananas\":1,\"kiwis\":true,\"island\":\"island\"}\n          </div>\n        </div>\n      </div>\n    `),\n  )\n})\n\nit('should replace the node at given selector if prop is given', async () => {\n  const r = render(<div data-island=\"island\"></div>)\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n    replace: true,\n  })\n\n  await waitFor(() =>\n    expect(r.container).toMatchInlineSnapshot(`\n      <div>\n        <div\n          data-testid=\"widget\"\n        >\n          {\"island\":\"island\"}\n        </div>\n      </div>\n    `),\n  )\n})\n\nit('should destroy mounted islands when destroy called', async () => {\n  const r = render(<div data-island=\"island\"></div>)\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n  })\n\n  await waitFor(() =>\n    expect(r.container).toMatchInlineSnapshot(`\n      <div>\n        <div\n          data-island=\"island\"\n        >\n          <div\n            data-testid=\"widget\"\n          >\n            {\"island\":\"island\"}\n          </div>\n        </div>\n      </div>\n    `),\n  )\n\n  island.destroy()\n\n  await waitFor(() =>\n    expect(r.container).toMatchInlineSnapshot(`\n      <div>\n        <div\n          data-island=\"island\"\n        />\n      </div>\n    `),\n  )\n})\n\nit('should destroy mounted islands when destroy called with replace: true', async () => {\n  const r = render(<div data-island=\"island\"></div>)\n\n  const island = createIsland(Widget)\n  island.render({\n    selector: '[data-island=\"island\"]',\n    replace: true,\n  })\n\n  await waitFor(() =>\n    expect(r.container).toMatchInlineSnapshot(`\n      <div>\n        <div\n          data-testid=\"widget\"\n        >\n          {\"island\":\"island\"}\n        </div>\n      </div>\n    `),\n  )\n\n  island.destroy()\n\n  await waitFor(() => expect(r.container).toMatchInlineSnapshot(`<div />`))\n})\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2017\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ES2015\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"declaration\": true,\n    \"preserveWatchOutput\": true,\n    \"jsx\": \"react\",\n    \"jsxFactory\": \"h\",\n    \"jsxFragmentFactory\": \"\"\n  },\n  \"include\": [\"src\"],\n  \"exclude\": [\"**/tests/**\"]\n}\n"
  }
]