🎉 initiate project *astro_rewrite*

This commit is contained in:
sindrekjelsrud 2023-07-19 21:31:30 +02:00
parent ffd4d5e86c
commit 2ba37bfbe3
8658 changed files with 2268794 additions and 2538 deletions

1
node_modules/astro/dist/runtime/client/hmr.d.ts generated vendored Normal file
View file

@ -0,0 +1 @@
export {};

37
node_modules/astro/dist/runtime/client/hmr.js generated vendored Normal file
View file

@ -0,0 +1,37 @@
if (import.meta.hot) {
const injectedStyles = getInjectedStyles();
const mo = new MutationObserver((records) => {
var _a;
for (const record of records) {
for (const node of record.addedNodes) {
if (isViteInjectedStyle(node)) {
(_a = injectedStyles.get(node.getAttribute("data-vite-dev-id"))) == null ? void 0 : _a.remove();
}
}
}
});
mo.observe(document.documentElement, { subtree: true, childList: true });
import.meta.hot.on("vite:beforeUpdate", async (payload) => {
for (const file of payload.updates) {
if (file.acceptedPath.includes("vue&type=style")) {
const link = document.querySelector(`link[href="${file.acceptedPath}"]`);
if (link) {
link.replaceWith(link.cloneNode(true));
}
}
}
});
}
function getInjectedStyles() {
const injectedStyles = /* @__PURE__ */ new Map();
document.querySelectorAll("style[data-astro-dev-id]").forEach((el) => {
injectedStyles.set(el.getAttribute("data-astro-dev-id"), el);
});
return injectedStyles;
}
function isStyle(node) {
return node.nodeType === node.ELEMENT_NODE && node.tagName.toLowerCase() === "style";
}
function isViteInjectedStyle(node) {
return isStyle(node) && node.getAttribute("type") === "text/css" && !!node.getAttribute("data-vite-dev-id");
}

3
node_modules/astro/dist/runtime/client/idle.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
import type { ClientDirective } from '../../@types/astro';
declare const idleDirective: ClientDirective;
export default idleDirective;

15
node_modules/astro/dist/runtime/client/idle.js generated vendored Normal file
View file

@ -0,0 +1,15 @@
const idleDirective = (load) => {
const cb = async () => {
const hydrate = await load();
await hydrate();
};
if ("requestIdleCallback" in window) {
window.requestIdleCallback(cb);
} else {
setTimeout(cb, 200);
}
};
var idle_default = idleDirective;
export {
idle_default as default
};

View file

@ -0,0 +1,7 @@
/**
* This file is prebuilt from packages/astro/src/runtime/client/idle.ts
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
declare const _default: "(()=>{var i=t=>{let e=async()=>{await(await t())()};\"requestIdleCallback\"in window?window.requestIdleCallback(e):setTimeout(e,200)};(self.Astro||(self.Astro={})).idle=i;window.dispatchEvent(new Event(\"astro:idle\"));})();";
export default _default;

View file

@ -0,0 +1,4 @@
var idle_prebuilt_default = `(()=>{var i=t=>{let e=async()=>{await(await t())()};"requestIdleCallback"in window?window.requestIdleCallback(e):setTimeout(e,200)};(self.Astro||(self.Astro={})).idle=i;window.dispatchEvent(new Event("astro:idle"));})();`;
export {
idle_prebuilt_default as default
};

3
node_modules/astro/dist/runtime/client/load.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
import type { ClientDirective } from '../../@types/astro';
declare const loadDirective: ClientDirective;
export default loadDirective;

8
node_modules/astro/dist/runtime/client/load.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
const loadDirective = async (load) => {
const hydrate = await load();
await hydrate();
};
var load_default = loadDirective;
export {
load_default as default
};

View file

@ -0,0 +1,7 @@
/**
* This file is prebuilt from packages/astro/src/runtime/client/load.ts
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
declare const _default: "(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).load=e;window.dispatchEvent(new Event(\"astro:load\"));})();";
export default _default;

View file

@ -0,0 +1,4 @@
var load_prebuilt_default = `(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).load=e;window.dispatchEvent(new Event("astro:load"));})();`;
export {
load_prebuilt_default as default
};

6
node_modules/astro/dist/runtime/client/media.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
import type { ClientDirective } from '../../@types/astro';
/**
* Hydrate this component when a matching media query is found
*/
declare const mediaDirective: ClientDirective;
export default mediaDirective;

18
node_modules/astro/dist/runtime/client/media.js generated vendored Normal file
View file

@ -0,0 +1,18 @@
const mediaDirective = (load, options) => {
const cb = async () => {
const hydrate = await load();
await hydrate();
};
if (options.value) {
const mql = matchMedia(options.value);
if (mql.matches) {
cb();
} else {
mql.addEventListener("change", cb, { once: true });
}
}
};
var media_default = mediaDirective;
export {
media_default as default
};

View file

@ -0,0 +1,7 @@
/**
* This file is prebuilt from packages/astro/src/runtime/client/media.ts
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
declare const _default: "(()=>{var s=(i,t)=>{let a=async()=>{await(await i())()};if(t.value){let e=matchMedia(t.value);e.matches?a():e.addEventListener(\"change\",a,{once:!0})}};(self.Astro||(self.Astro={})).media=s;window.dispatchEvent(new Event(\"astro:media\"));})();";
export default _default;

View file

@ -0,0 +1,4 @@
var media_prebuilt_default = `(()=>{var s=(i,t)=>{let a=async()=>{await(await i())()};if(t.value){let e=matchMedia(t.value);e.matches?a():e.addEventListener("change",a,{once:!0})}};(self.Astro||(self.Astro={})).media=s;window.dispatchEvent(new Event("astro:media"));})();`;
export {
media_prebuilt_default as default
};

6
node_modules/astro/dist/runtime/client/only.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
import type { ClientDirective } from '../../@types/astro';
/**
* Hydrate this component only on the client
*/
declare const onlyDirective: ClientDirective;
export default onlyDirective;

8
node_modules/astro/dist/runtime/client/only.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
const onlyDirective = async (load) => {
const hydrate = await load();
await hydrate();
};
var only_default = onlyDirective;
export {
only_default as default
};

View file

@ -0,0 +1,7 @@
/**
* This file is prebuilt from packages/astro/src/runtime/client/only.ts
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
declare const _default: "(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).only=e;window.dispatchEvent(new Event(\"astro:only\"));})();";
export default _default;

View file

@ -0,0 +1,4 @@
var only_prebuilt_default = `(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).only=e;window.dispatchEvent(new Event("astro:only"));})();`;
export {
only_prebuilt_default as default
};

8
node_modules/astro/dist/runtime/client/visible.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
import type { ClientDirective } from '../../@types/astro';
/**
* Hydrate this component when one of it's children becomes visible
* We target the children because `astro-island` is set to `display: contents`
* which doesn't work with IntersectionObserver
*/
declare const visibleDirective: ClientDirective;
export default visibleDirective;

22
node_modules/astro/dist/runtime/client/visible.js generated vendored Normal file
View file

@ -0,0 +1,22 @@
const visibleDirective = (load, _options, el) => {
const cb = async () => {
const hydrate = await load();
await hydrate();
};
const io = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting)
continue;
io.disconnect();
cb();
break;
}
});
for (const child of el.children) {
io.observe(child);
}
};
var visible_default = visibleDirective;
export {
visible_default as default
};

View file

