repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/Array2DRenderer/index.js
src/core/renderers/Array2DRenderer/index.js
import React from 'react'; import { Array1DRenderer, Renderer } from 'core/renderers'; import styles from './Array2DRenderer.module.scss'; import { classes } from 'common/util'; class Array2DRenderer extends Renderer { constructor(props) { super(props); this.togglePan(true); this.toggleZoom(true); } renderData() { const { data } = this.props.data; const isArray1D = this instanceof Array1DRenderer; let longestRow = data.reduce((longestRow, row) => longestRow.length < row.length ? row : longestRow, []); return ( <table className={styles.array_2d} style={{ marginLeft: -this.centerX * 2, marginTop: -this.centerY * 2, transform: `scale(${this.zoom})` }}> <tbody> <tr className={styles.row}> { !isArray1D && <td className={classes(styles.col, styles.index)} /> } { longestRow.map((_, i) => ( <td className={classes(styles.col, styles.index)} key={i}> <span className={styles.value}>{i}</span> </td> )) } </tr> { data.map((row, i) => ( <tr className={styles.row} key={i}> { !isArray1D && <td className={classes(styles.col, styles.index)}> <span className={styles.value}>{i}</span> </td> } { row.map((col, j) => ( <td className={classes(styles.col, col.selected && styles.selected, col.patched && styles.patched)} key={j}> <span className={styles.value}>{this.toString(col.value)}</span> </td> )) } </tr> )) } </tbody> </table> ); } } export default Array2DRenderer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/GraphRenderer/index.js
src/core/renderers/GraphRenderer/index.js
import React from 'react'; import { Renderer } from 'core/renderers'; import { classes, distance } from 'common/util'; import styles from './GraphRenderer.module.scss'; class GraphRenderer extends Renderer { constructor(props) { super(props); this.elementRef = React.createRef(); this.selectedNode = null; this.togglePan(true); this.toggleZoom(true); } handleMouseDown(e) { super.handleMouseDown(e); const coords = this.computeCoords(e); const { nodes, dimensions } = this.props.data; const { nodeRadius } = dimensions; this.selectedNode = nodes.find(node => distance(coords, node) <= nodeRadius); } handleMouseMove(e) { if (this.selectedNode) { const { x, y } = this.computeCoords(e); const node = this.props.data.findNode(this.selectedNode.id); node.x = x; node.y = y; this.refresh(); } else { super.handleMouseMove(e); } } computeCoords(e) { const svg = this.elementRef.current; const s = svg.createSVGPoint(); s.x = e.clientX; s.y = e.clientY; const { x, y } = s.matrixTransform(svg.getScreenCTM().inverse()); return { x, y }; } renderData() { const { nodes, edges, isDirected, isWeighted, dimensions } = this.props.data; const { baseWidth, baseHeight, nodeRadius, arrowGap, nodeWeightGap, edgeWeightGap } = dimensions; const viewBox = [ (this.centerX - baseWidth / 2) * this.zoom, (this.centerY - baseHeight / 2) * this.zoom, baseWidth * this.zoom, baseHeight * this.zoom, ]; return ( <svg className={styles.graph} viewBox={viewBox} ref={this.elementRef}> <defs> <marker id="markerArrow" markerWidth="4" markerHeight="4" refX="2" refY="2" orient="auto"> <path d="M0,0 L0,4 L4,2 L0,0" className={styles.arrow} /> </marker> <marker id="markerArrowSelected" markerWidth="4" markerHeight="4" refX="2" refY="2" orient="auto"> <path d="M0,0 L0,4 L4,2 L0,0" className={classes(styles.arrow, styles.selected)} /> </marker> <marker id="markerArrowVisited" markerWidth="4" markerHeight="4" refX="2" refY="2" orient="auto"> <path d="M0,0 L0,4 L4,2 L0,0" className={classes(styles.arrow, styles.visited)} /> </marker> </defs> { edges.sort((a, b) => a.visitedCount - b.visitedCount).map(edge => { const { source, target, weight, visitedCount, selectedCount } = edge; const sourceNode = this.props.data.findNode(source); const targetNode = this.props.data.findNode(target); if (!sourceNode || !targetNode) return undefined; const { x: sx, y: sy } = sourceNode; let { x: ex, y: ey } = targetNode; const mx = (sx + ex) / 2; const my = (sy + ey) / 2; const dx = ex - sx; const dy = ey - sy; const degree = Math.atan2(dy, dx) / Math.PI * 180; if (isDirected) { const length = Math.sqrt(dx * dx + dy * dy); if (length !== 0) { ex = sx + dx / length * (length - nodeRadius - arrowGap); ey = sy + dy / length * (length - nodeRadius - arrowGap); } } return ( <g className={classes(styles.edge, selectedCount && styles.selected, visitedCount && styles.visited)} key={`${source}-${target}`}> <path d={`M${sx},${sy} L${ex},${ey}`} className={classes(styles.line, isDirected && styles.directed)} /> { isWeighted && <g transform={`translate(${mx},${my})`}> <text className={styles.weight} transform={`rotate(${degree})`} y={-edgeWeightGap}>{this.toString(weight)}</text> </g> } </g> ); }) } { nodes.map(node => { const { id, x, y, weight, visitedCount, selectedCount } = node; return ( <g className={classes(styles.node, selectedCount && styles.selected, visitedCount && styles.visited)} key={id} transform={`translate(${x},${y})`}> <circle className={styles.circle} r={nodeRadius} /> <text className={styles.id}>{id}</text> { isWeighted && <text className={styles.weight} x={nodeRadius + nodeWeightGap}>{this.toString(weight)}</text> } </g> ); }) } </svg> ); } } export default GraphRenderer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/Array1DRenderer/index.js
src/core/renderers/Array1DRenderer/index.js
import { Array2DRenderer } from 'core/renderers'; class Array1DRenderer extends Array2DRenderer { } export default Array1DRenderer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/MarkdownRenderer/index.js
src/core/renderers/MarkdownRenderer/index.js
import React from 'react'; import { Renderer } from 'core/renderers'; import styles from './MarkdownRenderer.module.scss'; import ReactMarkdown from 'react-markdown'; class MarkdownRenderer extends Renderer { renderData() { const { markdown } = this.props.data; const heading = ({ level, children, ...rest }) => { const HeadingComponent = [ props => <h1 {...props} />, props => <h2 {...props} />, props => <h3 {...props} />, props => <h4 {...props} />, props => <h5 {...props} />, props => <h6 {...props} />, ][level - 1]; const idfy = text => text.toLowerCase().trim().replace(/[^\w \-]/g, '').replace(/ /g, '-'); const getText = children => { return React.Children.map(children, child => { if (!child) return ''; if (typeof child === 'string') return child; if ('props' in child) return getText(child.props.children); return ''; }).join(''); }; const id = idfy(getText(children)); return ( <HeadingComponent id={id} {...rest}> {children} </HeadingComponent> ); }; const link = ({ href, ...rest }) => { return /^#/.test(href) ? ( <a href={href} {...rest} /> ) : ( <a href={href} rel="noopener" target="_blank" {...rest} /> ); }; const image = ({ src, ...rest }) => { let newSrc = src; let style = { maxWidth: '100%' }; const CODECOGS = 'https://latex.codecogs.com/svg.latex?'; const WIKIMEDIA_IMAGE = 'https://upload.wikimedia.org/wikipedia/'; const WIKIMEDIA_MATH = 'https://wikimedia.org/api/rest_v1/media/math/render/svg/'; if (src.startsWith(CODECOGS)) { const latex = src.substring(CODECOGS.length); newSrc = `${CODECOGS}\\color{White}${latex}`; } else if (src.startsWith(WIKIMEDIA_IMAGE)) { style.backgroundColor = 'white'; } else if (src.startsWith(WIKIMEDIA_MATH)) { style.filter = 'invert(100%)'; } return <img src={newSrc} style={style} {...rest} />; }; return ( <div className={styles.markdown}> <ReactMarkdown className={styles.content} source={markdown} renderers={{ heading, link, image }} escapeHtml={false}/> </div> ); } } export default MarkdownRenderer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/LogRenderer/index.js
src/core/renderers/LogRenderer/index.js
import React from 'react'; import { Renderer } from 'core/renderers'; import styles from './LogRenderer.module.scss'; class LogRenderer extends Renderer { constructor(props) { super(props); this.elementRef = React.createRef(); } componentDidUpdate(prevProps, prevState, snapshot) { super.componentDidUpdate(prevProps, prevState, snapshot); const div = this.elementRef.current; div.scrollTop = div.scrollHeight; } renderData() { const { log } = this.props.data; return ( <div className={styles.log} ref={this.elementRef}> <div className={styles.content} dangerouslySetInnerHTML={{ __html: log }} /> </div> ); } } export default LogRenderer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/ScatterRenderer/index.js
src/core/renderers/ScatterRenderer/index.js
import React from 'react' import {Scatter} from 'react-chartjs-2' import Array2DRenderer from '../Array2DRenderer' const convertToObjectArray = ([x, y]) => ({ x, y }) const colors = ['white', 'green', 'blue', 'red', 'yellow', 'cyan'] class ScatterRenderer extends Array2DRenderer { renderData() { const { data } = this.props.data const datasets = data.map((series, index) => ( { backgroundColor: colors[index], data: series.map(s => convertToObjectArray(s.value)), label: Math.random(), radius: (index + 1) * 2, })) const chartData = { datasets, } return <Scatter data={chartData} options={{ legend: false, animation: false, layout: { padding: { left: 20, right: 20, top: 20, bottom: 20, }, }, scales: { yAxes: [ { ticks: { beginAtZero: false, }, }], xAxes: [ { ticks: { beginAtZero: false, }, }], }, }}/> } } export default ScatterRenderer
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/ChartTracer.js
src/core/tracers/ChartTracer.js
import { Array1DTracer } from 'core/tracers'; import { ChartRenderer } from 'core/renderers'; class ChartTracer extends Array1DTracer { getRendererClass() { return ChartRenderer; } } export default ChartTracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/Tracer.jsx
src/core/tracers/Tracer.jsx
import React from 'react'; import { Renderer } from 'core/renderers'; class Tracer { constructor(key, getObject, title) { this.key = key; this.getObject = getObject; this.title = title; this.init(); this.reset(); } getRendererClass() { return Renderer; } init() { } render() { const RendererClass = this.getRendererClass(); return ( <RendererClass key={this.key} title={this.title} data={this} /> ); } set() { } reset() { this.set(); } } export default Tracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/ScatterTracer.js
src/core/tracers/ScatterTracer.js
import { Array2DTracer } from 'core/tracers'; import { ScatterRenderer } from 'core/renderers'; class ScatterTracer extends Array2DTracer { getRendererClass() { return ScatterRenderer; } } export default ScatterTracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/index.js
src/core/tracers/index.js
export { default as Tracer } from './Tracer'; export { default as MarkdownTracer } from './MarkdownTracer'; export { default as LogTracer } from './LogTracer'; export { default as Array2DTracer } from './Array2DTracer'; export { default as Array1DTracer } from './Array1DTracer'; export { default as ChartTracer } from './ChartTracer'; export { default as GraphTracer } from './GraphTracer'; export { default as ScatterTracer} from './ScatterTracer';
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/Array2DTracer.js
src/core/tracers/Array2DTracer.js
import { Tracer } from 'core/tracers'; import { Array2DRenderer } from 'core/renderers'; class Element { constructor(value) { this.value = value; this.patched = false; this.selected = false; } } class Array2DTracer extends Tracer { getRendererClass() { return Array2DRenderer; } set(array2d = []) { this.data = array2d.map(array1d => [...array1d].map(value => new Element(value))); super.set(); } patch(x, y, v = this.data[x][y].value) { if (!this.data[x][y]) this.data[x][y] = new Element(); this.data[x][y].value = v; this.data[x][y].patched = true; } depatch(x, y) { this.data[x][y].patched = false; } select(sx, sy, ex = sx, ey = sy) { for (let x = sx; x <= ex; x++) { for (let y = sy; y <= ey; y++) { this.data[x][y].selected = true; } } } selectRow(x, sy, ey) { this.select(x, sy, x, ey); } selectCol(y, sx, ex) { this.select(sx, y, ex, y); } deselect(sx, sy, ex = sx, ey = sy) { for (let x = sx; x <= ex; x++) { for (let y = sy; y <= ey; y++) { this.data[x][y].selected = false; } } } deselectRow(x, sy, ey) { this.deselect(x, sy, x, ey); } deselectCol(y, sx, ex) { this.deselect(sx, y, ex, y); } } export default Array2DTracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/Array1DTracer.js
src/core/tracers/Array1DTracer.js
import { Array2DTracer } from 'core/tracers'; import { Array1DRenderer } from 'core/renderers'; class Array1DTracer extends Array2DTracer { getRendererClass() { return Array1DRenderer; } init() { super.init(); this.chartTracer = null; } set(array1d = []) { const array2d = [array1d]; super.set(array2d); this.syncChartTracer(); } patch(x, v) { super.patch(0, x, v); } depatch(x) { super.depatch(0, x); } select(sx, ex = sx) { super.select(0, sx, 0, ex); } deselect(sx, ex = sx) { super.deselect(0, sx, 0, ex); } chart(key) { this.chartTracer = key ? this.getObject(key) : null; this.syncChartTracer(); } syncChartTracer() { if (this.chartTracer) this.chartTracer.data = this.data; } } export default Array1DTracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/GraphTracer.js
src/core/tracers/GraphTracer.js
import { Tracer } from 'core/tracers'; import { distance } from 'common/util'; import { GraphRenderer } from 'core/renderers'; class GraphTracer extends Tracer { getRendererClass() { return GraphRenderer; } init() { super.init(); this.dimensions = { baseWidth: 320, baseHeight: 320, padding: 32, nodeRadius: 12, arrowGap: 4, nodeWeightGap: 4, edgeWeightGap: 4, }; this.isDirected = true; this.isWeighted = false; this.callLayout = { method: this.layoutCircle, args: [] }; this.logTracer = null; } set(array2d = []) { this.nodes = []; this.edges = []; for (let i = 0; i < array2d.length; i++) { this.addNode(i); for (let j = 0; j < array2d.length; j++) { const value = array2d[i][j]; if (value) { this.addEdge(i, j, this.isWeighted ? value : null); } } } this.layout(); super.set(); } directed(isDirected = true) { this.isDirected = isDirected; } weighted(isWeighted = true) { this.isWeighted = isWeighted; } addNode(id, weight = null, x = 0, y = 0, visitedCount = 0, selectedCount = 0) { if (this.findNode(id)) return; this.nodes.push({ id, weight, x, y, visitedCount, selectedCount }); this.layout(); } updateNode(id, weight, x, y, visitedCount, selectedCount) { const node = this.findNode(id); const update = { weight, x, y, visitedCount, selectedCount }; Object.keys(update).forEach(key => { if (update[key] === undefined) delete update[key]; }); Object.assign(node, update); } removeNode(id) { const node = this.findNode(id); if (!node) return; const index = this.nodes.indexOf(node); this.nodes.splice(index, 1); this.layout(); } addEdge(source, target, weight = null, visitedCount = 0, selectedCount = 0) { if (this.findEdge(source, target)) return; this.edges.push({ source, target, weight, visitedCount, selectedCount }); this.layout(); } updateEdge(source, target, weight, visitedCount, selectedCount) { const edge = this.findEdge(source, target); const update = { weight, visitedCount, selectedCount }; Object.keys(update).forEach(key => { if (update[key] === undefined) delete update[key]; }); Object.assign(edge, update); } removeEdge(source, target) { const edge = this.findEdge(source, target); if (!edge) return; const index = this.edges.indexOf(edge); this.edges.splice(index, 1); this.layout(); } findNode(id) { return this.nodes.find(node => node.id === id); } findEdge(source, target, isDirected = this.isDirected) { if (isDirected) { return this.edges.find(edge => edge.source === source && edge.target === target); } else { return this.edges.find(edge => (edge.source === source && edge.target === target) || (edge.source === target && edge.target === source)); } } findLinkedEdges(source, isDirected = this.isDirected) { if (isDirected) { return this.edges.filter(edge => edge.source === source); } else { return this.edges.filter(edge => edge.source === source || edge.target === source); } } findLinkedNodeIds(source, isDirected = this.isDirected) { const edges = this.findLinkedEdges(source, isDirected); return edges.map(edge => edge.source === source ? edge.target : edge.source); } findLinkedNodes(source, isDirected = this.isDirected) { const ids = this.findLinkedNodeIds(source, isDirected); return ids.map(id => this.findNode(id)); } getRect() { const { baseWidth, baseHeight, padding } = this.dimensions; const left = -baseWidth / 2 + padding; const top = -baseHeight / 2 + padding; const right = baseWidth / 2 - padding; const bottom = baseHeight / 2 - padding; const width = right - left; const height = bottom - top; return { left, top, right, bottom, width, height }; } layout() { const { method, args } = this.callLayout; method.apply(this, args); } layoutCircle() { this.callLayout = { method: this.layoutCircle, args: arguments }; const rect = this.getRect(); const unitAngle = 2 * Math.PI / this.nodes.length; let angle = -Math.PI / 2; for (const node of this.nodes) { const x = Math.cos(angle) * rect.width / 2; const y = Math.sin(angle) * rect.height / 2; node.x = x; node.y = y; angle += unitAngle; } } layoutTree(root = 0, sorted = false) { this.callLayout = { method: this.layoutTree, args: arguments }; const rect = this.getRect(); if (this.nodes.length === 1) { const [node] = this.nodes; node.x = (rect.left + rect.right) / 2; node.y = (rect.top + rect.bottom) / 2; return; } let maxDepth = 0; const leafCounts = {}; let marked = {}; const recursiveAnalyze = (id, depth) => { marked[id] = true; leafCounts[id] = 0; if (maxDepth < depth) maxDepth = depth; const linkedNodeIds = this.findLinkedNodeIds(id, false); for (const linkedNodeId of linkedNodeIds) { if (marked[linkedNodeId]) continue; leafCounts[id] += recursiveAnalyze(linkedNodeId, depth + 1); } if (leafCounts[id] === 0) leafCounts[id] = 1; return leafCounts[id]; }; recursiveAnalyze(root, 0); const hGap = rect.width / leafCounts[root]; const vGap = rect.height / maxDepth; marked = {}; const recursivePosition = (node, h, v) => { marked[node.id] = true; node.x = rect.left + (h + leafCounts[node.id] / 2) * hGap; node.y = rect.top + v * vGap; const linkedNodes = this.findLinkedNodes(node.id, false); if (sorted) linkedNodes.sort((a, b) => a.id - b.id); for (const linkedNode of linkedNodes) { if (marked[linkedNode.id]) continue; recursivePosition(linkedNode, h, v + 1); h += leafCounts[linkedNode.id]; } }; const rootNode = this.findNode(root); recursivePosition(rootNode, 0, 0); } layoutRandom() { this.callLayout = { method: this.layoutRandom, args: arguments }; const rect = this.getRect(); const placedNodes = []; for (const node of this.nodes) { do { node.x = rect.left + Math.random() * rect.width; node.y = rect.top + Math.random() * rect.height; } while (placedNodes.find(placedNode => distance(node, placedNode) < 48)); placedNodes.push(node); } } visit(target, source, weight) { this.visitOrLeave(true, target, source, weight); } leave(target, source, weight) { this.visitOrLeave(false, target, source, weight); } visitOrLeave(visit, target, source = null, weight) { const edge = this.findEdge(source, target); if (edge) edge.visitedCount += visit ? 1 : -1; const node = this.findNode(target); if (weight !== undefined) node.weight = weight; node.visitedCount += visit ? 1 : -1; if (this.logTracer) { this.logTracer.println(visit ? (source || '') + ' -> ' + target : (source || '') + ' <- ' + target); } } select(target, source) { this.selectOrDeselect(true, target, source); } deselect(target, source) { this.selectOrDeselect(false, target, source); } selectOrDeselect(select, target, source = null) { const edge = this.findEdge(source, target); if (edge) edge.selectedCount += select ? 1 : -1; const node = this.findNode(target); node.selectedCount += select ? 1 : -1; if (this.logTracer) { this.logTracer.println(select ? (source || '') + ' => ' + target : (source || '') + ' <= ' + target); } } log(key) { this.logTracer = key ? this.getObject(key) : null; } } export default GraphTracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/LogTracer.js
src/core/tracers/LogTracer.js
import { sprintf } from 'sprintf-js'; import { Tracer } from 'core/tracers'; import { LogRenderer } from 'core/renderers'; class LogTracer extends Tracer { getRendererClass() { return LogRenderer; } set(log = '') { this.log = log; super.set(); } print(message) { this.log += message; } println(message) { this.print(message + '\n'); } printf(format, ...args) { this.print(sprintf(format, ...args)); } } export default LogTracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/tracers/MarkdownTracer.js
src/core/tracers/MarkdownTracer.js
import { Tracer } from 'core/tracers'; import { MarkdownRenderer } from 'core/renderers'; class MarkdownTracer extends Tracer { getRendererClass() { return MarkdownRenderer; } set(markdown = '') { this.markdown = markdown; super.set(); } } export default MarkdownTracer;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/layouts/index.js
src/core/layouts/index.js
export { default as Layout } from './Layout'; export { default as HorizontalLayout } from './HorizontalLayout'; export { default as VerticalLayout } from './VerticalLayout';
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/layouts/Layout.js
src/core/layouts/Layout.js
import React from 'react'; import { ResizableContainer } from 'components'; import { HorizontalLayout } from 'core/layouts'; class Layout { constructor(key, getObject, children) { this.key = key; this.getObject = getObject; this.children = children.map(key => this.getObject(key)); this.weights = children.map(() => 1); this.ref = React.createRef(); this.handleChangeWeights = this.handleChangeWeights.bind(this); } add(key, index = this.children.length) { const child = this.getObject(key); this.children.splice(index, 0, child); this.weights.splice(index, 0, 1); } remove(key) { const child = this.getObject(key); const index = this.children.indexOf(child); if (~index) { this.children.splice(index, 1); this.weights.splice(index, 1); } } removeAll() { this.children = []; this.weights = []; } handleChangeWeights(weights) { this.weights.splice(0, this.weights.length, ...weights); this.ref.current.forceUpdate(); } render() { const horizontal = this instanceof HorizontalLayout; return ( <ResizableContainer key={this.key} ref={this.ref} weights={this.weights} horizontal={horizontal} onChangeWeights={this.handleChangeWeights}> { this.children.map(tracer => tracer && tracer.render()) } </ResizableContainer> ); } } export default Layout;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/layouts/HorizontalLayout.js
src/core/layouts/HorizontalLayout.js
import { Layout } from 'core/layouts'; class HorizontalLayout extends Layout { } export default HorizontalLayout;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/layouts/VerticalLayout.js
src/core/layouts/VerticalLayout.js
import { Layout } from 'core/layouts'; class VerticalLayout extends Layout { } export default VerticalLayout;
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
algorithm-visualizer/algorithm-visualizer
https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/apis/index.js
src/apis/index.js
import Promise from 'bluebird'; import axios from 'axios'; axios.interceptors.response.use(response => response.data); const request = (url, process) => { const tokens = url.split('/'); const baseURL = /^https?:\/\//i.test(url) ? '' : '/api'; return (...args) => { const mappedURL = baseURL + tokens.map((token, i) => token.startsWith(':') ? args.shift() : token).join('/'); return Promise.resolve(process(mappedURL, args)); }; }; const GET = URL => { return request(URL, (mappedURL, args) => { const [params, cancelToken] = args; return axios.get(mappedURL, { params, cancelToken }); }); }; const DELETE = URL => { return request(URL, (mappedURL, args) => { const [params, cancelToken] = args; return axios.delete(mappedURL, { params, cancelToken }); }); }; const POST = URL => { return request(URL, (mappedURL, args) => { const [body, params, cancelToken] = args; return axios.post(mappedURL, body, { params, cancelToken }); }); }; const PUT = URL => { return request(URL, (mappedURL, args) => { const [body, params, cancelToken] = args; return axios.put(mappedURL, body, { params, cancelToken }); }); }; const PATCH = URL => { return request(URL, (mappedURL, args) => { const [body, params, cancelToken] = args; return axios.patch(mappedURL, body, { params, cancelToken }); }); }; const AlgorithmApi = { getCategories: GET('/algorithms'), getAlgorithm: GET('/algorithms/:categoryKey/:algorithmKey'), }; const VisualizationApi = { getVisualization: GET('/visualizations/:visualizationId'), }; const GitHubApi = { auth: token => Promise.resolve(axios.defaults.headers.common['Authorization'] = token && `token ${token}`), getUser: GET('https://api.github.com/user'), listGists: GET('https://api.github.com/gists'), createGist: POST('https://api.github.com/gists'), editGist: PATCH('https://api.github.com/gists/:id'), getGist: GET('https://api.github.com/gists/:id'), deleteGist: DELETE('https://api.github.com/gists/:id'), forkGist: POST('https://api.github.com/gists/:id/forks'), }; const TracerApi = { md: ({ code }) => Promise.resolve([{ key: 'markdown', method: 'MarkdownTracer', args: ['Markdown'], }, { key: 'markdown', method: 'set', args: [code], }, { key: null, method: 'setRoot', args: ['markdown'], }]), json: ({ code }) => new Promise(resolve => resolve(JSON.parse(code))), js: ({ code }, params, cancelToken) => new Promise((resolve, reject) => { const worker = new Worker('/api/tracers/js/worker'); if (cancelToken) { cancelToken.promise.then(cancel => { worker.terminate(); reject(cancel); }); } worker.onmessage = e => { worker.terminate(); resolve(e.data); }; worker.onerror = error => { worker.terminate(); reject(error); }; worker.postMessage(code); }), cpp: POST('/tracers/cpp'), java: POST('/tracers/java'), }; export { AlgorithmApi, VisualizationApi, GitHubApi, TracerApi, };
javascript
MIT
18de2edf6b629e843ee4bcedfa2208d22b253f0f
2026-01-04T14:57:32.646812Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/svelte.config.js
svelte.config.js
// we need this so the VS Code extension doesn't yell at us export default { compilerOptions: { experimental: { async: true } } };
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/vitest.config.js
vitest.config.js
import * as fs from 'node:fs'; import * as path from 'node:path'; import { configDefaults, defineConfig } from 'vitest/config'; const pkg = JSON.parse(fs.readFileSync('packages/svelte/package.json', 'utf8')); export default defineConfig({ resolve: { alias: [ { find: /^svelte\/?/, customResolver: (id, importer) => { // For some reason this turns up as "undefined" instead of "svelte/" const exported = pkg.exports[id === 'undefined' ? '.' : id.replace('undefined', './')]; if (!exported) return; // When running the server version of the Svelte files, // we also want to use the server export of the Svelte package return path.resolve( 'packages/svelte', importer?.includes('_output/server') ? exported.default : exported.browser ?? exported.default ); } } ] }, test: { dir: '.', reporters: ['dot'], include: [ 'packages/svelte/**/*.test.ts', 'packages/svelte/tests/*/test.ts', 'packages/svelte/tests/runtime-browser/test-ssr.ts' ], exclude: [...configDefaults.exclude, '**/samples/**'], coverage: { provider: 'v8', reporter: ['lcov', 'html'], include: ['packages/svelte/src/**'], reportsDirectory: 'coverage', reportOnFailure: true } } });
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/eslint.config.js
eslint.config.js
import svelte_config from '@sveltejs/eslint-config'; import lube from 'eslint-plugin-lube'; const no_compiler_imports = { meta: { type: /** @type {const} */ ('problem'), docs: { description: 'Enforce that there are no imports to the compiler in runtime code. ' + 'This prevents accidental inclusion of the compiler runtime and ' + "ensures that TypeScript does not pick up more ambient types (for example from Node) that shouldn't be available in the browser." } }, create(context) { return { Program: () => { // Do a simple string search because ESLint doesn't provide a way to check JSDoc comments. // The string search could in theory yield false positives, but in practice it's unlikely. const text = context.sourceCode.getText(); const idx = Math.max(text.indexOf('../compiler/'), text.indexOf('#compiler')); if (idx !== -1) { context.report({ loc: { start: context.sourceCode.getLocFromIndex(idx), end: context.sourceCode.getLocFromIndex(idx + 12) }, message: 'References to compiler code are forbidden in runtime code (both for type and value imports)' }); } } }; } }; /** @type {import('eslint').Linter.FlatConfig[]} */ export default [ ...svelte_config, { languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname } }, plugins: { lube, custom: { rules: { no_compiler_imports } } }, rules: { '@typescript-eslint/await-thenable': 'error', '@typescript-eslint/require-await': 'error', 'no-console': 'error', 'lube/svelte-naming-convention': ['error', { fixSameNames: true }], // eslint isn't that well-versed with JSDoc to know that `foo: /** @type{..} */ (foo)` isn't a violation of this rule, so turn it off 'object-shorthand': 'off', // eslint is being a dummy here too '@typescript-eslint/prefer-promise-reject-errors': 'off', 'no-var': 'off', // TODO: enable these rules and run `pnpm lint:fix` // skipping that for now so as to avoid impacting real work '@stylistic/quotes': 'off', '@typescript-eslint/no-unused-vars': 'off', 'prefer-const': 'off' } }, { // If you get an error along the lines of "@typescript-eslint/await-thenable needs a project service configured", then that likely means // that eslint rules that need to be type-aware run through a Svelte file which seems unsupported at the moment. In that case, ensure that // these are excluded to run on Svelte files. files: ['**/*.svelte'], rules: { '@typescript-eslint/await-thenable': 'off', '@typescript-eslint/prefer-promise-reject-errors': 'off', '@typescript-eslint/require-await': 'off' } }, { files: ['packages/svelte/src/**/*'], ignores: ['packages/svelte/src/compiler/**/*'], rules: { 'custom/no_compiler_imports': 'error', 'svelte/no-svelte-internal': 'off' } }, { ignores: [ '**/*.d.ts', '**/tests', 'packages/svelte/scripts/process-messages/templates/*.js', 'packages/svelte/scripts/_bundle.js', 'packages/svelte/src/compiler/errors.js', 'packages/svelte/src/internal/client/errors.js', 'packages/svelte/src/internal/client/warnings.js', 'packages/svelte/src/internal/shared/warnings.js', 'packages/svelte/src/internal/server/warnings.js', 'packages/svelte/compiler/index.js', // stuff we don't want to lint 'benchmarking/**', 'coverage/**', 'playgrounds/sandbox/**', // exclude top level config files '*.config.js', // documentation can contain invalid examples 'documentation', 'tmp/**' ] } ];
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/run.js
benchmarking/run.js
import * as $ from '../packages/svelte/src/internal/client/index.js'; import { reactivity_benchmarks } from './benchmarks/reactivity/index.js'; import { ssr_benchmarks } from './benchmarks/ssr/index.js'; let total_time = 0; let total_gc_time = 0; const suites = [ { benchmarks: reactivity_benchmarks, name: 'reactivity benchmarks' }, { benchmarks: ssr_benchmarks, name: 'server-side rendering benchmarks' } ]; // eslint-disable-next-line no-console console.log('\x1b[1m', '-- Benchmarking Started --', '\x1b[0m'); $.push({}, true); try { for (const { benchmarks, name } of suites) { let suite_time = 0; let suite_gc_time = 0; // eslint-disable-next-line no-console console.log(`\nRunning ${name}...\n`); for (const benchmark of benchmarks) { const results = await benchmark(); // eslint-disable-next-line no-console console.log(results); total_time += Number(results.time); total_gc_time += Number(results.gc_time); suite_time += Number(results.time); suite_gc_time += Number(results.gc_time); } console.log(`\nFinished ${name}.\n`); // eslint-disable-next-line no-console console.log({ suite_time: suite_time.toFixed(2), suite_gc_time: suite_gc_time.toFixed(2) }); } } catch (e) { // eslint-disable-next-line no-console console.log('\x1b[1m', '\n-- Benchmarking Failed --\n', '\x1b[0m'); // eslint-disable-next-line no-console console.error(e); process.exit(1); } $.pop(); // eslint-disable-next-line no-console console.log('\x1b[1m', '\n-- Benchmarking Complete --\n', '\x1b[0m'); // eslint-disable-next-line no-console console.log({ total_time: total_time.toFixed(2), total_gc_time: total_gc_time.toFixed(2) });
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/utils.js
benchmarking/utils.js
import { performance, PerformanceObserver } from 'node:perf_hooks'; import v8 from 'v8-natives'; import * as fs from 'node:fs'; import * as path from 'node:path'; // Credit to https://github.com/milomg/js-reactivity-benchmark for the logic for timing + GC tracking. class GarbageTrack { track_id = 0; observer = new PerformanceObserver((list) => this.perf_entries.push(...list.getEntries())); perf_entries = []; periods = []; watch(fn) { this.track_id++; const start = performance.now(); const result = fn(); const end = performance.now(); this.periods.push({ track_id: this.track_id, start, end }); return { result, track_id: this.track_id }; } /** * @param {number} track_id */ async gcDuration(track_id) { await promise_delay(10); const period = this.periods.find((period) => period.track_id === track_id); if (!period) { // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors return Promise.reject('no period found'); } const entries = this.perf_entries.filter( (e) => e.startTime >= period.start && e.startTime < period.end ); return entries.reduce((t, e) => e.duration + t, 0); } destroy() { this.observer.disconnect(); } constructor() { this.observer.observe({ entryTypes: ['gc'] }); } } function promise_delay(timeout = 0) { return new Promise((resolve) => setTimeout(resolve, timeout)); } /** * @param {{ (): void; (): any; }} fn */ function run_timed(fn) { const start = performance.now(); const result = fn(); const time = performance.now() - start; return { result, time }; } /** * @param {() => void} fn */ async function run_tracked(fn) { v8.collectGarbage(); const gc_track = new GarbageTrack(); const { result: wrappedResult, track_id } = gc_track.watch(() => run_timed(fn)); const gc_time = await gc_track.gcDuration(track_id); const { result, time } = wrappedResult; gc_track.destroy(); return { result, timing: { time, gc_time } }; } /** * @param {number} times * @param {() => void} fn */ export async function fastest_test(times, fn) { const results = []; for (let i = 0; i < times; i++) { const run = await run_tracked(fn); results.push(run); } const fastest = results.reduce((a, b) => (a.timing.time < b.timing.time ? a : b)); return fastest; } /** * @param {boolean} a */ export function assert(a) { if (!a) { throw new Error('Assertion failed'); } } /** * @param {string} file */ export function read_file(file) { return fs.readFileSync(file, 'utf-8').replace(/\r\n/g, '\n'); } /** * @param {string} file * @param {string} contents */ export function write(file, contents) { try { fs.mkdirSync(path.dirname(file), { recursive: true }); } catch {} fs.writeFileSync(file, contents); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/ssr/index.js
benchmarking/benchmarks/ssr/index.js
import { wrapper_bench } from './wrapper/wrapper_bench.js'; export const ssr_benchmarks = [wrapper_bench];
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/ssr/wrapper/wrapper_bench.js
benchmarking/benchmarks/ssr/wrapper/wrapper_bench.js
import { render } from 'svelte/server'; import { fastest_test, read_file, write } from '../../../utils.js'; import { compile } from 'svelte/compiler'; const dir = `${process.cwd()}/benchmarking/benchmarks/ssr/wrapper`; async function compile_svelte() { const output = compile(read_file(`${dir}/App.svelte`), { generate: 'server' }); write(`${dir}/output/App.js`, output.js.code); const module = await import(`${dir}/output/App.js`); return module.default; } export async function wrapper_bench() { const App = await compile_svelte(); // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { render(App); } const { timing } = await fastest_test(10, () => { for (let i = 0; i < 100; i++) { render(App); } }); return { benchmark: 'wrapper_bench', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/mol_bench.js
benchmarking/benchmarks/reactivity/mol_bench.js
import { assert, fastest_test } from '../../utils.js'; import * as $ from 'svelte/internal/client'; /** * @param {number} n */ function fib(n) { if (n < 2) return 1; return fib(n - 1) + fib(n - 2); } /** * @param {number} n */ function hard(n) { return n + fib(16); } const numbers = Array.from({ length: 5 }, (_, i) => i); function setup() { let res = []; const A = $.state(0); const B = $.state(0); const C = $.derived(() => ($.get(A) % 2) + ($.get(B) % 2)); const D = $.derived(() => numbers.map((i) => i + ($.get(A) % 2) - ($.get(B) % 2))); D.equals = function (/** @type {number[]} */ l) { var r = this.v; return r !== null && l.length === r.length && l.every((v, i) => v === r[i]); }; const E = $.derived(() => hard($.get(C) + $.get(A) + $.get(D)[0])); const F = $.derived(() => hard($.get(D)[0] && $.get(B))); const G = $.derived(() => $.get(C) + ($.get(C) || $.get(E) % 2) + $.get(D)[0] + $.get(F)); const destroy = $.effect_root(() => { $.render_effect(() => { res.push(hard($.get(G))); }); $.render_effect(() => { res.push($.get(G)); }); $.render_effect(() => { res.push(hard($.get(F))); }); }); return { destroy, /** * @param {number} i */ run(i) { res.length = 0; $.flush(() => { $.set(B, 1); $.set(A, 1 + i * 2); }); $.flush(() => { $.set(A, 2 + i * 2); $.set(B, 2); }); assert(res[0] === 3198 && res[1] === 1601 && res[2] === 3195 && res[3] === 1598); } }; } export async function mol_bench_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(0); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1e4; i++) { run(i); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'mol_bench_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function mol_bench_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(0); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1e4; i++) { run(i); } }); destroy(); return { benchmark: 'mol_bench_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/sbench.js
benchmarking/benchmarks/reactivity/sbench.js
import { fastest_test } from '../../utils.js'; import * as $ from '../../../packages/svelte/src/internal/client/index.js'; const COUNT = 1e5; /** * @param {number} n * @param {any[]} sources */ function create_data_signals(n, sources) { for (let i = 0; i < n; i++) { sources[i] = $.state(i); } return sources; } /** * @param {number} i */ function create_computation_0(i) { $.derived(() => i); } /** * @param {any} s1 */ function create_computation_1(s1) { $.derived(() => $.get(s1)); } /** * @param {any} s1 * @param {any} s2 */ function create_computation_2(s1, s2) { $.derived(() => $.get(s1) + $.get(s2)); } function create_computation_1000(ss, offset) { $.derived(() => { let sum = 0; for (let i = 0; i < 1000; i++) { sum += $.get(ss[offset + i]); } return sum; }); } /** * @param {number} n */ function create_computations_0to1(n) { for (let i = 0; i < n; i++) { create_computation_0(i); } } /** * @param {number} n * @param {any[]} sources */ function create_computations_1to1(n, sources) { for (let i = 0; i < n; i++) { const source = sources[i]; create_computation_1(source); } } /** * @param {number} n * @param {any[]} sources */ function create_computations_2to1(n, sources) { for (let i = 0; i < n; i++) { create_computation_2(sources[i * 2], sources[i * 2 + 1]); } } function create_computation_4(s1, s2, s3, s4) { $.derived(() => $.get(s1) + $.get(s2) + $.get(s3) + $.get(s4)); } function create_computations_1000to1(n, sources) { for (let i = 0; i < n; i++) { create_computation_1000(sources, i * 1000); } } function create_computations_1to2(n, sources) { for (let i = 0; i < n / 2; i++) { const source = sources[i]; create_computation_1(source); create_computation_1(source); } } function create_computations_1to4(n, sources) { for (let i = 0; i < n / 4; i++) { const source = sources[i]; create_computation_1(source); create_computation_1(source); create_computation_1(source); create_computation_1(source); } } function create_computations_1to8(n, sources) { for (let i = 0; i < n / 8; i++) { const source = sources[i]; create_computation_1(source); create_computation_1(source); create_computation_1(source); create_computation_1(source); create_computation_1(source); create_computation_1(source); create_computation_1(source); create_computation_1(source); } } function create_computations_1to1000(n, sources) { for (let i = 0; i < n / 1000; i++) { const source = sources[i]; for (let j = 0; j < 1000; j++) { create_computation_1(source); } } } function create_computations_4to1(n, sources) { for (let i = 0; i < n; i++) { create_computation_4( sources[i * 4], sources[i * 4 + 1], sources[i * 4 + 2], sources[i * 4 + 3] ); } } /** * @param {any} fn * @param {number} count * @param {number} scount */ function bench(fn, count, scount) { let sources = create_data_signals(scount, []); fn(count, sources); } export async function sbench_create_signals() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_data_signals, COUNT, COUNT); } const { timing } = await fastest_test(10, () => { for (let i = 0; i < 100; i++) { bench(create_data_signals, COUNT, COUNT); } }); return { benchmark: 'sbench_create_signals', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_0to1() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_0to1, COUNT, 0); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_0to1, COUNT, 0); } }); destroy(); }); return { benchmark: 'sbench_create_0to1', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_1to1() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_1to1, COUNT, COUNT); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_1to1, COUNT, COUNT); } }); destroy(); }); return { benchmark: 'sbench_create_1to1', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_2to1() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_2to1, COUNT / 2, COUNT); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_2to1, COUNT / 2, COUNT); } }); destroy(); }); return { benchmark: 'sbench_create_2to1', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_4to1() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_4to1, COUNT / 4, COUNT); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_4to1, COUNT / 4, COUNT); } }); destroy(); }); return { benchmark: 'sbench_create_4to1', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_1000to1() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_1000to1, COUNT / 1000, COUNT); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_1000to1, COUNT / 1000, COUNT); } }); destroy(); }); return { benchmark: 'sbench_create_1000to1', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_1to2() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_1to2, COUNT, COUNT / 2); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_1to2, COUNT, COUNT / 2); } }); destroy(); }); return { benchmark: 'sbench_create_1to2', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_1to4() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_1to4, COUNT, COUNT / 4); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_1to4, COUNT, COUNT / 4); } }); destroy(); }); return { benchmark: 'sbench_create_1to4', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_1to8() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_1to8, COUNT, COUNT / 8); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_1to8, COUNT, COUNT / 8); } }); destroy(); }); return { benchmark: 'sbench_create_1to8', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function sbench_create_1to1000() { // Do 3 loops to warm up JIT for (let i = 0; i < 3; i++) { bench(create_computations_1to1000, COUNT, COUNT / 1000); } const { timing } = await fastest_test(10, () => { const destroy = $.effect_root(() => { for (let i = 0; i < 10; i++) { bench(create_computations_1to1000, COUNT, COUNT / 1000); } }); destroy(); }); return { benchmark: 'sbench_create_1to1000', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/index.js
benchmarking/benchmarks/reactivity/index.js
import { kairo_avoidable_owned, kairo_avoidable_unowned } from './kairo/kairo_avoidable.js'; import { kairo_broad_owned, kairo_broad_unowned } from './kairo/kairo_broad.js'; import { kairo_deep_owned, kairo_deep_unowned } from './kairo/kairo_deep.js'; import { kairo_diamond_owned, kairo_diamond_unowned } from './kairo/kairo_diamond.js'; import { kairo_mux_unowned, kairo_mux_owned } from './kairo/kairo_mux.js'; import { kairo_repeated_unowned, kairo_repeated_owned } from './kairo/kairo_repeated.js'; import { kairo_triangle_owned, kairo_triangle_unowned } from './kairo/kairo_triangle.js'; import { kairo_unstable_owned, kairo_unstable_unowned } from './kairo/kairo_unstable.js'; import { mol_bench_owned, mol_bench_unowned } from './mol_bench.js'; import { sbench_create_0to1, sbench_create_1000to1, sbench_create_1to1, sbench_create_1to1000, sbench_create_1to2, sbench_create_1to4, sbench_create_1to8, sbench_create_2to1, sbench_create_4to1, sbench_create_signals } from './sbench.js'; // This benchmark has been adapted from the js-reactivity-benchmark (https://github.com/milomg/js-reactivity-benchmark) // Not all tests are the same, and many parts have been tweaked to capture different data. export const reactivity_benchmarks = [ sbench_create_signals, sbench_create_0to1, sbench_create_1to1, sbench_create_2to1, sbench_create_4to1, sbench_create_1000to1, sbench_create_1to2, sbench_create_1to4, sbench_create_1to8, sbench_create_1to1000, kairo_avoidable_owned, kairo_avoidable_unowned, kairo_broad_owned, kairo_broad_unowned, kairo_deep_owned, kairo_deep_unowned, kairo_diamond_owned, kairo_diamond_unowned, kairo_triangle_owned, kairo_triangle_unowned, kairo_mux_owned, kairo_mux_unowned, kairo_repeated_owned, kairo_repeated_unowned, kairo_unstable_owned, kairo_unstable_unowned, mol_bench_owned, mol_bench_unowned ];
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_repeated.js
benchmarking/benchmarks/reactivity/kairo/kairo_repeated.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; let size = 30; function setup() { let head = $.state(0); let current = $.derived(() => { let result = 0; for (let i = 0; i < size; i++) { result += $.get(head); } return result; }); let counter = 0; const destroy = $.effect_root(() => { $.render_effect(() => { $.get(current); counter++; }); }); return { destroy, run() { $.flush(() => { $.set(head, 1); }); assert($.get(current) === size); counter = 0; for (let i = 0; i < 100; i++) { $.flush(() => { $.set(head, i); }); assert($.get(current) === i * size); } assert(counter === 100); } }; } export async function kairo_repeated_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_repeated_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_repeated_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_repeated_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_avoidable.js
benchmarking/benchmarks/reactivity/kairo/kairo_avoidable.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; import { busy } from './util.js'; function setup() { let head = $.state(0); let computed1 = $.derived(() => $.get(head)); let computed2 = $.derived(() => ($.get(computed1), 0)); let computed3 = $.derived(() => (busy(), $.get(computed2) + 1)); // heavy computation let computed4 = $.derived(() => $.get(computed3) + 2); let computed5 = $.derived(() => $.get(computed4) + 3); const destroy = $.effect_root(() => { $.render_effect(() => { $.get(computed5); busy(); // heavy side effect }); }); return { destroy, run() { $.flush(() => { $.set(head, 1); }); assert($.get(computed5) === 6); for (let i = 0; i < 1000; i++) { $.flush(() => { $.set(head, i); }); assert($.get(computed5) === 6); } } }; } export async function kairo_avoidable_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_avoidable_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_avoidable_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_avoidable_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_diamond.js
benchmarking/benchmarks/reactivity/kairo/kairo_diamond.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; let width = 5; function setup() { let head = $.state(0); let current = []; for (let i = 0; i < width; i++) { current.push( $.derived(() => { return $.get(head) + 1; }) ); } let sum = $.derived(() => { return current.map((x) => $.get(x)).reduce((a, b) => a + b, 0); }); let counter = 0; const destroy = $.effect_root(() => { $.render_effect(() => { $.get(sum); counter++; }); }); return { destroy, run() { $.flush(() => { $.set(head, 1); }); assert($.get(sum) === 2 * width); counter = 0; for (let i = 0; i < 500; i++) { $.flush(() => { $.set(head, i); }); assert($.get(sum) === (i + 1) * width); } assert(counter === 500); } }; } export async function kairo_diamond_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_diamond_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_diamond_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_diamond_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_unstable.js
benchmarking/benchmarks/reactivity/kairo/kairo_unstable.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; function setup() { let head = $.state(0); const double = $.derived(() => $.get(head) * 2); const inverse = $.derived(() => -$.get(head)); let current = $.derived(() => { let result = 0; for (let i = 0; i < 20; i++) { result += $.get(head) % 2 ? $.get(double) : $.get(inverse); } return result; }); let counter = 0; const destroy = $.effect_root(() => { $.render_effect(() => { $.get(current); counter++; }); }); return { destroy, run() { $.flush(() => { $.set(head, 1); }); assert($.get(current) === 40); counter = 0; for (let i = 0; i < 100; i++) { $.flush(() => { $.set(head, i); }); } assert(counter === 100); } }; } export async function kairo_unstable_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_unstable_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_unstable_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_unstable_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_mux.js
benchmarking/benchmarks/reactivity/kairo/kairo_mux.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; function setup() { let heads = new Array(100).fill(null).map((_) => $.state(0)); const mux = $.derived(() => { return Object.fromEntries(heads.map((h) => $.get(h)).entries()); }); const splited = heads .map((_, index) => $.derived(() => $.get(mux)[index])) .map((x) => $.derived(() => $.get(x) + 1)); const destroy = $.effect_root(() => { splited.forEach((x) => { $.render_effect(() => { $.get(x); }); }); }); return { destroy, run() { for (let i = 0; i < 10; i++) { $.flush(() => { $.set(heads[i], i); }); assert($.get(splited[i]) === i + 1); } for (let i = 0; i < 10; i++) { $.flush(() => { $.set(heads[i], i * 2); }); assert($.get(splited[i]) === i * 2 + 1); } } }; } export async function kairo_mux_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_mux_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_mux_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_mux_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_triangle.js
benchmarking/benchmarks/reactivity/kairo/kairo_triangle.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; let width = 10; function count(number) { return new Array(number) .fill(0) .map((_, i) => i + 1) .reduce((x, y) => x + y, 0); } function setup() { let head = $.state(0); let current = head; let list = []; for (let i = 0; i < width; i++) { let c = current; list.push(current); current = $.derived(() => { return $.get(c) + 1; }); } let sum = $.derived(() => { return list.map((x) => $.get(x)).reduce((a, b) => a + b, 0); }); let counter = 0; const destroy = $.effect_root(() => { $.render_effect(() => { $.get(sum); counter++; }); }); return { destroy, run() { const constant = count(width); $.flush(() => { $.set(head, 1); }); assert($.get(sum) === constant); counter = 0; for (let i = 0; i < 100; i++) { $.flush(() => { $.set(head, i); }); assert($.get(sum) === constant - width + i * width); } assert(counter === 100); } }; } export async function kairo_triangle_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_triangle_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_triangle_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_triangle_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_deep.js
benchmarking/benchmarks/reactivity/kairo/kairo_deep.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; let len = 50; const iter = 50; function setup() { let head = $.state(0); let current = head; for (let i = 0; i < len; i++) { let c = current; current = $.derived(() => { return $.get(c) + 1; }); } let counter = 0; const destroy = $.effect_root(() => { $.render_effect(() => { $.get(current); counter++; }); }); return { destroy, run() { $.flush(() => { $.set(head, 1); }); counter = 0; for (let i = 0; i < iter; i++) { $.flush(() => { $.set(head, i); }); assert($.get(current) === len + i); } assert(counter === iter); } }; } export async function kairo_deep_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_deep_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_deep_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_deep_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/util.js
benchmarking/benchmarks/reactivity/kairo/util.js
export function busy() { let a = 0; for (let i = 0; i < 1_00; i++) { a++; } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/benchmarks/reactivity/kairo/kairo_broad.js
benchmarking/benchmarks/reactivity/kairo/kairo_broad.js
import { assert, fastest_test } from '../../../utils.js'; import * as $ from 'svelte/internal/client'; function setup() { let head = $.state(0); let last = head; let counter = 0; const destroy = $.effect_root(() => { for (let i = 0; i < 50; i++) { let current = $.derived(() => { return $.get(head) + i; }); let current2 = $.derived(() => { return $.get(current) + 1; }); $.render_effect(() => { $.get(current2); counter++; }); last = current2; } }); return { destroy, run() { $.flush(() => { $.set(head, 1); }); counter = 0; for (let i = 0; i < 50; i++) { $.flush(() => { $.set(head, i); }); assert($.get(last) === i + 50); } assert(counter === 50 * 50); } }; } export async function kairo_broad_unowned() { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } const { run, destroy } = setup(); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); destroy(); return { benchmark: 'kairo_broad_unowned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; } export async function kairo_broad_owned() { let run, destroy; const destroy_owned = $.effect_root(() => { // Do 10 loops to warm up JIT for (let i = 0; i < 10; i++) { const { run, destroy } = setup(); run(); destroy(); } ({ run, destroy } = setup()); }); const { timing } = await fastest_test(10, () => { for (let i = 0; i < 1000; i++) { run(); } }); // @ts-ignore destroy(); destroy_owned(); return { benchmark: 'kairo_broad_owned', time: timing.time.toFixed(2), gc_time: timing.gc_time.toFixed(2) }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/compare/runner.js
benchmarking/compare/runner.js
import { reactivity_benchmarks } from '../benchmarks/reactivity/index.js'; const results = []; for (const benchmark of reactivity_benchmarks) { const result = await benchmark(); console.error(result.benchmark); results.push(result); } process.send(results);
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/benchmarking/compare/index.js
benchmarking/compare/index.js
import fs from 'node:fs'; import path from 'node:path'; import { execSync, fork } from 'node:child_process'; import { fileURLToPath } from 'node:url'; // if (execSync('git status --porcelain').toString().trim()) { // console.error('Working directory is not clean'); // process.exit(1); // } const filename = fileURLToPath(import.meta.url); const runner = path.resolve(filename, '../runner.js'); const outdir = path.resolve(filename, '../.results'); if (fs.existsSync(outdir)) fs.rmSync(outdir, { recursive: true }); fs.mkdirSync(outdir); const branches = []; for (const arg of process.argv.slice(2)) { if (arg.startsWith('--')) continue; if (arg === filename) continue; branches.push(arg); } if (branches.length === 0) { branches.push( execSync('git symbolic-ref --short -q HEAD || git rev-parse --short HEAD').toString().trim() ); } if (branches.length === 1) { branches.push('main'); } process.on('exit', () => { execSync(`git checkout ${branches[0]}`); }); for (const branch of branches) { console.group(`Benchmarking ${branch}`); execSync(`git checkout ${branch}`); await new Promise((fulfil, reject) => { const child = fork(runner); child.on('message', (results) => { fs.writeFileSync(`${outdir}/${branch}.json`, JSON.stringify(results, null, ' ')); fulfil(); }); child.on('error', reject); }); console.groupEnd(); } const results = branches.map((branch) => { return JSON.parse(fs.readFileSync(`${outdir}/${branch}.json`, 'utf-8')); }); for (let i = 0; i < results[0].length; i += 1) { console.group(`${results[0][i].benchmark}`); for (const metric of ['time', 'gc_time']) { const times = results.map((result) => +result[i][metric]); let min = Infinity; let max = -Infinity; let min_index = -1; for (let b = 0; b < times.length; b += 1) { const time = times[b]; if (time < min) { min = time; min_index = b; } if (time > max) { max = time; } } if (min !== 0) { console.group(`${metric}: fastest is ${char(min_index)} (${branches[min_index]})`); times.forEach((time, b) => { const SIZE = 20; const n = Math.round(SIZE * (time / max)); console.log(`${char(b)}: ${'◼'.repeat(n)}${' '.repeat(SIZE - n)} ${time.toFixed(2)}ms`); }); console.groupEnd(); } } console.groupEnd(); } function char(i) { return String.fromCharCode(97 + i); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/svelte.config.js
playgrounds/sandbox/svelte.config.js
export default { compilerOptions: { hmr: false, experimental: { async: true } } };
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/ssr-common.js
playgrounds/sandbox/ssr-common.js
Promise.withResolvers ??= () => { let resolve; let reject; const promise = new Promise((f, r) => { resolve = f; reject = r; }); return { promise, resolve, reject }; }; globalThis.delayed = (v, ms = 1000) => { return new Promise((f) => { setTimeout(() => f(v), ms); }); };
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/vite.config.js
playgrounds/sandbox/vite.config.js
import { defineConfig } from 'vite'; import inspect from 'vite-plugin-inspect'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import devtools from 'vite-plugin-devtools-json'; export default defineConfig({ build: { minify: false }, plugins: [devtools(), inspect(), svelte()], optimizeDeps: { // svelte is a local workspace package, optimizing it would require dev server restarts with --force for every change exclude: ['svelte'] } });
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/run.js
playgrounds/sandbox/run.js
import * as fs from 'node:fs'; import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; import { globSync } from 'tinyglobby'; import { compile, compileModule, parse, print, migrate } from 'svelte/compiler'; // toggle these to change what gets written to sandbox/output const AST = false; const MIGRATE = false; const FROM_HTML = true; const FROM_TREE = false; const DEV = false; const PRINT = false; const argv = parseArgs({ options: { runes: { type: 'boolean' } }, args: process.argv.slice(2) }); const cwd = fileURLToPath(new URL('.', import.meta.url)).slice(0, -1); // empty output directory if (fs.existsSync(`${cwd}/output`)) { for (const file of fs.readdirSync(`${cwd}/output`)) { if (file === '.gitkeep') continue; try { fs.rmSync(`${cwd}/output/${file}`, { recursive: true }); } catch {} } } /** @param {string} dir */ function mkdirp(dir) { try { fs.mkdirSync(dir, { recursive: true }); } catch {} } /** * @param {string} file * @param {string} contents */ function write(file, contents) { mkdirp(path.dirname(file)); fs.writeFileSync(file, contents); } const svelte_modules = globSync('**/*.svelte', { cwd: `${cwd}/src` }); const js_modules = globSync('**/*.js', { cwd: `${cwd}/src` }); for (const generate of /** @type {const} */ (['client', 'server'])) { console.error(`\n--- generating ${generate} ---\n`); for (const file of svelte_modules) { const input = `${cwd}/src/${file}`; const source = fs.readFileSync(input, 'utf-8'); const output_js = `${cwd}/output/${generate}/${file}.js`; const output_map = `${cwd}/output/${generate}/${file}.js.map`; const output_css = `${cwd}/output/${generate}/${file}.css`; mkdirp(path.dirname(output_js)); if (generate === 'client') { if (AST) { const ast = parse(source, { modern: true }); write( `${cwd}/output/ast/${file}.json`, JSON.stringify( ast, (key, value) => (typeof value === 'bigint' ? ['BigInt', value.toString()] : value), '\t' ) ); if (PRINT) { const printed = print(ast); write(`${cwd}/output/printed/${file}`, printed.code); } } if (MIGRATE) { try { const migrated = migrate(source); write(`${cwd}/output/migrated/${file}`, migrated.code); } catch (e) { console.warn(`Error migrating ${file}`, e); } } } let from_html; let from_tree; if (generate === 'server' || FROM_HTML) { from_html = compile(source, { dev: DEV, hmr: DEV, filename: input, generate, runes: argv.values.runes, experimental: { async: true } }); write(output_js, from_html.js.code + '\n//# sourceMappingURL=' + path.basename(output_map)); write(output_map, from_html.js.map.toString()); } // generate with fragments: 'tree' if (generate === 'client' && FROM_TREE) { from_tree = compile(source, { dev: false, filename: input, generate, runes: argv.values.runes, fragments: 'tree', experimental: { async: true } }); const output_js = `${cwd}/output/${generate}/${file}.tree.js`; const output_map = `${cwd}/output/${generate}/${file}.tree.js.map`; write(output_js, from_tree.js.code + '\n//# sourceMappingURL=' + path.basename(output_map)); write(output_map, from_tree.js.map.toString()); } const compiled = from_html ?? from_tree; if (compiled) { for (const warning of compiled.warnings) { console.warn(warning.code); console.warn(warning.frame); } if (compiled.css) { write(output_css, compiled.css.code); } } } for (const file of js_modules) { const input = `${cwd}/src/${file}`; const source = fs.readFileSync(input, 'utf-8'); const compiled = compileModule(source, { dev: false, filename: input, generate, experimental: { async: true } }); const output_js = `${cwd}/output/${generate}/${file}`; mkdirp(path.dirname(output_js)); write(output_js, compiled.js.code); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/ssr-dev.js
playgrounds/sandbox/ssr-dev.js
// @ts-check import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import polka from 'polka'; import { createServer as createViteServer } from 'vite'; import './ssr-common.js'; const PORT = process.env.PORT || '5173'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); process.env.NODE_ENV = 'development'; const vite = await createViteServer({ server: { middlewareMode: true }, appType: 'custom' }); polka() .use(vite.middlewares) .use(async (req, res) => { const template = fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf-8'); const transformed_template = await vite.transformIndexHtml(req.url, template); const { render } = await vite.ssrLoadModule('svelte/server'); const { default: App } = await vite.ssrLoadModule('/src/App.svelte'); const { head, body } = await render(App); const html = transformed_template .replace(`<!--ssr-head-->`, head) .replace(`<!--ssr-body-->`, body) // check that Safari doesn't break hydration .replaceAll('+636-555-3226', '<a href="tel:+636-555-3226">+636-555-3226</a>'); res.writeHead(200, { 'Content-Type': 'text/html' }).end(html); }) .listen(PORT, () => { console.log(`http://localhost:${PORT}`); });
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/ssr-prod.js
playgrounds/sandbox/ssr-prod.js
import fs from 'node:fs'; import path from 'node:path'; import polka from 'polka'; import { render } from 'svelte/server'; import App from './src/App.svelte'; import './ssr-common.js'; const { head, body } = await render(App); const rendered = fs .readFileSync(path.resolve('./dist/client/index.html'), 'utf-8') .replace(`<!--ssr-body-->`, body) .replace(`<!--ssr-head-->`, head); const types = { '.js': 'application/javascript', '.css': 'text/css' }; polka() .use((req, res) => { if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html' }); res.end(rendered); return; } const file = path.resolve('./dist/client' + req.url); if (fs.existsSync(file)) { const type = types[path.extname(req.url)] ?? 'application/octet-stream'; res.writeHead(200, { 'content-type': type }); fs.createReadStream(file).pipe(res); return; } res.writeHead(404); res.end('not found'); }) .listen('3000'); console.log('listening on http://localhost:3000');
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/scripts/create-test.js
playgrounds/sandbox/scripts/create-test.js
// Creates a test from the existing playground. cwd needs to be playground/sandbox import fs from 'fs'; import path from 'path'; // Get target folder from command line arguments let target_folder = process.argv[2]; if (!target_folder) { console.error( 'Please provide a target folder as an argument. Example: node create-test.js runtime-runes/my-test' ); process.exit(1); } if (!target_folder.includes('/')) { target_folder = 'runtime-runes/' + target_folder; } if (!target_folder.startsWith('runtime-')) { console.error( 'Target folder must start with "runtime-" (can only convert to these kinds of tests)' ); process.exit(1); } target_folder = path.join( path.resolve('../../packages/svelte/tests', target_folder.split('/')[0]), 'samples', target_folder.split('/')[1] ); const exists = fs.existsSync(target_folder); // Check if target folder already exists and ask for confirmation if (exists) { console.log(`Target folder "${target_folder}" already exists.`); process.stdout.write('Do you want to override the existing test? (Y/n): '); // Read user input synchronously const stdin = process.stdin; stdin.setRawMode(true); stdin.resume(); stdin.setEncoding('utf8'); const response = await new Promise((resolve) => { stdin.on('data', (key) => { stdin.setRawMode(false); stdin.pause(); process.stdout.write('\n'); resolve(key); }); }); if (response.toLowerCase() === 'n') { console.log('Operation cancelled.'); process.exit(0); } // Clear the existing target folder except for _config.js const files = fs.readdirSync(target_folder); for (const file of files) { if (file !== '_config.js') { const filePath = path.join(target_folder, file); fs.rmSync(filePath, { recursive: true, force: true }); } } } else { fs.mkdirSync(target_folder, { recursive: true }); } // Starting file const app_svelte_path = path.resolve('./src/App.svelte'); const collected_files = new Set(); const processed_files = new Set(); function collect_imports(file_path) { if (processed_files.has(file_path) || !fs.existsSync(file_path)) { return; } processed_files.add(file_path); collected_files.add(file_path); const content = fs.readFileSync(file_path, 'utf8'); // Regex to match import statements const import_regex = /import\s+(?:[^'"]*\s+from\s+)?['"]([^'"]+)['"]/g; let match; while ((match = import_regex.exec(content)) !== null) { const import_path = match[1]; // Skip node_modules imports if (!import_path.startsWith('.')) { continue; } // Resolve relative import path const resolved_path = path.resolve(path.dirname(file_path), import_path); // Try different extensions if file doesn't exist const extensions = ['', '.svelte', '.js', '.ts']; let actual_path = null; for (const ext of extensions) { const test_path = resolved_path + ext; if (fs.existsSync(test_path)) { actual_path = test_path; break; } } if (actual_path) { collect_imports(actual_path); } } } // Start collecting from App.svelte collect_imports(app_svelte_path); // Copy collected files to target folder for (const file_path of collected_files) { const relative_path = path.relative(path.resolve('./src'), file_path); let target_path = path.join(target_folder, relative_path); // Rename App.svelte to main.svelte if (path.basename(file_path) === 'App.svelte') { target_path = path.join(target_folder, path.dirname(relative_path), 'main.svelte'); } // Ensure target directory exists const target_dir = path.dirname(target_path); if (!fs.existsSync(target_dir)) { fs.mkdirSync(target_dir, { recursive: true }); } // Copy file fs.copyFileSync(file_path, target_path); console.log(`Copied: ${file_path} -> ${target_path}`); } // Create empty _config.js if (!exists) { const config_path = path.join(target_folder, '_config.js'); fs.writeFileSync( config_path, `import { test } from '../../test'; export default test({ async test({ assert, target }) { } }); ` ); console.log(`Created: ${config_path}`); } console.log(`\nTest files created in: ${target_folder}`);
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/scripts/create-app-svelte.js
playgrounds/sandbox/scripts/create-app-svelte.js
import fs from 'node:fs'; const destination = new URL('../src/main.svelte', import.meta.url); if (!fs.existsSync(destination)) { const template = new URL('./main.template.svelte', import.meta.url); try { fs.mkdirSync(new URL('../src', import.meta.url)); } catch {} fs.writeFileSync(destination, fs.readFileSync(template, 'utf-8'), 'utf-8'); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/scripts/hash.js
playgrounds/sandbox/scripts/hash.js
import fs from 'node:fs'; const files = []; for (const basename of fs.readdirSync('src')) { if (fs.statSync(`src/${basename}`).isDirectory()) continue; files.push({ type: 'file', name: basename, basename, contents: fs.readFileSync(`src/${basename}`, 'utf-8'), text: true // TODO might not be }); } const payload = JSON.stringify({ name: 'sandbox', files }); async function compress(payload) { const reader = new Blob([payload]) .stream() .pipeThrough(new CompressionStream('gzip')) .getReader(); let buffer = ''; for (;;) { const { done, value } = await reader.read(); if (done) { reader.releaseLock(); return btoa(buffer).replaceAll('+', '-').replaceAll('/', '_'); } else { for (let i = 0; i < value.length; i++) { // decoding as utf-8 will make btoa reject the string buffer += String.fromCharCode(value[i]); } } } } const hash = await compress(payload); console.log(`https://svelte.dev/playground/untitled#${hash}`);
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/playgrounds/sandbox/scripts/download.js
playgrounds/sandbox/scripts/download.js
import fs from 'node:fs'; const arg = process.argv[2]; /** @type {URL} */ let url; try { url = new URL(arg); } catch (e) { console.error(`${arg} is not a URL`); process.exit(1); } if (url.origin !== 'https://svelte.dev' || !url.pathname.startsWith('/playground/')) { console.error(`${arg} is not a Svelte playground URL`); process.exit(1); } let files; if (url.hash.length > 1) { const decoded = atob(url.hash.slice(1).replaceAll('-', '+').replaceAll('_', '/')); // putting it directly into the blob gives a corrupted file const u8 = new Uint8Array(decoded.length); for (let i = 0; i < decoded.length; i++) { u8[i] = decoded.charCodeAt(i); } const stream = new Blob([u8]).stream().pipeThrough(new DecompressionStream('gzip')); const json = await new Response(stream).text(); files = JSON.parse(json).files; } else { const id = url.pathname.split('/')[2]; const response = await fetch(`https://svelte.dev/playground/api/${id}.json`); files = (await response.json()).components.map((data) => { const basename = `${data.name}.${data.type}`; return { type: 'file', name: basename, basename, contents: data.source, text: true }; }); } for (const file of files) { fs.writeFileSync(`src/${file.name}`, file.contents); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/rollup.config.js
packages/svelte/rollup.config.js
import commonjs from '@rollup/plugin-commonjs'; import resolve from '@rollup/plugin-node-resolve'; import terser from '@rollup/plugin-terser'; import { defineConfig } from 'rollup'; // runs the version generation as a side-effect of importing import './scripts/generate-version.js'; export default defineConfig({ input: 'src/compiler/index.js', output: { file: 'compiler/index.js', format: 'umd', name: 'svelte' }, plugins: [resolve(), commonjs(), terser()] });
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/generate-types.js
packages/svelte/scripts/generate-types.js
import fs from 'node:fs'; import process from 'node:process'; import { fileURLToPath } from 'node:url'; import { createBundle } from 'dts-buddy'; const dir = fileURLToPath(new URL('..', import.meta.url)); const pkg = JSON.parse(fs.readFileSync(`${dir}/package.json`, 'utf-8')); // For people not using moduleResolution: 'bundler', we need to generate these files. Think about removing this in Svelte 6 or 7 // It may look weird, but the imports MUST be ending with index.js to be properly resolved in all TS modes for (const name of ['action', 'animate', 'easing', 'motion', 'store', 'transition', 'legacy']) { fs.writeFileSync(`${dir}/${name}.d.ts`, "import './types/index.js';\n"); } fs.writeFileSync(`${dir}/index.d.ts`, "import './types/index.js';\n"); fs.writeFileSync(`${dir}/compiler.d.ts`, "import './types/index.js';\n"); // TODO: Remove these in Svelte 6. They are here so that tooling (which historically made use of these) can support Svelte 4-6 in one minor version fs.mkdirSync(`${dir}/types/compiler`, { recursive: true }); fs.writeFileSync(`${dir}/types/compiler/preprocess.d.ts`, "import '../index.js';\n"); fs.writeFileSync(`${dir}/types/compiler/interfaces.d.ts`, "import '../index.js';\n"); await createBundle({ output: `${dir}/types/index.d.ts`, compilerOptions: { // so that types/properties with `@internal` (and its dependencies) are removed from the output stripInternal: true, paths: Object.fromEntries( Object.entries(pkg.imports).map( /** @param {[string,any]} import */ ([key, value]) => { return [key, [value.types ?? value.default ?? value]]; } ) ) }, modules: { [pkg.name]: `${dir}/src/index.d.ts`, [`${pkg.name}/action`]: `${dir}/src/action/public.d.ts`, [`${pkg.name}/animate`]: `${dir}/src/animate/public.d.ts`, [`${pkg.name}/attachments`]: `${dir}/src/attachments/public.d.ts`, [`${pkg.name}/compiler`]: `${dir}/src/compiler/public.d.ts`, [`${pkg.name}/easing`]: `${dir}/src/easing/index.js`, [`${pkg.name}/legacy`]: `${dir}/src/legacy/legacy-client.js`, [`${pkg.name}/motion`]: `${dir}/src/motion/public.d.ts`, [`${pkg.name}/reactivity`]: `${dir}/src/reactivity/index-client.js`, [`${pkg.name}/reactivity/window`]: `${dir}/src/reactivity/window/index.js`, [`${pkg.name}/server`]: `${dir}/src/server/index.d.ts`, [`${pkg.name}/store`]: `${dir}/src/store/public.d.ts`, [`${pkg.name}/transition`]: `${dir}/src/transition/public.d.ts`, [`${pkg.name}/events`]: `${dir}/src/events/public.d.ts`, // TODO remove in Svelte 6 [`${pkg.name}/types/compiler/preprocess`]: `${dir}/src/compiler/preprocess/legacy-public.d.ts`, [`${pkg.name}/types/compiler/interfaces`]: `${dir}/src/compiler/types/legacy-interfaces.d.ts` } }); fs.appendFileSync(`${dir}/types/index.d.ts`, '\n'); const types = fs.readFileSync(`${dir}/types/index.d.ts`, 'utf-8'); const bad_links = [...types.matchAll(/\]\((\/[^)]+)\)/g)]; if (bad_links.length > 0) { // eslint-disable-next-line no-console console.error( `The following links in JSDoc annotations should be prefixed with https://svelte.dev:` ); for (const [, link] of bad_links) { // eslint-disable-next-line no-console console.error(`- ${link}`); } process.exit(1); } if (types.includes('\texport { ')) { // eslint-disable-next-line no-console console.error( `The generated types file should not contain 'export { ... }' statements. ` + `TypeScript is bad at following these: when creating d.ts files through @sveltejs/package, and one of these types is used, ` + `TypeScript will likely fail at generating a d.ts file. ` + `To prevent this, do 'export interface Foo {}' instead of 'interface Foo {}' and then 'export { Foo }'` ); process.exit(1); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/generate-version.js
packages/svelte/scripts/generate-version.js
import fs from 'node:fs'; const pkg = JSON.parse(fs.readFileSync('package.json', 'utf-8')); fs.writeFileSync( './src/version.js', `// generated during release, do not modify /** * The current version, as set in package.json. * @type {string} */ export const VERSION = '${pkg.version}'; export const PUBLIC_VERSION = '${pkg.version.split('.')[0]}'; ` );
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/check-treeshakeability.js
packages/svelte/scripts/check-treeshakeability.js
import fs from 'node:fs'; import path from 'node:path'; import process from 'node:process'; import { rollup } from 'rollup'; import virtual from '@rollup/plugin-virtual'; import { nodeResolve } from '@rollup/plugin-node-resolve'; import { compile } from 'svelte/compiler'; /** * @param {string} entry */ async function bundle_code(entry) { const bundle = await rollup({ input: '__entry__', plugins: [ virtual({ __entry__: entry }), { name: 'resolve-svelte', resolveId(importee) { if (importee.startsWith('svelte')) { const entry = pkg.exports[importee.replace('svelte', '.')]; return path.resolve(entry.browser ?? entry.default); } } }, nodeResolve({ exportConditions: ['production', 'import', 'browser', 'default'] }) ], onwarn: (warning, handle) => { if (warning.code !== 'EMPTY_BUNDLE' && warning.code !== 'CIRCULAR_DEPENDENCY') { handle(warning); } } }); const { output } = await bundle.generate({}); if (output.length > 1) { throw new Error('errr what'); } return output[0].code.trim(); } const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); let failed = false; // eslint-disable-next-line no-console console.group('checking treeshakeability'); for (const key in pkg.exports) { // special cases if (key === './compiler') continue; if (key === './internal') continue; if (key === './internal/disclose-version') continue; if (key === './internal/flags/legacy') continue; if (key === './internal/flags/tracing') continue; for (const type of ['browser', 'default']) { if (!pkg.exports[key][type]) continue; const subpackage = path.join(pkg.name, key); const resolved = path.resolve(pkg.exports[key][type]); const code = await bundle_code(`import ${JSON.stringify(resolved)}`); if (code === '') { // eslint-disable-next-line no-console console.error(`✅ ${subpackage} (${type})`); } else { // eslint-disable-next-line no-console console.error(code); // eslint-disable-next-line no-console console.error(`❌ ${subpackage} (${type})`); failed = true; } } } const client_main = path.resolve(pkg.exports['.'].browser); const bundle = await bundle_code( // Use all features which contain hydration code to ensure it's treeshakeable compile( ` <svelte:options runes /> <script> import { mount } from ${JSON.stringify(client_main)}; mount(); let foo; </script> <svelte:head><title>hi</title></svelte:head> <input bind:value={foo} /> <a href={foo} class={foo}>a</a> <a {...foo}>a</a> <svelte:component this={foo} /> <svelte:element this={foo} /> <C {foo} /> {#if foo} {/if} {#each foo as bar} {/each} {#await foo} {/await} {#key foo} {/key} {#snippet x()} {/snippet} {@render x()} {@html foo} `, { filename: 'App.svelte' } ).js.code ); /** * @param {string} case_name * @param {string[]} strings */ function check_bundle(case_name, ...strings) { for (const string of strings) { const index = bundle.indexOf(string); if (index >= 0) { // eslint-disable-next-line no-console console.error(`❌ ${case_name} not treeshakeable`); failed = true; let lines = bundle.slice(index - 500, index + 500).split('\n'); const target_line = lines.findIndex((line) => line.includes(string)); // mark the failed line lines = lines .map((line, i) => (i === target_line ? `> ${line}` : `| ${line}`)) .slice(target_line - 5, target_line + 6); // eslint-disable-next-line no-console console.error('The first failed line:\n' + lines.join('\n')); return; } } // eslint-disable-next-line no-console console.error(`✅ ${case_name} treeshakeable`); } check_bundle('Hydration code', 'hydrate_node', 'hydrate_next'); check_bundle('Legacy code', 'component_context.l'); check_bundle('$inspect.trace', `'CreatedAt'`); if (failed) { // eslint-disable-next-line no-console console.error('Full bundle at', path.resolve('scripts/_bundle.js')); fs.writeFileSync('scripts/_bundle.js', bundle); } // eslint-disable-next-line no-console console.groupEnd(); if (failed) { process.exit(1); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/index.js
packages/svelte/scripts/process-messages/index.js
/** @import { Node } from 'esrap/languages/ts' */ /** @import * as ESTree from 'estree' */ /** @import { AST } from 'svelte/compiler' */ // @ts-check import process from 'node:process'; import fs from 'node:fs'; import * as acorn from 'acorn'; import { walk } from 'zimmerframe'; import * as esrap from 'esrap'; import ts from 'esrap/languages/ts'; const DIR = '../../documentation/docs/98-reference/.generated'; const watch = process.argv.includes('-w'); function run() { /** @type {Record<string, Record<string, { messages: string[], details: string | null }>>} */ const messages = {}; const seen = new Set(); fs.rmSync(DIR, { force: true, recursive: true }); fs.mkdirSync(DIR); for (const category of fs.readdirSync('messages')) { if (category.startsWith('.')) continue; messages[category] = {}; for (const file of fs.readdirSync(`messages/${category}`)) { if (!file.endsWith('.md')) continue; const markdown = fs .readFileSync(`messages/${category}/${file}`, 'utf-8') .replace(/\r\n/g, '\n'); const sorted = []; for (const match of markdown.matchAll(/## ([\w]+)\n\n([^]+?)(?=$|\n\n## )/g)) { const [_, code, text] = match; if (seen.has(code)) { throw new Error(`Duplicate message code ${category}/${code}`); } sorted.push({ code, _ }); const sections = text.trim().split('\n\n'); const details = []; while (!sections[sections.length - 1].startsWith('> ')) { details.unshift(/** @type {string} */ (sections.pop())); } if (sections.length === 0) { throw new Error('No message text'); } seen.add(code); messages[category][code] = { messages: sections.map((section) => section.replace(/^> /gm, '').replace(/^>\n/gm, '\n')), details: details.join('\n\n') }; } sorted.sort((a, b) => (a.code < b.code ? -1 : 1)); fs.writeFileSync( `messages/${category}/${file}`, sorted.map((x) => x._.trim()).join('\n\n') + '\n' ); } fs.writeFileSync( `${DIR}/${category}.md`, '<!-- This file is generated by scripts/process-messages/index.js. Do not edit! -->\n\n' + Object.entries(messages[category]) .map(([code, { messages, details }]) => { const chunks = [ `### ${code}`, ...messages.map((message) => '```\n' + message + '\n```') ]; if (details) { chunks.push(details); } return chunks.join('\n\n'); }) .sort() .join('\n\n') + '\n' ); } /** * @param {string} name * @param {string} dest */ function transform(name, dest) { const source = fs .readFileSync(new URL(`./templates/${name}.js`, import.meta.url), 'utf-8') .replace(/\r\n/g, '\n'); /** @type {AST.JSComment[]} */ const comments = []; let ast = /** @type {ESTree.Node} */ ( /** @type {unknown} */ ( acorn.parse(source, { ecmaVersion: 'latest', sourceType: 'module', locations: true, onComment: comments }) ) ); comments.forEach((comment) => { if (comment.type === 'Block') { comment.value = comment.value.replace(/^\t+/gm, ''); } }); ast = walk(ast, null, { Identifier(node, context) { if (node.name === 'CODES') { /** @type {ESTree.ArrayExpression} */ const array = { type: 'ArrayExpression', elements: Object.keys(messages[name]).map((code) => ({ type: 'Literal', value: code })) }; return array; } } }); const body = /** @type {ESTree.Program} */ (ast).body; const category = messages[name]; // find the `export function CODE` node const index = body.findIndex((node) => { if ( node.type === 'ExportNamedDeclaration' && node.declaration && node.declaration.type === 'FunctionDeclaration' ) { return node.declaration.id.name === 'CODE'; } }); if (index === -1) throw new Error(`missing export function CODE in ${name}.js`); const template_node = body[index]; body.splice(index, 1); const jsdoc = /** @type {AST.JSComment} */ ( comments.findLast((comment) => comment.start < /** @type {number} */ (template_node.start)) ); const printed = esrap.print( /** @type {Node} */ (ast), ts({ comments: comments.filter((comment) => comment !== jsdoc) }) ); for (const code in category) { const { messages } = category[code]; /** @type {string[]} */ const vars = []; const group = messages.map((text, i) => { for (const match of text.matchAll(/%(\w+)%/g)) { const name = match[1]; if (!vars.includes(name)) { vars.push(match[1]); } } return { text, vars: vars.slice() }; }); /** @type {ESTree.Expression} */ let message = { type: 'Literal', value: '' }; let prev_vars; for (let i = 0; i < group.length; i += 1) { const { text, vars } = group[i]; if (vars.length === 0) { message = { type: 'Literal', value: text }; prev_vars = vars; continue; } const parts = text.split(/(%\w+%)/); /** @type {ESTree.Expression[]} */ const expressions = []; /** @type {ESTree.TemplateElement[]} */ const quasis = []; for (let i = 0; i < parts.length; i += 1) { const part = parts[i]; if (i % 2 === 0) { const str = part.replace(/(`|\${)/g, '\\$1'); quasis.push({ type: 'TemplateElement', value: { raw: str, cooked: str }, tail: i === parts.length - 1 }); } else { expressions.push({ type: 'Identifier', name: part.slice(1, -1) }); } } /** @type {ESTree.Expression} */ const expression = { type: 'TemplateLiteral', expressions, quasis }; if (prev_vars) { if (vars.length === prev_vars.length) { throw new Error('Message overloads must have new parameters'); } message = { type: 'ConditionalExpression', test: { type: 'Identifier', name: vars[prev_vars.length] }, consequent: expression, alternate: message }; } else { message = expression; } prev_vars = vars; } const clone = /** @type {ESTree.Statement} */ ( walk(/** @type {ESTree.Node} */ (template_node), null, { FunctionDeclaration(node, context) { if (node.id.name !== 'CODE') return; const params = []; for (const param of node.params) { if (param.type === 'Identifier' && param.name === 'PARAMETER') { params.push(...vars.map((name) => ({ type: 'Identifier', name }))); } else { params.push(param); } } return /** @type {ESTree.FunctionDeclaration} */ ({ .../** @type {ESTree.FunctionDeclaration} */ (context.next()), params, id: { ...node.id, name: code } }); }, TemplateLiteral(node, context) { /** @type {ESTree.TemplateElement} */ let quasi = { type: 'TemplateElement', value: { ...node.quasis[0].value }, tail: node.quasis[0].tail }; /** @type {ESTree.TemplateLiteral} */ let out = { type: 'TemplateLiteral', quasis: [quasi], expressions: [] }; for (let i = 0; i < node.expressions.length; i += 1) { const q = structuredClone(node.quasis[i + 1]); const e = node.expressions[i]; if (e.type === 'Literal' && e.value === 'CODE') { quasi.value.raw += code + q.value.raw; continue; } if (e.type === 'Identifier' && e.name === 'MESSAGE') { if (message.type === 'Literal') { const str = /** @type {string} */ (message.value).replace(/(`|\${)/g, '\\$1'); quasi.value.raw += str + q.value.raw; continue; } if (message.type === 'TemplateLiteral') { const m = structuredClone(message); quasi.value.raw += m.quasis[0].value.raw; out.quasis.push(...m.quasis.slice(1)); out.expressions.push(...m.expressions); quasi = m.quasis[m.quasis.length - 1]; quasi.value.raw += q.value.raw; continue; } } out.quasis.push((quasi = q)); out.expressions.push(/** @type {ESTree.Expression} */ (context.visit(e))); } return out; }, Literal(node) { if (node.value === 'CODE') { return { type: 'Literal', value: code }; } }, Identifier(node) { if (node.name !== 'MESSAGE') return; return message; } }) ); const jsdoc_clone = { ...jsdoc, value: /** @type {string} */ (jsdoc.value) .split('\n') .map((line) => { if (line === ' * MESSAGE') { return messages[messages.length - 1] .split('\n') .map((line) => ` * ${line}`) .join('\n'); } if (line.includes('PARAMETER')) { return vars .map((name, i) => { const optional = i >= group[0].vars.length; return optional ? ` * @param {string | undefined | null} [${name}]` : ` * @param {string} ${name}`; }) .join('\n'); } return line; }) .filter((x) => x !== '') .join('\n') }; const block = esrap.print( // @ts-expect-error some bullshit /** @type {ESTree.Program} */ ({ ...ast, body: [clone] }), ts({ comments: [jsdoc_clone] }) ).code; printed.code += `\n\n${block}`; body.push(clone); } fs.writeFileSync( dest, `/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\n` + printed.code, 'utf-8' ); } transform('compile-errors', 'src/compiler/errors.js'); transform('compile-warnings', 'src/compiler/warnings.js'); transform('client-warnings', 'src/internal/client/warnings.js'); transform('client-errors', 'src/internal/client/errors.js'); transform('server-warnings', 'src/internal/server/warnings.js'); transform('server-errors', 'src/internal/server/errors.js'); transform('shared-errors', 'src/internal/shared/errors.js'); transform('shared-warnings', 'src/internal/shared/warnings.js'); } if (watch) { let running = false; let timeout; fs.watch('messages', { recursive: true }, (type, file) => { if (running) { timeout ??= setTimeout(() => { running = false; timeout = null; }); } else { running = true; // eslint-disable-next-line no-console console.log('Regenerating messages...'); run(); } }); } run();
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/shared-warnings.js
packages/svelte/scripts/process-messages/templates/shared-warnings.js
import { DEV } from 'esm-env'; var bold = 'font-weight: bold'; var normal = 'font-weight: normal'; /** * MESSAGE * @param {string} PARAMETER */ export function CODE(PARAMETER) { if (DEV) { console.warn( `%c[svelte] ${'CODE'}\n%c${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`, bold, normal ); } else { console.warn(`https://svelte.dev/e/${'CODE'}`); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/compile-warnings.js
packages/svelte/scripts/process-messages/templates/compile-warnings.js
import { warnings, ignore_stack, ignore_map, warning_filter } from './state.js'; import { CompileDiagnostic } from './utils/compile_diagnostic.js'; /** @typedef {{ start?: number, end?: number }} NodeLike */ class InternalCompileWarning extends CompileDiagnostic { name = 'CompileWarning'; /** * @param {string} code * @param {string} message * @param {[number, number] | undefined} position */ constructor(code, message, position) { super(code, message, position); } } /** * @param {null | NodeLike} node * @param {string} code * @param {string} message */ function w(node, code, message) { let stack = ignore_stack; if (node) { stack = ignore_map.get(node) ?? ignore_stack; } if (stack && stack.at(-1)?.has(code)) return; const warning = new InternalCompileWarning( code, message, node && node.start !== undefined ? [node.start, node.end ?? node.start] : undefined ); if (!warning_filter(warning)) return; warnings.push(warning); } export const codes = CODES; /** * MESSAGE * @param {null | NodeLike} node * @param {string} PARAMETER */ export function CODE(node, PARAMETER) { w(node, 'CODE', `${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/server-warnings.js
packages/svelte/scripts/process-messages/templates/server-warnings.js
import { DEV } from 'esm-env'; var bold = 'font-weight: bold'; var normal = 'font-weight: normal'; /** * MESSAGE * @param {string} PARAMETER */ export function CODE(PARAMETER) { if (DEV) { console.warn( `%c[svelte] ${'CODE'}\n%c${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`, bold, normal ); } else { console.warn(`https://svelte.dev/e/${'CODE'}`); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/client-errors.js
packages/svelte/scripts/process-messages/templates/client-errors.js
import { DEV } from 'esm-env'; export * from '../shared/errors.js'; /** * MESSAGE * @param {string} PARAMETER * @returns {never} */ export function CODE(PARAMETER) { if (DEV) { const error = new Error(`${'CODE'}\n${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`); error.name = 'Svelte error'; throw error; } else { throw new Error(`https://svelte.dev/e/${'CODE'}`); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/client-warnings.js
packages/svelte/scripts/process-messages/templates/client-warnings.js
import { DEV } from 'esm-env'; var bold = 'font-weight: bold'; var normal = 'font-weight: normal'; /** * MESSAGE * @param {string} PARAMETER */ export function CODE(PARAMETER) { if (DEV) { console.warn( `%c[svelte] ${'CODE'}\n%c${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`, bold, normal ); } else { console.warn(`https://svelte.dev/e/${'CODE'}`); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/compile-errors.js
packages/svelte/scripts/process-messages/templates/compile-errors.js
import { CompileDiagnostic } from './utils/compile_diagnostic.js'; /** @typedef {{ start?: number, end?: number }} NodeLike */ class InternalCompileError extends Error { message = ''; // ensure this property is enumerable #diagnostic; /** * @param {string} code * @param {string} message * @param {[number, number] | undefined} position */ constructor(code, message, position) { super(message); this.stack = ''; // avoid unnecessary noise; don't set it as a class property or it becomes enumerable // We want to extend from Error so that various bundler plugins properly handle it. // But we also want to share the same object shape with that of warnings, therefore // we create an instance of the shared class an copy over its properties. this.#diagnostic = new CompileDiagnostic(code, message, position); Object.assign(this, this.#diagnostic); this.name = 'CompileError'; } toString() { return this.#diagnostic.toString(); } toJSON() { return this.#diagnostic.toJSON(); } } /** * @param {null | number | NodeLike} node * @param {string} code * @param {string} message * @returns {never} */ function e(node, code, message) { const start = typeof node === 'number' ? node : node?.start; const end = typeof node === 'number' ? node : node?.end; throw new InternalCompileError( code, message, start !== undefined ? [start, end ?? start] : undefined ); } /** * MESSAGE * @param {null | number | NodeLike} node * @param {string} PARAMETER * @returns {never} */ export function CODE(node, PARAMETER) { e(node, 'CODE', `${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/server-errors.js
packages/svelte/scripts/process-messages/templates/server-errors.js
export * from '../shared/errors.js'; /** * MESSAGE * @param {string} PARAMETER * @returns {never} */ export function CODE(PARAMETER) { const error = new Error(`${'CODE'}\n${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`); error.name = 'Svelte error'; throw error; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/scripts/process-messages/templates/shared-errors.js
packages/svelte/scripts/process-messages/templates/shared-errors.js
import { DEV } from 'esm-env'; /** * MESSAGE * @param {string} PARAMETER * @returns {never} */ export function CODE(PARAMETER) { if (DEV) { const error = new Error(`${'CODE'}\n${MESSAGE}\nhttps://svelte.dev/e/${'CODE'}`); error.name = 'Svelte error'; throw error; } else { throw new Error(`https://svelte.dev/e/${'CODE'}`); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/escaping.js
packages/svelte/src/escaping.js
const ATTR_REGEX = /[&"<]/g; const CONTENT_REGEX = /[&<]/g; /** * @template V * @param {V} value * @param {boolean} [is_attr] */ export function escape_html(value, is_attr) { const str = String(value ?? ''); const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX; pattern.lastIndex = 0; let escaped = ''; let last = 0; while (pattern.test(str)) { const i = pattern.lastIndex - 1; const ch = str[i]; escaped += str.substring(last, i) + (ch === '&' ? '&amp;' : ch === '"' ? '&quot;' : '&lt;'); last = i + 1; } return escaped + str.substring(last); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/index-server.js
packages/svelte/src/index-server.js
/** @import { SSRContext } from '#server' */ /** @import { Renderer } from './internal/server/renderer.js' */ import { ssr_context } from './internal/server/context.js'; import { noop } from './internal/shared/utils.js'; import * as e from './internal/server/errors.js'; /** @param {() => void} fn */ export function onDestroy(fn) { /** @type {Renderer} */ (/** @type {SSRContext} */ (ssr_context).r).on_destroy(fn); } export { noop as beforeUpdate, noop as afterUpdate, noop as onMount, noop as flushSync, run as untrack } from './internal/shared/utils.js'; export function createEventDispatcher() { return noop; } export function mount() { e.lifecycle_function_unavailable('mount'); } export function hydrate() { e.lifecycle_function_unavailable('hydrate'); } export function unmount() { e.lifecycle_function_unavailable('unmount'); } export function fork() { e.lifecycle_function_unavailable('fork'); } export async function tick() {} export async function settled() {} export { getAbortSignal } from './internal/server/abort-signal.js'; export { createContext, getAllContexts, getContext, hasContext, setContext } from './internal/server/context.js'; export { hydratable } from './internal/server/hydratable.js'; export { createRawSnippet } from './internal/server/blocks/snippet.js';
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/constants.js
packages/svelte/src/constants.js
export const EACH_ITEM_REACTIVE = 1; export const EACH_INDEX_REACTIVE = 1 << 1; /** See EachBlock interface metadata.is_controlled for an explanation what this is */ export const EACH_IS_CONTROLLED = 1 << 2; export const EACH_IS_ANIMATED = 1 << 3; export const EACH_ITEM_IMMUTABLE = 1 << 4; export const PROPS_IS_IMMUTABLE = 1; export const PROPS_IS_RUNES = 1 << 1; export const PROPS_IS_UPDATED = 1 << 2; export const PROPS_IS_BINDABLE = 1 << 3; export const PROPS_IS_LAZY_INITIAL = 1 << 4; export const TRANSITION_IN = 1; export const TRANSITION_OUT = 1 << 1; export const TRANSITION_GLOBAL = 1 << 2; export const TEMPLATE_FRAGMENT = 1; export const TEMPLATE_USE_IMPORT_NODE = 1 << 1; export const TEMPLATE_USE_SVG = 1 << 2; export const TEMPLATE_USE_MATHML = 1 << 3; export const HYDRATION_START = '['; /** used to indicate that an `{:else}...` block was rendered */ export const HYDRATION_START_ELSE = '[!'; export const HYDRATION_END = ']'; export const HYDRATION_ERROR = {}; export const ELEMENT_IS_NAMESPACED = 1; export const ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1; export const ELEMENT_IS_INPUT = 1 << 2; export const UNINITIALIZED = Symbol(); // Dev-time component properties export const FILENAME = Symbol('filename'); export const HMR = Symbol('hmr'); export const NAMESPACE_HTML = 'http://www.w3.org/1999/xhtml'; export const NAMESPACE_SVG = 'http://www.w3.org/2000/svg'; export const NAMESPACE_MATHML = 'http://www.w3.org/1998/Math/MathML'; // we use a list of ignorable runtime warnings because not every runtime warning // can be ignored and we want to keep the validation for svelte-ignore in place export const IGNORABLE_RUNTIME_WARNINGS = /** @type {const} */ ([ 'await_waterfall', 'await_reactivity_loss', 'state_snapshot_uncloneable', 'binding_property_non_reactive', 'hydration_attribute_changed', 'hydration_html_changed', 'ownership_invalid_binding', 'ownership_invalid_mutation' ]); /** * Whitespace inside one of these elements will not result in * a whitespace node being created in any circumstances. (This * list is almost certainly very incomplete) * TODO this is currently unused */ export const ELEMENTS_WITHOUT_TEXT = ['audio', 'datalist', 'dl', 'optgroup', 'select', 'video']; export const ATTACHMENT_KEY = '@attach';
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/version.js
packages/svelte/src/version.js
// generated during release, do not modify /** * The current version, as set in package.json. * @type {string} */ export const VERSION = '5.46.1'; export const PUBLIC_VERSION = '5';
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/html-tree-validation.js
packages/svelte/src/html-tree-validation.js
/** * Map of elements that have certain elements that are not allowed inside them, in the sense that they will auto-close the parent/ancestor element. * Theoretically one could take advantage of it but most of the time it will just result in confusing behavior and break when SSR'd. * There are more elements that are invalid inside other elements, but they're not auto-closed and so don't break SSR and are therefore not listed here. * @type {Record<string, { direct: string[]} | { descendant: string[]; reset_by?: string[] }>} */ const autoclosing_children = { // based on http://developers.whatwg.org/syntax.html#syntax-tag-omission li: { direct: ['li'] }, // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt#technical_summary dt: { descendant: ['dt', 'dd'], reset_by: ['dl'] }, dd: { descendant: ['dt', 'dd'], reset_by: ['dl'] }, p: { descendant: [ 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul' ] }, rt: { descendant: ['rt', 'rp'] }, rp: { descendant: ['rt', 'rp'] }, optgroup: { descendant: ['optgroup'] }, option: { descendant: ['option', 'optgroup'] }, thead: { direct: ['tbody', 'tfoot'] }, tbody: { direct: ['tbody', 'tfoot'] }, tfoot: { direct: ['tbody'] }, tr: { direct: ['tr', 'tbody'] }, td: { direct: ['td', 'th', 'tr'] }, th: { direct: ['td', 'th', 'tr'] } }; /** * Returns true if the tag is either the last in the list of siblings and will be autoclosed, * or not allowed inside the parent tag such that it will auto-close it. The latter results * in the browser repairing the HTML, which will likely result in an error during hydration. * @param {string} current * @param {string} [next] */ export function closing_tag_omitted(current, next) { const disallowed = autoclosing_children[current]; if (disallowed) { if ( !next || ('direct' in disallowed ? disallowed.direct : disallowed.descendant).includes(next) ) { return true; } } return false; } /** * Map of elements that have certain elements that are not allowed inside them, in the sense that the browser will somehow repair the HTML. * There are more elements that are invalid inside other elements, but they're not repaired and so don't break SSR and are therefore not listed here. * @type {Record<string, { direct: string[]} | { descendant: string[]; reset_by?: string[]; only?: string[] } | { only: string[] }>} */ const disallowed_children = { ...autoclosing_children, optgroup: { only: ['option', '#text'] }, // Strictly speaking, seeing an <option> doesn't mean we're in a <select>, but we assume it here option: { only: ['#text'] }, form: { descendant: ['form'] }, a: { descendant: ['a'] }, button: { descendant: ['button'] }, h1: { descendant: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }, h2: { descendant: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }, h3: { descendant: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }, h4: { descendant: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }, h5: { descendant: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }, h6: { descendant: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }, // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect select: { only: ['option', 'optgroup', '#text', 'hr', 'script', 'template'] }, // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd tr: { only: ['th', 'td', 'style', 'script', 'template'] }, // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody tbody: { only: ['tr', 'style', 'script', 'template'] }, thead: { only: ['tr', 'style', 'script', 'template'] }, tfoot: { only: ['tr', 'style', 'script', 'template'] }, // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup colgroup: { only: ['col', 'template'] }, // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable table: { only: ['caption', 'colgroup', 'tbody', 'thead', 'tfoot', 'style', 'script', 'template'] }, // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead head: { only: [ 'base', 'basefont', 'bgsound', 'link', 'meta', 'title', 'noscript', 'noframes', 'style', 'script', 'template' ] }, // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element html: { only: ['head', 'body', 'frameset'] }, frameset: { only: ['frame'] }, '#document': { only: ['html'] } }; /** * Returns an error message if the tag is not allowed inside the ancestor tag (which is grandparent and above) such that it will result * in the browser repairing the HTML, which will likely result in an error during hydration. * @param {string} child_tag * @param {string[]} ancestors All nodes starting with the parent, up until the ancestor, which means two entries minimum * @param {string} [child_loc] * @param {string} [ancestor_loc] * @returns {string | null} */ export function is_tag_valid_with_ancestor(child_tag, ancestors, child_loc, ancestor_loc) { if (child_tag.includes('-')) return null; // custom elements can be anything const ancestor_tag = ancestors[ancestors.length - 1]; const disallowed = disallowed_children[ancestor_tag]; if (!disallowed) return null; if ('reset_by' in disallowed && disallowed.reset_by) { for (let i = ancestors.length - 2; i >= 0; i--) { const ancestor = ancestors[i]; if (ancestor.includes('-')) return null; // custom elements can be anything // A reset means that forbidden descendants are allowed again if (disallowed.reset_by.includes(ancestors[i])) { return null; } } } if ('descendant' in disallowed && disallowed.descendant.includes(child_tag)) { const child = child_loc ? `\`<${child_tag}>\` (${child_loc})` : `\`<${child_tag}>\``; const ancestor = ancestor_loc ? `\`<${ancestor_tag}>\` (${ancestor_loc})` : `\`<${ancestor_tag}>\``; return `${child} cannot be a descendant of ${ancestor}`; } return null; } /** * Returns an error message if the tag is not allowed inside the parent tag such that it will result * in the browser repairing the HTML, which will likely result in an error during hydration. * @param {string} child_tag * @param {string} parent_tag * @param {string} [child_loc] * @param {string} [parent_loc] * @returns {string | null} */ export function is_tag_valid_with_parent(child_tag, parent_tag, child_loc, parent_loc) { if (child_tag.includes('-') || parent_tag?.includes('-')) return null; // custom elements can be anything if (parent_tag === 'template') return null; // no errors or warning should be thrown in immediate children of template tags const disallowed = disallowed_children[parent_tag]; const child = child_loc ? `\`<${child_tag}>\` (${child_loc})` : `\`<${child_tag}>\``; const parent = parent_loc ? `\`<${parent_tag}>\` (${parent_loc})` : `\`<${parent_tag}>\``; if (disallowed) { if ('direct' in disallowed && disallowed.direct.includes(child_tag)) { return `${child} cannot be a direct child of ${parent}`; } if ('descendant' in disallowed && disallowed.descendant.includes(child_tag)) { return `${child} cannot be a child of ${parent}`; } if ('only' in disallowed && disallowed.only) { if (disallowed.only.includes(child_tag)) { return null; } else { return `${child} cannot be a child of ${parent}. \`<${parent_tag}>\` only allows these children: ${disallowed.only.map((d) => `\`<${d}>\``).join(', ')}`; } } } // These tags are only valid with a few parents that have special child // parsing rules - if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid (and we only get into this function if we know the parent). switch (child_tag) { case 'body': case 'caption': case 'col': case 'colgroup': case 'frameset': case 'frame': case 'head': case 'html': return `${child} cannot be a child of ${parent}`; case 'thead': case 'tbody': case 'tfoot': return `${child} must be the child of a \`<table>\`, not a ${parent}`; case 'td': case 'th': return `${child} must be the child of a \`<tr>\`, not a ${parent}`; case 'tr': return `\`<tr>\` must be the child of a \`<thead>\`, \`<tbody>\`, or \`<tfoot>\`, not a ${parent}`; } return null; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/index-client.js
packages/svelte/src/index-client.js
/** @import { ComponentContext, ComponentContextLegacy } from '#client' */ /** @import { EventDispatcher } from './index.js' */ /** @import { NotFunction } from './internal/types.js' */ import { active_reaction, untrack } from './internal/client/runtime.js'; import { is_array } from './internal/shared/utils.js'; import { user_effect } from './internal/client/index.js'; import * as e from './internal/client/errors.js'; import { legacy_mode_flag } from './internal/flags/index.js'; import { component_context } from './internal/client/context.js'; import { DEV } from 'esm-env'; if (DEV) { /** * @param {string} rune */ function throw_rune_error(rune) { if (!(rune in globalThis)) { // TODO if people start adjusting the "this can contain runes" config through v-p-s more, adjust this message /** @type {any} */ let value; // let's hope noone modifies this global, but belts and braces Object.defineProperty(globalThis, rune, { configurable: true, // eslint-disable-next-line getter-return get: () => { if (value !== undefined) { return value; } e.rune_outside_svelte(rune); }, set: (v) => { value = v; } }); } } throw_rune_error('$state'); throw_rune_error('$effect'); throw_rune_error('$derived'); throw_rune_error('$inspect'); throw_rune_error('$props'); throw_rune_error('$bindable'); } /** * Returns an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that aborts when the current [derived](https://svelte.dev/docs/svelte/$derived) or [effect](https://svelte.dev/docs/svelte/$effect) re-runs or is destroyed. * * Must be called while a derived or effect is running. * * ```svelte * <script> * import { getAbortSignal } from 'svelte'; * * let { id } = $props(); * * async function getData(id) { * const response = await fetch(`/items/${id}`, { * signal: getAbortSignal() * }); * * return await response.json(); * } * * const data = $derived(await getData(id)); * </script> * ``` */ export function getAbortSignal() { if (active_reaction === null) { e.get_abort_signal_outside_reaction(); } return (active_reaction.ac ??= new AbortController()).signal; } /** * `onMount`, like [`$effect`](https://svelte.dev/docs/svelte/$effect), schedules a function to run as soon as the component has been mounted to the DOM. * Unlike `$effect`, the provided function only runs once. * * It must be called during the component's initialisation (but doesn't need to live _inside_ the component; * it can be called from an external module). If a function is returned _synchronously_ from `onMount`, * it will be called when the component is unmounted. * * `onMount` functions do not run during [server-side rendering](https://svelte.dev/docs/svelte/svelte-server#render). * * @template T * @param {() => NotFunction<T> | Promise<NotFunction<T>> | (() => any)} fn * @returns {void} */ export function onMount(fn) { if (component_context === null) { e.lifecycle_outside_component('onMount'); } if (legacy_mode_flag && component_context.l !== null) { init_update_callbacks(component_context).m.push(fn); } else { user_effect(() => { const cleanup = untrack(fn); if (typeof cleanup === 'function') return /** @type {() => void} */ (cleanup); }); } } /** * Schedules a callback to run immediately before the component is unmounted. * * Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the * only one that runs inside a server-side component. * * @param {() => any} fn * @returns {void} */ export function onDestroy(fn) { if (component_context === null) { e.lifecycle_outside_component('onDestroy'); } onMount(() => () => untrack(fn)); } /** * @template [T=any] * @param {string} type * @param {T} [detail] * @param {any}params_0 * @returns {CustomEvent<T>} */ function create_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) { return new CustomEvent(type, { detail, bubbles, cancelable }); } /** * Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs/svelte/legacy-on#Component-events). * Event dispatchers are functions that can take two arguments: `name` and `detail`. * * Component events created with `createEventDispatcher` create a * [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). * These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture). * The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) * property and can contain any type of data. * * The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument: * ```ts * const dispatch = createEventDispatcher<{ * loaded: null; // does not take a detail argument * change: string; // takes a detail argument of type string, which is required * optional: number | null; // takes an optional detail argument of type number * }>(); * ``` * * @deprecated Use callback props and/or the `$host()` rune instead — see [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes-Component-events) * @template {Record<string, any>} [EventMap = any] * @returns {EventDispatcher<EventMap>} */ export function createEventDispatcher() { const active_component_context = component_context; if (active_component_context === null) { e.lifecycle_outside_component('createEventDispatcher'); } /** * @param [detail] * @param [options] */ return (type, detail, options) => { const events = /** @type {Record<string, Function | Function[]>} */ ( active_component_context.s.$$events )?.[/** @type {string} */ (type)]; if (events) { const callbacks = is_array(events) ? events.slice() : [events]; // TODO are there situations where events could be dispatched // in a server (non-DOM) environment? const event = create_custom_event(/** @type {string} */ (type), detail, options); for (const fn of callbacks) { fn.call(active_component_context.x, event); } return !event.defaultPrevented; } return true; }; } // TODO mark beforeUpdate and afterUpdate as deprecated in Svelte 6 /** * Schedules a callback to run immediately before the component is updated after any state change. * * The first time the callback runs will be before the initial `onMount`. * * In runes mode use `$effect.pre` instead. * * @deprecated Use [`$effect.pre`](https://svelte.dev/docs/svelte/$effect#$effect.pre) instead * @param {() => void} fn * @returns {void} */ export function beforeUpdate(fn) { if (component_context === null) { e.lifecycle_outside_component('beforeUpdate'); } if (component_context.l === null) { e.lifecycle_legacy_only('beforeUpdate'); } init_update_callbacks(component_context).b.push(fn); } /** * Schedules a callback to run immediately after the component has been updated. * * The first time the callback runs will be after the initial `onMount`. * * In runes mode use `$effect` instead. * * @deprecated Use [`$effect`](https://svelte.dev/docs/svelte/$effect) instead * @param {() => void} fn * @returns {void} */ export function afterUpdate(fn) { if (component_context === null) { e.lifecycle_outside_component('afterUpdate'); } if (component_context.l === null) { e.lifecycle_legacy_only('afterUpdate'); } init_update_callbacks(component_context).a.push(fn); } /** * Legacy-mode: Init callbacks object for onMount/beforeUpdate/afterUpdate * @param {ComponentContext} context */ function init_update_callbacks(context) { var l = /** @type {ComponentContextLegacy} */ (context).l; return (l.u ??= { a: [], b: [], m: [] }); } export { flushSync, fork } from './internal/client/reactivity/batch.js'; export { createContext, getContext, getAllContexts, hasContext, setContext } from './internal/client/context.js'; export { hydratable } from './internal/client/hydratable.js'; export { hydrate, mount, unmount } from './internal/client/render.js'; export { tick, untrack, settled } from './internal/client/runtime.js'; export { createRawSnippet } from './internal/client/dom/blocks/snippet.js';
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/utils.js
packages/svelte/src/utils.js
const regex_return_characters = /\r/g; /** * @param {string} str * @returns {string} */ export function hash(str) { str = str.replace(regex_return_characters, ''); let hash = 5381; let i = str.length; while (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i); return (hash >>> 0).toString(36); } const VOID_ELEMENT_NAMES = [ 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr' ]; /** * Returns `true` if `name` is of a void element * @param {string} name */ export function is_void(name) { return VOID_ELEMENT_NAMES.includes(name) || name.toLowerCase() === '!doctype'; } const RESERVED_WORDS = [ 'arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield' ]; /** * Returns `true` if `word` is a reserved JavaScript keyword * @param {string} word */ export function is_reserved(word) { return RESERVED_WORDS.includes(word); } /** * @param {string} name */ export function is_capture_event(name) { return name.endsWith('capture') && name !== 'gotpointercapture' && name !== 'lostpointercapture'; } /** List of Element events that will be delegated */ const DELEGATED_EVENTS = [ 'beforeinput', 'click', 'change', 'dblclick', 'contextmenu', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'pointerdown', 'pointermove', 'pointerout', 'pointerover', 'pointerup', 'touchend', 'touchmove', 'touchstart' ]; /** * Returns `true` if `event_name` is a delegated event * @param {string} event_name */ export function can_delegate_event(event_name) { return DELEGATED_EVENTS.includes(event_name); } /** * Attributes that are boolean, i.e. they are present or not present. */ const DOM_BOOLEAN_ATTRIBUTES = [ 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'disabled', 'formnovalidate', 'indeterminate', 'inert', 'ismap', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline', 'readonly', 'required', 'reversed', 'seamless', 'selected', 'webkitdirectory', 'defer', 'disablepictureinpicture', 'disableremoteplayback' ]; /** * Returns `true` if `name` is a boolean attribute * @param {string} name */ export function is_boolean_attribute(name) { return DOM_BOOLEAN_ATTRIBUTES.includes(name); } /** * @type {Record<string, string>} * List of attribute names that should be aliased to their property names * because they behave differently between setting them as an attribute and * setting them as a property. */ const ATTRIBUTE_ALIASES = { // no `class: 'className'` because we handle that separately formnovalidate: 'formNoValidate', ismap: 'isMap', nomodule: 'noModule', playsinline: 'playsInline', readonly: 'readOnly', defaultvalue: 'defaultValue', defaultchecked: 'defaultChecked', srcobject: 'srcObject', novalidate: 'noValidate', allowfullscreen: 'allowFullscreen', disablepictureinpicture: 'disablePictureInPicture', disableremoteplayback: 'disableRemotePlayback' }; /** * @param {string} name */ export function normalize_attribute(name) { name = name.toLowerCase(); return ATTRIBUTE_ALIASES[name] ?? name; } const DOM_PROPERTIES = [ ...DOM_BOOLEAN_ATTRIBUTES, 'formNoValidate', 'isMap', 'noModule', 'playsInline', 'readOnly', 'value', 'volume', 'defaultValue', 'defaultChecked', 'srcObject', 'noValidate', 'allowFullscreen', 'disablePictureInPicture', 'disableRemotePlayback' ]; /** * @param {string} name */ export function is_dom_property(name) { return DOM_PROPERTIES.includes(name); } const NON_STATIC_PROPERTIES = ['autofocus', 'muted', 'defaultValue', 'defaultChecked']; /** * Returns `true` if the given attribute cannot be set through the template * string, i.e. needs some kind of JavaScript handling to work. * @param {string} name */ export function cannot_be_set_statically(name) { return NON_STATIC_PROPERTIES.includes(name); } /** * Subset of delegated events which should be passive by default. * These two are already passive via browser defaults on window, document and body. * But since * - we're delegating them * - they happen often * - they apply to mobile which is generally less performant * we're marking them as passive by default for other elements, too. */ const PASSIVE_EVENTS = ['touchstart', 'touchmove']; /** * Returns `true` if `name` is a passive event * @param {string} name */ export function is_passive_event(name) { return PASSIVE_EVENTS.includes(name); } const CONTENT_EDITABLE_BINDINGS = ['textContent', 'innerHTML', 'innerText']; /** @param {string} name */ export function is_content_editable_binding(name) { return CONTENT_EDITABLE_BINDINGS.includes(name); } const LOAD_ERROR_ELEMENTS = [ 'body', 'embed', 'iframe', 'img', 'link', 'object', 'script', 'style', 'track' ]; /** * Returns `true` if the element emits `load` and `error` events * @param {string} name */ export function is_load_error_element(name) { return LOAD_ERROR_ELEMENTS.includes(name); } const SVG_ELEMENTS = [ 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'discard', 'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter', 'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hatch', 'hatchpath', 'hkern', 'image', 'line', 'linearGradient', 'marker', 'mask', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'metadata', 'missing-glyph', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'solidcolor', 'stop', 'svg', 'switch', 'symbol', 'text', 'textPath', 'tref', 'tspan', 'unknown', 'use', 'view', 'vkern' ]; /** @param {string} name */ export function is_svg(name) { return SVG_ELEMENTS.includes(name); } const MATHML_ELEMENTS = [ 'annotation', 'annotation-xml', 'maction', 'math', 'merror', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'semantics' ]; /** @param {string} name */ export function is_mathml(name) { return MATHML_ELEMENTS.includes(name); } const STATE_CREATION_RUNES = /** @type {const} */ ([ '$state', '$state.raw', '$derived', '$derived.by' ]); const RUNES = /** @type {const} */ ([ ...STATE_CREATION_RUNES, '$state.eager', '$state.snapshot', '$props', '$props.id', '$bindable', '$effect', '$effect.pre', '$effect.tracking', '$effect.root', '$effect.pending', '$inspect', '$inspect().with', '$inspect.trace', '$host' ]); /** @typedef {typeof RUNES[number]} RuneName */ /** * @param {string} name * @returns {name is RuneName} */ export function is_rune(name) { return RUNES.includes(/** @type {RuneName} */ (name)); } /** @typedef {typeof STATE_CREATION_RUNES[number]} StateCreationRuneName */ /** * @param {string} name * @returns {name is StateCreationRuneName} */ export function is_state_creation_rune(name) { return STATE_CREATION_RUNES.includes(/** @type {StateCreationRuneName} */ (name)); } /** List of elements that require raw contents and should not have SSR comments put in them */ const RAW_TEXT_ELEMENTS = /** @type {const} */ (['textarea', 'script', 'style', 'title']); /** @param {string} name */ export function is_raw_text_element(name) { return RAW_TEXT_ELEMENTS.includes(/** @type {typeof RAW_TEXT_ELEMENTS[number]} */ (name)); } /** * Prevent devtools trying to make `location` a clickable link by inserting a zero-width space * @template {string | undefined} T * @param {T} location * @returns {T}; */ export function sanitize_location(location) { return /** @type {T} */ (location?.replace(/\//g, '/\u200b')); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/easing/index.js
packages/svelte/src/easing/index.js
/* Adapted from https://github.com/mattdesl Distributed under MIT License https://github.com/mattdesl/eases/blob/master/LICENSE.md */ /** * @param {number} t * @returns {number} */ export function linear(t) { return t; } /** * @param {number} t * @returns {number} */ export function backInOut(t) { const s = 1.70158 * 1.525; if ((t *= 2) < 1) return 0.5 * (t * t * ((s + 1) * t - s)); return 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2); } /** * @param {number} t * @returns {number} */ export function backIn(t) { const s = 1.70158; return t * t * ((s + 1) * t - s); } /** * @param {number} t * @returns {number} */ export function backOut(t) { const s = 1.70158; return --t * t * ((s + 1) * t + s) + 1; } /** * @param {number} t * @returns {number} */ export function bounceOut(t) { const a = 4.0 / 11.0; const b = 8.0 / 11.0; const c = 9.0 / 10.0; const ca = 4356.0 / 361.0; const cb = 35442.0 / 1805.0; const cc = 16061.0 / 1805.0; const t2 = t * t; return t < a ? 7.5625 * t2 : t < b ? 9.075 * t2 - 9.9 * t + 3.4 : t < c ? ca * t2 - cb * t + cc : 10.8 * t * t - 20.52 * t + 10.72; } /** * @param {number} t * @returns {number} */ export function bounceInOut(t) { return t < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - t * 2.0)) : 0.5 * bounceOut(t * 2.0 - 1.0) + 0.5; } /** * @param {number} t * @returns {number} */ export function bounceIn(t) { return 1.0 - bounceOut(1.0 - t); } /** * @param {number} t * @returns {number} */ export function circInOut(t) { if ((t *= 2) < 1) return -0.5 * (Math.sqrt(1 - t * t) - 1); return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); } /** * @param {number} t * @returns {number} */ export function circIn(t) { return 1.0 - Math.sqrt(1.0 - t * t); } /** * @param {number} t * @returns {number} */ export function circOut(t) { return Math.sqrt(1 - --t * t); } /** * @param {number} t * @returns {number} */ export function cubicInOut(t) { return t < 0.5 ? 4.0 * t * t * t : 0.5 * Math.pow(2.0 * t - 2.0, 3.0) + 1.0; } /** * @param {number} t * @returns {number} */ export function cubicIn(t) { return t * t * t; } /** * @param {number} t * @returns {number} */ export function cubicOut(t) { const f = t - 1.0; return f * f * f + 1.0; } /** * @param {number} t * @returns {number} */ export function elasticInOut(t) { return t < 0.5 ? 0.5 * Math.sin(((+13.0 * Math.PI) / 2) * 2.0 * t) * Math.pow(2.0, 10.0 * (2.0 * t - 1.0)) : 0.5 * Math.sin(((-13.0 * Math.PI) / 2) * (2.0 * t - 1.0 + 1.0)) * Math.pow(2.0, -10.0 * (2.0 * t - 1.0)) + 1.0; } /** * @param {number} t * @returns {number} */ export function elasticIn(t) { return Math.sin((13.0 * t * Math.PI) / 2) * Math.pow(2.0, 10.0 * (t - 1.0)); } /** * @param {number} t * @returns {number} */ export function elasticOut(t) { return Math.sin((-13.0 * (t + 1.0) * Math.PI) / 2) * Math.pow(2.0, -10.0 * t) + 1.0; } /** * @param {number} t * @returns {number} */ export function expoInOut(t) { return t === 0.0 || t === 1.0 ? t : t < 0.5 ? +0.5 * Math.pow(2.0, 20.0 * t - 10.0) : -0.5 * Math.pow(2.0, 10.0 - t * 20.0) + 1.0; } /** * @param {number} t * @returns {number} */ export function expoIn(t) { return t === 0.0 ? t : Math.pow(2.0, 10.0 * (t - 1.0)); } /** * @param {number} t * @returns {number} */ export function expoOut(t) { return t === 1.0 ? t : 1.0 - Math.pow(2.0, -10.0 * t); } /** * @param {number} t * @returns {number} */ export function quadInOut(t) { t /= 0.5; if (t < 1) return 0.5 * t * t; t--; return -0.5 * (t * (t - 2) - 1); } /** * @param {number} t * @returns {number} */ export function quadIn(t) { return t * t; } /** * @param {number} t * @returns {number} */ export function quadOut(t) { return -t * (t - 2.0); } /** * @param {number} t * @returns {number} */ export function quartInOut(t) { return t < 0.5 ? +8.0 * Math.pow(t, 4.0) : -8.0 * Math.pow(t - 1.0, 4.0) + 1.0; } /** * @param {number} t * @returns {number} */ export function quartIn(t) { return Math.pow(t, 4.0); } /** * @param {number} t * @returns {number} */ export function quartOut(t) { return Math.pow(t - 1.0, 3.0) * (1.0 - t) + 1.0; } /** * @param {number} t * @returns {number} */ export function quintInOut(t) { if ((t *= 2) < 1) return 0.5 * t * t * t * t * t; return 0.5 * ((t -= 2) * t * t * t * t + 2); } /** * @param {number} t * @returns {number} */ export function quintIn(t) { return t * t * t * t * t; } /** * @param {number} t * @returns {number} */ export function quintOut(t) { return --t * t * t * t * t + 1; } /** * @param {number} t * @returns {number} */ export function sineInOut(t) { return -0.5 * (Math.cos(Math.PI * t) - 1); } /** * @param {number} t * @returns {number} */ export function sineIn(t) { const v = Math.cos(t * Math.PI * 0.5); if (Math.abs(v) < 1e-14) return 1; else return 1 - v; } /** * @param {number} t * @returns {number} */ export function sineOut(t) { return Math.sin((t * Math.PI) / 2); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/store/index-server.js
packages/svelte/src/store/index-server.js
/** @import { Readable, Writable } from './public.js' */ import { get, writable } from './shared/index.js'; export { derived, get, readable, readonly, writable } from './shared/index.js'; /** * @template V * @overload * @param {() => V} get * @param {(v: V) => void} set * @returns {Writable<V>} */ /** * @template V * @overload * @param {() => V} get * @returns {Readable<V>} */ /** * Create a store from a function that returns state, and (to make a writable store), an * optional second function that sets state. * * ```ts * import { toStore } from 'svelte/store'; * * let count = $state(0); * * const store = toStore(() => count, (v) => (count = v)); * ``` * @template V * @param {() => V} get * @param {(v: V) => void} [set] * @returns {Writable<V> | Readable<V>} */ export function toStore(get, set) { const store = writable(get()); if (set) { return { set, update: (fn) => set(fn(get())), subscribe: store.subscribe }; } return { subscribe: store.subscribe }; } /** * @template V * @overload * @param {Writable<V>} store * @returns {{ current: V }} */ /** * @template V * @overload * @param {Readable<V>} store * @returns {{ readonly current: V }} */ /** * Convert a store to an object with a reactive `current` property. If `store` * is a readable store, `current` will be a readonly property. * * ```ts * import { fromStore, get, writable } from 'svelte/store'; * * const store = writable(0); * * const count = fromStore(store); * * count.current; // 0; * store.set(1); * count.current; // 1 * * count.current += 1; * get(store); // 2 * ``` * @template V * @param {Writable<V> | Readable<V>} store */ export function fromStore(store) { if ('set' in store) { return { get current() { return get(store); }, set current(v) { store.set(v); } }; } return { get current() { return get(store); } }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/store/index-client.js
packages/svelte/src/store/index-client.js
/** @import { Readable, Writable } from './public.js' */ import { effect_root, effect_tracking, render_effect } from '../internal/client/reactivity/effects.js'; import { get, writable } from './shared/index.js'; import { createSubscriber } from '../reactivity/create-subscriber.js'; import { active_effect, active_reaction, set_active_effect, set_active_reaction } from '../internal/client/runtime.js'; export { derived, get, readable, readonly, writable } from './shared/index.js'; /** * @template V * @overload * @param {() => V} get * @param {(v: V) => void} set * @returns {Writable<V>} */ /** * @template V * @overload * @param {() => V} get * @returns {Readable<V>} */ /** * Create a store from a function that returns state, and (to make a writable store), an * optional second function that sets state. * * ```ts * import { toStore } from 'svelte/store'; * * let count = $state(0); * * const store = toStore(() => count, (v) => (count = v)); * ``` * @template V * @param {() => V} get * @param {(v: V) => void} [set] * @returns {Writable<V> | Readable<V>} */ export function toStore(get, set) { var effect = active_effect; var reaction = active_reaction; var init_value = get(); const store = writable(init_value, (set) => { // If the value has changed before we call subscribe, then // we need to treat the value as already having run var ran = init_value !== get(); // TODO do we need a different implementation on the server? var teardown; // Apply the reaction and effect at the time of toStore being called var previous_reaction = active_reaction; var previous_effect = active_effect; set_active_reaction(reaction); set_active_effect(effect); try { teardown = effect_root(() => { render_effect(() => { const value = get(); if (ran) set(value); }); }); } finally { set_active_reaction(previous_reaction); set_active_effect(previous_effect); } ran = true; return teardown; }); if (set) { return { set, update: (fn) => set(fn(get())), subscribe: store.subscribe }; } return { subscribe: store.subscribe }; } /** * @template V * @overload * @param {Writable<V>} store * @returns {{ current: V }} */ /** * @template V * @overload * @param {Readable<V>} store * @returns {{ readonly current: V }} */ /** * Convert a store to an object with a reactive `current` property. If `store` * is a readable store, `current` will be a readonly property. * * ```ts * import { fromStore, get, writable } from 'svelte/store'; * * const store = writable(0); * * const count = fromStore(store); * * count.current; // 0; * store.set(1); * count.current; // 1 * * count.current += 1; * get(store); // 2 * ``` * @template V * @param {Writable<V> | Readable<V>} store */ export function fromStore(store) { let value = /** @type {V} */ (undefined); const subscribe = createSubscriber((update) => { let ran = false; const unsubscribe = store.subscribe((v) => { value = v; if (ran) update(); }); ran = true; return unsubscribe; }); function current() { if (effect_tracking()) { subscribe(); return value; } return get(store); } if ('set' in store) { return { get current() { return current(); }, set current(v) { store.set(v); } }; } return { get current() { return current(); } }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/store/utils.js
packages/svelte/src/store/utils.js
/** @import { Readable } from './public' */ import { untrack } from '../index-client.js'; import { noop } from '../internal/shared/utils.js'; /** * @template T * @param {Readable<T> | null | undefined} store * @param {(value: T) => void} run * @param {(value: T) => void} [invalidate] * @returns {() => void} */ export function subscribe_to_store(store, run, invalidate) { if (store == null) { // @ts-expect-error run(undefined); // @ts-expect-error if (invalidate) invalidate(undefined); return noop; } // Svelte store takes a private second argument // StartStopNotifier could mutate state, and we want to silence the corresponding validation error const unsub = untrack(() => store.subscribe( run, // @ts-expect-error invalidate ) ); // Also support RxJS // @ts-expect-error TODO fix this in the types? return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/store/shared/index.js
packages/svelte/src/store/shared/index.js
/** @import { Readable, StartStopNotifier, Subscriber, Unsubscriber, Updater, Writable } from '../public.js' */ /** @import { Stores, StoresValues, SubscribeInvalidateTuple } from '../private.js' */ import { noop, run_all } from '../../internal/shared/utils.js'; import { safe_not_equal } from '../../internal/client/reactivity/equality.js'; import { subscribe_to_store } from '../utils.js'; /** * @type {Array<SubscribeInvalidateTuple<any> | any>} */ const subscriber_queue = []; /** * Creates a `Readable` store that allows reading by subscription. * * @template T * @param {T} [value] initial value * @param {StartStopNotifier<T>} [start] * @returns {Readable<T>} */ export function readable(value, start) { return { subscribe: writable(value, start).subscribe }; } /** * Create a `Writable` store that allows both updating and reading by subscription. * * @template T * @param {T} [value] initial value * @param {StartStopNotifier<T>} [start] * @returns {Writable<T>} */ export function writable(value, start = noop) { /** @type {Unsubscriber | null} */ let stop = null; /** @type {Set<SubscribeInvalidateTuple<T>>} */ const subscribers = new Set(); /** * @param {T} new_value * @returns {void} */ function set(new_value) { if (safe_not_equal(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (const subscriber of subscribers) { subscriber[1](); subscriber_queue.push(subscriber, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } /** * @param {Updater<T>} fn * @returns {void} */ function update(fn) { set(fn(/** @type {T} */ (value))); } /** * @param {Subscriber<T>} run * @param {() => void} [invalidate] * @returns {Unsubscriber} */ function subscribe(run, invalidate = noop) { /** @type {SubscribeInvalidateTuple<T>} */ const subscriber = [run, invalidate]; subscribers.add(subscriber); if (subscribers.size === 1) { stop = start(set, update) || noop; } run(/** @type {T} */ (value)); return () => { subscribers.delete(subscriber); if (subscribers.size === 0 && stop) { stop(); stop = null; } }; } return { set, update, subscribe }; } /** * Derived value store by synchronizing one or more readable stores and * applying an aggregation function over its input values. * * @template {Stores} S * @template T * @overload * @param {S} stores * @param {(values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void} fn * @param {T} [initial_value] * @returns {Readable<T>} */ /** * Derived value store by synchronizing one or more readable stores and * applying an aggregation function over its input values. * * @template {Stores} S * @template T * @overload * @param {S} stores * @param {(values: StoresValues<S>) => T} fn * @param {T} [initial_value] * @returns {Readable<T>} */ /** * @template {Stores} S * @template T * @param {S} stores * @param {Function} fn * @param {T} [initial_value] * @returns {Readable<T>} */ export function derived(stores, fn, initial_value) { const single = !Array.isArray(stores); /** @type {Array<Readable<any>>} */ const stores_array = single ? [stores] : stores; if (!stores_array.every(Boolean)) { throw new Error('derived() expects stores as input, got a falsy value'); } const auto = fn.length < 2; return readable(initial_value, (set, update) => { let started = false; /** @type {T[]} */ const values = []; let pending = 0; let cleanup = noop; const sync = () => { if (pending) { return; } cleanup(); const result = fn(single ? values[0] : values, set, update); if (auto) { set(result); } else { cleanup = typeof result === 'function' ? result : noop; } }; const unsubscribers = stores_array.map((store, i) => subscribe_to_store( store, (value) => { values[i] = value; pending &= ~(1 << i); if (started) { sync(); } }, () => { pending |= 1 << i; } ) ); started = true; sync(); return function stop() { run_all(unsubscribers); cleanup(); // We need to set this to false because callbacks can still happen despite having unsubscribed: // Callbacks might already be placed in the queue which doesn't know it should no longer // invoke this derived store. started = false; }; }); } /** * Takes a store and returns a new one derived from the old one that is readable. * * @template T * @param {Readable<T>} store - store to make readonly * @returns {Readable<T>} */ export function readonly(store) { return { // @ts-expect-error TODO i suspect the bind is unnecessary subscribe: store.subscribe.bind(store) }; } /** * Get the current value from a store by subscribing and immediately unsubscribing. * * @template T * @param {Readable<T>} store * @returns {T} */ export function get(store) { let value; subscribe_to_store(store, (_) => (value = _))(); // @ts-expect-error return value; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/events/index.js
packages/svelte/src/events/index.js
export { on } from '../internal/client/dom/elements/events.js';
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/index.js
packages/svelte/src/internal/index.js
// TODO we may, on a best-effort basis, reimplement some of the legacy private APIs here so that certain libraries continue to work. Those APIs will be marked as deprecated (and should noisily warn the user) and will be removed in a future version of Svelte. throw new Error( `Your application, or one of its dependencies, imported from 'svelte/internal', which was a private module used by Svelte 4 components that no longer exists in Svelte 5. It is not intended to be public API. If you're a library author and you used 'svelte/internal' deliberately, please raise an issue on https://github.com/sveltejs/svelte/issues detailing your use case.` );
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/disclose-version.js
packages/svelte/src/internal/disclose-version.js
import { PUBLIC_VERSION } from '../version.js'; if (typeof window !== 'undefined') { // @ts-expect-error ((window.__svelte ??= {}).v ??= new Set()).add(PUBLIC_VERSION); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/flags/index.js
packages/svelte/src/internal/flags/index.js
/** True if experimental.async=true */ export let async_mode_flag = false; /** True if we're not certain that we only have Svelte 5 code in the compilation */ export let legacy_mode_flag = false; /** True if $inspect.trace is used */ export let tracing_mode_flag = false; export function enable_async_mode_flag() { async_mode_flag = true; } /** ONLY USE THIS DURING TESTING */ export function disable_async_mode_flag() { async_mode_flag = false; } export function enable_legacy_mode_flag() { legacy_mode_flag = true; } export function enable_tracing_mode_flag() { tracing_mode_flag = true; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/flags/legacy.js
packages/svelte/src/internal/flags/legacy.js
import { enable_legacy_mode_flag } from './index.js'; enable_legacy_mode_flag();
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/flags/async.js
packages/svelte/src/internal/flags/async.js
import { enable_async_mode_flag } from './index.js'; enable_async_mode_flag();
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/flags/tracing.js
packages/svelte/src/internal/flags/tracing.js
import { enable_tracing_mode_flag } from './index.js'; enable_tracing_mode_flag();
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/warnings.js
packages/svelte/src/internal/server/warnings.js
/* This file is generated by scripts/process-messages/index.js. Do not edit! */ import { DEV } from 'esm-env'; var bold = 'font-weight: bold'; var normal = 'font-weight: normal'; /** * A `hydratable` value with key `%key%` was created, but at least part of it was not used during the render. * * The `hydratable` was initialized in: * %stack% * @param {string} key * @param {string} stack */ export function unresolved_hydratable(key, stack) { if (DEV) { console.warn( `%c[svelte] unresolved_hydratable\n%cA \`hydratable\` value with key \`${key}\` was created, but at least part of it was not used during the render. The \`hydratable\` was initialized in: ${stack}\nhttps://svelte.dev/e/unresolved_hydratable`, bold, normal ); } else { console.warn(`https://svelte.dev/e/unresolved_hydratable`); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/index.js
packages/svelte/src/internal/server/index.js
/** @import { ComponentType, SvelteComponent, Component } from 'svelte' */ /** @import { Csp, RenderOutput } from '#server' */ /** @import { Store } from '#shared' */ export { FILENAME, HMR } from '../../constants.js'; import { attr, clsx, to_class, to_style } from '../shared/attributes.js'; import { is_promise, noop } from '../shared/utils.js'; import { subscribe_to_store } from '../../store/utils.js'; import { UNINITIALIZED, ELEMENT_PRESERVE_ATTRIBUTE_CASE, ELEMENT_IS_NAMESPACED, ELEMENT_IS_INPUT } from '../../constants.js'; import { escape_html } from '../../escaping.js'; import { DEV } from 'esm-env'; import { EMPTY_COMMENT, BLOCK_CLOSE, BLOCK_OPEN, BLOCK_OPEN_ELSE } from './hydration.js'; import { validate_store } from '../shared/validate.js'; import { is_boolean_attribute, is_raw_text_element, is_void } from '../../utils.js'; import { Renderer } from './renderer.js'; import * as e from './errors.js'; // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 // https://infra.spec.whatwg.org/#noncharacter const INVALID_ATTR_NAME_CHAR_REGEX = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u; /** * @param {Renderer} renderer * @param {string} tag * @param {() => void} attributes_fn * @param {() => void} children_fn * @returns {void} */ export function element(renderer, tag, attributes_fn = noop, children_fn = noop) { renderer.push('<!---->'); if (tag) { renderer.push(`<${tag}`); attributes_fn(); renderer.push(`>`); if (!is_void(tag)) { children_fn(); if (!is_raw_text_element(tag)) { renderer.push(EMPTY_COMMENT); } renderer.push(`</${tag}>`); } } renderer.push('<!---->'); } /** * Only available on the server and when compiling with the `server` option. * Takes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app. * @template {Record<string, any>} Props * @param {Component<Props> | ComponentType<SvelteComponent<Props>>} component * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} [options] * @returns {RenderOutput} */ export function render(component, options = {}) { if (options.csp?.hash && options.csp.nonce) { e.invalid_csp(); } return Renderer.render(/** @type {Component<Props>} */ (component), options); } /** * @param {string} hash * @param {Renderer} renderer * @param {(renderer: Renderer) => Promise<void> | void} fn * @returns {void} */ export function head(hash, renderer, fn) { renderer.head((renderer) => { renderer.push(`<!--${hash}-->`); renderer.child(fn); renderer.push(EMPTY_COMMENT); }); } /** * @param {Renderer} renderer * @param {boolean} is_html * @param {Record<string, string>} props * @param {() => void} component * @param {boolean} dynamic * @returns {void} */ export function css_props(renderer, is_html, props, component, dynamic = false) { const styles = style_object_to_string(props); if (is_html) { renderer.push(`<svelte-css-wrapper style="display: contents; ${styles}">`); } else { renderer.push(`<g style="${styles}">`); } if (dynamic) { renderer.push('<!---->'); } component(); if (is_html) { renderer.push(`<!----></svelte-css-wrapper>`); } else { renderer.push(`<!----></g>`); } } /** * @param {Record<string, unknown>} attrs * @param {string} [css_hash] * @param {Record<string, boolean>} [classes] * @param {Record<string, string>} [styles] * @param {number} [flags] * @returns {string} */ export function attributes(attrs, css_hash, classes, styles, flags = 0) { if (styles) { attrs.style = to_style(attrs.style, styles); } if (attrs.class) { attrs.class = clsx(attrs.class); } if (css_hash || classes) { attrs.class = to_class(attrs.class, css_hash, classes); } let attr_str = ''; let name; const is_html = (flags & ELEMENT_IS_NAMESPACED) === 0; const lowercase = (flags & ELEMENT_PRESERVE_ATTRIBUTE_CASE) === 0; const is_input = (flags & ELEMENT_IS_INPUT) !== 0; for (name in attrs) { // omit functions, internal svelte properties and invalid attribute names if (typeof attrs[name] === 'function') continue; if (name[0] === '$' && name[1] === '$') continue; // faster than name.startsWith('$$') if (INVALID_ATTR_NAME_CHAR_REGEX.test(name)) continue; var value = attrs[name]; if (lowercase) { name = name.toLowerCase(); } if (is_input) { if (name === 'defaultvalue' || name === 'defaultchecked') { name = name === 'defaultvalue' ? 'value' : 'checked'; if (attrs[name]) continue; } } attr_str += attr(name, value, is_html && is_boolean_attribute(name)); } return attr_str; } /** * @param {Record<string, unknown>[]} props * @returns {Record<string, unknown>} */ export function spread_props(props) { /** @type {Record<string, unknown>} */ const merged_props = {}; let key; for (let i = 0; i < props.length; i++) { const obj = props[i]; for (key in obj) { const desc = Object.getOwnPropertyDescriptor(obj, key); if (desc) { Object.defineProperty(merged_props, key, desc); } else { merged_props[key] = obj[key]; } } } return merged_props; } /** * @param {unknown} value * @returns {string} */ export function stringify(value) { return typeof value === 'string' ? value : value == null ? '' : value + ''; } /** @param {Record<string, string>} style_object */ function style_object_to_string(style_object) { return Object.keys(style_object) .filter(/** @param {any} key */ (key) => style_object[key] != null && style_object[key] !== '') .map(/** @param {any} key */ (key) => `${key}: ${escape_html(style_object[key], true)};`) .join(' '); } /** * @param {any} value * @param {string | undefined} [hash] * @param {Record<string, boolean>} [directives] */ export function attr_class(value, hash, directives) { var result = to_class(value, hash, directives); return result ? ` class="${escape_html(result, true)}"` : ''; } /** * @param {any} value * @param {Record<string,any>|[Record<string,any>,Record<string,any>]} [directives] */ export function attr_style(value, directives) { var result = to_style(value, directives); return result ? ` style="${escape_html(result, true)}"` : ''; } /** * @template V * @param {Record<string, [any, any, any]>} store_values * @param {string} store_name * @param {Store<V> | null | undefined} store * @returns {V} */ export function store_get(store_values, store_name, store) { if (DEV) { validate_store(store, store_name.slice(1)); } // it could be that someone eagerly updates the store in the instance script, so // we should only reuse the store value in the template if (store_name in store_values && store_values[store_name][0] === store) { return store_values[store_name][2]; } store_values[store_name]?.[1](); // if store was switched, unsubscribe from old store store_values[store_name] = [store, null, undefined]; const unsub = subscribe_to_store( store, /** @param {any} v */ (v) => (store_values[store_name][2] = v) ); store_values[store_name][1] = unsub; return store_values[store_name][2]; } /** * Sets the new value of a store and returns that value. * @template V * @param {Store<V>} store * @param {V} value * @returns {V} */ export function store_set(store, value) { store.set(value); return value; } /** * Updates a store with a new value. * @template V * @param {Record<string, [any, any, any]>} store_values * @param {string} store_name * @param {Store<V>} store * @param {any} expression */ export function store_mutate(store_values, store_name, store, expression) { store_set(store, store_get(store_values, store_name, store)); return expression; } /** * @param {Record<string, [any, any, any]>} store_values * @param {string} store_name * @param {Store<number>} store * @param {1 | -1} [d] * @returns {number} */ export function update_store(store_values, store_name, store, d = 1) { let store_value = store_get(store_values, store_name, store); store.set(store_value + d); return store_value; } /** * @param {Record<string, [any, any, any]>} store_values * @param {string} store_name * @param {Store<number>} store * @param {1 | -1} [d] * @returns {number} */ export function update_store_pre(store_values, store_name, store, d = 1) { const value = store_get(store_values, store_name, store) + d; store.set(value); return value; } /** @param {Record<string, [any, any, any]>} store_values */ export function unsubscribe_stores(store_values) { for (const store_name in store_values) { store_values[store_name][1](); } } /** * @param {Renderer} renderer * @param {Record<string, any>} $$props * @param {string} name * @param {Record<string, unknown>} slot_props * @param {null | (() => void)} fallback_fn * @returns {void} */ export function slot(renderer, $$props, name, slot_props, fallback_fn) { var slot_fn = $$props.$$slots?.[name]; // Interop: Can use snippets to fill slots if (slot_fn === true) { slot_fn = $$props[name === 'default' ? 'children' : name]; } if (slot_fn !== undefined) { slot_fn(renderer, slot_props); } else { fallback_fn?.(); } } /** * @param {Record<string, unknown>} props * @param {string[]} rest * @returns {Record<string, unknown>} */ export function rest_props(props, rest) { /** @type {Record<string, unknown>} */ const rest_props = {}; let key; for (key in props) { if (!rest.includes(key)) { rest_props[key] = props[key]; } } return rest_props; } /** * @param {Record<string, unknown>} props * @returns {Record<string, unknown>} */ export function sanitize_props(props) { const { children, $$slots, ...sanitized } = props; return sanitized; } /** * @param {Record<string, any>} props * @returns {Record<string, boolean>} */ export function sanitize_slots(props) { /** @type {Record<string, boolean>} */ const sanitized = {}; if (props.children) sanitized.default = true; for (const key in props.$$slots) { sanitized[key] = true; } return sanitized; } /** * Legacy mode: If the prop has a fallback and is bound in the * parent component, propagate the fallback value upwards. * @param {Record<string, unknown>} props_parent * @param {Record<string, unknown>} props_now */ export function bind_props(props_parent, props_now) { for (const key in props_now) { const initial_value = props_parent[key]; const value = props_now[key]; if ( initial_value === undefined && value !== undefined && Object.getOwnPropertyDescriptor(props_parent, key)?.set ) { props_parent[key] = value; } } } /** * @template V * @param {Renderer} renderer * @param {Promise<V>} promise * @param {null | (() => void)} pending_fn * @param {(value: V) => void} then_fn * @returns {void} */ function await_block(renderer, promise, pending_fn, then_fn) { if (is_promise(promise)) { renderer.push(BLOCK_OPEN); promise.then(null, noop); if (pending_fn !== null) { pending_fn(); } } else if (then_fn !== null) { renderer.push(BLOCK_OPEN_ELSE); then_fn(promise); } } export { await_block as await }; /** @param {any} array_like_or_iterator */ export function ensure_array_like(array_like_or_iterator) { if (array_like_or_iterator) { return array_like_or_iterator.length !== undefined ? array_like_or_iterator : Array.from(array_like_or_iterator); } return []; } /** * @template V * @param {() => V} get_value */ export function once(get_value) { let value = /** @type {V} */ (UNINITIALIZED); return () => { if (value === UNINITIALIZED) { value = get_value(); } return value; }; } /** * Create an unique ID * @param {Renderer} renderer * @returns {string} */ export function props_id(renderer) { const uid = renderer.global.uid(); renderer.push('<!--$' + uid + '-->'); return uid; } export { attr, clsx }; export { html } from './blocks/html.js'; export { save } from './context.js'; export { push_element, pop_element, validate_snippet_args } from './dev.js'; export { snapshot } from '../shared/clone.js'; export { fallback, to_array } from '../shared/utils.js'; export { invalid_default_snippet, validate_dynamic_element_tag, validate_void_dynamic_element, prevent_snippet_stringification } from '../shared/validate.js'; export { escape_html as escape }; /** * @template T * @param {()=>T} fn * @returns {(new_value?: T) => (T | void)} */ export function derived(fn) { const get_value = once(fn); /** * @type {T | undefined} */ let updated_value; return function (new_value) { if (arguments.length === 0) { return updated_value ?? get_value(); } updated_value = new_value; return updated_value; }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/hydratable.js
packages/svelte/src/internal/server/hydratable.js
/** @import { HydratableLookupEntry } from '#server' */ import { async_mode_flag } from '../flags/index.js'; import { get_render_context } from './render-context.js'; import * as e from './errors.js'; import * as devalue from 'devalue'; import { get_stack } from '../shared/dev.js'; import { DEV } from 'esm-env'; import { get_user_code_location } from './dev.js'; /** * @template T * @param {string} key * @param {() => T} fn * @returns {T} */ export function hydratable(key, fn) { if (!async_mode_flag) { e.experimental_async_required('hydratable'); } const { hydratable } = get_render_context(); let entry = hydratable.lookup.get(key); if (entry !== undefined) { if (DEV) { const comparison = compare(key, entry, encode(key, fn())); comparison.catch(() => {}); hydratable.comparisons.push(comparison); } return /** @type {T} */ (entry.value); } const value = fn(); entry = encode(key, value, hydratable.unresolved_promises); hydratable.lookup.set(key, entry); return value; } /** * @param {string} key * @param {any} value * @param {Map<Promise<any>, string>} [unresolved] */ function encode(key, value, unresolved) { /** @type {HydratableLookupEntry} */ const entry = { value, serialized: '' }; if (DEV) { entry.stack = get_user_code_location(); } let uid = 1; entry.serialized = devalue.uneval(entry.value, (value, uneval) => { if (is_promise(value)) { // we serialize promises as `"${i}"`, because it's impossible for that string // to occur 'naturally' (since the quote marks would have to be escaped) // this placeholder is returned synchronously from `uneval`, which includes it in the // serialized string. Later (at least one microtask from now), when `p.then` runs, it'll // be replaced. const placeholder = `"${uid++}"`; const p = value .then((v) => { entry.serialized = entry.serialized.replace(placeholder, `r(${uneval(v)})`); }) .catch((devalue_error) => e.hydratable_serialization_failed( key, serialization_stack(entry.stack, devalue_error?.stack) ) ); unresolved?.set(p, key); // prevent unhandled rejections from crashing the server, track which promises are still resolving when render is complete p.catch(() => {}).finally(() => unresolved?.delete(p)); (entry.promises ??= []).push(p); return placeholder; } }); return entry; } /** * @param {any} value * @returns {value is Promise<any>} */ function is_promise(value) { // we use this check rather than `instanceof Promise` // because it works cross-realm return Object.prototype.toString.call(value) === '[object Promise]'; } /** * @param {string} key * @param {HydratableLookupEntry} a * @param {HydratableLookupEntry} b */ async function compare(key, a, b) { // note: these need to be loops (as opposed to Promise.all) because // additional promises can get pushed to them while we're awaiting // an earlier one for (const p of a?.promises ?? []) { await p; } for (const p of b?.promises ?? []) { await p; } if (a.serialized !== b.serialized) { const a_stack = /** @type {string} */ (a.stack); const b_stack = /** @type {string} */ (b.stack); const stack = a_stack === b_stack ? `Occurred at:\n${a_stack}` : `First occurrence at:\n${a_stack}\n\nSecond occurrence at:\n${b_stack}`; e.hydratable_clobbering(key, stack); } } /** * @param {string | undefined} root_stack * @param {string | undefined} uneval_stack */ function serialization_stack(root_stack, uneval_stack) { let out = ''; if (root_stack) { out += root_stack + '\n'; } if (uneval_stack) { out += 'Caused by:\n' + uneval_stack + '\n'; } return out || '<missing stack trace>'; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/crypto.js
packages/svelte/src/internal/server/crypto.js
import { BROWSER } from 'esm-env'; let text_encoder; // TODO - remove this and use global `crypto` when we drop Node 18 let crypto; /** @param {string} data */ export async function sha256(data) { text_encoder ??= new TextEncoder(); // @ts-expect-error crypto ??= globalThis.crypto?.subtle?.digest ? globalThis.crypto : // @ts-ignore - we don't install node types in the prod build (await import('node:crypto')).webcrypto; const hash_buffer = await crypto.subtle.digest('SHA-256', text_encoder.encode(data)); return base64_encode(hash_buffer); } /** * @param {Uint8Array} bytes * @returns {string} */ export function base64_encode(bytes) { // Using `Buffer` is faster than iterating // @ts-ignore if (!BROWSER && globalThis.Buffer) { // @ts-ignore return globalThis.Buffer.from(bytes).toString('base64'); } let binary = ''; for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/context.js
packages/svelte/src/internal/server/context.js
/** @import { SSRContext } from '#server' */ import { DEV } from 'esm-env'; import * as e from './errors.js'; /** @type {SSRContext | null} */ export var ssr_context = null; /** @param {SSRContext | null} v */ export function set_ssr_context(v) { ssr_context = v; } /** * @template T * @returns {[() => T, (context: T) => T]} * @since 5.40.0 */ export function createContext() { const key = {}; return [() => getContext(key), (context) => setContext(key, context)]; } /** * @template T * @param {any} key * @returns {T} */ export function getContext(key) { const context_map = get_or_init_context_map('getContext'); const result = /** @type {T} */ (context_map.get(key)); return result; } /** * @template T * @param {any} key * @param {T} context * @returns {T} */ export function setContext(key, context) { get_or_init_context_map('setContext').set(key, context); return context; } /** * @param {any} key * @returns {boolean} */ export function hasContext(key) { return get_or_init_context_map('hasContext').has(key); } /** @returns {Map<any, any>} */ export function getAllContexts() { return get_or_init_context_map('getAllContexts'); } /** * @param {string} name * @returns {Map<unknown, unknown>} */ function get_or_init_context_map(name) { if (ssr_context === null) { e.lifecycle_outside_component(name); } return (ssr_context.c ??= new Map(get_parent_context(ssr_context) || undefined)); } /** * @param {Function} [fn] */ export function push(fn) { ssr_context = { p: ssr_context, c: null, r: null }; if (DEV) { ssr_context.function = fn; ssr_context.element = ssr_context.p?.element; } } export function pop() { ssr_context = /** @type {SSRContext} */ (ssr_context).p; } /** * @param {SSRContext} ssr_context * @returns {Map<unknown, unknown> | null} */ function get_parent_context(ssr_context) { let parent = ssr_context.p; while (parent !== null) { const context_map = parent.c; if (context_map !== null) { return context_map; } parent = parent.p; } return null; } /** * Wraps an `await` expression in such a way that the component context that was * active before the expression evaluated can be reapplied afterwards — * `await a + b()` becomes `(await $.save(a))() + b()`, meaning `b()` will have access * to the context of its component. * @template T * @param {Promise<T>} promise * @returns {Promise<() => T>} */ export async function save(promise) { var previous_context = ssr_context; var value = await promise; return () => { ssr_context = previous_context; return value; }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/renderer.js
packages/svelte/src/internal/server/renderer.js
/** @import { Component } from 'svelte' */ /** @import { Csp, HydratableContext, RenderOutput, SSRContext, SyncRenderOutput, Sha256Source } from './types.js' */ /** @import { MaybePromise } from '#shared' */ import { async_mode_flag } from '../flags/index.js'; import { abort } from './abort-signal.js'; import { pop, push, set_ssr_context, ssr_context, save } from './context.js'; import * as e from './errors.js'; import * as w from './warnings.js'; import { BLOCK_CLOSE, BLOCK_OPEN } from './hydration.js'; import { attributes } from './index.js'; import { get_render_context, with_render_context, init_render_context } from './render-context.js'; import { sha256 } from './crypto.js'; /** @typedef {'head' | 'body'} RendererType */ /** @typedef {{ [key in RendererType]: string }} AccumulatedContent */ /** * @typedef {string | Renderer} RendererItem */ /** * Renderers are basically a tree of `string | Renderer`s, where each `Renderer` in the tree represents * work that may or may not have completed. A renderer can be {@link collect}ed to aggregate the * content from itself and all of its children, but this will throw if any of the children are * performing asynchronous work. To asynchronously collect a renderer, just `await` it. * * The `string` values within a renderer are always associated with the {@link type} of that renderer. To switch types, * call {@link child} with a different `type` argument. */ export class Renderer { /** * The contents of the renderer. * @type {RendererItem[]} */ #out = []; /** * Any `onDestroy` callbacks registered during execution of this renderer. * @type {(() => void)[] | undefined} */ #on_destroy = undefined; /** * Whether this renderer is a component body. * @type {boolean} */ #is_component_body = false; /** * The type of string content that this renderer is accumulating. * @type {RendererType} */ type; /** @type {Renderer | undefined} */ #parent; /** * Asynchronous work associated with this renderer * @type {Promise<void> | undefined} */ promise = undefined; /** * State which is associated with the content tree as a whole. * It will be re-exposed, uncopied, on all children. * @type {SSRState} * @readonly */ global; /** * State that is local to the branch it is declared in. * It will be shallow-copied to all children. * * @type {{ select_value: string | undefined }} */ local; /** * @param {SSRState} global * @param {Renderer | undefined} [parent] */ constructor(global, parent) { this.#parent = parent; this.global = global; this.local = parent ? { ...parent.local } : { select_value: undefined }; this.type = parent ? parent.type : 'body'; } /** * @param {(renderer: Renderer) => void} fn */ head(fn) { const head = new Renderer(this.global, this); head.type = 'head'; this.#out.push(head); head.child(fn); } /** * @param {Array<Promise<void>>} blockers * @param {(renderer: Renderer) => void} fn */ async_block(blockers, fn) { this.#out.push(BLOCK_OPEN); this.async(blockers, fn); this.#out.push(BLOCK_CLOSE); } /** * @param {Array<Promise<void>>} blockers * @param {(renderer: Renderer) => void} fn */ async(blockers, fn) { let callback = fn; if (blockers.length > 0) { const context = ssr_context; callback = (renderer) => { return Promise.all(blockers).then(() => { const previous_context = ssr_context; try { set_ssr_context(context); return fn(renderer); } finally { set_ssr_context(previous_context); } }); }; } this.child(callback); } /** * @param {Array<() => void>} thunks */ run(thunks) { const context = ssr_context; let promise = Promise.resolve(thunks[0]()); const promises = [promise]; for (const fn of thunks.slice(1)) { promise = promise.then(() => { const previous_context = ssr_context; set_ssr_context(context); try { return fn(); } finally { set_ssr_context(previous_context); } }); promises.push(promise); } return promises; } /** * Create a child renderer. The child renderer inherits the state from the parent, * but has its own content. * @param {(renderer: Renderer) => MaybePromise<void>} fn */ child(fn) { const child = new Renderer(this.global, this); this.#out.push(child); const parent = ssr_context; set_ssr_context({ ...ssr_context, p: parent, c: null, r: child }); const result = fn(child); set_ssr_context(parent); if (result instanceof Promise) { if (child.global.mode === 'sync') { e.await_invalid(); } // just to avoid unhandled promise rejections -- we'll end up throwing in `collect_async` if something fails result.catch(() => {}); child.promise = result; } return child; } /** * Create a component renderer. The component renderer inherits the state from the parent, * but has its own content. It is treated as an ordering boundary for ondestroy callbacks. * @param {(renderer: Renderer) => MaybePromise<void>} fn * @param {Function} [component_fn] * @returns {void} */ component(fn, component_fn) { push(component_fn); const child = this.child(fn); child.#is_component_body = true; pop(); } /** * @param {Record<string, any>} attrs * @param {(renderer: Renderer) => void} fn * @param {string | undefined} [css_hash] * @param {Record<string, boolean> | undefined} [classes] * @param {Record<string, string> | undefined} [styles] * @param {number | undefined} [flags] * @returns {void} */ select(attrs, fn, css_hash, classes, styles, flags) { const { value, ...select_attrs } = attrs; this.push(`<select${attributes(select_attrs, css_hash, classes, styles, flags)}>`); this.child((renderer) => { renderer.local.select_value = value; fn(renderer); }); this.push('</select>'); } /** * @param {Record<string, any>} attrs * @param {string | number | boolean | ((renderer: Renderer) => void)} body * @param {string | undefined} [css_hash] * @param {Record<string, boolean> | undefined} [classes] * @param {Record<string, string> | undefined} [styles] * @param {number | undefined} [flags] */ option(attrs, body, css_hash, classes, styles, flags) { this.#out.push(`<option${attributes(attrs, css_hash, classes, styles, flags)}`); /** * @param {Renderer} renderer * @param {any} value * @param {{ head?: string, body: any }} content */ const close = (renderer, value, { head, body }) => { if ('value' in attrs) { value = attrs.value; } if (value === this.local.select_value) { renderer.#out.push(' selected'); } renderer.#out.push(`>${body}</option>`); // super edge case, but may as well handle it if (head) { renderer.head((child) => child.push(head)); } }; if (typeof body === 'function') { this.child((renderer) => { const r = new Renderer(this.global, this); body(r); if (this.global.mode === 'async') { return r.#collect_content_async().then((content) => { close(renderer, content.body.replaceAll('<!---->', ''), content); }); } else { const content = r.#collect_content(); close(renderer, content.body.replaceAll('<!---->', ''), content); } }); } else { close(this, body, { body }); } } /** * @param {(renderer: Renderer) => void} fn */ title(fn) { const path = this.get_path(); /** @param {string} head */ const close = (head) => { this.global.set_title(head, path); }; this.child((renderer) => { const r = new Renderer(renderer.global, renderer); fn(r); if (renderer.global.mode === 'async') { return r.#collect_content_async().then((content) => { close(content.head); }); } else { const content = r.#collect_content(); close(content.head); } }); } /** * @param {string | (() => Promise<string>)} content */ push(content) { if (typeof content === 'function') { this.child(async (renderer) => renderer.push(await content())); } else { this.#out.push(content); } } /** * @param {() => void} fn */ on_destroy(fn) { (this.#on_destroy ??= []).push(fn); } /** * @returns {number[]} */ get_path() { return this.#parent ? [...this.#parent.get_path(), this.#parent.#out.indexOf(this)] : []; } /** * @deprecated this is needed for legacy component bindings */ copy() { const copy = new Renderer(this.global, this.#parent); copy.#out = this.#out.map((item) => (item instanceof Renderer ? item.copy() : item)); copy.promise = this.promise; return copy; } /** * @param {Renderer} other * @deprecated this is needed for legacy component bindings */ subsume(other) { if (this.global.mode !== other.global.mode) { throw new Error( "invariant: A renderer cannot switch modes. If you're seeing this, there's a compiler bug. File an issue!" ); } this.local = other.local; this.#out = other.#out.map((item) => { if (item instanceof Renderer) { item.subsume(item); } return item; }); this.promise = other.promise; this.type = other.type; } get length() { return this.#out.length; } /** * Only available on the server and when compiling with the `server` option. * Takes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app. * @template {Record<string, any>} Props * @param {Component<Props>} component * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} [options] * @returns {RenderOutput} */ static render(component, options = {}) { /** @type {AccumulatedContent | undefined} */ let sync; /** @type {Promise<AccumulatedContent & { hashes: { script: Sha256Source[] } }> | undefined} */ let async; const result = /** @type {RenderOutput} */ ({}); // making these properties non-enumerable so that console.logging // doesn't trigger a sync render Object.defineProperties(result, { html: { get: () => { return (sync ??= Renderer.#render(component, options)).body; } }, head: { get: () => { return (sync ??= Renderer.#render(component, options)).head; } }, body: { get: () => { return (sync ??= Renderer.#render(component, options)).body; } }, hashes: { value: { script: '' } }, then: { value: /** * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. * * @template TResult1 * @template [TResult2=never] * @param { (value: SyncRenderOutput) => TResult1 } onfulfilled * @param { (reason: unknown) => TResult2 } onrejected */ (onfulfilled, onrejected) => { if (!async_mode_flag) { const result = (sync ??= Renderer.#render(component, options)); const user_result = onfulfilled({ head: result.head, body: result.body, html: result.body, hashes: { script: [] } }); return Promise.resolve(user_result); } async ??= init_render_context().then(() => with_render_context(() => Renderer.#render_async(component, options)) ); return async.then((result) => { Object.defineProperty(result, 'html', { // eslint-disable-next-line getter-return get: () => { e.html_deprecated(); } }); return onfulfilled(/** @type {SyncRenderOutput} */ (result)); }, onrejected); } } }); return result; } /** * Collect all of the `onDestroy` callbacks registered during rendering. In an async context, this is only safe to call * after awaiting `collect_async`. * * Child renderers are "porous" and don't affect execution order, but component body renderers * create ordering boundaries. Within a renderer, callbacks run in order until hitting a component boundary. * @returns {Iterable<() => void>} */ *#collect_on_destroy() { for (const component of this.#traverse_components()) { yield* component.#collect_ondestroy(); } } /** * Performs a depth-first search of renderers, yielding the deepest components first, then additional components as we backtrack up the tree. * @returns {Iterable<Renderer>} */ *#traverse_components() { for (const child of this.#out) { if (typeof child !== 'string') { yield* child.#traverse_components(); } } if (this.#is_component_body) { yield this; } } /** * @returns {Iterable<() => void>} */ *#collect_ondestroy() { if (this.#on_destroy) { for (const fn of this.#on_destroy) { yield fn; } } for (const child of this.#out) { if (child instanceof Renderer && !child.#is_component_body) { yield* child.#collect_ondestroy(); } } } /** * Render a component. Throws if any of the children are performing asynchronous work. * * @template {Record<string, any>} Props * @param {Component<Props>} component * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string }} options * @returns {AccumulatedContent} */ static #render(component, options) { var previous_context = ssr_context; try { const renderer = Renderer.#open_render('sync', component, options); const content = renderer.#collect_content(); return Renderer.#close_render(content, renderer); } finally { abort(); set_ssr_context(previous_context); } } /** * Render a component. * * @template {Record<string, any>} Props * @param {Component<Props>} component * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} options * @returns {Promise<AccumulatedContent & { hashes: { script: Sha256Source[] } }>} */ static async #render_async(component, options) { const previous_context = ssr_context; try { const renderer = Renderer.#open_render('async', component, options); const content = await renderer.#collect_content_async(); const hydratables = await renderer.#collect_hydratables(); if (hydratables !== null) { content.head = hydratables + content.head; } return Renderer.#close_render(content, renderer); } finally { set_ssr_context(previous_context); abort(); } } /** * Collect all of the code from the `out` array and return it as a string, or a promise resolving to a string. * @param {AccumulatedContent} content * @returns {AccumulatedContent} */ #collect_content(content = { head: '', body: '' }) { for (const item of this.#out) { if (typeof item === 'string') { content[this.type] += item; } else if (item instanceof Renderer) { item.#collect_content(content); } } return content; } /** * Collect all of the code from the `out` array and return it as a string. * @param {AccumulatedContent} content * @returns {Promise<AccumulatedContent>} */ async #collect_content_async(content = { head: '', body: '' }) { await this.promise; // no danger to sequentially awaiting stuff in here; all of the work is already kicked off for (const item of this.#out) { if (typeof item === 'string') { content[this.type] += item; } else if (item instanceof Renderer) { await item.#collect_content_async(content); } } return content; } async #collect_hydratables() { const ctx = get_render_context().hydratable; for (const [_, key] of ctx.unresolved_promises) { // this is a problem -- it means we've finished the render but we're still waiting on a promise to resolve so we can // serialize it, so we're blocking the response on useless content. w.unresolved_hydratable(key, ctx.lookup.get(key)?.stack ?? '<missing stack trace>'); } for (const comparison of ctx.comparisons) { // these reject if there's a mismatch await comparison; } return await this.#hydratable_block(ctx); } /** * @template {Record<string, any>} Props * @param {'sync' | 'async'} mode * @param {import('svelte').Component<Props>} component * @param {{ props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; idPrefix?: string; csp?: Csp }} options * @returns {Renderer} */ static #open_render(mode, component, options) { const renderer = new Renderer( new SSRState(mode, options.idPrefix ? options.idPrefix + '-' : '', options.csp) ); renderer.push(BLOCK_OPEN); if (options.context) { push(); /** @type {SSRContext} */ (ssr_context).c = options.context; /** @type {SSRContext} */ (ssr_context).r = renderer; } // @ts-expect-error component(renderer, options.props ?? {}); if (options.context) { pop(); } renderer.push(BLOCK_CLOSE); return renderer; } /** * @param {AccumulatedContent} content * @param {Renderer} renderer * @returns {AccumulatedContent & { hashes: { script: Sha256Source[] } }} */ static #close_render(content, renderer) { for (const cleanup of renderer.#collect_on_destroy()) { cleanup(); } let head = content.head + renderer.global.get_title(); let body = content.body; for (const { hash, code } of renderer.global.css) { head += `<style id="${hash}">${code}</style>`; } return { head, body, hashes: { script: renderer.global.csp.script_hashes } }; } /** * @param {HydratableContext} ctx */ async #hydratable_block(ctx) { if (ctx.lookup.size === 0) { return null; } let entries = []; let has_promises = false; for (const [k, v] of ctx.lookup) { if (v.promises) { has_promises = true; for (const p of v.promises) await p; } entries.push(`[${JSON.stringify(k)},${v.serialized}]`); } let prelude = `const h = (window.__svelte ??= {}).h ??= new Map();`; if (has_promises) { prelude = `const r = (v) => Promise.resolve(v); ${prelude}`; } const body = ` { ${prelude} for (const [k, v] of [ ${entries.join(',\n\t\t\t\t\t')} ]) { h.set(k, v); } } `; let csp_attr = ''; if (this.global.csp.nonce) { csp_attr = ` nonce="${this.global.csp.nonce}"`; } else if (this.global.csp.hash) { // note to future selves: this doesn't need to be optimized with a Map<body, hash> // because the it's impossible for identical data to occur multiple times in a single render // (this would require the same hydratable key:value pair to be serialized multiple times) const hash = await sha256(body); this.global.csp.script_hashes.push(`sha256-${hash}`); } return `\n\t\t<script${csp_attr}>${body}</script>`; } } export class SSRState { /** @readonly @type {Csp & { script_hashes: Sha256Source[] }} */ csp; /** @readonly @type {'sync' | 'async'} */ mode; /** @readonly @type {() => string} */ uid; /** @readonly @type {Set<{ hash: string; code: string }>} */ css = new Set(); /** @type {{ path: number[], value: string }} */ #title = { path: [], value: '' }; /** * @param {'sync' | 'async'} mode * @param {string} id_prefix * @param {Csp} csp */ constructor(mode, id_prefix = '', csp = { hash: false }) { this.mode = mode; this.csp = { ...csp, script_hashes: [] }; let uid = 1; this.uid = () => `${id_prefix}s${uid++}`; } get_title() { return this.#title.value; } /** * Performs a depth-first (lexicographic) comparison using the path. Rejects sets * from earlier than or equal to the current value. * @param {string} value * @param {number[]} path */ set_title(value, path) { const current = this.#title.path; let i = 0; let l = Math.min(path.length, current.length); // skip identical prefixes - [1, 2, 3, ...] === [1, 2, 3, ...] while (i < l && path[i] === current[i]) i += 1; if (path[i] === undefined) return; // replace title if // - incoming path is longer - [7, 8, 9] > [7, 8] // - incoming path is later - [7, 8, 9] > [7, 8, 8] if (current[i] === undefined || path[i] > current[i]) { this.#title.path = path; this.#title.value = value; } } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/dev.js
packages/svelte/src/internal/server/dev.js
/** @import { SSRContext } from '#server' */ import { FILENAME } from '../../constants.js'; import { is_tag_valid_with_ancestor, is_tag_valid_with_parent } from '../../html-tree-validation.js'; import { get_stack } from '../shared/dev.js'; import { set_ssr_context, ssr_context } from './context.js'; import * as e from './errors.js'; import { Renderer } from './renderer.js'; // TODO move this /** * @typedef {{ * tag: string; * parent: undefined | Element; * filename: undefined | string; * line: number; * column: number; * }} Element */ /** * This is exported so that it can be cleared between tests * @type {Set<string>} */ export let seen; /** * @param {Renderer} renderer * @param {string} message */ function print_error(renderer, message) { message = `node_invalid_placement_ssr: ${message}\n\n` + 'This can cause content to shift around as the browser repairs the HTML, and will likely result in a `hydration_mismatch` warning.'; if ((seen ??= new Set()).has(message)) return; seen.add(message); // eslint-disable-next-line no-console console.error(message); renderer.head((r) => r.push(`<script>console.error(${JSON.stringify(message)})</script>`)); } /** * @param {Renderer} renderer * @param {string} tag * @param {number} line * @param {number} column */ export function push_element(renderer, tag, line, column) { var context = /** @type {SSRContext} */ (ssr_context); var filename = context.function[FILENAME]; var parent = context.element; var element = { tag, parent, filename, line, column }; if (parent !== undefined) { var ancestor = parent.parent; var ancestors = [parent.tag]; const child_loc = filename ? `${filename}:${line}:${column}` : undefined; const parent_loc = parent.filename ? `${parent.filename}:${parent.line}:${parent.column}` : undefined; const message = is_tag_valid_with_parent(tag, parent.tag, child_loc, parent_loc); if (message) print_error(renderer, message); while (ancestor != null) { ancestors.push(ancestor.tag); const ancestor_loc = ancestor.filename ? `${ancestor.filename}:${ancestor.line}:${ancestor.column}` : undefined; const message = is_tag_valid_with_ancestor(tag, ancestors, child_loc, ancestor_loc); if (message) print_error(renderer, message); ancestor = ancestor.parent; } } set_ssr_context({ ...context, p: context, element }); } export function pop_element() { set_ssr_context(/** @type {SSRContext} */ (ssr_context).p); } /** * @param {Renderer} renderer */ export function validate_snippet_args(renderer) { if ( typeof renderer !== 'object' || // for some reason typescript consider the type of renderer as never after the first instanceof !(renderer instanceof Renderer) ) { e.invalid_snippet_arguments(); } } export function get_user_code_location() { const stack = get_stack(); return stack .filter((line) => line.trim().startsWith('at ')) .map((line) => line.replace(/\((.*):\d+:\d+\)$/, (_, file) => `(${file})`)) .join('\n'); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/render-context.js
packages/svelte/src/internal/server/render-context.js
// @ts-ignore -- we don't include node types in the production build /** @import { AsyncLocalStorage } from 'node:async_hooks' */ /** @import { RenderContext } from '#server' */ import { deferred, noop } from '../shared/utils.js'; import * as e from './errors.js'; /** @type {Promise<void> | null} */ let current_render = null; /** @type {RenderContext | null} */ let context = null; /** @returns {RenderContext} */ export function get_render_context() { const store = context ?? als?.getStore(); if (!store) { e.server_context_required(); } return store; } /** * @template T * @param {() => Promise<T>} fn * @returns {Promise<T>} */ export async function with_render_context(fn) { context = { hydratable: { lookup: new Map(), comparisons: [], unresolved_promises: new Map() } }; if (in_webcontainer()) { const { promise, resolve } = deferred(); const previous_render = current_render; current_render = promise; await previous_render; return fn().finally(resolve); } try { if (als === null) { e.async_local_storage_unavailable(); } return als.run(context, fn); } finally { context = null; } } /** @type {AsyncLocalStorage<RenderContext | null> | null} */ let als = null; /** @type {Promise<void> | null} */ let als_import = null; /** * * @returns {Promise<void>} */ export function init_render_context() { // It's important the right side of this assignment can run a maximum of one time // otherwise it's possible for a very, very well-timed race condition to assign to `als` // at the beginning of a render, and then another render to assign to it again, which causes // the first render's second half to use a new instance of `als` which doesn't have its // context anymore. // @ts-ignore -- we don't include node types in the production build als_import ??= import('node:async_hooks') .then((hooks) => { als = new hooks.AsyncLocalStorage(); }) .then(noop, noop); return als_import; } // this has to be a function because rollup won't treeshake it if it's a constant function in_webcontainer() { // @ts-ignore -- this will fail when we run typecheck because we exclude node types // eslint-disable-next-line n/prefer-global/process return !!globalThis.process?.versions?.webcontainer; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/errors.js
packages/svelte/src/internal/server/errors.js
/* This file is generated by scripts/process-messages/index.js. Do not edit! */ export * from '../shared/errors.js'; /** * The node API `AsyncLocalStorage` is not available, but is required to use async server rendering. * @returns {never} */ export function async_local_storage_unavailable() { const error = new Error(`async_local_storage_unavailable\nThe node API \`AsyncLocalStorage\` is not available, but is required to use async server rendering.\nhttps://svelte.dev/e/async_local_storage_unavailable`); error.name = 'Svelte error'; throw error; } /** * Encountered asynchronous work while rendering synchronously. * @returns {never} */ export function await_invalid() { const error = new Error(`await_invalid\nEncountered asynchronous work while rendering synchronously.\nhttps://svelte.dev/e/await_invalid`); error.name = 'Svelte error'; throw error; } /** * The `html` property of server render results has been deprecated. Use `body` instead. * @returns {never} */ export function html_deprecated() { const error = new Error(`html_deprecated\nThe \`html\` property of server render results has been deprecated. Use \`body\` instead.\nhttps://svelte.dev/e/html_deprecated`); error.name = 'Svelte error'; throw error; } /** * Attempted to set `hydratable` with key `%key%` twice with different values. * * %stack% * @param {string} key * @param {string} stack * @returns {never} */ export function hydratable_clobbering(key, stack) { const error = new Error(`hydratable_clobbering\nAttempted to set \`hydratable\` with key \`${key}\` twice with different values. ${stack}\nhttps://svelte.dev/e/hydratable_clobbering`); error.name = 'Svelte error'; throw error; } /** * Failed to serialize `hydratable` data for key `%key%`. * * `hydratable` can serialize anything [`uneval` from `devalue`](https://npmjs.com/package/uneval) can, plus Promises. * * Cause: * %stack% * @param {string} key * @param {string} stack * @returns {never} */ export function hydratable_serialization_failed(key, stack) { const error = new Error(`hydratable_serialization_failed\nFailed to serialize \`hydratable\` data for key \`${key}\`. \`hydratable\` can serialize anything [\`uneval\` from \`devalue\`](https://npmjs.com/package/uneval) can, plus Promises. Cause: ${stack}\nhttps://svelte.dev/e/hydratable_serialization_failed`); error.name = 'Svelte error'; throw error; } /** * `csp.nonce` was set while `csp.hash` was `true`. These options cannot be used simultaneously. * @returns {never} */ export function invalid_csp() { const error = new Error(`invalid_csp\n\`csp.nonce\` was set while \`csp.hash\` was \`true\`. These options cannot be used simultaneously.\nhttps://svelte.dev/e/invalid_csp`); error.name = 'Svelte error'; throw error; } /** * `%name%(...)` is not available on the server * @param {string} name * @returns {never} */ export function lifecycle_function_unavailable(name) { const error = new Error(`lifecycle_function_unavailable\n\`${name}(...)\` is not available on the server\nhttps://svelte.dev/e/lifecycle_function_unavailable`); error.name = 'Svelte error'; throw error; } /** * Could not resolve `render` context. * @returns {never} */ export function server_context_required() { const error = new Error(`server_context_required\nCould not resolve \`render\` context.\nhttps://svelte.dev/e/server_context_required`); error.name = 'Svelte error'; throw error; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/abort-signal.js
packages/svelte/src/internal/server/abort-signal.js
import { STALE_REACTION } from '#client/constants'; /** @type {AbortController | null} */ let controller = null; export function abort() { controller?.abort(STALE_REACTION); controller = null; } export function getAbortSignal() { return (controller ??= new AbortController()).signal; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/hydration.js
packages/svelte/src/internal/server/hydration.js
import { HYDRATION_END, HYDRATION_START, HYDRATION_START_ELSE } from '../../constants.js'; export const BLOCK_OPEN = `<!--${HYDRATION_START}-->`; export const BLOCK_OPEN_ELSE = `<!--${HYDRATION_START_ELSE}-->`; export const BLOCK_CLOSE = `<!--${HYDRATION_END}-->`; export const EMPTY_COMMENT = `<!---->`;
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/blocks/snippet.js
packages/svelte/src/internal/server/blocks/snippet.js
/** @import { Snippet } from 'svelte' */ /** @import { Renderer } from '../renderer' */ /** @import { Getters } from '#shared' */ /** * Create a snippet programmatically * @template {unknown[]} Params * @param {(...params: Getters<Params>) => { * render: () => string * setup?: (element: Element) => void | (() => void) * }} fn * @returns {Snippet<Params>} */ export function createRawSnippet(fn) { // @ts-expect-error the types are a lie return (/** @type {Renderer} */ renderer, /** @type {Params} */ ...args) => { var getters = /** @type {Getters<Params>} */ (args.map((value) => () => value)); renderer.push( fn(...getters) .render() .trim() ); }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/server/blocks/html.js
packages/svelte/src/internal/server/blocks/html.js
import { DEV } from 'esm-env'; import { hash } from '../../../utils.js'; /** * @param {string} value */ export function html(value) { var html = String(value ?? ''); var open = DEV ? `<!--${hash(html)}-->` : '<!---->'; return open + html + '<!---->'; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/client/loop.js
packages/svelte/src/internal/client/loop.js
/** @import { TaskCallback, Task, TaskEntry } from '#client' */ import { raf } from './timing.js'; // TODO move this into timing.js where it probably belongs /** * @returns {void} */ function run_tasks() { // use `raf.now()` instead of the `requestAnimationFrame` callback argument, because // otherwise things can get wonky https://github.com/sveltejs/svelte/pull/14541 const now = raf.now(); raf.tasks.forEach((task) => { if (!task.c(now)) { raf.tasks.delete(task); task.f(); } }); if (raf.tasks.size !== 0) { raf.tick(run_tasks); } } /** * Creates a new task that runs on each raf frame * until it returns a falsy value or is aborted * @param {TaskCallback} callback * @returns {Task} */ export function loop(callback) { /** @type {TaskEntry} */ let task; if (raf.tasks.size === 0) { raf.tick(run_tasks); } return { promise: new Promise((fulfill) => { raf.tasks.add((task = { c: callback, f: fulfill })); }), abort() { raf.tasks.delete(task); } }; }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/client/runtime.js
packages/svelte/src/internal/client/runtime.js
/** @import { Derived, Effect, Reaction, Signal, Source, Value } from '#client' */ import { DEV } from 'esm-env'; import { get_descriptors, get_prototype_of, index_of } from '../shared/utils.js'; import { destroy_block_effect_children, destroy_effect_children, effect_tracking, execute_effect_teardown } from './reactivity/effects.js'; import { DIRTY, MAYBE_DIRTY, CLEAN, DERIVED, DESTROYED, BRANCH_EFFECT, STATE_SYMBOL, BLOCK_EFFECT, ROOT_EFFECT, CONNECTED, REACTION_IS_UPDATING, STALE_REACTION, ERROR_VALUE, WAS_MARKED, MANAGED_EFFECT } from './constants.js'; import { old_values } from './reactivity/sources.js'; import { destroy_derived_effects, execute_derived, current_async_effect, recent_async_deriveds, update_derived } from './reactivity/deriveds.js'; import { async_mode_flag, tracing_mode_flag } from '../flags/index.js'; import { tracing_expressions } from './dev/tracing.js'; import { get_error } from '../shared/dev.js'; import { component_context, dev_current_component_function, dev_stack, is_runes, set_component_context, set_dev_current_component_function, set_dev_stack } from './context.js'; import * as w from './warnings.js'; import { Batch, batch_values, current_batch, flushSync, schedule_effect } from './reactivity/batch.js'; import { handle_error } from './error-handling.js'; import { UNINITIALIZED } from '../../constants.js'; import { captured_signals } from './legacy.js'; import { without_reactive_context } from './dom/elements/bindings/shared.js'; export let is_updating_effect = false; /** @param {boolean} value */ export function set_is_updating_effect(value) { is_updating_effect = value; } export let is_destroying_effect = false; /** @param {boolean} value */ export function set_is_destroying_effect(value) { is_destroying_effect = value; } /** @type {null | Reaction} */ export let active_reaction = null; export let untracking = false; /** @param {null | Reaction} reaction */ export function set_active_reaction(reaction) { active_reaction = reaction; } /** @type {null | Effect} */ export let active_effect = null; /** @param {null | Effect} effect */ export function set_active_effect(effect) { active_effect = effect; } /** * When sources are created within a reaction, reading and writing * them within that reaction should not cause a re-run * @type {null | Source[]} */ export let current_sources = null; /** @param {Value} value */ export function push_reaction_value(value) { if (active_reaction !== null && (!async_mode_flag || (active_reaction.f & DERIVED) !== 0)) { if (current_sources === null) { current_sources = [value]; } else { current_sources.push(value); } } } /** * The dependencies of the reaction that is currently being executed. In many cases, * the dependencies are unchanged between runs, and so this will be `null` unless * and until a new dependency is accessed — we track this via `skipped_deps` * @type {null | Value[]} */ let new_deps = null; let skipped_deps = 0; /** * Tracks writes that the effect it's executed in doesn't listen to yet, * so that the dependency can be added to the effect later on if it then reads it * @type {null | Source[]} */ export let untracked_writes = null; /** @param {null | Source[]} value */ export function set_untracked_writes(value) { untracked_writes = value; } /** * @type {number} Used by sources and deriveds for handling updates. * Version starts from 1 so that unowned deriveds differentiate between a created effect and a run one for tracing **/ export let write_version = 1; /** @type {number} Used to version each read of a source of derived to avoid duplicating depedencies inside a reaction */ let read_version = 0; export let update_version = read_version; /** @param {number} value */ export function set_update_version(value) { update_version = value; } export function increment_write_version() { return ++write_version; } /** * Determines whether a derived or effect is dirty. * If it is MAYBE_DIRTY, will set the status to CLEAN * @param {Reaction} reaction * @returns {boolean} */ export function is_dirty(reaction) { var flags = reaction.f; if ((flags & DIRTY) !== 0) { return true; } if (flags & DERIVED) { reaction.f &= ~WAS_MARKED; } if ((flags & MAYBE_DIRTY) !== 0) { var dependencies = reaction.deps; if (dependencies !== null) { var length = dependencies.length; for (var i = 0; i < length; i++) { var dependency = dependencies[i]; if (is_dirty(/** @type {Derived} */ (dependency))) { update_derived(/** @type {Derived} */ (dependency)); } if (dependency.wv > reaction.wv) { return true; } } } if ( (flags & CONNECTED) !== 0 && // During time traveling we don't want to reset the status so that // traversal of the graph in the other batches still happens batch_values === null ) { set_signal_status(reaction, CLEAN); } } return false; } /** * @param {Value} signal * @param {Effect} effect * @param {boolean} [root] */ function schedule_possible_effect_self_invalidation(signal, effect, root = true) { var reactions = signal.reactions; if (reactions === null) return; if (!async_mode_flag && current_sources?.includes(signal)) { return; } for (var i = 0; i < reactions.length; i++) { var reaction = reactions[i]; if ((reaction.f & DERIVED) !== 0) { schedule_possible_effect_self_invalidation(/** @type {Derived} */ (reaction), effect, false); } else if (effect === reaction) { if (root) { set_signal_status(reaction, DIRTY); } else if ((reaction.f & CLEAN) !== 0) { set_signal_status(reaction, MAYBE_DIRTY); } schedule_effect(/** @type {Effect} */ (reaction)); } } } /** @param {Reaction} reaction */ export function update_reaction(reaction) { var previous_deps = new_deps; var previous_skipped_deps = skipped_deps; var previous_untracked_writes = untracked_writes; var previous_reaction = active_reaction; var previous_sources = current_sources; var previous_component_context = component_context; var previous_untracking = untracking; var previous_update_version = update_version; var flags = reaction.f; new_deps = /** @type {null | Value[]} */ (null); skipped_deps = 0; untracked_writes = null; active_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null; current_sources = null; set_component_context(reaction.ctx); untracking = false; update_version = ++read_version; if (reaction.ac !== null) { without_reactive_context(() => { /** @type {AbortController} */ (reaction.ac).abort(STALE_REACTION); }); reaction.ac = null; } try { reaction.f |= REACTION_IS_UPDATING; var fn = /** @type {Function} */ (reaction.fn); var result = fn(); var deps = reaction.deps; if (new_deps !== null) { var i; remove_reactions(reaction, skipped_deps); if (deps !== null && skipped_deps > 0) { deps.length = skipped_deps + new_deps.length; for (i = 0; i < new_deps.length; i++) { deps[skipped_deps + i] = new_deps[i]; } } else { reaction.deps = deps = new_deps; } if (effect_tracking() && (reaction.f & CONNECTED) !== 0) { for (i = skipped_deps; i < deps.length; i++) { (deps[i].reactions ??= []).push(reaction); } } } else if (deps !== null && skipped_deps < deps.length) { remove_reactions(reaction, skipped_deps); deps.length = skipped_deps; } // If we're inside an effect and we have untracked writes, then we need to // ensure that if any of those untracked writes result in re-invalidation // of the current effect, then that happens accordingly if ( is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0 ) { for (i = 0; i < /** @type {Source[]} */ (untracked_writes).length; i++) { schedule_possible_effect_self_invalidation( untracked_writes[i], /** @type {Effect} */ (reaction) ); } } // If we are returning to an previous reaction then // we need to increment the read version to ensure that // any dependencies in this reaction aren't marked with // the same version if (previous_reaction !== null && previous_reaction !== reaction) { read_version++; if (untracked_writes !== null) { if (previous_untracked_writes === null) { previous_untracked_writes = untracked_writes; } else { previous_untracked_writes.push(.../** @type {Source[]} */ (untracked_writes)); } } } if ((reaction.f & ERROR_VALUE) !== 0) { reaction.f ^= ERROR_VALUE; } return result; } catch (error) { return handle_error(error); } finally { reaction.f ^= REACTION_IS_UPDATING; new_deps = previous_deps; skipped_deps = previous_skipped_deps; untracked_writes = previous_untracked_writes; active_reaction = previous_reaction; current_sources = previous_sources; set_component_context(previous_component_context); untracking = previous_untracking; update_version = previous_update_version; } } /** * @template V * @param {Reaction} signal * @param {Value<V>} dependency * @returns {void} */ function remove_reaction(signal, dependency) { let reactions = dependency.reactions; if (reactions !== null) { var index = index_of.call(reactions, signal); if (index !== -1) { var new_length = reactions.length - 1; if (new_length === 0) { reactions = dependency.reactions = null; } else { // Swap with last element and then remove. reactions[index] = reactions[new_length]; reactions.pop(); } } } // If the derived has no reactions, then we can disconnect it from the graph, // allowing it to either reconnect in the future, or be GC'd by the VM. if ( reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps` // allows us to skip the expensive work of disconnecting and immediately reconnecting it (new_deps === null || !new_deps.includes(dependency)) ) { set_signal_status(dependency, MAYBE_DIRTY); // If we are working with a derived that is owned by an effect, then mark it as being // disconnected and remove the mark flag, as it cannot be reliably removed otherwise if ((dependency.f & CONNECTED) !== 0) { dependency.f ^= CONNECTED; dependency.f &= ~WAS_MARKED; } // Disconnect any reactions owned by this reaction destroy_derived_effects(/** @type {Derived} **/ (dependency)); remove_reactions(/** @type {Derived} **/ (dependency), 0); } } /** * @param {Reaction} signal * @param {number} start_index * @returns {void} */ export function remove_reactions(signal, start_index) { var dependencies = signal.deps; if (dependencies === null) return; for (var i = start_index; i < dependencies.length; i++) { remove_reaction(signal, dependencies[i]); } } /** * @param {Effect} effect * @returns {void} */ export function update_effect(effect) { var flags = effect.f; if ((flags & DESTROYED) !== 0) { return; } set_signal_status(effect, CLEAN); var previous_effect = active_effect; var was_updating_effect = is_updating_effect; active_effect = effect; is_updating_effect = true; if (DEV) { var previous_component_fn = dev_current_component_function; set_dev_current_component_function(effect.component_function); var previous_stack = /** @type {any} */ (dev_stack); // only block effects have a dev stack, keep the current one otherwise set_dev_stack(effect.dev_stack ?? dev_stack); } try { if ((flags & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) { destroy_block_effect_children(effect); } else { destroy_effect_children(effect); } execute_effect_teardown(effect); var teardown = update_reaction(effect); effect.teardown = typeof teardown === 'function' ? teardown : null; effect.wv = write_version; // In DEV, increment versions of any sources that were written to during the effect, // so that they are correctly marked as dirty when the effect re-runs if (DEV && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) { for (var dep of effect.deps) { if (dep.set_during_effect) { dep.wv = increment_write_version(); dep.set_during_effect = false; } } } } finally { is_updating_effect = was_updating_effect; active_effect = previous_effect; if (DEV) { set_dev_current_component_function(previous_component_fn); set_dev_stack(previous_stack); } } } /** * Returns a promise that resolves once any pending state changes have been applied. * @returns {Promise<void>} */ export async function tick() { if (async_mode_flag) { return new Promise((f) => { // Race them against each other - in almost all cases requestAnimationFrame will fire first, // but e.g. in case the window is not focused or a view transition happens, requestAnimationFrame // will be delayed and setTimeout helps us resolve fast enough in that case requestAnimationFrame(() => f()); setTimeout(() => f()); }); } await Promise.resolve(); // By calling flushSync we guarantee that any pending state changes are applied after one tick. // TODO look into whether we can make flushing subsequent updates synchronously in the future. flushSync(); } /** * Returns a promise that resolves once any state changes, and asynchronous work resulting from them, * have resolved and the DOM has been updated * @returns {Promise<void>} * @since 5.36 */ export function settled() { return Batch.ensure().settled(); } /** * @template V * @param {Value<V>} signal * @returns {V} */ export function get(signal) { var flags = signal.f; var is_derived = (flags & DERIVED) !== 0; captured_signals?.add(signal); // Register the dependency on the current reaction signal. if (active_reaction !== null && !untracking) { // if we're in a derived that is being read inside an _async_ derived, // it's possible that the effect was already destroyed. In this case, // we don't add the dependency, because that would create a memory leak var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0; if (!destroyed && !current_sources?.includes(signal)) { var deps = active_reaction.deps; if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) { // we're in the effect init/update cycle if (signal.rv < read_version) { signal.rv = read_version; // If the signal is accessing the same dependencies in the same // order as it did last time, increment `skipped_deps` // rather than updating `new_deps`, which creates GC cost if (new_deps === null && deps !== null && deps[skipped_deps] === signal) { skipped_deps++; } else if (new_deps === null) { new_deps = [signal]; } else if (!new_deps.includes(signal)) { new_deps.push(signal); } } } else { // we're adding a dependency outside the init/update cycle // (i.e. after an `await`) (active_reaction.deps ??= []).push(signal); var reactions = signal.reactions; if (reactions === null) { signal.reactions = [active_reaction]; } else if (!reactions.includes(active_reaction)) { reactions.push(active_reaction); } } } } if (DEV) { // TODO reinstate this, but make it actually work // if (current_async_effect) { // var tracking = (current_async_effect.f & REACTION_IS_UPDATING) !== 0; // var was_read = current_async_effect.deps?.includes(signal); // if (!tracking && !untracking && !was_read) { // w.await_reactivity_loss(/** @type {string} */ (signal.label)); // var trace = get_error('traced at'); // // eslint-disable-next-line no-console // if (trace) console.warn(trace); // } // } recent_async_deriveds.delete(signal); if ( tracing_mode_flag && !untracking && tracing_expressions !== null && active_reaction !== null && tracing_expressions.reaction === active_reaction ) { // Used when mapping state between special blocks like `each` if (signal.trace) { signal.trace(); } else { var trace = get_error('traced at'); if (trace) { var entry = tracing_expressions.entries.get(signal); if (entry === undefined) { entry = { traces: [] }; tracing_expressions.entries.set(signal, entry); } var last = entry.traces[entry.traces.length - 1]; // traces can be duplicated, e.g. by `snapshot` invoking both // both `getOwnPropertyDescriptor` and `get` traps at once if (trace.stack !== last?.stack) { entry.traces.push(trace); } } } } } if (is_destroying_effect) { if (old_values.has(signal)) { return old_values.get(signal); } if (is_derived) { var derived = /** @type {Derived} */ (signal); var value = derived.v; // if the derived is dirty and has reactions, or depends on the values that just changed, re-execute // (a derived can be maybe_dirty due to the effect destroy removing its last reaction) if ( ((derived.f & CLEAN) === 0 && derived.reactions !== null) || depends_on_old_values(derived) ) { value = execute_derived(derived); } old_values.set(derived, value); return value; } } else if ( is_derived && (!batch_values?.has(signal) || (current_batch?.is_fork && !effect_tracking())) ) { derived = /** @type {Derived} */ (signal); if (is_dirty(derived)) { update_derived(derived); } if (is_updating_effect && effect_tracking() && (derived.f & CONNECTED) === 0) { reconnect(derived); } } if (batch_values?.has(signal)) { return batch_values.get(signal); } if ((signal.f & ERROR_VALUE) !== 0) { throw signal.v; } return signal.v; } /** * (Re)connect a disconnected derived, so that it is notified * of changes in `mark_reactions` * @param {Derived} derived */ function reconnect(derived) { if (derived.deps === null) return; derived.f ^= CONNECTED; for (const dep of derived.deps) { (dep.reactions ??= []).push(derived); if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) { reconnect(/** @type {Derived} */ (dep)); } } } /** @param {Derived} derived */ function depends_on_old_values(derived) { if (derived.v === UNINITIALIZED) return true; // we don't know, so assume the worst if (derived.deps === null) return false; for (const dep of derived.deps) { if (old_values.has(dep)) { return true; } if ((dep.f & DERIVED) !== 0 && depends_on_old_values(/** @type {Derived} */ (dep))) { return true; } } return false; } /** * Like `get`, but checks for `undefined`. Used for `var` declarations because they can be accessed before being declared * @template V * @param {Value<V> | undefined} signal * @returns {V | undefined} */ export function safe_get(signal) { return signal && get(signal); } /** * When used inside a [`$derived`](https://svelte.dev/docs/svelte/$derived) or [`$effect`](https://svelte.dev/docs/svelte/$effect), * any state read inside `fn` will not be treated as a dependency. * * ```ts * $effect(() => { * // this will run when `data` changes, but not when `time` changes * save(data, { * timestamp: untrack(() => time) * }); * }); * ``` * @template T * @param {() => T} fn * @returns {T} */ export function untrack(fn) { var previous_untracking = untracking; try { untracking = true; return fn(); } finally { untracking = previous_untracking; } } const STATUS_MASK = ~(DIRTY | MAYBE_DIRTY | CLEAN); /** * @param {Signal} signal * @param {number} status * @returns {void} */ export function set_signal_status(signal, status) { signal.f = (signal.f & STATUS_MASK) | status; } /** * @param {Record<string | symbol, unknown>} obj * @param {Array<string | symbol>} keys * @returns {Record<string | symbol, unknown>} */ export function exclude_from_object(obj, keys) { /** @type {Record<string | symbol, unknown>} */ var result = {}; for (var key in obj) { if (!keys.includes(key)) { result[key] = obj[key]; } } for (var symbol of Object.getOwnPropertySymbols(obj)) { if (Object.propertyIsEnumerable.call(obj, symbol) && !keys.includes(symbol)) { result[symbol] = obj[symbol]; } } return result; } /** * Possibly traverse an object and read all its properties so that they're all reactive in case this is `$state`. * Does only check first level of an object for performance reasons (heuristic should be good for 99% of all cases). * @param {any} value * @returns {void} */ export function deep_read_state(value) { if (typeof value !== 'object' || !value || value instanceof EventTarget) { return; } if (STATE_SYMBOL in value) { deep_read(value); } else if (!Array.isArray(value)) { for (let key in value) { const prop = value[key]; if (typeof prop === 'object' && prop && STATE_SYMBOL in prop) { deep_read(prop); } } } } /** * Deeply traverse an object and read all its properties * so that they're all reactive in case this is `$state` * @param {any} value * @param {Set<any>} visited * @returns {void} */ export function deep_read(value, visited = new Set()) { if ( typeof value === 'object' && value !== null && // We don't want to traverse DOM elements !(value instanceof EventTarget) && !visited.has(value) ) { visited.add(value); // When working with a possible SvelteDate, this // will ensure we capture changes to it. if (value instanceof Date) { value.getTime(); } for (let key in value) { try { deep_read(value[key], visited); } catch (e) { // continue } } const proto = get_prototype_of(value); if ( proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype ) { const descriptors = get_descriptors(proto); for (let key in descriptors) { const get = descriptors[key].get; if (get) { try { get.call(value); } catch (e) { // continue } } } } } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/client/proxy.js
packages/svelte/src/internal/client/proxy.js
/** @import { Source } from '#client' */ import { DEV } from 'esm-env'; import { get, active_effect, update_version, active_reaction, set_update_version, set_active_reaction } from './runtime.js'; import { array_prototype, get_descriptor, get_prototype_of, is_array, object_prototype } from '../shared/utils.js'; import { state as source, set, increment, flush_eager_effects, set_eager_effects_deferred } from './reactivity/sources.js'; import { PROXY_PATH_SYMBOL, STATE_SYMBOL } from '#client/constants'; import { UNINITIALIZED } from '../../constants.js'; import * as e from './errors.js'; import { tag } from './dev/tracing.js'; import { get_error } from '../shared/dev.js'; import { tracing_mode_flag } from '../flags/index.js'; // TODO move all regexes into shared module? const regex_is_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/; /** * @template T * @param {T} value * @returns {T} */ export function proxy(value) { // if non-proxyable, or is already a proxy, return `value` if (typeof value !== 'object' || value === null || STATE_SYMBOL in value) { return value; } const prototype = get_prototype_of(value); if (prototype !== object_prototype && prototype !== array_prototype) { return value; } /** @type {Map<any, Source<any>>} */ var sources = new Map(); var is_proxied_array = is_array(value); var version = source(0); var stack = DEV && tracing_mode_flag ? get_error('created at') : null; var parent_version = update_version; /** * Executes the proxy in the context of the reaction it was originally created in, if any * @template T * @param {() => T} fn */ var with_parent = (fn) => { if (update_version === parent_version) { return fn(); } // child source is being created after the initial proxy — // prevent it from being associated with the current reaction var reaction = active_reaction; var version = update_version; set_active_reaction(null); set_update_version(parent_version); var result = fn(); set_active_reaction(reaction); set_update_version(version); return result; }; if (is_proxied_array) { // We need to create the length source eagerly to ensure that // mutations to the array are properly synced with our proxy sources.set('length', source(/** @type {any[]} */ (value).length, stack)); if (DEV) { value = /** @type {any} */ (inspectable_array(/** @type {any[]} */ (value))); } } /** Used in dev for $inspect.trace() */ var path = ''; let updating = false; /** @param {string} new_path */ function update_path(new_path) { if (updating) return; updating = true; path = new_path; tag(version, `${path} version`); // rename all child sources and child proxies for (const [prop, source] of sources) { tag(source, get_label(path, prop)); } updating = false; } return new Proxy(/** @type {any} */ (value), { defineProperty(_, prop, descriptor) { if ( !('value' in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false ) { // we disallow non-basic descriptors, because unless they are applied to the // target object — which we avoid, so that state can be forked — we will run // afoul of the various invariants // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor#invariants e.state_descriptors_fixed(); } var s = sources.get(prop); if (s === undefined) { s = with_parent(() => { var s = source(descriptor.value, stack); sources.set(prop, s); if (DEV && typeof prop === 'string') { tag(s, get_label(path, prop)); } return s; }); } else { set(s, descriptor.value, true); } return true; }, deleteProperty(target, prop) { var s = sources.get(prop); if (s === undefined) { if (prop in target) { const s = with_parent(() => source(UNINITIALIZED, stack)); sources.set(prop, s); increment(version); if (DEV) { tag(s, get_label(path, prop)); } } } else { set(s, UNINITIALIZED); increment(version); } return true; }, get(target, prop, receiver) { if (prop === STATE_SYMBOL) { return value; } if (DEV && prop === PROXY_PATH_SYMBOL) { return update_path; } var s = sources.get(prop); var exists = prop in target; // create a source, but only if it's an own property and not a prototype property if (s === undefined && (!exists || get_descriptor(target, prop)?.writable)) { s = with_parent(() => { var p = proxy(exists ? target[prop] : UNINITIALIZED); var s = source(p, stack); if (DEV) { tag(s, get_label(path, prop)); } return s; }); sources.set(prop, s); } if (s !== undefined) { var v = get(s); return v === UNINITIALIZED ? undefined : v; } return Reflect.get(target, prop, receiver); }, getOwnPropertyDescriptor(target, prop) { var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); if (descriptor && 'value' in descriptor) { var s = sources.get(prop); if (s) descriptor.value = get(s); } else if (descriptor === undefined) { var source = sources.get(prop); var value = source?.v; if (source !== undefined && value !== UNINITIALIZED) { return { enumerable: true, configurable: true, value, writable: true }; } } return descriptor; }, has(target, prop) { if (prop === STATE_SYMBOL) { return true; } var s = sources.get(prop); var has = (s !== undefined && s.v !== UNINITIALIZED) || Reflect.has(target, prop); if ( s !== undefined || (active_effect !== null && (!has || get_descriptor(target, prop)?.writable)) ) { if (s === undefined) { s = with_parent(() => { var p = has ? proxy(target[prop]) : UNINITIALIZED; var s = source(p, stack); if (DEV) { tag(s, get_label(path, prop)); } return s; }); sources.set(prop, s); } var value = get(s); if (value === UNINITIALIZED) { return false; } } return has; }, set(target, prop, value, receiver) { var s = sources.get(prop); var has = prop in target; // variable.length = value -> clear all signals with index >= value if (is_proxied_array && prop === 'length') { for (var i = value; i < /** @type {Source<number>} */ (s).v; i += 1) { var other_s = sources.get(i + ''); if (other_s !== undefined) { set(other_s, UNINITIALIZED); } else if (i in target) { // If the item exists in the original, we need to create an uninitialized source, // else a later read of the property would result in a source being created with // the value of the original item at that index. other_s = with_parent(() => source(UNINITIALIZED, stack)); sources.set(i + '', other_s); if (DEV) { tag(other_s, get_label(path, i)); } } } } // If we haven't yet created a source for this property, we need to ensure // we do so otherwise if we read it later, then the write won't be tracked and // the heuristics of effects will be different vs if we had read the proxied // object property before writing to that property. if (s === undefined) { if (!has || get_descriptor(target, prop)?.writable) { s = with_parent(() => source(undefined, stack)); if (DEV) { tag(s, get_label(path, prop)); } set(s, proxy(value)); sources.set(prop, s); } } else { has = s.v !== UNINITIALIZED; var p = with_parent(() => proxy(value)); set(s, p); } var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); // Set the new value before updating any signals so that any listeners get the new value if (descriptor?.set) { descriptor.set.call(receiver, value); } if (!has) { // If we have mutated an array directly, we might need to // signal that length has also changed. Do it before updating metadata // to ensure that iterating over the array as a result of a metadata update // will not cause the length to be out of sync. if (is_proxied_array && typeof prop === 'string') { var ls = /** @type {Source<number>} */ (sources.get('length')); var n = Number(prop); if (Number.isInteger(n) && n >= ls.v) { set(ls, n + 1); } } increment(version); } return true; }, ownKeys(target) { get(version); var own_keys = Reflect.ownKeys(target).filter((key) => { var source = sources.get(key); return source === undefined || source.v !== UNINITIALIZED; }); for (var [key, source] of sources) { if (source.v !== UNINITIALIZED && !(key in target)) { own_keys.push(key); } } return own_keys; }, setPrototypeOf() { e.state_prototype_fixed(); } }); } /** * @param {string} path * @param {string | symbol} prop */ function get_label(path, prop) { if (typeof prop === 'symbol') return `${path}[Symbol(${prop.description ?? ''})]`; if (regex_is_valid_identifier.test(prop)) return `${path}.${prop}`; return /^\d+$/.test(prop) ? `${path}[${prop}]` : `${path}['${prop}']`; } /** * @param {any} value */ export function get_proxied_value(value) { try { if (value !== null && typeof value === 'object' && STATE_SYMBOL in value) { return value[STATE_SYMBOL]; } } catch { // the above if check can throw an error if the value in question // is the contentWindow of an iframe on another domain, in which // case we want to just return the value (because it's definitely // not a proxied value) so we don't break any JavaScript interacting // with that iframe (such as various payment companies client side // JavaScript libraries interacting with their iframes on the same // domain) } return value; } /** * @param {any} a * @param {any} b */ export function is(a, b) { return Object.is(get_proxied_value(a), get_proxied_value(b)); } const ARRAY_MUTATING_METHODS = new Set([ 'copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift' ]); /** * Wrap array mutating methods so $inspect is triggered only once and * to prevent logging an array in intermediate state (e.g. with an empty slot) * @param {any[]} array */ function inspectable_array(array) { return new Proxy(array, { get(target, prop, receiver) { var value = Reflect.get(target, prop, receiver); if (!ARRAY_MUTATING_METHODS.has(/** @type {string} */ (prop))) { return value; } /** * @this {any[]} * @param {any[]} args */ return function (...args) { set_eager_effects_deferred(); var result = value.apply(this, args); flush_eager_effects(); return result; }; } }); }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false
sveltejs/svelte
https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/internal/client/warnings.js
packages/svelte/src/internal/client/warnings.js
/* This file is generated by scripts/process-messages/index.js. Do not edit! */ import { DEV } from 'esm-env'; var bold = 'font-weight: bold'; var normal = 'font-weight: normal'; /** * Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour. * @param {string} property * @param {string} location */ export function assignment_value_stale(property, location) { if (DEV) { console.warn(`%c[svelte] assignment_value_stale\n%cAssignment to \`${property}\` property (${location}) will evaluate to the right-hand side, not the value of \`${property}\` following the assignment. This may result in unexpected behaviour.\nhttps://svelte.dev/e/assignment_value_stale`, bold, normal); } else { console.warn(`https://svelte.dev/e/assignment_value_stale`); } } /** * Detected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await` * @param {string} name */ export function await_reactivity_loss(name) { if (DEV) { console.warn(`%c[svelte] await_reactivity_loss\n%cDetected reactivity loss when reading \`${name}\`. This happens when state is read in an async function after an earlier \`await\`\nhttps://svelte.dev/e/await_reactivity_loss`, bold, normal); } else { console.warn(`https://svelte.dev/e/await_reactivity_loss`); } } /** * An async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app * @param {string} name * @param {string} location */ export function await_waterfall(name, location) { if (DEV) { console.warn(`%c[svelte] await_waterfall\n%cAn async derived, \`${name}\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\nhttps://svelte.dev/e/await_waterfall`, bold, normal); } else { console.warn(`https://svelte.dev/e/await_waterfall`); } } /** * `%binding%` (%location%) is binding to a non-reactive property * @param {string} binding * @param {string | undefined | null} [location] */ export function binding_property_non_reactive(binding, location) { if (DEV) { console.warn( `%c[svelte] binding_property_non_reactive\n%c${location ? `\`${binding}\` (${location}) is binding to a non-reactive property` : `\`${binding}\` is binding to a non-reactive property`}\nhttps://svelte.dev/e/binding_property_non_reactive`, bold, normal ); } else { console.warn(`https://svelte.dev/e/binding_property_non_reactive`); } } /** * Your `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead * @param {string} method */ export function console_log_state(method) { if (DEV) { console.warn(`%c[svelte] console_log_state\n%cYour \`console.${method}\` contained \`$state\` proxies. Consider using \`$inspect(...)\` or \`$state.snapshot(...)\` instead\nhttps://svelte.dev/e/console_log_state`, bold, normal); } else { console.warn(`https://svelte.dev/e/console_log_state`); } } /** * %handler% should be a function. Did you mean to %suggestion%? * @param {string} handler * @param {string} suggestion */ export function event_handler_invalid(handler, suggestion) { if (DEV) { console.warn(`%c[svelte] event_handler_invalid\n%c${handler} should be a function. Did you mean to ${suggestion}?\nhttps://svelte.dev/e/event_handler_invalid`, bold, normal); } else { console.warn(`https://svelte.dev/e/event_handler_invalid`); } } /** * Expected to find a hydratable with key `%key%` during hydration, but did not. * @param {string} key */ export function hydratable_missing_but_expected(key) { if (DEV) { console.warn(`%c[svelte] hydratable_missing_but_expected\n%cExpected to find a hydratable with key \`${key}\` during hydration, but did not.\nhttps://svelte.dev/e/hydratable_missing_but_expected`, bold, normal); } else { console.warn(`https://svelte.dev/e/hydratable_missing_but_expected`); } } /** * The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value * @param {string} attribute * @param {string} html * @param {string} value */ export function hydration_attribute_changed(attribute, html, value) { if (DEV) { console.warn(`%c[svelte] hydration_attribute_changed\n%cThe \`${attribute}\` attribute on \`${html}\` changed its value between server and client renders. The client value, \`${value}\`, will be ignored in favour of the server value\nhttps://svelte.dev/e/hydration_attribute_changed`, bold, normal); } else { console.warn(`https://svelte.dev/e/hydration_attribute_changed`); } } /** * The value of an `{@html ...}` block %location% changed between server and client renders. The client value will be ignored in favour of the server value * @param {string | undefined | null} [location] */ export function hydration_html_changed(location) { if (DEV) { console.warn( `%c[svelte] hydration_html_changed\n%c${location ? `The value of an \`{@html ...}\` block ${location} changed between server and client renders. The client value will be ignored in favour of the server value` : 'The value of an `{@html ...}` block changed between server and client renders. The client value will be ignored in favour of the server value'}\nhttps://svelte.dev/e/hydration_html_changed`, bold, normal ); } else { console.warn(`https://svelte.dev/e/hydration_html_changed`); } } /** * Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near %location% * @param {string | undefined | null} [location] */ export function hydration_mismatch(location) { if (DEV) { console.warn( `%c[svelte] hydration_mismatch\n%c${location ? `Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}` : 'Hydration failed because the initial UI does not match what was rendered on the server'}\nhttps://svelte.dev/e/hydration_mismatch`, bold, normal ); } else { console.warn(`https://svelte.dev/e/hydration_mismatch`); } } /** * The `render` function passed to `createRawSnippet` should return HTML for a single element */ export function invalid_raw_snippet_render() { if (DEV) { console.warn(`%c[svelte] invalid_raw_snippet_render\n%cThe \`render\` function passed to \`createRawSnippet\` should return HTML for a single element\nhttps://svelte.dev/e/invalid_raw_snippet_render`, bold, normal); } else { console.warn(`https://svelte.dev/e/invalid_raw_snippet_render`); } } /** * Detected a migrated `$:` reactive block in `%filename%` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an `$effect`. * @param {string} filename */ export function legacy_recursive_reactive_block(filename) { if (DEV) { console.warn(`%c[svelte] legacy_recursive_reactive_block\n%cDetected a migrated \`$:\` reactive block in \`${filename}\` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an \`$effect\`.\nhttps://svelte.dev/e/legacy_recursive_reactive_block`, bold, normal); } else { console.warn(`https://svelte.dev/e/legacy_recursive_reactive_block`); } } /** * Tried to unmount a component that was not mounted */ export function lifecycle_double_unmount() { if (DEV) { console.warn(`%c[svelte] lifecycle_double_unmount\n%cTried to unmount a component that was not mounted\nhttps://svelte.dev/e/lifecycle_double_unmount`, bold, normal); } else { console.warn(`https://svelte.dev/e/lifecycle_double_unmount`); } } /** * %parent% passed property `%prop%` to %child% with `bind:`, but its parent component %owner% did not declare `%prop%` as a binding. Consider creating a binding between %owner% and %parent% (e.g. `bind:%prop%={...}` instead of `%prop%={...}`) * @param {string} parent * @param {string} prop * @param {string} child * @param {string} owner */ export function ownership_invalid_binding(parent, prop, child, owner) { if (DEV) { console.warn(`%c[svelte] ownership_invalid_binding\n%c${parent} passed property \`${prop}\` to ${child} with \`bind:\`, but its parent component ${owner} did not declare \`${prop}\` as a binding. Consider creating a binding between ${owner} and ${parent} (e.g. \`bind:${prop}={...}\` instead of \`${prop}={...}\`)\nhttps://svelte.dev/e/ownership_invalid_binding`, bold, normal); } else { console.warn(`https://svelte.dev/e/ownership_invalid_binding`); } } /** * Mutating unbound props (`%name%`, at %location%) is strongly discouraged. Consider using `bind:%prop%={...}` in %parent% (or using a callback) instead * @param {string} name * @param {string} location * @param {string} prop * @param {string} parent */ export function ownership_invalid_mutation(name, location, prop, parent) { if (DEV) { console.warn(`%c[svelte] ownership_invalid_mutation\n%cMutating unbound props (\`${name}\`, at ${location}) is strongly discouraged. Consider using \`bind:${prop}={...}\` in ${parent} (or using a callback) instead\nhttps://svelte.dev/e/ownership_invalid_mutation`, bold, normal); } else { console.warn(`https://svelte.dev/e/ownership_invalid_mutation`); } } /** * The `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is. */ export function select_multiple_invalid_value() { if (DEV) { console.warn(`%c[svelte] select_multiple_invalid_value\n%cThe \`value\` property of a \`<select multiple>\` element should be an array, but it received a non-array value. The selection will be kept as is.\nhttps://svelte.dev/e/select_multiple_invalid_value`, bold, normal); } else { console.warn(`https://svelte.dev/e/select_multiple_invalid_value`); } } /** * Reactive `$state(...)` proxies and the values they proxy have different identities. Because of this, comparisons with `%operator%` will produce unexpected results * @param {string} operator */ export function state_proxy_equality_mismatch(operator) { if (DEV) { console.warn(`%c[svelte] state_proxy_equality_mismatch\n%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${operator}\` will produce unexpected results\nhttps://svelte.dev/e/state_proxy_equality_mismatch`, bold, normal); } else { console.warn(`https://svelte.dev/e/state_proxy_equality_mismatch`); } } /** * Tried to unmount a state proxy, rather than a component */ export function state_proxy_unmount() { if (DEV) { console.warn(`%c[svelte] state_proxy_unmount\n%cTried to unmount a state proxy, rather than a component\nhttps://svelte.dev/e/state_proxy_unmount`, bold, normal); } else { console.warn(`https://svelte.dev/e/state_proxy_unmount`); } } /** * A `<svelte:boundary>` `reset` function only resets the boundary the first time it is called */ export function svelte_boundary_reset_noop() { if (DEV) { console.warn(`%c[svelte] svelte_boundary_reset_noop\n%cA \`<svelte:boundary>\` \`reset\` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop`, bold, normal); } else { console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`); } } /** * The `slide` transition does not work correctly for elements with `display: %value%` * @param {string} value */ export function transition_slide_display(value) { if (DEV) { console.warn(`%c[svelte] transition_slide_display\n%cThe \`slide\` transition does not work correctly for elements with \`display: ${value}\`\nhttps://svelte.dev/e/transition_slide_display`, bold, normal); } else { console.warn(`https://svelte.dev/e/transition_slide_display`); } }
javascript
MIT
b1f44c46c3336df55ee6ebe38225ad746841af70
2026-01-04T14:56:49.602508Z
false