Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
nridwan committed May 10, 2024
0 parents commit 09946ba
Show file tree
Hide file tree
Showing 11 changed files with 543 additions and 0 deletions.
59 changes: 59 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
"""
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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/
50 changes: 50 additions & 0 deletions client-v5.js
Original file line number Diff line number Diff line change
@@ -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 = `<astro-slot${
key === 'default' ? '' : ` name="${key}"`
}>${children}</astro-slot>`;
parent.insertBefore(el.children[0], $$anchor);
};
return tagSlotAsSnippet(fn);
}
118 changes: 118 additions & 0 deletions client.js
Original file line number Diff line number Diff line change
@@ -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',
`<astro-slot${key === 'default' ? '' : ` name="${key}"`}>${children}</astro-slot>`
);
},
// 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);
}
46 changes: 46 additions & 0 deletions dist/editor.cjs
Original file line number Diff line number Diff line change
@@ -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 = '/// <reference types="svelte2tsx/svelte-shims" />\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
});
1 change: 1 addition & 0 deletions dist/editor.d.cts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function toTSX(code: string, className: string): string;
6 changes: 6 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -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 };
Loading

0 comments on commit 09946ba

Please sign in to comment.