@ -0,0 +1,7 @@
/**
* This file is prebuilt from packages/astro/src/runtime/client/visible.ts
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
declare const _default: "(()=>{var r=(i,c,n)=>{let s=async()=>{await(await i())()},t=new IntersectionObserver(e=>{for(let o of e)if(o.isIntersecting){t.disconnect(),s();break}});for(let e of n.children)t.observe(e)};(self.Astro||(self.Astro={})).visible=r;window.dispatchEvent(new Event(\"astro:visible\"));})();";
export default _default;

View file

@ -0,0 +1,4 @@
var visible_prebuilt_default = `(()=>{var r=(i,c,n)=>{let s=async()=>{await(await i())()},t=new IntersectionObserver(e=>{for(let o of e)if(o.isIntersecting){t.disconnect(),s();break}});for(let e of n.children)t.observe(e)};(self.Astro||(self.Astro={})).visible=r;window.dispatchEvent(new Event("astro:visible"));})();`;
export {
visible_prebuilt_default as default
};

View file

@ -0,0 +1,9 @@
import type { PropagationHint } from '../../@types/astro';
import type { AstroComponentFactory } from './render/index.js';
interface CreateComponentOptions {
factory: AstroComponentFactory;
moduleId?: string;
propagation?: PropagationHint;
}
export declare function createComponent(arg1: AstroComponentFactory | CreateComponentOptions, moduleId?: string): AstroComponentFactory;
export {};

View file

@ -0,0 +1,40 @@
import { AstroError, AstroErrorData } from "../../core/errors/index.js";
function validateArgs(args) {
if (args.length !== 3)
return false;
if (!args[0] || typeof args[0] !== "object")
return false;
return true;
}
function baseCreateComponent(cb, moduleId) {
var _a;
const name = ((_a = moduleId == null ? void 0 : moduleId.split("/").pop()) == null ? void 0 : _a.replace(".astro", "")) ?? "";
const fn = (...args) => {
if (!validateArgs(args)) {
throw new AstroError({
...AstroErrorData.InvalidComponentArgs,
message: AstroErrorData.InvalidComponentArgs.message(name)
});
}
return cb(...args);
};
Object.defineProperty(fn, "name", { value: name, writable: false });
fn.isAstroComponentFactory = true;
fn.moduleId = moduleId;
return fn;
}
function createComponentWithOptions(opts) {
const cb = baseCreateComponent(opts.factory, opts.moduleId);
cb.propagation = opts.propagation;
return cb;
}
function createComponent(arg1, moduleId) {
if (typeof arg1 === "function") {
return baseCreateComponent(arg1, moduleId);
} else {
return createComponentWithOptions(arg1);
}
}
export {
createComponent
};

View file

@ -0,0 +1,2 @@
import type { AstroGlobalPartial } from '../../@types/astro';
export declare function createAstro(site: string | undefined): AstroGlobalPartial;

31
node_modules/astro/dist/runtime/server/astro-global.js generated vendored Normal file
View file

@ -0,0 +1,31 @@
import { ASTRO_VERSION } from "../../core/constants.js";
import { AstroError, AstroErrorData } from "../../core/errors/index.js";
function createAstroGlobFn() {
const globHandler = (importMetaGlobResult) => {
if (typeof importMetaGlobResult === "string") {
throw new AstroError({
...AstroErrorData.AstroGlobUsedOutside,
message: AstroErrorData.AstroGlobUsedOutside.message(JSON.stringify(importMetaGlobResult))
});
}
let allEntries = [...Object.values(importMetaGlobResult)];
if (allEntries.length === 0) {
throw new AstroError({
...AstroErrorData.AstroGlobNoMatch,
message: AstroErrorData.AstroGlobNoMatch.message(JSON.stringify(importMetaGlobResult))
});
}
return Promise.all(allEntries.map((fn) => fn()));
};
return globHandler;
}
function createAstro(site) {
return {
site: site ? new URL(site) : void 0,
generator: `Astro v${ASTRO_VERSION}`,
glob: createAstroGlobFn()
};
}
export {
createAstro
};

View file

@ -0,0 +1,4 @@
type directiveAstroKeys = 'load' | 'idle' | 'visible' | 'media' | 'only';
declare const Astro: {
[k in directiveAstroKeys]?: (fn: () => Promise<() => void>, opts: Record<string, any>, root: HTMLElement) => void;
};

117
node_modules/astro/dist/runtime/server/astro-island.js generated vendored Normal file
View file

@ -0,0 +1,117 @@
var _a;
{
const propTypes = {
0: (value) => value,
1: (value) => JSON.parse(value, reviver),
2: (value) => new RegExp(value),
3: (value) => new Date(value),
4: (value) => new Map(JSON.parse(value, reviver)),
5: (value) => new Set(JSON.parse(value, reviver)),
6: (value) => BigInt(value),
7: (value) => new URL(value),
8: (value) => new Uint8Array(JSON.parse(value)),
9: (value) => new Uint16Array(JSON.parse(value)),
10: (value) => new Uint32Array(JSON.parse(value))
};
const reviver = (propKey, raw) => {
if (propKey === "" || !Array.isArray(raw))
return raw;
const [type, value] = raw;
return type in propTypes ? propTypes[type](value) : void 0;
};
if (!customElements.get("astro-island")) {
customElements.define(
"astro-island",
(_a = class extends HTMLElement {
constructor() {
super(...arguments);
this.hydrate = async () => {
var _a2;
if (!this.hydrator)
return;
if (!this.isConnected)
return;
const parentSsrIsland = (_a2 = this.parentElement) == null ? void 0 : _a2.closest("astro-island[ssr]");
if (parentSsrIsland) {
parentSsrIsland.addEventListener("astro:hydrate", this.hydrate, { once: true });
return;
}
const slotted = this.querySelectorAll("astro-slot");
const slots = {};
const templates = this.querySelectorAll("template[data-astro-template]");
for (const template of templates) {
const closest = template.closest(this.tagName);
if (!(closest == null ? void 0 : closest.isSameNode(this)))
continue;
slots[template.getAttribute("data-astro-template") || "default"] = template.innerHTML;
template.remove();
}
for (const slot of slotted) {
const closest = slot.closest(this.tagName);
if (!(closest == null ? void 0 : closest.isSameNode(this)))
continue;
slots[slot.getAttribute("name") || "default"] = slot.innerHTML;
}
const props = this.hasAttribute("props") ? JSON.parse(this.getAttribute("props"), reviver) : {};
await this.hydrator(this)(this.Component, props, slots, {
client: this.getAttribute("client")
});
this.removeAttribute("ssr");
this.dispatchEvent(new CustomEvent("astro:hydrate"));
};
}
connectedCallback() {
if (!this.hasAttribute("await-children") || this.firstChild) {
this.childrenConnectedCallback();
} else {
new MutationObserver((_, mo) => {
mo.disconnect();
setTimeout(() => this.childrenConnectedCallback(), 0);
}).observe(this, { childList: true });
}
}
async childrenConnectedCallback() {
let beforeHydrationUrl = this.getAttribute("before-hydration-url");
if (beforeHydrationUrl) {
await import(beforeHydrationUrl);
}
this.start();
}
start() {
const opts = JSON.parse(this.getAttribute("opts"));
const directive = this.getAttribute("client");
if (Astro[directive] === void 0) {
window.addEventListener(`astro:${directive}`, () => this.start(), { once: true });
return;
}
Astro[directive](
async () => {
const rendererUrl = this.getAttribute("renderer-url");
const [componentModule, { default: hydrator }] = await Promise.all([
import(this.getAttribute("component-url")),
rendererUrl ? import(rendererUrl) : () => () => {
}
]);
const componentExport = this.getAttribute("component-export") || "default";
if (!componentExport.includes(".")) {
this.Component = componentModule[componentExport];
} else {
this.Component = componentModule;
for (const part of componentExport.split(".")) {
this.Component = this.Component[part];
}
}
this.hydrator = hydrator;
return this.hydrate;
},
opts,
this
);
}
attributeChangedCallback() {
this.hydrate();
}
}, _a.observedAttributes = ["props"], _a)
);
}
}

View file

@ -0,0 +1,7 @@
/**
* This file is prebuilt from packages/astro/src/runtime/server/astro-island.ts
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
declare const _default: "(()=>{var d;{let h={0:t=>t,1:t=>JSON.parse(t,a),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,a)),5:t=>new Set(JSON.parse(t,a)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(JSON.parse(t)),9:t=>new Uint16Array(JSON.parse(t)),10:t=>new Uint32Array(JSON.parse(t))},a=(t,e)=>{if(t===\"\"||!Array.isArray(e))return e;let[r,n]=e;return r in h?h[r](n):void 0};customElements.get(\"astro-island\")||customElements.define(\"astro-island\",(d=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=async()=>{var o;if(!this.hydrator||!this.isConnected)return;let e=(o=this.parentElement)==null?void 0:o.closest(\"astro-island[ssr]\");if(e){e.addEventListener(\"astro:hydrate\",this.hydrate,{once:!0});return}let r=this.querySelectorAll(\"astro-slot\"),n={},c=this.querySelectorAll(\"template[data-astro-template]\");for(let s of c){let i=s.closest(this.tagName);i!=null&&i.isSameNode(this)&&(n[s.getAttribute(\"data-astro-template\")||\"default\"]=s.innerHTML,s.remove())}for(let s of r){let i=s.closest(this.tagName);i!=null&&i.isSameNode(this)&&(n[s.getAttribute(\"name\")||\"default\"]=s.innerHTML)}let l=this.hasAttribute(\"props\")?JSON.parse(this.getAttribute(\"props\"),a):{};await this.hydrator(this)(this.Component,l,n,{client:this.getAttribute(\"client\")}),this.removeAttribute(\"ssr\"),this.dispatchEvent(new CustomEvent(\"astro:hydrate\"))}}connectedCallback(){!this.hasAttribute(\"await-children\")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((e,r)=>{r.disconnect(),setTimeout(()=>this.childrenConnectedCallback(),0)}).observe(this,{childList:!0})}async childrenConnectedCallback(){let e=this.getAttribute(\"before-hydration-url\");e&&await import(e),this.start()}start(){let e=JSON.parse(this.getAttribute(\"opts\")),r=this.getAttribute(\"client\");if(Astro[r]===void 0){window.addEventListener(`astro:${r}`,()=>this.start(),{once:!0});return}Astro[r](async()=>{let n=this.getAttribute(\"renderer-url\"),[c,{default:l}]=await Promise.all([import(this.getAttribute(\"component-url\")),n?import(n):()=>()=>{}]),o=this.getAttribute(\"component-export\")||\"default\";if(!o.includes(\".\"))this.Component=c[o];else{this.Component=c;for(let s of o.split(\".\"))this.Component=this.Component[s]}return this.hydrator=l,this.hydrate},e,this)}attributeChangedCallback(){this.hydrate()}},d.observedAttributes=[\"props\"],d))}})();";
export default _default;

View file

@ -0,0 +1,4 @@
var astro_island_prebuilt_default = `(()=>{var d;{let h={0:t=>t,1:t=>JSON.parse(t,a),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(JSON.parse(t,a)),5:t=>new Set(JSON.parse(t,a)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(JSON.parse(t)),9:t=>new Uint16Array(JSON.parse(t)),10:t=>new Uint32Array(JSON.parse(t))},a=(t,e)=>{if(t===""||!Array.isArray(e))return e;let[r,n]=e;return r in h?h[r](n):void 0};customElements.get("astro-island")||customElements.define("astro-island",(d=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=async()=>{var o;if(!this.hydrator||!this.isConnected)return;let e=(o=this.parentElement)==null?void 0:o.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let r=this.querySelectorAll("astro-slot"),n={},c=this.querySelectorAll("template[data-astro-template]");for(let s of c){let i=s.closest(this.tagName);i!=null&&i.isSameNode(this)&&(n[s.getAttribute("data-astro-template")||"default"]=s.innerHTML,s.remove())}for(let s of r){let i=s.closest(this.tagName);i!=null&&i.isSameNode(this)&&(n[s.getAttribute("name")||"default"]=s.innerHTML)}let l=this.hasAttribute("props")?JSON.parse(this.getAttribute("props"),a):{};await this.hydrator(this)(this.Component,l,n,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))}}connectedCallback(){!this.hasAttribute("await-children")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((e,r)=>{r.disconnect(),setTimeout(()=>this.childrenConnectedCallback(),0)}).observe(this,{childList:!0})}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}start(){let e=JSON.parse(this.getAttribute("opts")),r=this.getAttribute("client");if(Astro[r]===void 0){window.addEventListener(\`astro:\${r}\`,()=>this.start(),{once:!0});return}Astro[r](async()=>{let n=this.getAttribute("renderer-url"),[c,{default:l}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),o=this.getAttribute("component-export")||"default";if(!o.includes("."))this.Component=c[o];else{this.Component=c;for(let s of o.split("."))this.Component=this.Component[s]}return this.hydrator=l,this.hydrate},e,this)}attributeChangedCallback(){this.hydrate()}},d.observedAttributes=["props"],d))}})();`;
export {
astro_island_prebuilt_default as default
};

3
node_modules/astro/dist/runtime/server/endpoint.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
import type { APIContext, EndpointHandler } from '../../@types/astro';
/** Renders an endpoint request to completion, returning the body. */
export declare function renderEndpoint(mod: EndpointHandler, context: APIContext, ssr: boolean): Promise<Response | import("../../@types/astro").EndpointOutput>;

64
node_modules/astro/dist/runtime/server/endpoint.js generated vendored Normal file
View file

@ -0,0 +1,64 @@
function getHandlerFromModule(mod, method) {
if (mod[method]) {
return mod[method];
}
if (method === "delete" && mod["del"]) {
return mod["del"];
}
if (mod["all"]) {
return mod["all"];
}
return void 0;
}
async function renderEndpoint(mod, context, ssr) {
var _a;
const { request, params } = context;
const chosenMethod = (_a = request.method) == null ? void 0 : _a.toLowerCase();
const handler = getHandlerFromModule(mod, chosenMethod);
if (!ssr && ssr === false && chosenMethod && chosenMethod !== "get") {
console.warn(`
${chosenMethod} requests are not available when building a static site. Update your config to \`output: 'server'\` or \`output: 'hybrid'\` with an \`export const prerender = false\` to handle ${chosenMethod} requests.`);
}
if (!handler || typeof handler !== "function") {
let response = new Response(null, {
status: 404,
headers: {
"X-Astro-Response": "Not-Found"
}
});
return response;
}
if (handler.length > 1) {
console.warn(`
API routes with 2 arguments have been deprecated. Instead they take a single argument in the form of:
export function get({ params, request }) {
//...
}
Update your code to remove this warning.`);
}
const proxy = new Proxy(context, {
get(target, prop) {
if (prop in target) {
return Reflect.get(target, prop);
} else if (prop in params) {
console.warn(`
API routes no longer pass params as the first argument. Instead an object containing a params property is provided in the form of:
export function get({ params }) {
// ...
}
Update your code to remove this warning.`);
return Reflect.get(params, prop);
} else {
return void 0;
}
}
});
return handler.call(mod, proxy, request);
}
export {
renderEndpoint
};

22
node_modules/astro/dist/runtime/server/escape.d.ts generated vendored Normal file
View file

@ -0,0 +1,22 @@
import { escape } from 'html-escaper';
export declare const escapeHTML: typeof escape;
export declare class HTMLBytes extends Uint8Array {
}
/**
* A "blessed" extension of String that tells Astro that the string
* has already been escaped. This helps prevent double-escaping of HTML.
*/
export declare class HTMLString extends String {
get [Symbol.toStringTag](): string;
}
type BlessedType = string | HTMLBytes;
/**
* markHTMLString marks a string as raw or "already escaped" by returning
* a `HTMLString` instance. This is meant for internal use, and should not
* be returned through any public JS API.
*/
export declare const markHTMLString: (value: any) => any;
export declare function isHTMLString(value: any): value is HTMLString;
export declare function isHTMLBytes(value: any): value is HTMLBytes;
export declare function unescapeHTML(str: any): BlessedType | Promise<BlessedType | AsyncGenerator<BlessedType, void, unknown>> | AsyncGenerator<BlessedType, void, unknown>;
export {};

80
node_modules/astro/dist/runtime/server/escape.js generated vendored Normal file
View file

