From 09946ba82875e29090560faad7e68de9698a1e2d Mon Sep 17 00:00:00 2001 From: Nie Ridwan Susanto Date: Fri, 10 May 2024 13:20:10 +0700 Subject: [PATCH] fix: https://github.com/withastro/astro/issues/10512 --- LICENSE | 59 +++++++++++++++++++++++ README.md | 38 +++++++++++++++ client-v5.js | 50 ++++++++++++++++++++ client.js | 118 ++++++++++++++++++++++++++++++++++++++++++++++ dist/editor.cjs | 46 ++++++++++++++++++ dist/editor.d.cts | 1 + dist/index.d.ts | 6 +++ dist/index.js | 89 ++++++++++++++++++++++++++++++++++ package.json | 65 +++++++++++++++++++++++++ server-v5.js | 46 ++++++++++++++++++ server.js | 25 ++++++++++ 11 files changed, 543 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 client-v5.js create mode 100644 client.js create mode 100644 dist/editor.cjs create mode 100644 dist/editor.d.cts create mode 100644 dist/index.d.ts create mode 100644 dist/index.js create mode 100644 package.json create mode 100644 server-v5.js create mode 100644 server.js diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b3cd0c0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,59 @@ +MIT License + +Copyright (c) 2021 Fred K. Schott + +Permission 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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE 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. + +""" +This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository: + +Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors) + +Permission 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: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE 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. +""" + +""" +This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository: + +MIT License + +Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors + +Permission 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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE 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. +""" diff --git a/README.md b/README.md new file mode 100644 index 0000000..1f9bde8 --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# @astrojs/svelte đŸ§¡ + +This **[Astro integration][astro-integration]** enables server-side rendering and client-side hydration for your [Svelte](https://svelte.dev/) components. It supports Svelte 3, 4, and 5 (experimental). + +## Documentation + +Read the [`@astrojs/svelte` docs][docs] + +## Support + +- Get help in the [Astro Discord][discord]. Post questions in our `#support` forum, or visit our dedicated `#dev` channel to discuss current development and more! + +- Check our [Astro Integration Documentation][astro-integration] for more on integrations. + +- Submit bug reports and feature requests as [GitHub issues][issues]. + +## Contributing + +This package is maintained by Astro's Core team. You're welcome to submit an issue or PR! These links will help you get started: + +- [Contributor Manual][contributing] +- [Code of Conduct][coc] +- [Community Guide][community] + +## License + +MIT + +Copyright (c) 2023–present [Astro][astro] + +[astro]: https://astro.build/ +[docs]: https://docs.astro.build/en/guides/integrations-guide/svelte/ +[contributing]: https://github.com/withastro/astro/blob/main/CONTRIBUTING.md +[coc]: https://github.com/withastro/.github/blob/main/CODE_OF_CONDUCT.md +[community]: https://github.com/withastro/.github/blob/main/COMMUNITY_GUIDE.md +[discord]: https://astro.build/chat/ +[issues]: https://github.com/withastro/astro/issues +[astro-integration]: https://docs.astro.build/en/guides/integrations-guide/ diff --git a/client-v5.js b/client-v5.js new file mode 100644 index 0000000..755a6aa --- /dev/null +++ b/client-v5.js @@ -0,0 +1,50 @@ +import { hydrate, mount, unmount } from 'svelte'; +import { add_snippet_symbol } from 'svelte/internal/client'; + +// Allow a slot to be rendered as a snippet (dev validation only) +const tagSlotAsSnippet = import.meta.env.DEV ? add_snippet_symbol : (s) => s; + +export default (element) => { + return async (Component, props, slotted, { client }) => { + if (!element.hasAttribute('ssr')) return; + + let children = undefined; + let $$slots = undefined; + for (const [key, value] of Object.entries(slotted)) { + if (key === 'default') { + children = createSlotDefinition(key, value); + } else { + $$slots ??= {}; + $$slots[key] = createSlotDefinition(key, value); + } + } + + const bootstrap = client !== 'only' ? hydrate : mount; + + const component = bootstrap(Component, { + target: element, + props: { + ...props, + children, + $$slots, + }, + }); + + element.addEventListener('astro:unmount', () => unmount(component), { once: true }); + }; +}; + +function createSlotDefinition(key, children) { + /** + * @param {Comment} $$anchor A comment node for slots in Svelte 5 + */ + const fn = ($$anchor, _$$slotProps) => { + const parent = $$anchor.parentNode; + const el = document.createElement('div'); + el.innerHTML = `${children}`; + parent.insertBefore(el.children[0], $$anchor); + }; + return tagSlotAsSnippet(fn); +} diff --git a/client.js b/client.js new file mode 100644 index 0000000..c9552c8 --- /dev/null +++ b/client.js @@ -0,0 +1,118 @@ +const noop = () => {}; + +let originalConsoleWarning; +let consoleFilterRefs = 0; + +export default (element) => { + return (Component, props, slotted, { client }) => { + if (!element.hasAttribute('ssr')) return; + const slots = {}; + for (const [key, value] of Object.entries(slotted)) { + slots[key] = createSlotDefinition(key, value); + } + + try { + if (import.meta.env.DEV) useConsoleFilter(); + + const component = new Component({ + target: element, + props: { + ...props, + $$slots: slots, + $$scope: { ctx: [] }, + }, + hydrate: client !== 'only', + $$inline: true, + }); + + element.addEventListener('astro:unmount', () => component.$destroy(), { once: true }); + } finally { + if (import.meta.env.DEV) finishUsingConsoleFilter(); + } + }; +}; + +function createSlotDefinition(key, children) { + let parent; + return [ + () => ({ + // mount + m(target) { + parent = target; + target.insertAdjacentHTML( + 'beforeend', + `${children}` + ); + }, + // create + c: noop, + // hydrate + l: noop, + // destroy + d() { + if (!parent) return; + const slot = parent.querySelector( + `astro-slot${key === 'default' ? ':not([name])' : `[name="${key}"]`}` + ); + if (slot) slot.remove(); + }, + }), + noop, + noop, + ]; +} + +/** + * Reduces console noise by filtering known non-problematic warnings. + * + * Performs reference counting to allow parallel usage from async code. + * + * To stop filtering, please ensure that there always is a matching call + * to `finishUsingConsoleFilter` afterwards. + */ +function useConsoleFilter() { + consoleFilterRefs++; + + if (!originalConsoleWarning) { + originalConsoleWarning = console.warn; + try { + console.warn = filteredConsoleWarning; + } catch (error) { + // If we're unable to hook `console.warn`, just accept it + } + } +} + +/** + * Indicates that the filter installed by `useConsoleFilter` + * is no longer needed by the calling code. + */ +function finishUsingConsoleFilter() { + consoleFilterRefs--; + + // Note: Instead of reverting `console.warning` back to the original + // when the reference counter reaches 0, we leave our hook installed + // to prevent potential race conditions once `check` is made async +} + +/** + * Hook/wrapper function for the global `console.warning` function. + * + * Ignores known non-problematic errors while any code is using the console filter. + * Otherwise, simply forwards all arguments to the original function. + */ +function filteredConsoleWarning(msg, ...rest) { + if (consoleFilterRefs > 0 && typeof msg === 'string') { + // Astro passes `class` and `data-astro-cid` props to the Svelte component, which + // outputs the following warning, which we can safely filter out. + + // NOTE: In practice data-astro-cid props have a hash suffix. Hence the use of a + // quoted prop name string without a closing quote. + + const isKnownSvelteError = + msg.endsWith("was created with unknown prop 'class'") || + msg.includes("was created with unknown prop 'data-astro-cid"); + if (isKnownSvelteError) return; + } + originalConsoleWarning(msg, ...rest); +} diff --git a/dist/editor.cjs b/dist/editor.cjs new file mode 100644 index 0000000..109e819 --- /dev/null +++ b/dist/editor.cjs @@ -0,0 +1,46 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var editor_exports = {}; +__export(editor_exports, { + toTSX: () => toTSX +}); +module.exports = __toCommonJS(editor_exports); +var import_svelte2tsx = require("svelte2tsx"); +function toTSX(code, className) { + let result = ` + let ${className}__AstroComponent_: Error + export default ${className}__AstroComponent_ + `; + try { + let tsx = (0, import_svelte2tsx.svelte2tsx)(code, { mode: "ts" }).code; + tsx = '/// \n' + tsx; + result = tsx.replace( + "export default class extends __sveltets_2_createSvelte2TsxComponent(", + `export default function ${className}__AstroComponent_(_props: typeof Component.props): any {} +let Component = ` + ); + } catch (e) { + return result; + } + return result; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + toTSX +}); diff --git a/dist/editor.d.cts b/dist/editor.d.cts new file mode 100644 index 0000000..6313cff --- /dev/null +++ b/dist/editor.d.cts @@ -0,0 +1 @@ +export declare function toTSX(code: string, className: string): string; diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..e76dedc --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,6 @@ +import type { Options } from '@sveltejs/vite-plugin-svelte'; +import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; +import type { AstroIntegration } from 'astro'; +type OptionsCallback = (defaultOptions: Options) => Options; +export default function (options?: Options | OptionsCallback): AstroIntegration; +export { vitePreprocess }; diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..04b03df --- /dev/null +++ b/dist/index.js @@ -0,0 +1,89 @@ +import { fileURLToPath } from "node:url"; +import { svelte, vitePreprocess } from "@sveltejs/vite-plugin-svelte"; +import { VERSION } from "svelte/compiler"; +const isSvelte5 = Number.parseInt(VERSION.split(".").at(0)) >= 5; +function getRenderer() { + return { + name: "@astrojs/svelte", + clientEntrypoint: isSvelte5 ? "@astrojs/svelte/client-v5.js" : "@astrojs/svelte/client.js", + serverEntrypoint: isSvelte5 ? "@astrojs/svelte/server-v5.js" : "@astrojs/svelte/server.js" + }; +} +async function svelteConfigHasPreprocess(root) { + const svelteConfigFiles = ["./svelte.config.js", "./svelte.config.cjs", "./svelte.config.mjs"]; + for (const file of svelteConfigFiles) { + const filePath = fileURLToPath(new URL(file, root)); + try { + const config = (await import( + /* @vite-ignore */ + filePath + )).default; + return !!config.preprocess; + } catch { + } + } +} +async function getViteConfiguration({ + options, + isDev, + root +}) { + const defaultOptions = { + emitCss: true, + compilerOptions: { dev: isDev } + }; + if (!isSvelte5) { + defaultOptions.compilerOptions.hydratable = true; + } + if (!isDev) { + defaultOptions.hot = false; + } + let resolvedOptions; + if (!options) { + resolvedOptions = defaultOptions; + } else if (typeof options === "function") { + resolvedOptions = options(defaultOptions); + } else { + resolvedOptions = { + ...options, + ...defaultOptions, + compilerOptions: { + ...options.compilerOptions, + // Always use dev and hydratable from defaults + ...defaultOptions.compilerOptions + } + }; + } + if (!resolvedOptions.preprocess && !await svelteConfigHasPreprocess(root)) { + resolvedOptions.preprocess = vitePreprocess(); + } + return { + optimizeDeps: { + include: [isSvelte5 ? "@astrojs/svelte/client-v5.js" : "@astrojs/svelte/client.js"], + exclude: [isSvelte5 ? "@astrojs/svelte/server-v5.js" : "@astrojs/svelte/server.js"] + }, + plugins: [svelte(resolvedOptions)] + }; +} +function src_default(options) { + return { + name: "@astrojs/svelte", + hooks: { + // Anything that gets returned here is merged into Astro Config + "astro:config:setup": async ({ command, updateConfig, addRenderer, config }) => { + addRenderer(getRenderer()); + updateConfig({ + vite: await getViteConfiguration({ + options, + isDev: command === "dev", + root: config.root + }) + }); + } + } + }; +} +export { + src_default as default, + vitePreprocess +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..0888c80 --- /dev/null +++ b/package.json @@ -0,0 +1,65 @@ +{ + "name": "@astrojs/svelte", + "version": "5.4.0", + "description": "Use Svelte components within Astro", + "type": "module", + "types": "./dist/index.d.ts", + "author": "withastro", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/withastro/astro.git", + "directory": "packages/integrations/svelte" + }, + "keywords": [ + "astro-integration", + "astro-component", + "renderer", + "svelte" + ], + "bugs": "https://github.com/withastro/astro/issues", + "homepage": "https://docs.astro.build/en/guides/integrations-guide/svelte/", + "exports": { + ".": "./dist/index.js", + "./editor": "./dist/editor.cjs", + "./*": "./*", + "./client.js": "./client.js", + "./client-v5.js": "./client-v5.js", + "./server.js": "./server.js", + "./server-v5.js": "./server-v5.js", + "./package.json": "./package.json" + }, + "files": [ + "dist", + "client.js", + "client-v5.js", + "server.js", + "server-v5.js" + ], + "dependencies": { + "@sveltejs/vite-plugin-svelte": "^3.0.0", + "svelte2tsx": "^0.6.27" + }, + "devDependencies": { + "svelte": "^4.2.5", + "vite": "^5.1.4", + "astro": "4.6.0", + "astro-scripts": "0.0.14" + }, + "peerDependencies": { + "astro": "^4.0.0", + "svelte": "^4.0.0 || ^5.0.0-next.90", + "typescript": "^5.3.3" + }, + "engines": { + "node": "^18.17.1 || ^20.3.0 || >=21.0.0" + }, + "publishConfig": { + "provenance": true + }, + "scripts": { + "build": "astro-scripts build \"src/index.ts\" && astro-scripts build \"src/editor.cts\" --force-cjs --no-clean-dist && tsc", + "build:ci": "astro-scripts build \"src/**/*.ts\" && astro-scripts build \"src/editor.cts\" --force-cjs --no-clean-dist", + "dev": "astro-scripts dev \"src/**/*.ts\"" + } +} \ No newline at end of file diff --git a/server-v5.js b/server-v5.js new file mode 100644 index 0000000..82c9cf0 --- /dev/null +++ b/server-v5.js @@ -0,0 +1,46 @@ +import { add_snippet_symbol } from 'svelte/internal/server'; +import { render } from 'svelte/server'; + +// Allow a slot to be rendered as a snippet (dev validation only) +const tagSlotAsSnippet = import.meta.env.DEV ? add_snippet_symbol : (s) => s; + +function check(Component) { + // Svelte 5 generated components always accept these two props + const str = Component.toString(); + return str.includes('$$payload') && str.includes('$$props'); +} + +function needsHydration(metadata) { + // Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot` + return metadata.astroStaticSlot ? !!metadata.hydrate : true; +} + +async function renderToStaticMarkup(Component, props, slotted, metadata) { + const tagName = needsHydration(metadata) ? 'astro-slot' : 'astro-static-slot'; + + let children = undefined; + let $$slots = undefined; + for (const [key, value] of Object.entries(slotted)) { + if (key === 'default') { + children = tagSlotAsSnippet(($$payload) => $$payload.out += `<${tagName}>${value}`); + } else { + $$slots ??= {}; + $$slots[key] = tagSlotAsSnippet(($$payload) => $$payload.out += `<${tagName} name="${key}">${value}`); + } + } + + const { html } = render(Component, { + props: { + ...props, + children, + $$slots, + }, + }); + return { html }; +} + +export default { + check, + renderToStaticMarkup, + supportsAstroStaticSlot: true, +}; diff --git a/server.js b/server.js new file mode 100644 index 0000000..9878d3b --- /dev/null +++ b/server.js @@ -0,0 +1,25 @@ +function check(Component) { + return Component['render'] && Component['$$render']; +} + +function needsHydration(metadata) { + // Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot` + return metadata.astroStaticSlot ? !!metadata.hydrate : true; +} + +async function renderToStaticMarkup(Component, props, slotted, metadata) { + const tagName = needsHydration(metadata) ? 'astro-slot' : 'astro-static-slot'; + const slots = {}; + for (const [key, value] of Object.entries(slotted)) { + slots[key] = () => + `<${tagName}${key === 'default' ? '' : ` name="${key}"`}>${value}`; + } + const { html } = Component.render(props, { $$slots: slots }); + return { html }; +} + +export default { + check, + renderToStaticMarkup, + supportsAstroStaticSlot: true, +};