@ -0,0 +1,80 @@
import { escape } from "html-escaper";
import { streamAsyncIterator } from "./util.js";
const escapeHTML = escape;
class HTMLBytes extends Uint8Array {
}
Object.defineProperty(HTMLBytes.prototype, Symbol.toStringTag, {
get() {
return "HTMLBytes";
}
});
class HTMLString extends String {
get [Symbol.toStringTag]() {
return "HTMLString";
}
}
const markHTMLString = (value) => {
if (value instanceof HTMLString) {
return value;
}
if (typeof value === "string") {
return new HTMLString(value);
}
return value;
};
function isHTMLString(value) {
return Object.prototype.toString.call(value) === "[object HTMLString]";
}
function markHTMLBytes(bytes) {
return new HTMLBytes(bytes);
}
function isHTMLBytes(value) {
return Object.prototype.toString.call(value) === "[object HTMLBytes]";
}
function hasGetReader(obj) {
return typeof obj.getReader === "function";
}
async function* unescapeChunksAsync(iterable) {
if (hasGetReader(iterable)) {
for await (const chunk of streamAsyncIterator(iterable)) {
yield unescapeHTML(chunk);
}
} else {
for await (const chunk of iterable) {
yield unescapeHTML(chunk);
}
}
}
function* unescapeChunks(iterable) {
for (const chunk of iterable) {
yield unescapeHTML(chunk);
}
}
function unescapeHTML(str) {
if (!!str && typeof str === "object") {
if (str instanceof Uint8Array) {
return markHTMLBytes(str);
} else if (str instanceof Response && str.body) {
const body = str.body;
return unescapeChunksAsync(body);
} else if (typeof str.then === "function") {
return Promise.resolve(str).then((value) => {
return unescapeHTML(value);
});
} else if (Symbol.iterator in str) {
return unescapeChunks(str);
} else if (Symbol.asyncIterator in str || hasGetReader(str)) {
return unescapeChunksAsync(str);
}
}
return markHTMLString(str);
}
export {
HTMLBytes,
HTMLString,
escapeHTML,
isHTMLBytes,
isHTMLString,
markHTMLString,
unescapeHTML
};

25
node_modules/astro/dist/runtime/server/hydration.d.ts generated vendored Normal file
View file

@ -0,0 +1,25 @@
import type { AstroComponentMetadata, SSRElement, SSRLoadedRenderer, SSRResult } from '../../@types/astro';
export interface HydrationMetadata {
directive: string;
value: string;
componentUrl: string;
componentExport: {
value: string;
};
}
interface ExtractedProps {
isPage: boolean;
hydration: HydrationMetadata | null;
props: Record<string | number | symbol, any>;
}
export declare function extractDirectives(inputProps: Record<string | number | symbol, any>, clientDirectives: SSRResult['clientDirectives']): ExtractedProps;
interface HydrateScriptOptions {
renderer: SSRLoadedRenderer;
result: SSRResult;
astroId: string;
props: Record<string | number, any>;
attrs: Record<string, string> | undefined;
}
/** For hydrated components, generate a <script type="module"> to load the component */
export declare function generateHydrateScript(scriptOptions: HydrateScriptOptions, metadata: Required<AstroComponentMetadata>): Promise<SSRElement>;
export {};

112
node_modules/astro/dist/runtime/server/hydration.js generated vendored Normal file
View file

@ -0,0 +1,112 @@
import { AstroError, AstroErrorData } from "../../core/errors/index.js";
import { escapeHTML } from "./escape.js";
import { serializeProps } from "./serialize.js";
import { serializeListValue } from "./util.js";
function extractDirectives(inputProps, clientDirectives) {
let extracted = {
isPage: false,
hydration: null,
props: {}
};
for (const [key, value] of Object.entries(inputProps)) {
if (key.startsWith("server:")) {
if (key === "server:root") {
extracted.isPage = true;
}
}
if (key.startsWith("client:")) {
if (!extracted.hydration) {
extracted.hydration = {
directive: "",
value: "",
componentUrl: "",
componentExport: { value: "" }
};
}
switch (key) {
case "client:component-path": {
extracted.hydration.componentUrl = value;
break;
}
case "client:component-export": {
extracted.hydration.componentExport.value = value;
break;
}
case "client:component-hydration": {
break;
}
case "client:display-name": {
break;
}
default: {
extracted.hydration.directive = key.split(":")[1];
extracted.hydration.value = value;
if (!clientDirectives.has(extracted.hydration.directive)) {
const hydrationMethods = Array.from(clientDirectives.keys()).map((d) => `client:${d}`).join(", ");
throw new Error(
`Error: invalid hydration directive "${key}". Supported hydration methods: ${hydrationMethods}`
);
}
if (extracted.hydration.directive === "media" && typeof extracted.hydration.value !== "string") {
throw new AstroError(AstroErrorData.MissingMediaQueryDirective);
}
break;
}
}
} else if (key === "class:list") {
if (value) {
extracted.props[key.slice(0, -5)] = serializeListValue(value);
}
} else {
extracted.props[key] = value;
}
}
for (const sym of Object.getOwnPropertySymbols(inputProps)) {
extracted.props[sym] = inputProps[sym];
}
return extracted;
}
async function generateHydrateScript(scriptOptions, metadata) {
const { renderer, result, astroId, props, attrs } = scriptOptions;
const { hydrate, componentUrl, componentExport } = metadata;
if (!componentExport.value) {
throw new Error(
`Unable to resolve a valid export for "${metadata.displayName}"! Please open an issue at https://astro.build/issues!`
);
}
const island = {
children: "",
props: {
// This is for HMR, probably can avoid it in prod
uid: astroId
}
};
if (attrs) {
for (const [key, value] of Object.entries(attrs)) {
island.props[key] = escapeHTML(value);
}
}
island.props["component-url"] = await result.resolve(decodeURI(componentUrl));
if (renderer.clientEntrypoint) {
island.props["component-export"] = componentExport.value;
island.props["renderer-url"] = await result.resolve(decodeURI(renderer.clientEntrypoint));
island.props["props"] = escapeHTML(serializeProps(props, metadata));
}
island.props["ssr"] = "";
island.props["client"] = hydrate;
let beforeHydrationUrl = await result.resolve("astro:scripts/before-hydration.js");
if (beforeHydrationUrl.length) {
island.props["before-hydration-url"] = beforeHydrationUrl;
}
island.props["opts"] = escapeHTML(
JSON.stringify({
name: metadata.displayName,
value: metadata.hydrateArgs || ""
})
);
return island;
}
export {
extractDirectives,
generateHydrateScript
};

14
node_modules/astro/dist/runtime/server/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,14 @@
export { createComponent } from './astro-component.js';
export { createAstro } from './astro-global.js';
export { renderEndpoint } from './endpoint.js';
export { escapeHTML, HTMLBytes, HTMLString, isHTMLString, markHTMLString, unescapeHTML, } from './escape.js';
export { renderJSX } from './jsx.js';
export { addAttribute, createHeadAndContent, defineScriptVars, Fragment, maybeRenderHead, renderAstroTemplateResult as renderAstroComponent, renderComponent, renderComponentToIterable, Renderer as Renderer, renderHead, renderHTMLElement, renderPage, renderScriptElement, renderSlot, renderSlotToString, renderTemplate as render, renderTemplate, renderToString, renderUniqueStylesheet, stringifyChunk, voidElementNames, } from './render/index.js';
export type { AstroComponentFactory, AstroComponentInstance, ComponentSlots, RenderInstruction, } from './render/index.js';
export declare function mergeSlots(...slotted: unknown[]): Record<string, () => any>;
/** @internal Associate JSX components with a specific renderer (see /src/vite-plugin-jsx/tag.ts) */
export declare function __astro_tag_component__(Component: unknown, rendererName: string): void;
export declare function spreadAttributes(values?: Record<any, any>, _name?: string, { class: scopedClassName }?: {
class?: string;
}): any;
export declare function defineStyleVars(defs: Record<any, any> | Record<any, any>[]): any;

126
node_modules/astro/dist/runtime/server/index.js generated vendored Normal file
View file

@ -0,0 +1,126 @@
import { createComponent } from "./astro-component.js";
import { createAstro } from "./astro-global.js";
import { renderEndpoint } from "./endpoint.js";
import {
escapeHTML,
HTMLBytes,
HTMLString,
isHTMLString,
markHTMLString,
unescapeHTML
} from "./escape.js";
import { renderJSX } from "./jsx.js";
import {
addAttribute,
createHeadAndContent,
defineScriptVars,
Fragment,
maybeRenderHead,
renderAstroTemplateResult,
renderComponent,
renderComponentToIterable,
Renderer,
renderHead,
renderHTMLElement,
renderPage,
renderScriptElement,
renderSlot,
renderSlotToString,
renderTemplate,
renderTemplate as renderTemplate2,
renderToString,
renderUniqueStylesheet,
stringifyChunk,
voidElementNames
} from "./render/index.js";
import { markHTMLString as markHTMLString2 } from "./escape.js";
import { addAttribute as addAttribute2, Renderer as Renderer2 } from "./render/index.js";
function mergeSlots(...slotted) {
const slots = {};
for (const slot of slotted) {
if (!slot)
continue;
if (typeof slot === "object") {
Object.assign(slots, slot);
} else if (typeof slot === "function") {
Object.assign(slots, mergeSlots(slot()));
}
}
return slots;
}
function __astro_tag_component__(Component, rendererName) {
if (!Component)
return;
if (typeof Component !== "function")
return;
Object.defineProperty(Component, Renderer2, {
value: rendererName,
enumerable: false,
writable: false
});
}
function spreadAttributes(values = {}, _name, { class: scopedClassName } = {}) {
let output = "";
if (scopedClassName) {
if (typeof values.class !== "undefined") {
values.class += ` ${scopedClassName}`;
} else if (typeof values["class:list"] !== "undefined") {
values["class:list"] = [values["class:list"], scopedClassName];
} else {
values.class = scopedClassName;
}
}
for (const [key, value] of Object.entries(values)) {
output += addAttribute2(value, key, true);
}
return markHTMLString2(output);
}
function defineStyleVars(defs) {
let output = "";
let arr = !Array.isArray(defs) ? [defs] : defs;
for (const vars of arr) {
for (const [key, value] of Object.entries(vars)) {
if (value || value === 0) {
output += `--${key}: ${value};`;
}
}
}
return markHTMLString2(output);
}
export {
Fragment,
HTMLBytes,
HTMLString,
Renderer,
__astro_tag_component__,
addAttribute,
createAstro,
createComponent,
createHeadAndContent,
defineScriptVars,
defineStyleVars,
escapeHTML,
isHTMLString,
markHTMLString,
maybeRenderHead,
mergeSlots,
renderTemplate as render,
renderAstroTemplateResult as renderAstroComponent,
renderComponent,
renderComponentToIterable,
renderEndpoint,
renderHTMLElement,
renderHead,
renderJSX,
renderPage,
renderScriptElement,
renderSlot,
renderSlotToString,
renderTemplate2 as renderTemplate,
renderToString,
renderUniqueStylesheet,
spreadAttributes,
stringifyChunk,
unescapeHTML,
voidElementNames
};

2
node_modules/astro/dist/runtime/server/jsx.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
import type { SSRResult } from '../../@types/astro.js';
export declare function renderJSX(result: SSRResult, vnode: any): Promise<any>;

229
node_modules/astro/dist/runtime/server/jsx.js generated vendored Normal file
View file

@ -0,0 +1,229 @@
import { AstroJSX, isVNode } from "../../jsx-runtime/index.js";
import {
escapeHTML,
HTMLString,
markHTMLString,
renderComponentToIterable,
renderToString,
spreadAttributes,
voidElementNames
} from "./index.js";
import { HTMLParts } from "./render/common.js";
const ClientOnlyPlaceholder = "astro-client-only";
class Skip {
constructor(vnode) {
this.vnode = vnode;
this.count = 0;
}
increment() {
this.count++;
}
haveNoTried() {
return this.count === 0;
}
isCompleted() {
return this.count > 2;
}
}
Skip.symbol = Symbol("astro:jsx:skip");
let originalConsoleError;
let consoleFilterRefs = 0;
async function renderJSX(result, vnode) {
switch (true) {
case vnode instanceof HTMLString:
if (vnode.toString().trim() === "") {
return "";
}
return vnode;
case typeof vnode === "string":
return markHTMLString(escapeHTML(vnode));
case typeof vnode === "function":
return vnode;
case (!vnode && vnode !== 0):
return "";
case Array.isArray(vnode):
return markHTMLString(
(await Promise.all(vnode.map((v) => renderJSX(result, v)))).join("")
);
}
let skip;
if (vnode.props) {
if (vnode.props[Skip.symbol]) {
skip = vnode.props[Skip.symbol];
} else {
skip = new Skip(vnode);
}
} else {
skip = new Skip(vnode);
}
return renderJSXVNode(result, vnode, skip);
}
async function renderJSXVNode(result, vnode, skip) {
if (isVNode(vnode)) {
switch (true) {
case !vnode.type: {
throw new Error(`Unable to render ${result.pathname} because it contains an undefined Component!
Did you forget to import the component or is it possible there is a typo?`);
}
case vnode.type === Symbol.for("astro:fragment"):
return renderJSX(result, vnode.props.children);
case vnode.type.isAstroComponentFactory: {
let props = {};
let slots = {};
for (const [key, value] of Object.entries(vnode.props ?? {})) {
if (key === "children" || value && typeof value === "object" && value["$$slot"]) {
slots[key === "children" ? "default" : key] = () => renderJSX(result, value);
} else {
props[key] = value;
}
}
const html = markHTMLString(await renderToString(result, vnode.type, props, slots));
return html;
}
case (!vnode.type && vnode.type !== 0):
return "";
case (typeof vnode.type === "string" && vnode.type !== ClientOnlyPlaceholder):
return markHTMLString(await renderElement(result, vnode.type, vnode.props ?? {}));
}
if (vnode.type) {
let extractSlots2 = function(child) {
if (Array.isArray(child)) {
return child.map((c) => extractSlots2(c));
}
if (!isVNode(child)) {
_slots.default.push(child);
return;
}
if ("slot" in child.props) {
_slots[child.props.slot] = [..._slots[child.props.slot] ?? [], child];
delete child.props.slot;
return;
}
_slots.default.push(child);
};
var extractSlots = extractSlots2;
if (typeof vnode.type === "function" && vnode.type["astro:renderer"]) {
skip.increment();
}
if (typeof vnode.type === "function" && vnode.props["server:root"]) {
const output2 = await vnode.type(vnode.props ?? {});
return await renderJSX(result, output2);
}
if (typeof vnode.type === "function") {
if (skip.haveNoTried() || skip.isCompleted()) {
useConsoleFilter();
try {
const output2 = await vnode.type(vnode.props ?? {});
let renderResult;
if (output2 == null ? void 0 : output2[AstroJSX]) {
renderResult = await renderJSXVNode(result, output2, skip);
return renderResult;
} else if (!output2) {
renderResult = await renderJSXVNode(result, output2, skip);
return renderResult;
}
} catch (e) {
if (skip.isCompleted()) {
throw e;
}
skip.increment();
} finally {
finishUsingConsoleFilter();
}
} else {
skip.increment();
}
}
const { children = null, ...props } = vnode.props ?? {};
const _slots = {
default: []
};
extractSlots2(children);
for (const [key, value] of Object.entries(props)) {
if (value["$$slot"]) {
_slots[key] = value;
delete props[key];
}
}
const slotPromises = [];
const slots = {};
for (const [key, value] of Object.entries(_slots)) {
slotPromises.push(
renderJSX(result, value).then((output2) => {
if (output2.toString().trim().length === 0)
return;
slots[key] = () => output2;
})
);
}
await Promise.all(slotPromises);
props[Skip.symbol] = skip;
let output;
if (vnode.type === ClientOnlyPlaceholder && vnode.props["client:only"]) {
output = await renderComponentToIterable(
result,
vnode.props["client:display-name"] ?? "",
null,
props,
slots
);
} else {
output = await renderComponentToIterable(
result,
typeof vnode.type === "function" ? vnode.type.name : vnode.type,
vnode.type,
props,
slots
);
}
if (typeof output !== "string" && Symbol.asyncIterator in output) {
let parts = new HTMLParts();
for await (const chunk of output) {
parts.append(chunk, result);
}
return markHTMLString(parts.toString());
} else {
return markHTMLString(output);
}
}
}
return markHTMLString(`${vnode}`);
}
async function renderElement(result, tag, { children, ...props }) {
return markHTMLString(
`<${tag}${spreadAttributes(props)}${markHTMLString(
(children == null || children == "") && voidElementNames.test(tag) ? `/>` : `>${children == null ? "" : await renderJSX(result, prerenderElementChildren(tag, children))}</${tag}>`
)}`
);
}
function prerenderElementChildren(tag, children) {
if (typeof children === "string" && (tag === "style" || tag === "script")) {
return markHTMLString(children);
} else {
return children;
}
}
function useConsoleFilter() {
consoleFilterRefs++;
if (!originalConsoleError) {
originalConsoleError = console.error;
try {
console.error = filteredConsoleError;
} catch (error) {
}
}
}
function finishUsingConsoleFilter() {
consoleFilterRefs--;
}
function filteredConsoleError(msg, ...rest) {
if (consoleFilterRefs > 0 && typeof msg === "string") {
const isKnownReactHookError = msg.includes("Warning: Invalid hook call.") && msg.includes("https://reactjs.org/link/invalid-hook-call");
if (isKnownReactHookError)
return;
}
originalConsoleError(msg, ...rest);
}
export {
renderJSX
};

View file

@ -0,0 +1 @@
export declare function renderChild(child: any): AsyncIterable<any>;

42
node_modules/astro/dist/runtime/server/render/any.js generated vendored Normal file
View file

@ -0,0 +1,42 @@
import { escapeHTML, isHTMLString, markHTMLString } from "../escape.js";
import {
isAstroComponentInstance,
isRenderTemplateResult,
renderAstroTemplateResult
} from "./astro/index.js";
import { SlotString } from "./slot.js";
import { bufferIterators } from "./util.js";
async function* renderChild(child) {
child = await child;
if (child instanceof SlotString) {
if (child.instructions) {
yield* child.instructions;
}
yield child;
} else if (isHTMLString(child)) {
yield child;
} else if (Array.isArray(child)) {
const bufferedIterators = bufferIterators(child.map((c) => renderChild(c)));
for (const value of bufferedIterators) {
yield markHTMLString(await value);
}
} else if (typeof child === "function") {
yield* renderChild(child());
} else if (typeof child === "string") {
yield markHTMLString(escapeHTML(child));
} else if (!child && child !== 0) {
} else if (isRenderTemplateResult(child)) {
yield* renderAstroTemplateResult(child);
} else if (isAstroComponentInstance(child)) {
yield* child.render();
} else if (ArrayBuffer.isView(child)) {
yield child;
} else if (typeof child === "object" && (Symbol.asyncIterator in child || Symbol.iterator in child)) {
yield* child;
} else {
yield child;
}
}
export {
renderChild
};

View file

@ -0,0 +1,13 @@
import type { PropagationHint, SSRResult } from '../../../../@types/astro';
import type { HeadAndContent } from './head-and-content';
import type { RenderTemplateResult } from './render-template';
export type AstroFactoryReturnValue = RenderTemplateResult | Response | HeadAndContent;
export interface AstroComponentFactory {
(result: any, props: any, slots: any): AstroFactoryReturnValue;
isAstroComponentFactory?: boolean;
moduleId?: string | undefined;
propagation?: PropagationHint;
}
export declare function isAstroComponentFactory(obj: any): obj is AstroComponentFactory;
export declare function renderToString(result: SSRResult, componentFactory: AstroComponentFactory, props: any, children: any): Promise<string>;
export declare function isAPropagatingComponent(result: SSRResult, factory: AstroComponentFactory): boolean;

View file

@ -0,0 +1,31 @@
import { HTMLParts } from "../common.js";
import { isHeadAndContent } from "./head-and-content.js";
import { renderAstroTemplateResult } from "./render-template.js";
function isAstroComponentFactory(obj) {
return obj == null ? false : obj.isAstroComponentFactory === true;
}
async function renderToString(result, componentFactory, props, children) {
const factoryResult = await componentFactory(result, props, children);
if (factoryResult instanceof Response) {
const response = factoryResult;
throw response;
}
let parts = new HTMLParts();
const templateResult = isHeadAndContent(factoryResult) ? factoryResult.content : factoryResult;
for await (const chunk of renderAstroTemplateResult(templateResult)) {
parts.append(chunk, result);
}
return parts.toString();
}
function isAPropagatingComponent(result, factory) {
let hint = factory.propagation || "none";
if (factory.moduleId && result.componentMetadata.has(factory.moduleId) && hint === "none") {
hint = result.componentMetadata.get(factory.moduleId).propagation;
}
return hint === "in-tree" || hint === "self";
}
export {
isAPropagatingComponent,
isAstroComponentFactory,
renderToString
};

View file

@ -0,0 +1,10 @@
import type { RenderTemplateResult } from './render-template';
declare const headAndContentSym: unique symbol;
export type HeadAndContent = {
[headAndContentSym]: true;
head: string;
content: RenderTemplateResult;
};
export declare function isHeadAndContent(obj: unknown): obj is HeadAndContent;
export declare function createHeadAndContent(head: string, content: RenderTemplateResult): HeadAndContent;
export {};

View file

@ -0,0 +1,15 @@
const headAndContentSym = Symbol.for("astro.headAndContent");
function isHeadAndContent(obj) {
return typeof obj === "object" && !!obj[headAndContentSym];
}
function createHeadAndContent(head, content) {
return {
[headAndContentSym]: true,
head,
content
};
}
export {
createHeadAndContent,
isHeadAndContent
};

View file

@ -0,0 +1,6 @@
export type { AstroComponentFactory } from './factory';
export { isAstroComponentFactory, renderToString } from './factory.js';
export { createHeadAndContent, isHeadAndContent } from './head-and-content.js';
export type { AstroComponentInstance } from './instance';
export { createAstroComponentInstance, isAstroComponentInstance } from './instance.js';
export { isRenderTemplateResult, renderAstroTemplateResult, renderTemplate, } from './render-template.js';

View file

@ -0,0 +1,19 @@
import { isAstroComponentFactory, renderToString } from "./factory.js";
import { createHeadAndContent, isHeadAndContent } from "./head-and-content.js";
import { createAstroComponentInstance, isAstroComponentInstance } from "./instance.js";
import {
isRenderTemplateResult,
renderAstroTemplateResult,
renderTemplate
} from "./render-template.js";
export {
createAstroComponentInstance,
createHeadAndContent,
isAstroComponentFactory,
isAstroComponentInstance,
isHeadAndContent,
isRenderTemplateResult,
renderAstroTemplateResult,
renderTemplate,
renderToString
};

View file

@ -0,0 +1,19 @@
import type { SSRResult } from '../../../../@types/astro';
import type { ComponentSlots } from '../slot.js';
import type { AstroComponentFactory, AstroFactoryReturnValue } from './factory.js';
type ComponentProps = Record<string | number, any>;
declare const astroComponentInstanceSym: unique symbol;
export declare class AstroComponentInstance {
[astroComponentInstanceSym]: boolean;
private readonly result;
private readonly props;
private readonly slotValues;
private readonly factory;
private returnValue;
constructor(result: SSRResult, props: ComponentProps, slots: ComponentSlots, factory: AstroComponentFactory);
init(result: SSRResult): Promise<AstroFactoryReturnValue>;
render(): AsyncGenerator<any, void, undefined>;
}
export declare function createAstroComponentInstance(result: SSRResult, displayName: string, factory: AstroComponentFactory, props: ComponentProps, slots?: any): AstroComponentInstance;
export declare function isAstroComponentInstance(obj: unknown): obj is AstroComponentInstance;
export {};

View file

@ -0,0 +1,65 @@
var _a;
import { isPromise } from "../../util.js";
import { renderChild } from "../any.js";
import { isAPropagatingComponent } from "./factory.js";
import { isHeadAndContent } from "./head-and-content.js";
const astroComponentInstanceSym = Symbol.for("astro.componentInstance");
class AstroComponentInstance {
constructor(result, props, slots, factory) {
this[_a] = true;
this.result = result;
this.props = props;
this.factory = factory;
this.slotValues = {};
for (const name in slots) {
const value = slots[name](result);
this.slotValues[name] = () => value;
}
}
async init(result) {
this.returnValue = this.factory(result, this.props, this.slotValues);
return this.returnValue;
}
async *render() {
if (this.returnValue === void 0) {
await this.init(this.result);
}
let value = this.returnValue;
if (isPromise(value)) {
value = await value;
}
if (isHeadAndContent(value)) {
yield* value.content;
} else {
yield* renderChild(value);
}
}
}
_a = astroComponentInstanceSym;
function validateComponentProps(props, displayName) {
if (props != null) {
for (const prop of Object.keys(props)) {
if (prop.startsWith("client:")) {
console.warn(
`You are attempting to render <${displayName} ${prop} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`
);
}
}
}
}
function createAstroComponentInstance(result, displayName, factory, props, slots = {}) {
validateComponentProps(props, displayName);
const instance = new AstroComponentInstance(result, props, slots, factory);
if (isAPropagatingComponent(result, factory) && !result._metadata.propagators.has(factory)) {
result._metadata.propagators.set(factory, instance);
}
return instance;
}
function isAstroComponentInstance(obj) {
return typeof obj === "object" && !!obj[astroComponentInstanceSym];
}
export {
AstroComponentInstance,
createAstroComponentInstance,
isAstroComponentInstance
};

View file

@ -0,0 +1,15 @@
import type { RenderInstruction } from '../types';
import { HTMLBytes } from '../../escape.js';
declare const renderTemplateResultSym: unique symbol;
export declare class RenderTemplateResult {
[renderTemplateResultSym]: boolean;
private htmlParts;
private expressions;
private error;
constructor(htmlParts: TemplateStringsArray, expressions: unknown[]);
[Symbol.asyncIterator](): AsyncGenerator<any, void, undefined>;
}
export declare function isRenderTemplateResult(obj: unknown): obj is RenderTemplateResult;
export declare function renderAstroTemplateResult(component: RenderTemplateResult): AsyncIterable<string | HTMLBytes | RenderInstruction>;
export declare function renderTemplate(htmlParts: TemplateStringsArray, ...expressions: any[]): RenderTemplateResult;
export {};

View file

@ -0,0 +1,66 @@
var _a;
import { markHTMLString } from "../../escape.js";
import { isPromise } from "../../util.js";
import { renderChild } from "../any.js";
import { bufferIterators } from "../util.js";
const renderTemplateResultSym = Symbol.for("astro.renderTemplateResult");
class RenderTemplateResult {
constructor(htmlParts, expressions) {
this[_a] = true;
this.htmlParts = htmlParts;
this.error = void 0;
this.expressions = expressions.map((expression) => {
if (isPromise(expression)) {
return Promise.resolve(expression).catch((err) => {
if (!this.error) {
this.error = err;
throw err;
}
});
}
return expression;
});
}
async *[(_a = renderTemplateResultSym, Symbol.asyncIterator)]() {
const { htmlParts, expressions } = this;
let iterables = bufferIterators(expressions.map((e) => renderChild(e)));
for (let i = 0; i < htmlParts.length; i++) {
const html = htmlParts[i];
const iterable = iterables[i];
yield markHTMLString(html);
if (iterable) {
yield* iterable;
}
}
}
}
function isRenderTemplateResult(obj) {
return typeof obj === "object" && !!obj[renderTemplateResultSym];
}
async function* renderAstroTemplateResult(component) {
for await (const value of component) {
if (value || value === 0) {
for await (const chunk of renderChild(value)) {
switch (chunk.type) {
case "directive": {
yield chunk;
break;
}
default: {
yield markHTMLString(chunk);
break;
}
}
}
}
}
}
function renderTemplate(htmlParts, ...expressions) {
return new RenderTemplateResult(htmlParts, expressions);
}
export {
RenderTemplateResult,
isRenderTemplateResult,
renderAstroTemplateResult,
renderTemplate
};

View file

@ -0,0 +1,17 @@
import type { SSRResult } from '../../../@types/astro';
import type { RenderInstruction } from './types.js';
import { HTMLBytes } from '../escape.js';
import { type SlotString } from './slot.js';
export declare const Fragment: unique symbol;
export declare const Renderer: unique symbol;
export declare const encoder: TextEncoder;
export declare const decoder: TextDecoder;
export declare function stringifyChunk(result: SSRResult, chunk: string | SlotString | RenderInstruction): string;
export declare class HTMLParts {
parts: string;
constructor();
append(part: string | HTMLBytes | RenderInstruction, result: SSRResult): void;
toString(): string;
toArrayBuffer(): Uint8Array;
}
export declare function chunkToByteArray(result: SSRResult, chunk: string | HTMLBytes | RenderInstruction): Uint8Array;

View file

@ -0,0 +1,96 @@
import { markHTMLString } from "../escape.js";
import {
determineIfNeedsHydrationScript,
determinesIfNeedsDirectiveScript,
getPrescripts
} from "../scripts.js";
import { renderAllHeadContent } from "./head.js";
import { isSlotString } from "./slot.js";
const Fragment = Symbol.for("astro:fragment");
const Renderer = Symbol.for("astro:renderer");
const encoder = new TextEncoder();
const decoder = new TextDecoder();
function stringifyChunk(result, chunk) {
if (typeof chunk.type === "string") {
const instruction = chunk;
switch (instruction.type) {
case "directive": {
const { hydration } = instruction;
let needsHydrationScript = hydration && determineIfNeedsHydrationScript(result);
let needsDirectiveScript = hydration && determinesIfNeedsDirectiveScript(result, hydration.directive);
let prescriptType = needsHydrationScript ? "both" : needsDirectiveScript ? "directive" : null;
if (prescriptType) {
let prescripts = getPrescripts(result, prescriptType, hydration.directive);
return markHTMLString(prescripts);
} else {
return "";
}
}
case "head": {
if (result._metadata.hasRenderedHead) {
return "";
}
return renderAllHeadContent(result);
}
case "maybe-head": {
if (result._metadata.hasRenderedHead || result._metadata.headInTree) {
return "";
}
return renderAllHeadContent(result);
}
default: {
if (chunk instanceof Response) {
return "";
}
throw new Error(`Unknown chunk type: ${chunk.type}`);
}
}
} else {
if (isSlotString(chunk)) {
let out = "";
const c = chunk;
if (c.instructions) {
for (const instr of c.instructions) {
out += stringifyChunk(result, instr);
}
}
out += chunk.toString();
return out;
}
return chunk.toString();
}
}
class HTMLParts {
constructor() {
this.parts = "";
}
append(part, result) {
if (ArrayBuffer.isView(part)) {
this.parts += decoder.decode(part);
} else {
this.parts += stringifyChunk(result, part);
}
}
toString() {
return this.parts;
}
toArrayBuffer() {
return encoder.encode(this.parts);
}
}
function chunkToByteArray(result, chunk) {
if (chunk instanceof Uint8Array) {
return chunk;
}
let stringified = stringifyChunk(result, chunk);
return encoder.encode(stringified.toString());
}
export {
Fragment,
HTMLParts,
Renderer,
chunkToByteArray,
decoder,
encoder,
stringifyChunk
};

View file

@ -0,0 +1,7 @@
import type { SSRResult } from '../../../@types/astro';
import type { RenderInstruction } from './types.js';
import { HTMLBytes } from '../escape.js';
import { type AstroComponentInstance } from './astro/index.js';
export type ComponentIterable = AsyncIterable<string | HTMLBytes | RenderInstruction>;
export declare function renderComponent(result: SSRResult, displayName: string, Component: unknown, props: Record<string | number, any>, slots?: any): Promise<ComponentIterable> | ComponentIterable | AstroComponentInstance;
export declare function renderComponentToIterable(result: SSRResult, displayName: string, Component: unknown, props: Record<string | number, any>, slots?: any): Promise<ComponentIterable> | ComponentIterable;

View file

@ -0,0 +1,317 @@
import { AstroError, AstroErrorData } from "../../../core/errors/index.js";
import { markHTMLString } from "../escape.js";
import { extractDirectives, generateHydrateScript } from "../hydration.js";
import { serializeProps } from "../serialize.js";
import { shorthash } from "../shorthash.js";
import { isPromise } from "../util.js";
import {
createAstroComponentInstance,
isAstroComponentFactory,
isAstroComponentInstance,
renderAstroTemplateResult,
renderTemplate
} from "./astro/index.js";
import { Fragment, Renderer, stringifyChunk } from "./common.js";
import { componentIsHTMLElement, renderHTMLElement } from "./dom.js";
import { renderSlots, renderSlotToString } from "./slot.js";
import { formatList, internalSpreadAttributes, renderElement, voidElementNames } from "./util.js";
const rendererAliases = /* @__PURE__ */ new Map([["solid", "solid-js"]]);
function guessRenderers(componentUrl) {
const extname = componentUrl == null ? void 0 : componentUrl.split(".").pop();
switch (extname) {
case "svelte":
return ["@astrojs/svelte"];
case "vue":
return ["@astrojs/vue"];
case "jsx":
case "tsx":
return ["@astrojs/react", "@astrojs/preact", "@astrojs/solid-js", "@astrojs/vue (jsx)"];
default:
return [
"@astrojs/react",
"@astrojs/preact",
"@astrojs/solid-js",
"@astrojs/vue",
"@astrojs/svelte",
"@astrojs/lit"
];
}
}
function isFragmentComponent(Component) {
return Component === Fragment;
}
function isHTMLComponent(Component) {
return Component && Component["astro:html"] === true;
}
const ASTRO_SLOT_EXP = /\<\/?astro-slot\b[^>]*>/g;
const ASTRO_STATIC_SLOT_EXP = /\<\/?astro-static-slot\b[^>]*>/g;
function removeStaticAstroSlot(html, supportsAstroStaticSlot) {
const exp = supportsAstroStaticSlot ? ASTRO_STATIC_SLOT_EXP : ASTRO_SLOT_EXP;
return html.replace(exp, "");
}
async function renderFrameworkComponent(result, displayName, Component, _props, slots = {}) {
var _a, _b, _c;
if (!Component && !_props["client:only"]) {
throw new Error(
`Unable to render ${displayName} because it is ${Component}!
Did you forget to import the component or is it possible there is a typo?`
);
}
const { renderers, clientDirectives } = result;
const metadata = {
astroStaticSlot: true,
displayName
};
const { hydration, isPage, props } = extractDirectives(_props, clientDirectives);
let html = "";
let attrs = void 0;
if (hydration) {
metadata.hydrate = hydration.directive;
metadata.hydrateArgs = hydration.value;
metadata.componentExport = hydration.componentExport;
metadata.componentUrl = hydration.componentUrl;
}
const probableRendererNames = guessRenderers(metadata.componentUrl);
const validRenderers = renderers.filter((r) => r.name !== "astro:jsx");
const { children, slotInstructions } = await renderSlots(result, slots);
let renderer;
if (metadata.hydrate !== "only") {
let isTagged = false;
try {
isTagged = Component && Component[Renderer];
} catch {
}
if (isTagged) {
const rendererName = Component[Renderer];
renderer = renderers.find(({ name }) => name === rendererName);
}
if (!renderer) {
let error;
for (const r of renderers) {
try {
if (await r.ssr.check.call({ result }, Component, props, children)) {
renderer = r;
break;
}
} catch (e) {
error ??= e;
}
}
if (!renderer && error) {
throw error;
}
}
if (!renderer && typeof HTMLElement === "function" && componentIsHTMLElement(Component)) {
const output = renderHTMLElement(result, Component, _props, slots);
return output;
}
} else {
if (metadata.hydrateArgs) {
const passedName = metadata.hydrateArgs;
const rendererName = rendererAliases.has(passedName) ? rendererAliases.get(passedName) : passedName;
renderer = renderers.find(
({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
);
}
if (!renderer && validRenderers.length === 1) {
renderer = validRenderers[0];
}
if (!renderer) {
const extname = (_a = metadata.componentUrl) == null ? void 0 : _a.split(".").pop();
renderer = renderers.filter(
({ name }) => name === `@astrojs/${extname}` || name === extname
)[0];
}
}
if (!renderer) {
if (metadata.hydrate === "only") {
throw new AstroError({
...AstroErrorData.NoClientOnlyHint,
message: AstroErrorData.NoClientOnlyHint.message(metadata.displayName),
hint: AstroErrorData.NoClientOnlyHint.hint(
probableRendererNames.map((r) => r.replace("@astrojs/", "")).join("|")
)
});
} else if (typeof Component !== "string") {
const matchingRenderers = validRenderers.filter(
(r) => probableRendererNames.includes(r.name)
);
const plural = validRenderers.length > 1;
if (matchingRenderers.length === 0) {
throw new AstroError({
...AstroErrorData.NoMatchingRenderer,
message: AstroErrorData.NoMatchingRenderer.message(
metadata.displayName,
(_b = metadata == null ? void 0 : metadata.componentUrl) == null ? void 0 : _b.split(".").pop(),
plural,
validRenderers.length
),
hint: AstroErrorData.NoMatchingRenderer.hint(
formatList(probableRendererNames.map((r) => "`" + r + "`"))
)
});
} else if (matchingRenderers.length === 1) {
renderer = matchingRenderers[0];
({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
{ result },
Component,
props,
children,
metadata
));
} else {
throw new Error(`Unable to render ${metadata.displayName}!
This component likely uses ${formatList(probableRendererNames)},
but Astro encountered an error during server-side rendering.
Please ensure that ${metadata.displayName}:
1. Does not unconditionally access browser-specific globals like \`window\` or \`document\`.
If this is unavoidable, use the \`client:only\` hydration directive.
2. Does not conditionally return \`null\` or \`undefined\` when rendered on the server.
If you're still stuck, please open an issue on GitHub or join us at https://astro.build/chat.`);
}
}
} else {
if (metadata.hydrate === "only") {
html = await renderSlotToString(result, slots == null ? void 0 : slots.fallback);
} else {
({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
{ result },
Component,
props,
children,
metadata
));
}
}
if (renderer && !renderer.clientEntrypoint && renderer.name !== "@astrojs/lit" && metadata.hydrate) {
throw new AstroError({
...AstroErrorData.NoClientEntrypoint,
message: AstroErrorData.NoClientEntrypoint.message(
displayName,
metadata.hydrate,
renderer.name
)
});
}
if (!html && typeof Component === "string") {
const Tag = sanitizeElementName(Component);
const childSlots = Object.values(children).join("");
const iterable = renderAstroTemplateResult(
await renderTemplate`<${Tag}${internalSpreadAttributes(props)}${markHTMLString(
childSlots === "" && voidElementNames.test(Tag) ? `/>` : `>${childSlots}</${Tag}>`
)}`
);
html = "";
for await (const chunk of iterable) {
html += chunk;
}
}
if (!hydration) {
return async function* () {
var _a2;
if (slotInstructions) {
yield* slotInstructions;
}
if (isPage || (renderer == null ? void 0 : renderer.name) === "astro:jsx") {
yield html;
} else if (html && html.length > 0) {
yield markHTMLString(
removeStaticAstroSlot(html, ((_a2 = renderer == null ? void 0 : renderer.ssr) == null ? void 0 : _a2.supportsAstroStaticSlot) ?? false)
);
} else {
yield "";
}
}();
}
const astroId = shorthash(
`<!--${metadata.componentExport.value}:${metadata.componentUrl}-->
${html}
${serializeProps(
props,
metadata
)}`
);
const island = await generateHydrateScript(
{ renderer, result, astroId, props, attrs },
metadata
);
let unrenderedSlots = [];
if (html) {
if (Object.keys(children).length > 0) {
for (const key of Object.keys(children)) {
let tagName = ((_c = renderer == null ? void 0 : renderer.ssr) == null ? void 0 : _c.supportsAstroStaticSlot) ? !!metadata.hydrate ? "astro-slot" : "astro-static-slot" : "astro-slot";
let expectedHTML = key === "default" ? `<${tagName}>` : `<${tagName} name="${key}">`;
if (!html.includes(expectedHTML)) {
unrenderedSlots.push(key);
}
}
}
} else {
unrenderedSlots = Object.keys(children);
}
const template = unrenderedSlots.length > 0 ? unrenderedSlots.map(
(key) => `<template data-astro-template${key !== "default" ? `="${key}"` : ""}>${children[key]}</template>`
).join("") : "";
island.children = `${html ?? ""}${template}`;
if (island.children) {
island.props["await-children"] = "";
}
async function* renderAll() {
if (slotInstructions) {
yield* slotInstructions;
}
yield { type: "directive", hydration, result };
yield markHTMLString(renderElement("astro-island", island, false));
}
return renderAll();
}
function sanitizeElementName(tag) {
const unsafe = /[&<>'"\s]+/g;
if (!unsafe.test(tag))
return tag;
return tag.trim().split(unsafe)[0].trim();
}
async function renderFragmentComponent(result, slots = {}) {
const children = await renderSlotToString(result, slots == null ? void 0 : slots.default);
if (children == null) {
return children;
}
return markHTMLString(children);
}
async function renderHTMLComponent(result, Component, _props, slots = {}) {
const { slotInstructions, children } = await renderSlots(result, slots);
const html = Component({ slots: children });
const hydrationHtml = slotInstructions ? slotInstructions.map((instr) => stringifyChunk(result, instr)).join("") : "";
return markHTMLString(hydrationHtml + html);
}
function renderComponent(result, displayName, Component, props, slots = {}) {
if (isPromise(Component)) {
return Promise.resolve(Component).then((Unwrapped) => {
return renderComponent(result, displayName, Unwrapped, props, slots);
});
}
if (isFragmentComponent(Component)) {
return renderFragmentComponent(result, slots);
}
if (isHTMLComponent(Component)) {
return renderHTMLComponent(result, Component, props, slots);
}
if (isAstroComponentFactory(Component)) {
return createAstroComponentInstance(result, displayName, Component, props, slots);
}
return renderFrameworkComponent(result, displayName, Component, props, slots);
}
function renderComponentToIterable(result, displayName, Component, props, slots = {}) {
const renderResult = renderComponent(result, displayName, Component, props, slots);
if (isAstroComponentInstance(renderResult)) {
return renderResult.render();
}
return renderResult;
}
export {
renderComponent,
renderComponentToIterable
};

View file

@ -0,0 +1,3 @@
import type { SSRResult } from '../../../@types/astro';
export declare function componentIsHTMLElement(Component: unknown): boolean;
export declare function renderHTMLElement(result: SSRResult, constructor: typeof HTMLElement, props: any, slots: any): Promise<any>;

27
node_modules/astro/dist/runtime/server/render/dom.js generated vendored Normal file
View file

@ -0,0 +1,27 @@
import { markHTMLString } from "../escape.js";
import { renderSlotToString } from "./slot.js";
import { toAttributeString } from "./util.js";
function componentIsHTMLElement(Component) {
return typeof HTMLElement !== "undefined" && HTMLElement.isPrototypeOf(Component);
}
async function renderHTMLElement(result, constructor, props, slots) {
const name = getHTMLElementName(constructor);
let attrHTML = "";
for (const attr in props) {
attrHTML += ` ${attr}="${toAttributeString(await props[attr])}"`;
}
return markHTMLString(
`<${name}${attrHTML}>${await renderSlotToString(result, slots == null ? void 0 : slots.default)}</${name}>`
);
}
function getHTMLElementName(constructor) {
const definedName = customElements.getName(constructor);
if (definedName)
return definedName;
const assignedName = constructor.name.replace(/^HTML|Element$/g, "").replace(/[A-Z]/g, "-$&").toLowerCase().replace(/^-/, "html-");
return assignedName;
}
export {
componentIsHTMLElement,
renderHTMLElement
};

View file

@ -0,0 +1,5 @@
import type { SSRResult } from '../../../@types/astro';
import type { MaybeRenderHeadInstruction, RenderHeadInstruction } from './types';
export declare function renderAllHeadContent(result: SSRResult): any;
export declare function renderHead(): Generator<RenderHeadInstruction>;
export declare function maybeRenderHead(): Generator<MaybeRenderHeadInstruction>;

36
node_modules/astro/dist/runtime/server/render/head.js generated vendored Normal file
View file

@ -0,0 +1,36 @@
import { markHTMLString } from "../escape.js";
import { renderElement } from "./util.js";
const uniqueElements = (item, index, all) => {
const props = JSON.stringify(item.props);
const children = item.children;
return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children);
};
function renderAllHeadContent(result) {
result._metadata.hasRenderedHead = true;
const styles = Array.from(result.styles).filter(uniqueElements).map(
(style) => style.props.rel === "stylesheet" ? renderElement("link", style) : renderElement("style", style)
);
result.styles.clear();
const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => {
return renderElement("script", script, false);
});
const links = Array.from(result.links).filter(uniqueElements).map((link) => renderElement("link", link, false));
let content = links.join("\n") + styles.join("\n") + scripts.join("\n");
if (result._metadata.extraHead.length > 0) {
for (const part of result._metadata.extraHead) {
content += part;
}
}
return markHTMLString(content);
}
function* renderHead() {
yield { type: "head" };
}
function* maybeRenderHead() {
yield { type: "maybe-head" };
}
export {
maybeRenderHead,
renderAllHeadContent,
renderHead
};

View file

@ -0,0 +1,11 @@
export type { AstroComponentFactory, AstroComponentInstance } from './astro/index';
export { createHeadAndContent, renderAstroTemplateResult, renderTemplate, renderToString, } from './astro/index.js';
export { Fragment, Renderer, stringifyChunk } from './common.js';
export { renderComponent, renderComponentToIterable } from './component.js';
export { renderHTMLElement } from './dom.js';
export { maybeRenderHead, renderHead } from './head.js';
export { renderPage } from './page.js';
export { renderSlot, renderSlotToString, type ComponentSlots } from './slot.js';
export { renderScriptElement, renderUniqueStylesheet } from './tags.js';
export type { RenderInstruction } from './types';
export { addAttribute, defineScriptVars, voidElementNames } from './util.js';

36
node_modules/astro/dist/runtime/server/render/index.js generated vendored Normal file
View file

@ -0,0 +1,36 @@
import {
createHeadAndContent,
renderAstroTemplateResult,
renderTemplate,
renderToString
} from "./astro/index.js";
import { Fragment, Renderer, stringifyChunk } from "./common.js";
import { renderComponent, renderComponentToIterable } from "./component.js";
import { renderHTMLElement } from "./dom.js";
import { maybeRenderHead, renderHead } from "./head.js";
import { renderPage } from "./page.js";
import { renderSlot, renderSlotToString } from "./slot.js";
import { renderScriptElement, renderUniqueStylesheet } from "./tags.js";
import { addAttribute, defineScriptVars, voidElementNames } from "./util.js";
export {
Fragment,
Renderer,
addAttribute,
createHeadAndContent,
defineScriptVars,
maybeRenderHead,
renderAstroTemplateResult,
renderComponent,
renderComponentToIterable,
renderHTMLElement,
renderHead,
renderPage,
renderScriptElement,
renderSlot,
renderSlotToString,
renderTemplate,
renderToString,
renderUniqueStylesheet,
stringifyChunk,
voidElementNames
};

View file

@ -0,0 +1,9 @@
import type { RouteData, SSRResult } from '../../../@types/astro';
import type { AstroComponentFactory } from './index';
declare const needsHeadRenderingSymbol: unique symbol;
type NonAstroPageComponent = {
name: string;
[needsHeadRenderingSymbol]: boolean;
};
export declare function renderPage(result: SSRResult, componentFactory: AstroComponentFactory | NonAstroPageComponent, props: any, children: any, streaming: boolean, route?: RouteData | undefined): Promise<Response>;
export {};

168
node_modules/astro/dist/runtime/server/render/page.js generated vendored Normal file
View file

@ -0,0 +1,168 @@
import { AstroError, AstroErrorData } from "../../../core/errors/index.js";
import { isHTMLString } from "../escape.js";
import { createResponse } from "../response.js";
import {
isAstroComponentFactory,
isAstroComponentInstance,
isHeadAndContent,
isRenderTemplateResult,
renderAstroTemplateResult
} from "./astro/index.js";
import { chunkToByteArray, encoder, HTMLParts } from "./common.js";
import { renderComponent } from "./component.js";
import { maybeRenderHead } from "./head.js";
const needsHeadRenderingSymbol = Symbol.for("astro.needsHeadRendering");
function nonAstroPageNeedsHeadInjection(pageComponent) {
return needsHeadRenderingSymbol in pageComponent && !!pageComponent[needsHeadRenderingSymbol];
}
async function iterableToHTMLBytes(result, iterable, onDocTypeInjection) {
const parts = new HTMLParts();
let i = 0;
for await (const chunk of iterable) {
if (isHTMLString(chunk)) {
if (i === 0) {
i++;
if (!/<!doctype html/i.test(String(chunk))) {
parts.append(`${result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n"}`, result);
if (onDocTypeInjection) {
await onDocTypeInjection(parts);
}
}
}
}
parts.append(chunk, result);
}
return parts.toArrayBuffer();
}
async function bufferHeadContent(result) {
const iterator = result._metadata.propagators.values();
while (true) {
const { value, done } = iterator.next();
if (done) {
break;
}
const returnValue = await value.init(result);
if (isHeadAndContent(returnValue)) {
result._metadata.extraHead.push(returnValue.head);
}
}
}
async function renderPage(result, componentFactory, props, children, streaming, route) {
var _a, _b;
if (!isAstroComponentFactory(componentFactory)) {
result._metadata.headInTree = ((_a = result.componentMetadata.get(componentFactory.moduleId)) == null ? void 0 : _a.containsHead) ?? false;
const pageProps = { ...props ?? {}, "server:root": true };
let output;
let head = "";
try {
if (nonAstroPageNeedsHeadInjection(componentFactory)) {
const parts = new HTMLParts();
for await (const chunk of maybeRenderHead()) {
parts.append(chunk, result);
}
head = parts.toString();
}
const renderResult = await renderComponent(
result,
componentFactory.name,
componentFactory,
pageProps,
null
);
if (isAstroComponentInstance(renderResult)) {
output = renderResult.render();
} else {
output = renderResult;
}
} catch (e) {
if (AstroError.is(e) && !e.loc) {
e.setLocation({
file: route == null ? void 0 : route.component
});
}
throw e;
}
const bytes = await iterableToHTMLBytes(result, output, async (parts) => {
parts.append(head, result);
});
return new Response(bytes, {
headers: new Headers([
["Content-Type", "text/html; charset=utf-8"],
["Content-Length", bytes.byteLength.toString()]
])
});
}
result._metadata.headInTree = ((_b = result.componentMetadata.get(componentFactory.moduleId)) == null ? void 0 : _b.containsHead) ?? false;
const factoryReturnValue = await componentFactory(result, props, children);
const factoryIsHeadAndContent = isHeadAndContent(factoryReturnValue);
if (isRenderTemplateResult(factoryReturnValue) || factoryIsHeadAndContent) {
await bufferHeadContent(result);
const templateResult = factoryIsHeadAndContent ? factoryReturnValue.content : factoryReturnValue;
let iterable = renderAstroTemplateResult(templateResult);
let init = result.response;
let headers = new Headers(init.headers);
let body;
if (streaming) {
body = new ReadableStream({
start(controller) {
async function read() {
let i = 0;
try {
for await (const chunk of iterable) {
if (isHTMLString(chunk)) {
if (i === 0) {
if (!/<!doctype html/i.test(String(chunk))) {
controller.enqueue(
encoder.encode(
`${result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n"}`
)
);
}
}
}
if (chunk instanceof Response) {
throw new AstroError({
...AstroErrorData.ResponseSentError
});
}
const bytes = chunkToByteArray(result, chunk);
controller.enqueue(bytes);
i++;
}
controller.close();
} catch (e) {
if (AstroError.is(e) && !e.loc) {
e.setLocation({
file: route == null ? void 0 : route.component
});
}
controller.error(e);
}
}
read();
}
});
} else {
body = await iterableToHTMLBytes(result, iterable);
headers.set("Content-Length", body.byteLength.toString());
}
let response = createResponse(body, { ...init, headers });
return response;
}
if (!(factoryReturnValue instanceof Response)) {
throw new AstroError({
...AstroErrorData.OnlyResponseCanBeReturned,
message: AstroErrorData.OnlyResponseCanBeReturned.message(
route == null ? void 0 : route.route,
typeof factoryReturnValue
),
location: {
file: route == null ? void 0 : route.component
}
});
}
return factoryReturnValue;
}
export {
renderPage
};

View file

@ -0,0 +1,22 @@
import type { SSRResult } from '../../../@types/astro.js';
import type { renderTemplate } from './astro/render-template.js';
import type { RenderInstruction } from './types.js';
import { HTMLString } from '../escape.js';
type RenderTemplateResult = ReturnType<typeof renderTemplate>;
export type ComponentSlots = Record<string, ComponentSlotValue>;
export type ComponentSlotValue = (result: SSRResult) => RenderTemplateResult | Promise<RenderTemplateResult>;
declare const slotString: unique symbol;
export declare class SlotString extends HTMLString {
instructions: null | RenderInstruction[];
[slotString]: boolean;
constructor(content: string, instructions: null | RenderInstruction[]);
}
export declare function isSlotString(str: string): str is any;
export declare function renderSlot(result: SSRResult, slotted: ComponentSlotValue | RenderTemplateResult, fallback?: ComponentSlotValue | RenderTemplateResult): AsyncGenerator<any, void, undefined>;
export declare function renderSlotToString(result: SSRResult, slotted: ComponentSlotValue | RenderTemplateResult, fallback?: ComponentSlotValue | RenderTemplateResult): Promise<string>;
interface RenderSlotsResult {
slotInstructions: null | RenderInstruction[];
children: Record<string, string>;
}
export declare function renderSlots(result: SSRResult, slots?: ComponentSlots): Promise<RenderSlotsResult>;
export {};

66
node_modules/astro/dist/runtime/server/render/slot.js generated vendored Normal file
View file

@ -0,0 +1,66 @@
import { HTMLString, markHTMLString } from "../escape.js";
import { renderChild } from "./any.js";
const slotString = Symbol.for("astro:slot-string");
class SlotString extends HTMLString {
constructor(content, instructions) {
super(content);
this.instructions = instructions;
this[slotString] = true;
}
}
slotString;
function isSlotString(str) {
return !!str[slotString];
}
async function* renderSlot(result, slotted, fallback) {
if (slotted) {
let iterator = renderChild(typeof slotted === "function" ? slotted(result) : slotted);
yield* iterator;
}
if (fallback && !slotted) {
yield* renderSlot(result, fallback);
}
}
async function renderSlotToString(result, slotted, fallback) {
let content = "";
let instructions = null;
let iterator = renderSlot(result, slotted, fallback);
for await (const chunk of iterator) {
if (typeof chunk.type === "string") {
if (instructions === null) {
instructions = [];
}
instructions.push(chunk);
} else {
content += chunk;
}
}
return markHTMLString(new SlotString(content, instructions));
}
async function renderSlots(result, slots = {}) {
let slotInstructions = null;
let children = {};
if (slots) {
await Promise.all(
Object.entries(slots).map(
([key, value]) => renderSlotToString(result, value).then((output) => {
if (output.instructions) {
if (slotInstructions === null) {
slotInstructions = [];
}
slotInstructions.push(...output.instructions);
}
children[key] = output;
})
)
);
}
return { slotInstructions, children };
}
export {
SlotString,
isSlotString,
renderSlot,
renderSlotToString,
renderSlots
};

View file

@ -0,0 +1,4 @@
import type { SSRElement, SSRResult } from '../../../@types/astro';
import type { StylesheetAsset } from '../../../core/app/types';
export declare function renderScriptElement({ props, children }: SSRElement): string;
export declare function renderUniqueStylesheet(result: SSRResult, sheet: StylesheetAsset): string | undefined;

23
node_modules/astro/dist/runtime/server/render/tags.js generated vendored Normal file
View file

@ -0,0 +1,23 @@
import { renderElement } from "./util.js";
function renderScriptElement({ props, children }) {
return renderElement("script", {
props,
children
});
}
function renderUniqueStylesheet(result, sheet) {
if (sheet.type === "external") {
if (Array.from(result.styles).some((s) => s.props.href === sheet.src))
return "";
return renderElement("link", { props: { rel: "stylesheet", href: sheet.src }, children: "" });
}
if (sheet.type === "inline") {
if (Array.from(result.styles).some((s) => s.children.includes(sheet.content)))
return "";
return renderElement("style", { props: { type: "text/css" }, children: sheet.content });
}
}
export {
renderScriptElement,
renderUniqueStylesheet
};

View file

@ -0,0 +1,12 @@
import type { HydrationMetadata } from '../hydration.js';
export type RenderDirectiveInstruction = {
type: 'directive';
hydration: HydrationMetadata;
};
export type RenderHeadInstruction = {
type: 'head';
};
export type MaybeRenderHeadInstruction = {
type: 'maybe-head';
};
export type RenderInstruction = RenderDirectiveInstruction | RenderHeadInstruction | MaybeRenderHeadInstruction;

View file

View file

@ -0,0 +1,26 @@
import type { SSRElement } from '../../../@types/astro';
export declare const voidElementNames: RegExp;
export declare const toAttributeString: (value: any, shouldEscape?: boolean) => any;
export declare function defineScriptVars(vars: Record<any, any>): any;
export declare function formatList(values: string[]): string;
export declare function addAttribute(value: any, key: string, shouldEscape?: boolean): any;
export declare function internalSpreadAttributes(values: Record<any, any>, shouldEscape?: boolean): any;
export declare function renderElement(name: string, { props: _props, children }: SSRElement, shouldEscape?: boolean): string;
/**
* This will take an array of async iterables and start buffering them eagerly.
* To avoid useless buffering, it will only start buffering the next tick, so the
* first sync iterables won't be buffered.
*/
export declare function bufferIterators<T>(iterators: AsyncIterable<T>[]): AsyncIterable<T>[];
export declare class EagerAsyncIterableIterator {
#private;
constructor(iterable: AsyncIterable<any>);
/**
* Starts to eagerly fetch the inner iterator and cache the results.
* Note: This might not be called after next() has been called once, e.g. the iterator is started
*/
buffer(): Promise<void>;
next(): Promise<IteratorResult<any, any>>;
isStarted(): boolean;
[Symbol.asyncIterator](): this;
}

215
node_modules/astro/dist/runtime/server/render/util.js generated vendored Normal file
View file

@ -0,0 +1,215 @@
import { HTMLString, markHTMLString } from "../escape.js";
import { serializeListValue } from "../util.js";
const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
const htmlBooleanAttributes = /^(allowfullscreen|async|autofocus|autoplay|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|itemscope)$/i;
const htmlEnumAttributes = /^(contenteditable|draggable|spellcheck|value)$/i;
const svgEnumAttributes = /^(autoReverse|externalResourcesRequired|focusable|preserveAlpha)$/i;
const STATIC_DIRECTIVES = /* @__PURE__ */ new Set(["set:html", "set:text"]);
const toIdent = (k) => k.trim().replace(/(?:(?!^)\b\w|\s+|[^\w]+)/g, (match, index) => {
if (/[^\w]|\s/.test(match))
return "";
return index === 0 ? match : match.toUpperCase();
});
const toAttributeString = (value, shouldEscape = true) => shouldEscape ? String(value).replace(/&/g, "&#38;").replace(/"/g, "&#34;") : value;
const kebab = (k) => k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
const toStyleString = (obj) => Object.entries(obj).map(([k, v]) => {
if (k[0] !== "-" && k[1] !== "-")
return `${kebab(k)}:${v}`;
if (kebab(k) !== k)
return `${kebab(k)}:var(${k});${k}:${v}`;
return `${k}:${v}`;
}).join(";");
function defineScriptVars(vars) {
var _a;
let output = "";
for (const [key, value] of Object.entries(vars)) {
output += `const ${toIdent(key)} = ${(_a = JSON.stringify(value)) == null ? void 0 : _a.replace(
/<\/script>/g,
"\\x3C/script>"
)};
`;
}
return markHTMLString(output);
}
function formatList(values) {
if (values.length === 1) {
return values[0];
}
return `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`;
}
function addAttribute(value, key, shouldEscape = true) {
if (value == null) {
return "";
}
if (value === false) {
if (htmlEnumAttributes.test(key) || svgEnumAttributes.test(key)) {
return markHTMLString(` ${key}="false"`);
}
return "";
}
if (STATIC_DIRECTIVES.has(key)) {
console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute.
Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`);
return "";
}
if (key === "class:list") {
const listValue = toAttributeString(serializeListValue(value), shouldEscape);
if (listValue === "") {
return "";
}
return markHTMLString(` ${key.slice(0, -5)}="${listValue}"`);
}
if (key === "style" && !(value instanceof HTMLString)) {
if (Array.isArray(value) && value.length === 2) {
return markHTMLString(
` ${key}="${toAttributeString(`${toStyleString(value[0])};${value[1]}`, shouldEscape)}"`
);
}
if (typeof value === "object") {
return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`);
}
}
if (key === "className") {
return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`);
}
if (value === true && (key.startsWith("data-") || htmlBooleanAttributes.test(key))) {
return markHTMLString(` ${key}`);
} else {
return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
}
}
function internalSpreadAttributes(values, shouldEscape = true) {
let output = "";
for (const [key, value] of Object.entries(values)) {
output += addAttribute(value, key, shouldEscape);
}
return markHTMLString(output);
}
function renderElement(name, { props: _props, children = "" }, shouldEscape = true) {
const { lang: _, "data-astro-id": astroId, "define:vars": defineVars, ...props } = _props;
if (defineVars) {
if (name === "style") {
delete props["is:global"];
delete props["is:scoped"];
}
if (name === "script") {
delete props.hoist;
children = defineScriptVars(defineVars) + "\n" + children;
}
}
if ((children == null || children == "") && voidElementNames.test(name)) {
return `<${name}${internalSpreadAttributes(props, shouldEscape)} />`;
}
return `<${name}${internalSpreadAttributes(props, shouldEscape)}>${children}</${name}>`;
}
const iteratorQueue = [];
function queueIteratorBuffers(iterators) {
if (iteratorQueue.length === 0) {
setTimeout(() => {
iteratorQueue.forEach((its) => its.forEach((it) => !it.isStarted() && it.buffer()));
iteratorQueue.length = 0;
});
}
iteratorQueue.push(iterators);
}
function bufferIterators(iterators) {
const eagerIterators = iterators.map((it) => new EagerAsyncIterableIterator(it));
queueIteratorBuffers(eagerIterators);
return eagerIterators;
}
class EagerAsyncIterableIterator {
#iterable;
#queue = new Queue();
#error = void 0;
#next;
/**
* Whether the proxy is running in buffering or pass-through mode
*/
#isBuffering = false;
#gen = void 0;
#isStarted = false;
constructor(iterable) {
this.#iterable = iterable;
}
/**
* Starts to eagerly fetch the inner iterator and cache the results.
* Note: This might not be called after next() has been called once, e.g. the iterator is started
*/
async buffer() {
if (this.#gen) {
throw new Error("Cannot not switch from non-buffer to buffer mode");
}
this.#isBuffering = true;
this.#isStarted = true;
this.#gen = this.#iterable[Symbol.asyncIterator]();
let value = void 0;
do {
this.#next = this.#gen.next();
try {
value = await this.#next;
this.#queue.push(value);
} catch (e) {
this.#error = e;
}
} while (value && !value.done);
}
async next() {
if (this.#error) {
throw this.#error;
}
if (!this.#isBuffering) {
if (!this.#gen) {
this.#isStarted = true;
this.#gen = this.#iterable[Symbol.asyncIterator]();
}
return await this.#gen.next();
}
if (!this.#queue.isEmpty()) {
return this.#queue.shift();
}
await this.#next;
return this.#queue.shift();
}
isStarted() {
return this.#isStarted;
}
[Symbol.asyncIterator]() {
return this;
}
}
class Queue {
constructor() {
this.head = void 0;
this.tail = void 0;
}
push(item) {
if (this.head === void 0) {
this.head = { item };
this.tail = this.head;
} else {
this.tail.next = { item };
this.tail = this.tail.next;
}
}
isEmpty() {
return this.head === void 0;
}
shift() {
var _a, _b;
const val = (_a = this.head) == null ? void 0 : _a.item;
this.head = (_b = this.head) == null ? void 0 : _b.next;
return val;
}
}
export {
EagerAsyncIterableIterator,
addAttribute,
bufferIterators,
defineScriptVars,
formatList,
internalSpreadAttributes,
renderElement,
toAttributeString,
voidElementNames
};

3
node_modules/astro/dist/runtime/server/response.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
type CreateResponseFn = (body?: BodyInit | null, init?: ResponseInit) => Response;
export declare const createResponse: CreateResponseFn;
export {};

69
node_modules/astro/dist/runtime/server/response.js generated vendored Normal file
View file

@ -0,0 +1,69 @@
import { streamAsyncIterator } from "./util.js";
const isNodeJS = typeof process === "object" && Object.prototype.toString.call(process) === "[object process]";
let StreamingCompatibleResponse;
function createResponseClass() {
StreamingCompatibleResponse = class extends Response {
#isStream;
#body;
constructor(body, init) {
let isStream = body instanceof ReadableStream;
super(isStream ? null : body, init);
this.#isStream = isStream;
this.#body = body;
}
get body() {
return this.#body;
}
async text() {
if (this.#isStream && isNodeJS) {
let decoder = new TextDecoder();
let body = this.#body;
let out = "";
for await (let chunk of streamAsyncIterator(body)) {
out += decoder.decode(chunk);
}
return out;
}
return super.text();
}
async arrayBuffer() {
if (this.#isStream && isNodeJS) {
let body = this.#body;
let chunks = [];
let len = 0;
for await (let chunk of streamAsyncIterator(body)) {
chunks.push(chunk);
len += chunk.length;
}
let ab = new Uint8Array(len);
let offset = 0;
for (const chunk of chunks) {
ab.set(chunk, offset);
offset += chunk.length;
}
return ab;
}
return super.arrayBuffer();
}
clone() {
return new StreamingCompatibleResponse(this.#body, {
status: this.status,
statusText: this.statusText,
headers: this.headers
});
}
};
return StreamingCompatibleResponse;
}
const createResponse = isNodeJS ? (body, init) => {
if (typeof body === "string" || ArrayBuffer.isView(body)) {
return new Response(body, init);
}
if (typeof StreamingCompatibleResponse === "undefined") {
return new (createResponseClass())(body, init);
}
return new StreamingCompatibleResponse(body, init);
} : (body, init) => new Response(body, init);
export {
createResponse
};

5
node_modules/astro/dist/runtime/server/scripts.d.ts generated vendored Normal file
View file

@ -0,0 +1,5 @@
import type { SSRResult } from '../../@types/astro';
export declare function determineIfNeedsHydrationScript(result: SSRResult): boolean;
export declare function determinesIfNeedsDirectiveScript(result: SSRResult, directive: string): boolean;
export type PrescriptType = null | 'both' | 'directive';
export declare function getPrescripts(result: SSRResult, type: PrescriptType, directive: string): string;

40
node_modules/astro/dist/runtime/server/scripts.js generated vendored Normal file
View file

@ -0,0 +1,40 @@
import islandScript from "./astro-island.prebuilt.js";
const ISLAND_STYLES = `<style>astro-island,astro-slot,astro-static-slot{display:contents}</style>`;
function determineIfNeedsHydrationScript(result) {
if (result._metadata.hasHydrationScript) {
return false;
}
return result._metadata.hasHydrationScript = true;
}
function determinesIfNeedsDirectiveScript(result, directive) {
if (result._metadata.hasDirectives.has(directive)) {
return false;
}
result._metadata.hasDirectives.add(directive);
return true;
}
function getDirectiveScriptText(result, directive) {
const clientDirectives = result.clientDirectives;
const clientDirective = clientDirectives.get(directive);
if (!clientDirective) {
throw new Error(`Unknown directive: ${directive}`);
}
return clientDirective;
}
function getPrescripts(result, type, directive) {
switch (type) {
case "both":
return `${ISLAND_STYLES}<script>${getDirectiveScriptText(
result,
directive
)};${islandScript}</script>`;
case "directive":
return `<script>${getDirectiveScriptText(result, directive)}</script>`;
}
return "";
}
export {
determineIfNeedsHydrationScript,
determinesIfNeedsDirectiveScript,
getPrescripts
};

View file

@ -0,0 +1,2 @@
import type { AstroComponentMetadata } from '../../@types/astro';
export declare function serializeProps(props: any, metadata: AstroComponentMetadata): string;

98
node_modules/astro/dist/runtime/server/serialize.js generated vendored Normal file
View file

@ -0,0 +1,98 @@
const PROP_TYPE = {
Value: 0,
JSON: 1,
RegExp: 2,
Date: 3,
Map: 4,
Set: 5,
BigInt: 6,
URL: 7,
Uint8Array: 8,
Uint16Array: 9,
Uint32Array: 10
};
function serializeArray(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
if (parents.has(value)) {
throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
}
parents.add(value);
const serialized = value.map((v) => {
return convertToSerializedForm(v, metadata, parents);
});
parents.delete(value);
return serialized;
}
function serializeObject(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
if (parents.has(value)) {
throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
}
parents.add(value);
const serialized = Object.fromEntries(
Object.entries(value).map(([k, v]) => {
return [k, convertToSerializedForm(v, metadata, parents)];
})
);
parents.delete(value);
return serialized;
}
function convertToSerializedForm(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
const tag = Object.prototype.toString.call(value);
switch (tag) {
case "[object Date]": {
return [PROP_TYPE.Date, value.toISOString()];
}
case "[object RegExp]": {
return [PROP_TYPE.RegExp, value.source];
}
case "[object Map]": {
return [
PROP_TYPE.Map,
JSON.stringify(serializeArray(Array.from(value), metadata, parents))
];
}
case "[object Set]": {
return [
PROP_TYPE.Set,
JSON.stringify(serializeArray(Array.from(value), metadata, parents))
];
}
case "[object BigInt]": {
return [PROP_TYPE.BigInt, value.toString()];
}
case "[object URL]": {
return [PROP_TYPE.URL, value.toString()];
}
case "[object Array]": {
return [PROP_TYPE.JSON, JSON.stringify(serializeArray(value, metadata, parents))];
}
case "[object Uint8Array]": {
return [PROP_TYPE.Uint8Array, JSON.stringify(Array.from(value))];
}
case "[object Uint16Array]": {
return [PROP_TYPE.Uint16Array, JSON.stringify(Array.from(value))];
}
case "[object Uint32Array]": {
return [PROP_TYPE.Uint32Array, JSON.stringify(Array.from(value))];
}
default: {
if (value !== null && typeof value === "object") {
return [PROP_TYPE.Value, serializeObject(value, metadata, parents)];
} else if (value === void 0) {
return [PROP_TYPE.Value];
} else {
return [PROP_TYPE.Value, value];
}
}
}
}
function serializeProps(props, metadata) {
const serialized = JSON.stringify(serializeObject(props, metadata));
return serialized;
}
export {
serializeProps
};

31
node_modules/astro/dist/runtime/server/shorthash.d.ts generated vendored Normal file
View file

@ -0,0 +1,31 @@
/**
* shortdash - https://github.com/bibig/node-shorthash
*
* @license
*
* (The MIT License)
*
* Copyright (c) 2013 Bibig <bibig@me.com>
*
* 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.
*/
export declare function shorthash(text: string): string;

62
node_modules/astro/dist/runtime/server/shorthash.js generated vendored Normal file
View file

@ -0,0 +1,62 @@
/**
* shortdash - https://github.com/bibig/node-shorthash
*
* @license
*
* (The MIT License)
*
* Copyright (c) 2013 Bibig <bibig@me.com>
*
* 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.
*/
const dictionary = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY";
const binary = dictionary.length;
function bitwise(str) {
let hash = 0;
if (str.length === 0)
return hash;
for (let i = 0; i < str.length; i++) {
const ch = str.charCodeAt(i);
hash = (hash << 5) - hash + ch;
hash = hash & hash;
}
return hash;
}
function shorthash(text) {
let num;
let result = "";
let integer = bitwise(text);
const sign = integer < 0 ? "Z" : "";
integer = Math.abs(integer);
while (integer >= binary) {
num = integer % binary;
integer = Math.floor(integer / binary);
result = dictionary[num] + result;
}
if (integer > 0) {
result = dictionary[integer] + result;
}
return sign + result;
}
export {
shorthash
};

3
node_modules/astro/dist/runtime/server/util.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
export declare function serializeListValue(value: any): string;
export declare function isPromise<T = any>(value: any): value is Promise<T>;
export declare function streamAsyncIterator(stream: ReadableStream): AsyncGenerator<any, void, unknown>;

43
node_modules/astro/dist/runtime/server/util.js generated vendored Normal file
View file

@ -0,0 +1,43 @@
function serializeListValue(value) {
const hash = {};
push(value);
return Object.keys(hash).join(" ");
function push(item) {
if (item && typeof item.forEach === "function")
item.forEach(push);
else if (item === Object(item))
Object.keys(item).forEach((name) => {
if (item[name])
push(name);
});
else {
item = item === false || item == null ? "" : String(item).trim();
if (item) {
item.split(/\s+/).forEach((name) => {
hash[name] = true;
});
}
}
}
}
function isPromise(value) {
return !!value && typeof value === "object" && typeof value.then === "function";
}
async function* streamAsyncIterator(stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done)
return;
yield value;
}
} finally {
reader.releaseLock();
}
}
export {
isPromise,
serializeListValue,
streamAsyncIterator
};