Upload folder using huggingface_hub (part 49)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tools/ui/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts +54 -0
- tools/ui/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js +18 -0
- tools/ui/node_modules/runed/dist/utilities/use-geolocation/index.d.ts +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-geolocation/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts +27 -0
- tools/ui/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js +71 -0
- tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts +28 -0
- tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js +49 -0
- tools/ui/node_modules/runed/dist/utilities/use-interval/index.d.ts +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-interval/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-interval/use-interval.svelte.d.ts +51 -0
- tools/ui/node_modules/runed/dist/utilities/use-interval/use-interval.svelte.js +61 -0
- tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts +15 -0
- tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js +38 -0
- tools/ui/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-resize-observer/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts +39 -0
- tools/ui/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js +34 -0
- tools/ui/node_modules/runed/dist/utilities/use-search-params/index.d.ts +2 -0
- tools/ui/node_modules/runed/dist/utilities/use-search-params/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-search-params/use-search-params.svelte.d.ts +448 -0
- tools/ui/node_modules/runed/dist/utilities/use-search-params/use-search-params.svelte.js +1277 -0
- tools/ui/node_modules/runed/dist/utilities/use-throttle/index.d.ts +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-throttle/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/use-throttle/use-throttle.svelte.d.ts +7 -0
- tools/ui/node_modules/runed/dist/utilities/use-throttle/use-throttle.svelte.js +82 -0
- tools/ui/node_modules/runed/dist/utilities/watch/index.d.ts +1 -0
- tools/ui/node_modules/runed/dist/utilities/watch/index.js +1 -0
- tools/ui/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts +36 -0
- tools/ui/node_modules/runed/dist/utilities/watch/watch.svelte.js +69 -0
- tools/ui/node_modules/runed/package.json +106 -0
- tools/ui/node_modules/rw/.eslintrc +5 -0
- tools/ui/node_modules/rw/.npmignore +3 -0
- tools/ui/node_modules/rw/LICENSE +26 -0
- tools/ui/node_modules/rw/README.md +120 -0
- tools/ui/node_modules/rw/index.js +5 -0
- tools/ui/node_modules/rw/lib/rw/dash.js +14 -0
- tools/ui/node_modules/rw/lib/rw/decode.js +23 -0
- tools/ui/node_modules/rw/lib/rw/encode.js +7 -0
- tools/ui/node_modules/rw/lib/rw/read-file-sync.js +29 -0
- tools/ui/node_modules/rw/lib/rw/read-file.js +23 -0
- tools/ui/node_modules/rw/lib/rw/write-file-sync.js +32 -0
- tools/ui/node_modules/rw/lib/rw/write-file.js +22 -0
- tools/ui/node_modules/rw/package.json +32 -0
- tools/ui/node_modules/rw/test/cat-async +10 -0
- tools/ui/node_modules/rw/test/cat-sync +5 -0
tools/ui/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { MaybeGetter } from "../../internal/types.js";
|
| 2 |
+
export type EventHandler<TEvent extends Event, TTarget extends EventTarget> = (this: TTarget, event: TEvent & {
|
| 3 |
+
currentTarget: TTarget;
|
| 4 |
+
}) => unknown;
|
| 5 |
+
/**
|
| 6 |
+
* Adds an event listener to the specified target element for the given event(s), and returns a function to remove it.
|
| 7 |
+
* @param target The target element to add the event listener to.
|
| 8 |
+
* @param event The event(s) to listen for.
|
| 9 |
+
* @param handler The function to be called when the event is triggered.
|
| 10 |
+
* @param options An optional object that specifies characteristics about the event listener.
|
| 11 |
+
*
|
| 12 |
+
* @see {@link https://runed.dev/docs/utilities/use-event-listener}
|
| 13 |
+
*/
|
| 14 |
+
export declare function useEventListener<TEvent extends keyof WindowEventMap>(target: MaybeGetter<Window | null | undefined>, event: MaybeGetter<TEvent | TEvent[]>, handler: EventHandler<WindowEventMap[TEvent], Window>, options?: AddEventListenerOptions): void;
|
| 15 |
+
/**
|
| 16 |
+
* Adds an event listener to the specified target element for the given event(s), and returns a function to remove it.
|
| 17 |
+
* @param target The target element to add the event listener to.
|
| 18 |
+
* @param event The event(s) to listen for.
|
| 19 |
+
* @param handler The function to be called when the event is triggered.
|
| 20 |
+
* @param options An optional object that specifies characteristics about the event listener.
|
| 21 |
+
*
|
| 22 |
+
* @see {@link https://runed.dev/docs/utilities/use-event-listener}
|
| 23 |
+
*/
|
| 24 |
+
export declare function useEventListener<TEvent extends keyof DocumentEventMap>(target: MaybeGetter<Document | null | undefined>, event: MaybeGetter<TEvent | TEvent[]>, handler: EventHandler<DocumentEventMap[TEvent], Document>, options?: AddEventListenerOptions): void;
|
| 25 |
+
/**
|
| 26 |
+
* Adds an event listener to the specified target element for the given event(s), and returns a function to remove it.
|
| 27 |
+
* @param target The target element to add the event listener to.
|
| 28 |
+
* @param event The event(s) to listen for.
|
| 29 |
+
* @param handler The function to be called when the event is triggered.
|
| 30 |
+
* @param options An optional object that specifies characteristics about the event listener.
|
| 31 |
+
*
|
| 32 |
+
* @see {@link https://runed.dev/docs/utilities/use-event-listener}
|
| 33 |
+
*/
|
| 34 |
+
export declare function useEventListener<TElement extends HTMLElement, TEvent extends keyof HTMLElementEventMap>(target: MaybeGetter<TElement | null | undefined>, event: MaybeGetter<TEvent | TEvent[]>, handler: EventHandler<HTMLElementEventMap[TEvent], TElement>, options?: AddEventListenerOptions): void;
|
| 35 |
+
/**
|
| 36 |
+
* Adds an event listener to the specified target element for the given event(s), and returns a function to remove it.
|
| 37 |
+
* @param target The target element to add the event listener to.
|
| 38 |
+
* @param event The event(s) to listen for.
|
| 39 |
+
* @param handler The function to be called when the event is triggered.
|
| 40 |
+
* @param options An optional object that specifies characteristics about the event listener.
|
| 41 |
+
*
|
| 42 |
+
* @see {@link https://runed.dev/docs/utilities/use-event-listener}
|
| 43 |
+
*/
|
| 44 |
+
export declare function useEventListener<TEvent extends keyof MediaQueryListEventMap>(target: MaybeGetter<MediaQueryList | null | undefined>, event: MaybeGetter<TEvent | TEvent[]>, handler: EventHandler<MediaQueryListEventMap[TEvent], MediaQueryList>, options?: AddEventListenerOptions): void;
|
| 45 |
+
/**
|
| 46 |
+
* Adds an event listener to the specified target element for the given event(s), and returns a function to remove it.
|
| 47 |
+
* @param target The target element to add the event listener to.
|
| 48 |
+
* @param event The event(s) to listen for.
|
| 49 |
+
* @param handler The function to be called when the event is triggered.
|
| 50 |
+
* @param options An optional object that specifies characteristics about the event listener.
|
| 51 |
+
*
|
| 52 |
+
* @see {@link https://runed.dev/docs/utilities/use-event-listener}
|
| 53 |
+
*/
|
| 54 |
+
export declare function useEventListener(target: MaybeGetter<EventTarget | null | undefined>, event: MaybeGetter<string | string[]>, handler: EventListener, options?: AddEventListenerOptions): void;
|
tools/ui/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { extract } from "../extract/extract.svelte.js";
|
| 2 |
+
import { on } from "svelte/events";
|
| 3 |
+
export function useEventListener(_target, _events, handler, options) {
|
| 4 |
+
$effect(() => {
|
| 5 |
+
const target = extract(_target);
|
| 6 |
+
if (target == null)
|
| 7 |
+
return;
|
| 8 |
+
const events = extract(_events);
|
| 9 |
+
if (Array.isArray(events)) {
|
| 10 |
+
for (const event of events) {
|
| 11 |
+
$effect(() => on(target, event, handler, options));
|
| 12 |
+
}
|
| 13 |
+
}
|
| 14 |
+
else {
|
| 15 |
+
return on(target, events, handler, options);
|
| 16 |
+
}
|
| 17 |
+
});
|
| 18 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/use-geolocation/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-geolocation.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-geolocation/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-geolocation.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { type ConfigurableNavigator } from "../../internal/configurable-globals.js";
|
| 2 |
+
export type UseGeolocationOptions = Partial<PositionOptions> & {
|
| 3 |
+
/**
|
| 4 |
+
* Whether to start the watcher immediately upon creation. If set to `false`, the watcher
|
| 5 |
+
* will only start tracking the position when `resume()` is called.
|
| 6 |
+
*
|
| 7 |
+
* @defaultValue true
|
| 8 |
+
*/
|
| 9 |
+
immediate?: boolean;
|
| 10 |
+
} & ConfigurableNavigator;
|
| 11 |
+
export type UseGeolocationPosition = Omit<GeolocationPosition, "toJSON" | "coords"> & {
|
| 12 |
+
coords: Omit<GeolocationPosition["coords"], "toJSON">;
|
| 13 |
+
};
|
| 14 |
+
export type UseGeolocationReturn = {
|
| 15 |
+
readonly isSupported: boolean;
|
| 16 |
+
readonly position: UseGeolocationPosition;
|
| 17 |
+
readonly error: GeolocationPositionError | null;
|
| 18 |
+
readonly isPaused: boolean;
|
| 19 |
+
resume: () => void;
|
| 20 |
+
pause: () => void;
|
| 21 |
+
};
|
| 22 |
+
/**
|
| 23 |
+
* Reactive access to the browser's [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API).
|
| 24 |
+
*
|
| 25 |
+
* @see https://runed.dev/docs/utilities/use-geolocation
|
| 26 |
+
*/
|
| 27 |
+
export declare function useGeolocation(options?: UseGeolocationOptions): UseGeolocationReturn;
|
tools/ui/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { defaultNavigator, } from "../../internal/configurable-globals.js";
|
| 2 |
+
/**
|
| 3 |
+
* Reactive access to the browser's [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API).
|
| 4 |
+
*
|
| 5 |
+
* @see https://runed.dev/docs/utilities/use-geolocation
|
| 6 |
+
*/
|
| 7 |
+
export function useGeolocation(options = {}) {
|
| 8 |
+
const { enableHighAccuracy = true, maximumAge = 30000, timeout = 27000, immediate = true, navigator = defaultNavigator, } = options;
|
| 9 |
+
const isSupported = Boolean(navigator);
|
| 10 |
+
let error = $state.raw(null);
|
| 11 |
+
let position = $state({
|
| 12 |
+
timestamp: 0,
|
| 13 |
+
coords: {
|
| 14 |
+
accuracy: 0,
|
| 15 |
+
latitude: Number.POSITIVE_INFINITY,
|
| 16 |
+
longitude: Number.POSITIVE_INFINITY,
|
| 17 |
+
altitude: null,
|
| 18 |
+
altitudeAccuracy: null,
|
| 19 |
+
heading: null,
|
| 20 |
+
speed: null,
|
| 21 |
+
},
|
| 22 |
+
});
|
| 23 |
+
let isPaused = $state(false);
|
| 24 |
+
function updatePosition(_position) {
|
| 25 |
+
error = null;
|
| 26 |
+
position.timestamp = _position.timestamp;
|
| 27 |
+
position.coords.accuracy = _position.coords.accuracy;
|
| 28 |
+
position.coords.altitude = _position.coords.altitude;
|
| 29 |
+
position.coords.altitudeAccuracy = _position.coords.altitudeAccuracy;
|
| 30 |
+
position.coords.heading = _position.coords.heading;
|
| 31 |
+
position.coords.latitude = _position.coords.latitude;
|
| 32 |
+
position.coords.longitude = _position.coords.longitude;
|
| 33 |
+
position.coords.speed = _position.coords.speed;
|
| 34 |
+
}
|
| 35 |
+
let watcher;
|
| 36 |
+
function resume() {
|
| 37 |
+
if (!navigator)
|
| 38 |
+
return;
|
| 39 |
+
watcher = navigator.geolocation.watchPosition(updatePosition, (err) => (error = err), {
|
| 40 |
+
enableHighAccuracy,
|
| 41 |
+
maximumAge,
|
| 42 |
+
timeout,
|
| 43 |
+
});
|
| 44 |
+
isPaused = false;
|
| 45 |
+
}
|
| 46 |
+
function pause() {
|
| 47 |
+
if (watcher && navigator) {
|
| 48 |
+
navigator.geolocation.clearWatch(watcher);
|
| 49 |
+
}
|
| 50 |
+
isPaused = true;
|
| 51 |
+
}
|
| 52 |
+
$effect(() => {
|
| 53 |
+
if (immediate)
|
| 54 |
+
resume();
|
| 55 |
+
return () => pause();
|
| 56 |
+
});
|
| 57 |
+
return {
|
| 58 |
+
get isSupported() {
|
| 59 |
+
return isSupported;
|
| 60 |
+
},
|
| 61 |
+
position,
|
| 62 |
+
get error() {
|
| 63 |
+
return error;
|
| 64 |
+
},
|
| 65 |
+
get isPaused() {
|
| 66 |
+
return isPaused;
|
| 67 |
+
},
|
| 68 |
+
resume,
|
| 69 |
+
pause,
|
| 70 |
+
};
|
| 71 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-intersection-observer.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-intersection-observer.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { MaybeElementGetter, MaybeGetter } from "../../internal/types.js";
|
| 2 |
+
import { type ConfigurableWindow } from "../../internal/configurable-globals.js";
|
| 3 |
+
export interface UseIntersectionObserverOptions extends Omit<IntersectionObserverInit, "root">, ConfigurableWindow {
|
| 4 |
+
/**
|
| 5 |
+
* Whether to start the observer immediately upon creation. If set to `false`, the observer
|
| 6 |
+
* will only start observing when `resume()` is called.
|
| 7 |
+
*
|
| 8 |
+
* @defaultValue true
|
| 9 |
+
*/
|
| 10 |
+
immediate?: boolean;
|
| 11 |
+
/**
|
| 12 |
+
* The root document/element to use as the bounding box for the intersection.
|
| 13 |
+
*/
|
| 14 |
+
root?: MaybeElementGetter;
|
| 15 |
+
}
|
| 16 |
+
/**
|
| 17 |
+
* Watch for intersection changes of a target element.
|
| 18 |
+
*
|
| 19 |
+
* @see https://runed.dev/docs/utilities/useIntersectionObserver
|
| 20 |
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver IntersectionObserver MDN
|
| 21 |
+
*/
|
| 22 |
+
export declare function useIntersectionObserver(target: MaybeGetter<HTMLElement | HTMLElement[] | null | undefined>, callback: IntersectionObserverCallback, options?: UseIntersectionObserverOptions): {
|
| 23 |
+
readonly isActive: boolean;
|
| 24 |
+
stop: () => void;
|
| 25 |
+
pause(): void;
|
| 26 |
+
resume(): void;
|
| 27 |
+
};
|
| 28 |
+
export type UseIntersectionObserverReturn = ReturnType<typeof useIntersectionObserver>;
|
tools/ui/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { extract } from "../extract/extract.svelte.js";
|
| 2 |
+
import { get } from "../../internal/utils/get.js";
|
| 3 |
+
import { defaultWindow } from "../../internal/configurable-globals.js";
|
| 4 |
+
/**
|
| 5 |
+
* Watch for intersection changes of a target element.
|
| 6 |
+
*
|
| 7 |
+
* @see https://runed.dev/docs/utilities/useIntersectionObserver
|
| 8 |
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver IntersectionObserver MDN
|
| 9 |
+
*/
|
| 10 |
+
export function useIntersectionObserver(target, callback, options = {}) {
|
| 11 |
+
const { root, rootMargin = "0px", threshold = 0.1, immediate = true, window = defaultWindow, } = options;
|
| 12 |
+
let isActive = $state(immediate);
|
| 13 |
+
let observer;
|
| 14 |
+
const targets = $derived.by(() => {
|
| 15 |
+
const value = extract(target);
|
| 16 |
+
return new Set(value ? (Array.isArray(value) ? value : [value]) : []);
|
| 17 |
+
});
|
| 18 |
+
const stop = $effect.root(() => {
|
| 19 |
+
$effect(() => {
|
| 20 |
+
if (!targets.size || !isActive || !window)
|
| 21 |
+
return;
|
| 22 |
+
observer = new window.IntersectionObserver(callback, {
|
| 23 |
+
rootMargin,
|
| 24 |
+
root: get(root),
|
| 25 |
+
threshold,
|
| 26 |
+
});
|
| 27 |
+
for (const el of targets)
|
| 28 |
+
observer.observe(el);
|
| 29 |
+
return () => {
|
| 30 |
+
observer?.disconnect();
|
| 31 |
+
};
|
| 32 |
+
});
|
| 33 |
+
});
|
| 34 |
+
$effect(() => {
|
| 35 |
+
return stop;
|
| 36 |
+
});
|
| 37 |
+
return {
|
| 38 |
+
get isActive() {
|
| 39 |
+
return isActive;
|
| 40 |
+
},
|
| 41 |
+
stop,
|
| 42 |
+
pause() {
|
| 43 |
+
isActive = false;
|
| 44 |
+
},
|
| 45 |
+
resume() {
|
| 46 |
+
isActive = true;
|
| 47 |
+
},
|
| 48 |
+
};
|
| 49 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/use-interval/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-interval.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-interval/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-interval.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-interval/use-interval.svelte.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { MaybeGetter } from "../../internal/types.js";
|
| 2 |
+
export type UseIntervalOptions = {
|
| 3 |
+
/**
|
| 4 |
+
* Start the timer immediately
|
| 5 |
+
*
|
| 6 |
+
* @default true
|
| 7 |
+
*/
|
| 8 |
+
immediate?: boolean;
|
| 9 |
+
/**
|
| 10 |
+
* Execute the callback immediately after calling `resume`
|
| 11 |
+
*
|
| 12 |
+
* @default false
|
| 13 |
+
*/
|
| 14 |
+
immediateCallback?: boolean;
|
| 15 |
+
/**
|
| 16 |
+
* Callback to execute on every interval tick, receives the current counter value
|
| 17 |
+
*/
|
| 18 |
+
callback?: (count: number) => void;
|
| 19 |
+
};
|
| 20 |
+
export type UseIntervalReturn = {
|
| 21 |
+
/**
|
| 22 |
+
* Pause the interval
|
| 23 |
+
*/
|
| 24 |
+
pause: () => void;
|
| 25 |
+
/**
|
| 26 |
+
* Resume the interval
|
| 27 |
+
*/
|
| 28 |
+
resume: () => void;
|
| 29 |
+
/**
|
| 30 |
+
* Reset the counter to 0
|
| 31 |
+
*/
|
| 32 |
+
reset: () => void;
|
| 33 |
+
/**
|
| 34 |
+
* Whether the interval is currently active
|
| 35 |
+
*/
|
| 36 |
+
readonly isActive: boolean;
|
| 37 |
+
/**
|
| 38 |
+
* The current counter value
|
| 39 |
+
*/
|
| 40 |
+
readonly counter: number;
|
| 41 |
+
};
|
| 42 |
+
/**
|
| 43 |
+
* Wrapper for `setInterval` with controls for pausing and resuming.
|
| 44 |
+
*
|
| 45 |
+
* @see https://runed.dev/docs/utilities/use-interval
|
| 46 |
+
*
|
| 47 |
+
* @param delay - The interval in milliseconds between executions
|
| 48 |
+
* @param options - Configuration options
|
| 49 |
+
* @returns Object with pause, resume, reset methods, counter and isActive state
|
| 50 |
+
*/
|
| 51 |
+
export declare function useInterval(delay: MaybeGetter<number>, options?: UseIntervalOptions): UseIntervalReturn;
|
tools/ui/node_modules/runed/dist/utilities/use-interval/use-interval.svelte.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { extract } from "../extract/index.js";
|
| 2 |
+
import { watch } from "../watch/watch.svelte.js";
|
| 3 |
+
/**
|
| 4 |
+
* Wrapper for `setInterval` with controls for pausing and resuming.
|
| 5 |
+
*
|
| 6 |
+
* @see https://runed.dev/docs/utilities/use-interval
|
| 7 |
+
*
|
| 8 |
+
* @param delay - The interval in milliseconds between executions
|
| 9 |
+
* @param options - Configuration options
|
| 10 |
+
* @returns Object with pause, resume, reset methods, counter and isActive state
|
| 11 |
+
*/
|
| 12 |
+
export function useInterval(delay, options = {}) {
|
| 13 |
+
const { immediate = true, immediateCallback = false, callback } = options;
|
| 14 |
+
let intervalId = $state(null);
|
| 15 |
+
let counter = $state(0);
|
| 16 |
+
const delay$ = $derived(extract(delay));
|
| 17 |
+
const isActive = $derived(intervalId !== null);
|
| 18 |
+
function runCallback() {
|
| 19 |
+
counter++;
|
| 20 |
+
callback?.(counter);
|
| 21 |
+
}
|
| 22 |
+
function createInterval() {
|
| 23 |
+
intervalId = setInterval(runCallback, delay$);
|
| 24 |
+
}
|
| 25 |
+
const pause = () => {
|
| 26 |
+
if (intervalId === null)
|
| 27 |
+
return;
|
| 28 |
+
clearInterval(intervalId);
|
| 29 |
+
intervalId = null;
|
| 30 |
+
};
|
| 31 |
+
const resume = () => {
|
| 32 |
+
if (intervalId !== null)
|
| 33 |
+
return;
|
| 34 |
+
if (immediateCallback)
|
| 35 |
+
runCallback();
|
| 36 |
+
createInterval();
|
| 37 |
+
};
|
| 38 |
+
if (immediate) {
|
| 39 |
+
resume();
|
| 40 |
+
}
|
| 41 |
+
// Sync interval's delay with the prop
|
| 42 |
+
watch(() => delay$, () => {
|
| 43 |
+
if (!isActive)
|
| 44 |
+
return;
|
| 45 |
+
pause();
|
| 46 |
+
createInterval();
|
| 47 |
+
});
|
| 48 |
+
// Cleanup on disposal
|
| 49 |
+
$effect(() => pause);
|
| 50 |
+
return {
|
| 51 |
+
pause,
|
| 52 |
+
resume,
|
| 53 |
+
reset: () => (counter = 0),
|
| 54 |
+
get isActive() {
|
| 55 |
+
return isActive;
|
| 56 |
+
},
|
| 57 |
+
get counter() {
|
| 58 |
+
return counter;
|
| 59 |
+
},
|
| 60 |
+
};
|
| 61 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-mutation-observer.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-mutation-observer.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { MaybeGetter } from "../../internal/types.js";
|
| 2 |
+
import { type ConfigurableWindow } from "../../internal/configurable-globals.js";
|
| 3 |
+
export interface UseMutationObserverOptions extends MutationObserverInit, ConfigurableWindow {
|
| 4 |
+
}
|
| 5 |
+
/**
|
| 6 |
+
* Watch for changes being made to the DOM tree.
|
| 7 |
+
*
|
| 8 |
+
* @see https://runed.dev/docs/utilities/useMutationObserver
|
| 9 |
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN
|
| 10 |
+
*/
|
| 11 |
+
export declare function useMutationObserver(target: MaybeGetter<HTMLElement | HTMLElement[] | null | undefined>, callback: MutationCallback, options?: UseMutationObserverOptions): {
|
| 12 |
+
stop: () => void;
|
| 13 |
+
takeRecords(): MutationRecord[] | undefined;
|
| 14 |
+
};
|
| 15 |
+
export type UseMutationObserverReturn = ReturnType<typeof useMutationObserver>;
|
tools/ui/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { extract } from "../extract/extract.svelte.js";
|
| 2 |
+
import { defaultWindow } from "../../internal/configurable-globals.js";
|
| 3 |
+
/**
|
| 4 |
+
* Watch for changes being made to the DOM tree.
|
| 5 |
+
*
|
| 6 |
+
* @see https://runed.dev/docs/utilities/useMutationObserver
|
| 7 |
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN
|
| 8 |
+
*/
|
| 9 |
+
export function useMutationObserver(target, callback, options = {}) {
|
| 10 |
+
const { window = defaultWindow } = options;
|
| 11 |
+
let observer;
|
| 12 |
+
const targets = $derived.by(() => {
|
| 13 |
+
const value = extract(target);
|
| 14 |
+
return new Set(value ? (Array.isArray(value) ? value : [value]) : []);
|
| 15 |
+
});
|
| 16 |
+
const stop = $effect.root(() => {
|
| 17 |
+
$effect(() => {
|
| 18 |
+
if (!targets.size || !window)
|
| 19 |
+
return;
|
| 20 |
+
observer = new window.MutationObserver(callback);
|
| 21 |
+
for (const el of targets)
|
| 22 |
+
observer.observe(el, options);
|
| 23 |
+
return () => {
|
| 24 |
+
observer?.disconnect();
|
| 25 |
+
observer = undefined;
|
| 26 |
+
};
|
| 27 |
+
});
|
| 28 |
+
});
|
| 29 |
+
$effect(() => {
|
| 30 |
+
return stop;
|
| 31 |
+
});
|
| 32 |
+
return {
|
| 33 |
+
stop,
|
| 34 |
+
takeRecords() {
|
| 35 |
+
return observer?.takeRecords();
|
| 36 |
+
},
|
| 37 |
+
};
|
| 38 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export { useResizeObserver } from "./use-resize-observer.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-resize-observer/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export { useResizeObserver } from "./use-resize-observer.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { MaybeGetter } from "../../internal/types.js";
|
| 2 |
+
import { type ConfigurableWindow } from "../../internal/configurable-globals.js";
|
| 3 |
+
export interface ResizeObserverSize {
|
| 4 |
+
readonly inlineSize: number;
|
| 5 |
+
readonly blockSize: number;
|
| 6 |
+
}
|
| 7 |
+
export interface ResizeObserverEntry {
|
| 8 |
+
readonly target: Element;
|
| 9 |
+
readonly contentRect: DOMRectReadOnly;
|
| 10 |
+
readonly borderBoxSize?: ReadonlyArray<ResizeObserverSize>;
|
| 11 |
+
readonly contentBoxSize?: ReadonlyArray<ResizeObserverSize>;
|
| 12 |
+
readonly devicePixelContentBoxSize?: ReadonlyArray<ResizeObserverSize>;
|
| 13 |
+
}
|
| 14 |
+
export type ResizeObserverCallback = (entries: ReadonlyArray<ResizeObserverEntry>, observer: ResizeObserver) => void;
|
| 15 |
+
export interface UseResizeObserverOptions extends ConfigurableWindow {
|
| 16 |
+
/**
|
| 17 |
+
* Sets which box model the observer will observe changes to. Possible values
|
| 18 |
+
* are `content-box` (the default), `border-box` and `device-pixel-content-box`.
|
| 19 |
+
*
|
| 20 |
+
* @default 'content-box'
|
| 21 |
+
*/
|
| 22 |
+
box?: ResizeObserverBoxOptions;
|
| 23 |
+
}
|
| 24 |
+
declare class ResizeObserver {
|
| 25 |
+
constructor(callback: ResizeObserverCallback);
|
| 26 |
+
disconnect(): void;
|
| 27 |
+
observe(target: Element, options?: UseResizeObserverOptions): void;
|
| 28 |
+
unobserve(target: Element): void;
|
| 29 |
+
}
|
| 30 |
+
/**
|
| 31 |
+
* Reports changes to the dimensions of an Element's content or the border-box
|
| 32 |
+
*
|
| 33 |
+
* @see https://runed.dev/docs/utilities/useResizeObserver
|
| 34 |
+
*/
|
| 35 |
+
export declare function useResizeObserver(target: MaybeGetter<HTMLElement | HTMLElement[] | null | undefined>, callback: ResizeObserverCallback, options?: UseResizeObserverOptions): {
|
| 36 |
+
stop: () => void;
|
| 37 |
+
};
|
| 38 |
+
export type UseResizeObserverReturn = ReturnType<typeof useResizeObserver>;
|
| 39 |
+
export {};
|
tools/ui/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { extract } from "../extract/extract.svelte.js";
|
| 2 |
+
import { defaultWindow } from "../../internal/configurable-globals.js";
|
| 3 |
+
/**
|
| 4 |
+
* Reports changes to the dimensions of an Element's content or the border-box
|
| 5 |
+
*
|
| 6 |
+
* @see https://runed.dev/docs/utilities/useResizeObserver
|
| 7 |
+
*/
|
| 8 |
+
export function useResizeObserver(target, callback, options = {}) {
|
| 9 |
+
const { window = defaultWindow } = options;
|
| 10 |
+
let observer;
|
| 11 |
+
const targets = $derived.by(() => {
|
| 12 |
+
const value = extract(target);
|
| 13 |
+
return new Set(value ? (Array.isArray(value) ? value : [value]) : []);
|
| 14 |
+
});
|
| 15 |
+
const stop = $effect.root(() => {
|
| 16 |
+
$effect(() => {
|
| 17 |
+
if (!targets.size || !window)
|
| 18 |
+
return;
|
| 19 |
+
observer = new window.ResizeObserver(callback);
|
| 20 |
+
for (const el of targets)
|
| 21 |
+
observer.observe(el, options);
|
| 22 |
+
return () => {
|
| 23 |
+
observer?.disconnect();
|
| 24 |
+
observer = undefined;
|
| 25 |
+
};
|
| 26 |
+
});
|
| 27 |
+
});
|
| 28 |
+
$effect(() => {
|
| 29 |
+
return stop;
|
| 30 |
+
});
|
| 31 |
+
return {
|
| 32 |
+
stop,
|
| 33 |
+
};
|
| 34 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/use-search-params/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export { useSearchParams, createSearchParamsSchema, validateSearchParams, } from "./use-search-params.svelte.js";
|
| 2 |
+
export type { SearchParamsOptions, StandardSchemaV1, SchemaTypeConfig, ReturnUseSearchParams, } from "./use-search-params.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-search-params/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export { useSearchParams, createSearchParamsSchema, validateSearchParams, } from "./use-search-params.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-search-params/use-search-params.svelte.d.ts
ADDED
|
@@ -0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Configuration options for useSearchParams
|
| 3 |
+
*/
|
| 4 |
+
export interface SearchParamsOptions {
|
| 5 |
+
/**
|
| 6 |
+
* If true, parameters set to their default values will be shown in the URL.
|
| 7 |
+
* If false, parameters with default values will be omitted from the URL.
|
| 8 |
+
* @default false
|
| 9 |
+
*/
|
| 10 |
+
showDefaults?: boolean;
|
| 11 |
+
/**
|
| 12 |
+
* The number of milliseconds to delay URL updates when parameters change.
|
| 13 |
+
* This helps avoid cluttering browser history when values change rapidly
|
| 14 |
+
* (like during typing in an input field).
|
| 15 |
+
* @default 0 (no debounce)
|
| 16 |
+
*/
|
| 17 |
+
debounce?: number;
|
| 18 |
+
/**
|
| 19 |
+
* Controls whether URL updates create new browser history entries.
|
| 20 |
+
* If true (default), each update adds a new entry to the browser history.
|
| 21 |
+
* If false, updates replace the current URL without creating new history entries.
|
| 22 |
+
* @default true
|
| 23 |
+
*/
|
| 24 |
+
pushHistory?: boolean;
|
| 25 |
+
/**
|
| 26 |
+
* Enable lz-string compression for all parameters.
|
| 27 |
+
* When true, all parameters are compressed into a single parameter in the URL.
|
| 28 |
+
* This helps reduce URL length and provides basic parameter obfuscation.
|
| 29 |
+
* @default false
|
| 30 |
+
*/
|
| 31 |
+
compress?: boolean;
|
| 32 |
+
/**
|
| 33 |
+
* The name of the parameter used to store compressed data when compression is enabled.
|
| 34 |
+
* You can customize this to avoid conflicts with your schema parameters.
|
| 35 |
+
*
|
| 36 |
+
* For example, if your schema already uses '_data', you might want to use '_compressed'
|
| 37 |
+
* or another unique name.
|
| 38 |
+
*
|
| 39 |
+
* @default '_data'
|
| 40 |
+
*/
|
| 41 |
+
compressedParamName?: string;
|
| 42 |
+
/**
|
| 43 |
+
* Controls whether to update the URL when parameters change.
|
| 44 |
+
* If `true` (default), changes to parameters will update the URL.
|
| 45 |
+
* If `false`, parameters will only be stored in memory without updating the URL.
|
| 46 |
+
*
|
| 47 |
+
* Note: When `false`, compress option will be ignored.
|
| 48 |
+
* @default true
|
| 49 |
+
*/
|
| 50 |
+
updateURL?: boolean;
|
| 51 |
+
/**
|
| 52 |
+
* If `true`, the scroll position will be preserved when the URL is updated.
|
| 53 |
+
*
|
| 54 |
+
* If `false`, the scroll position will be reset to the top when the URL is updated.
|
| 55 |
+
* @default false
|
| 56 |
+
*/
|
| 57 |
+
noScroll?: boolean;
|
| 58 |
+
}
|
| 59 |
+
/** The Standard Schema interface. */
|
| 60 |
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
| 61 |
+
/** The Standard Schema properties. */
|
| 62 |
+
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
| 63 |
+
}
|
| 64 |
+
export declare namespace StandardSchemaV1 {
|
| 65 |
+
/** The Standard Schema properties interface. */
|
| 66 |
+
interface Props<Input = unknown, Output = Input> {
|
| 67 |
+
/** The version number of the standard. */
|
| 68 |
+
readonly version: 1;
|
| 69 |
+
/** The vendor name of the schema library. */
|
| 70 |
+
readonly vendor: string;
|
| 71 |
+
/** Validates unknown input values. */
|
| 72 |
+
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
|
| 73 |
+
/** Inferred types associated with the schema. */
|
| 74 |
+
readonly types?: Types<Input, Output> | undefined;
|
| 75 |
+
}
|
| 76 |
+
/** The result interface of the validate function. */
|
| 77 |
+
type Result<T> = SuccessResult<T> | FailureResult;
|
| 78 |
+
/** The result interface if validation succeeds. */
|
| 79 |
+
interface SuccessResult<T> {
|
| 80 |
+
/** The typed output value. */
|
| 81 |
+
readonly value: T;
|
| 82 |
+
/** The non-existent issues. */
|
| 83 |
+
readonly issues?: undefined;
|
| 84 |
+
}
|
| 85 |
+
/** The result interface if validation fails. */
|
| 86 |
+
interface FailureResult {
|
| 87 |
+
/** The issues of failed validation. */
|
| 88 |
+
readonly issues: ReadonlyArray<Issue>;
|
| 89 |
+
}
|
| 90 |
+
/** The issue interface of the failure output. */
|
| 91 |
+
interface Issue {
|
| 92 |
+
/** The error message of the issue. */
|
| 93 |
+
readonly message: string;
|
| 94 |
+
/** The path of the issue, if any. */
|
| 95 |
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
| 96 |
+
}
|
| 97 |
+
/** The path segment interface of the issue. */
|
| 98 |
+
interface PathSegment {
|
| 99 |
+
/** The key representing a path segment. */
|
| 100 |
+
readonly key: PropertyKey;
|
| 101 |
+
}
|
| 102 |
+
/** The Standard Schema types interface. */
|
| 103 |
+
interface Types<Input = unknown, Output = Input> {
|
| 104 |
+
/** The input type of the schema. */
|
| 105 |
+
readonly input: Input;
|
| 106 |
+
/** The output type of the schema. */
|
| 107 |
+
readonly output: Output;
|
| 108 |
+
}
|
| 109 |
+
/** Infers the input type of a Standard Schema. */
|
| 110 |
+
type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
| 111 |
+
/** Infers the output type of a Standard Schema. */
|
| 112 |
+
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
| 113 |
+
}
|
| 114 |
+
/**
|
| 115 |
+
* Core class that handles URL search parameter operations with schema validation
|
| 116 |
+
*
|
| 117 |
+
* This class provides the foundation for the useSearchParams hook. It:
|
| 118 |
+
* 1. Validates values against a schema
|
| 119 |
+
* 2. Handles type conversion between URL strings and JavaScript types
|
| 120 |
+
* 3. Updates the URL when values change
|
| 121 |
+
* 4. Maintains a cache of valid schema keys for performance
|
| 122 |
+
*/
|
| 123 |
+
declare class SearchParams<Schema extends StandardSchemaV1> {
|
| 124 |
+
#private;
|
| 125 |
+
/**
|
| 126 |
+
* Create a new SearchParams instance with the given schema and options
|
| 127 |
+
*
|
| 128 |
+
* @param schema A StandardSchemaV1-compatible schema
|
| 129 |
+
* @param options Configuration options
|
| 130 |
+
*/
|
| 131 |
+
constructor(schema: Schema, options?: SearchParamsOptions);
|
| 132 |
+
/**
|
| 133 |
+
* Get a typed parameter value by key
|
| 134 |
+
* Retrieves the current value from the local cache, runs it through schema validation,
|
| 135 |
+
* and returns the validated, typed result
|
| 136 |
+
*
|
| 137 |
+
* @param key The parameter key to get
|
| 138 |
+
* @returns The typed value after schema validation
|
| 139 |
+
*/
|
| 140 |
+
get<K extends keyof StandardSchemaV1.InferOutput<Schema>>(key: K & string): StandardSchemaV1.InferOutput<Schema>[K];
|
| 141 |
+
/**
|
| 142 |
+
* Set a parameter value and update the URL
|
| 143 |
+
* Validates the value through the schema before updating the URL
|
| 144 |
+
*
|
| 145 |
+
* @param key The parameter key to set
|
| 146 |
+
* @param value The value to set (will be type-converted and validated)
|
| 147 |
+
*/
|
| 148 |
+
set<K extends keyof StandardSchemaV1.InferOutput<Schema>>(key: K & string, value: StandardSchemaV1.InferOutput<Schema>[K]): void;
|
| 149 |
+
/**
|
| 150 |
+
* Clean up resources used by this instance
|
| 151 |
+
*
|
| 152 |
+
* IMPORTANT: You only need to call this method when using the debounce option.
|
| 153 |
+
* If you're not using debounce, there's no need to call cleanup.
|
| 154 |
+
*
|
| 155 |
+
* Call this when the component unmounts to prevent memory leaks from debounce timers.
|
| 156 |
+
*
|
| 157 |
+
* @example
|
| 158 |
+
* Example in a Svelte component with Svelte 5 runes:
|
| 159 |
+
* ```svelte
|
| 160 |
+
* <script>
|
| 161 |
+
* import { useSearchParams } from '../../hooks/useSearchParams.svelte';
|
| 162 |
+
*
|
| 163 |
+
* // Using debounce, so we need to handle cleanup
|
| 164 |
+
* const searchParams = useSearchParams(schema, { debounce: 300 });
|
| 165 |
+
*
|
| 166 |
+
* // Register cleanup in a Svelte 5 effect
|
| 167 |
+
* $effect(() => {
|
| 168 |
+
* return () => {
|
| 169 |
+
* // Prevent memory leaks by cleaning up debounce timer
|
| 170 |
+
* searchParams.cleanup();
|
| 171 |
+
* };
|
| 172 |
+
* });
|
| 173 |
+
* </script>
|
| 174 |
+
* ```
|
| 175 |
+
*/
|
| 176 |
+
cleanup(): void;
|
| 177 |
+
/**
|
| 178 |
+
* Update multiple parameters at once
|
| 179 |
+
*
|
| 180 |
+
* This is more efficient than setting multiple parameters individually
|
| 181 |
+
* because it only triggers one URL update or one in-memory store update.
|
| 182 |
+
*
|
| 183 |
+
* @param values An object containing parameter key-value pairs to update
|
| 184 |
+
*/
|
| 185 |
+
update(values: Partial<StandardSchemaV1.InferOutput<Schema>>): void;
|
| 186 |
+
/**
|
| 187 |
+
* Check if a key exists in the schema
|
| 188 |
+
* This is a critical method used by the Proxy handler to determine
|
| 189 |
+
* which properties should be treated as URL parameters
|
| 190 |
+
*
|
| 191 |
+
* @param key The key to check
|
| 192 |
+
* @returns True if the key is defined in the schema
|
| 193 |
+
*/
|
| 194 |
+
has(key: string): boolean;
|
| 195 |
+
/**
|
| 196 |
+
* Reset all parameters to their default values
|
| 197 |
+
*
|
| 198 |
+
* This method removes all current URL parameters or in-memory parameters
|
| 199 |
+
* and optionally sets parameters with non-default values back to their defaults.
|
| 200 |
+
*
|
| 201 |
+
* @param showDefaults Whether to show default values in the URL or in-memory store after reset.
|
| 202 |
+
* If not provided, uses the instance's showDefaults option.
|
| 203 |
+
*/
|
| 204 |
+
reset(showDefaults?: boolean): void;
|
| 205 |
+
/**
|
| 206 |
+
* Validate a value against the schema
|
| 207 |
+
* This is the core method that enforces schema validation
|
| 208 |
+
*
|
| 209 |
+
* @param value The value to validate
|
| 210 |
+
* @returns A StandardSchemaV1.Result containing either the validated value or validation errors
|
| 211 |
+
*/
|
| 212 |
+
validate(value: unknown): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>;
|
| 213 |
+
}
|
| 214 |
+
/**
|
| 215 |
+
* Schema type for createSearchParamsSchema
|
| 216 |
+
* Allows specifying more precise types for arrays and objects
|
| 217 |
+
*/
|
| 218 |
+
export type SchemaTypeConfig<ArrayType = unknown, ObjectType = unknown> = {
|
| 219 |
+
type: "string";
|
| 220 |
+
default?: string;
|
| 221 |
+
} | {
|
| 222 |
+
type: "number";
|
| 223 |
+
default?: number;
|
| 224 |
+
} | {
|
| 225 |
+
type: "boolean";
|
| 226 |
+
default?: boolean;
|
| 227 |
+
} | {
|
| 228 |
+
type: "array";
|
| 229 |
+
default?: ArrayType[];
|
| 230 |
+
arrayType?: ArrayType;
|
| 231 |
+
} | {
|
| 232 |
+
type: "object";
|
| 233 |
+
default?: ObjectType;
|
| 234 |
+
objectType?: ObjectType;
|
| 235 |
+
};
|
| 236 |
+
/**
|
| 237 |
+
* Creates a simple schema compatible with useSearchParams without requiring external validation libraries.
|
| 238 |
+
*
|
| 239 |
+
* This is a lightweight alternative to using full schema validation libraries like Zod, Valibot, or Arktype.
|
| 240 |
+
* Use this when you need basic type conversion and default values without adding dependencies.
|
| 241 |
+
*
|
| 242 |
+
* Limitations:
|
| 243 |
+
* - For 'array' type: supports basic arrays, but doesn't validate array items
|
| 244 |
+
* - For 'object' type: supports generic objects, but doesn't validate nested properties
|
| 245 |
+
* - No custom validation rules or transformations
|
| 246 |
+
* - No granular reactivity: nested property changes require whole-value reassignment
|
| 247 |
+
* (e.g., params.items = [...params.items, newItem] instead of params.items.push(newItem))
|
| 248 |
+
*
|
| 249 |
+
* For complex validation needs (nested validation, refined rules, etc.), use a dedicated
|
| 250 |
+
* validation library instead.
|
| 251 |
+
*
|
| 252 |
+
* Example usage:
|
| 253 |
+
* ```
|
| 254 |
+
* const productSearchSchema = createSearchParamsSchema({
|
| 255 |
+
* // Basic types with defaults
|
| 256 |
+
* page: { type: 'number', default: 1 },
|
| 257 |
+
* filter: { type: 'string', default: '' },
|
| 258 |
+
* sort: { type: 'string', default: 'newest' },
|
| 259 |
+
*
|
| 260 |
+
* // Array type with specific element type
|
| 261 |
+
* tags: {
|
| 262 |
+
* type: 'array',
|
| 263 |
+
* default: ['new'],
|
| 264 |
+
* arrayType: '' // Specify string[] type
|
| 265 |
+
* },
|
| 266 |
+
*
|
| 267 |
+
* // Object type with specific shape
|
| 268 |
+
* config: {
|
| 269 |
+
* type: 'object',
|
| 270 |
+
* default: { theme: 'light' },
|
| 271 |
+
* objectType: { theme: '' } // Specify { theme: string } type
|
| 272 |
+
* }
|
| 273 |
+
* });
|
| 274 |
+
* ```
|
| 275 |
+
*
|
| 276 |
+
* URL storage format:
|
| 277 |
+
* - Arrays are stored as JSON strings: ?tags=["sale","featured"]
|
| 278 |
+
* - Objects are stored as JSON strings: ?config={"theme":"dark","fontSize":14}
|
| 279 |
+
* - Primitive values are stored directly: ?page=2&filter=red
|
| 280 |
+
*/
|
| 281 |
+
export declare function createSearchParamsSchema<T extends Record<string, SchemaTypeConfig>>(schema: T): StandardSchemaV1<unknown, {
|
| 282 |
+
[K in keyof T]: T[K] extends {
|
| 283 |
+
type: "number";
|
| 284 |
+
} ? number : T[K] extends {
|
| 285 |
+
type: "boolean";
|
| 286 |
+
} ? boolean : T[K] extends {
|
| 287 |
+
type: "array";
|
| 288 |
+
arrayType?: infer A;
|
| 289 |
+
} ? unknown extends A ? unknown[] : A[] : T[K] extends {
|
| 290 |
+
type: "object";
|
| 291 |
+
objectType?: infer O;
|
| 292 |
+
} ? unknown extends O ? Record<string, unknown> : O : string;
|
| 293 |
+
}>;
|
| 294 |
+
/**
|
| 295 |
+
* A utility function to extract, validate and convert URL search parameters to [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
|
| 296 |
+
*
|
| 297 |
+
* This function makes it easy to use the same schema validation in
|
| 298 |
+
* both client-side components (via useSearchParams) and server-side load functions.
|
| 299 |
+
* Unlike useSearchParams, this function doesn't modify the URL - it only validates
|
| 300 |
+
* parameters and returns them as a new URLSearchParams object.
|
| 301 |
+
*
|
| 302 |
+
* **Important for SvelteKit fine-grained reactivity**: This function only accesses URL parameters
|
| 303 |
+
* that are defined in your schema, ensuring that load functions only re-run when schema-defined
|
| 304 |
+
* parameters change, not when any URL parameter changes.
|
| 305 |
+
*
|
| 306 |
+
* Handles both standard URL parameters and compressed parameters (when compression is enabled).
|
| 307 |
+
*
|
| 308 |
+
* @param url The URL object from SvelteKit load function
|
| 309 |
+
* @param schema A validation schema (createSearchParamsSchema, Zod, Valibot, etc.)
|
| 310 |
+
* @param options Optional configuration (like custom compressedParamName)
|
| 311 |
+
* @returns URLSearchParams object with the validated values
|
| 312 |
+
*
|
| 313 |
+
* Example with SvelteKit page or layout load function:
|
| 314 |
+
* ```ts
|
| 315 |
+
* import { validateSearchParams } from '../../hooks/useSearchParams.svelte';
|
| 316 |
+
* import { productSchema } from './schemas';
|
| 317 |
+
*
|
| 318 |
+
* export const load = ({ url }) => {
|
| 319 |
+
* // Get validated search params as URLSearchParams object
|
| 320 |
+
* // Only accesses 'page', 'filter', 'sort' parameters from the URL
|
| 321 |
+
* // Load function will only re-run when these specific parameters change
|
| 322 |
+
* const searchParams = validateSearchParams(url, productSchema, {
|
| 323 |
+
* compressedParamName: '_compressed'
|
| 324 |
+
* });
|
| 325 |
+
*
|
| 326 |
+
* // Use URLSearchParams directly with fetch
|
| 327 |
+
* const response = await fetch(`/api/products?${searchParams.toString()}`);
|
| 328 |
+
* return {
|
| 329 |
+
* products: await response.json()
|
| 330 |
+
* };
|
| 331 |
+
* };
|
| 332 |
+
* ```
|
| 333 |
+
*/
|
| 334 |
+
export declare function validateSearchParams<Schema extends StandardSchemaV1>(url: URL, schema: Schema, options?: {
|
| 335 |
+
compressedParamName?: string;
|
| 336 |
+
}): {
|
| 337 |
+
searchParams: URLSearchParams;
|
| 338 |
+
data: StandardSchemaV1.InferOutput<Schema>;
|
| 339 |
+
};
|
| 340 |
+
export type ReturnUseSearchParams<T extends StandardSchemaV1> = SearchParams<T> & StandardSchemaV1.InferOutput<T> & {
|
| 341 |
+
/**
|
| 342 |
+
* Convert the current schema parameters to a URLSearchParams object
|
| 343 |
+
* This includes all values defined in the schema, regardless of their presence in the URL
|
| 344 |
+
* @returns URLSearchParams object containing all current parameter values
|
| 345 |
+
*/
|
| 346 |
+
toURLSearchParams(): URLSearchParams;
|
| 347 |
+
};
|
| 348 |
+
/**
|
| 349 |
+
* Hook to create a reactive search params object with property access
|
| 350 |
+
*
|
| 351 |
+
* This client-side hook automatically updates the URL when parameters change.
|
| 352 |
+
* It provides type-safe access to URL search parameters through direct property access.
|
| 353 |
+
*
|
| 354 |
+
* @param schema A validation schema compatible with StandardSchemaV1
|
| 355 |
+
* @param options Configuration options that affect URL behavior
|
| 356 |
+
* @returns A reactive object for working with typed search parameters
|
| 357 |
+
*
|
| 358 |
+
* Available options:
|
| 359 |
+
* - `showDefaults` (boolean): When true, parameters with default values will be shown in the URL.
|
| 360 |
+
* When false (default), parameters with default values will be omitted from the URL.
|
| 361 |
+
* - `debounce` (number): Milliseconds to delay URL updates when parameters change.
|
| 362 |
+
* Useful to avoid cluttering browser history when values change rapidly (default: 0, no debounce).
|
| 363 |
+
* - `pushHistory` (boolean): Controls whether URL updates create new browser history entries.
|
| 364 |
+
* If true (default), each update adds a new entry to the browser history.
|
| 365 |
+
* If false, updates replace the current URL without creating new history entries.
|
| 366 |
+
* - `compress` (boolean): When true, all parameters are compressed into a single parameter
|
| 367 |
+
* using lz-string compression. This helps reduce URL length and provides basic obfuscation (default: false).
|
| 368 |
+
* Use validateSearchParams with the same compressedParamName option when handling compressed URLs server-side.
|
| 369 |
+
* - `compressedParamName` (string): The name of the parameter used to store compressed data
|
| 370 |
+
* when compression is enabled. Customize this to avoid conflicts with parameters in your schema.
|
| 371 |
+
* Default is '_data'.
|
| 372 |
+
* - `updateURL` (boolean): When true (default), the URL is updated when parameters change.
|
| 373 |
+
* When false, only in-memory parameters are updated.
|
| 374 |
+
*
|
| 375 |
+
* Example with Zod:
|
| 376 |
+
* ```
|
| 377 |
+
* import { z } from 'zod';
|
| 378 |
+
*
|
| 379 |
+
* const productSearchSchema = z.object({
|
| 380 |
+
* page: z.number().catch(1),
|
| 381 |
+
* filter: z.string().catch(''),
|
| 382 |
+
* sort: z.enum(['newest', 'oldest', 'price']).catch('newest'),
|
| 383 |
+
* });
|
| 384 |
+
*
|
| 385 |
+
* const params = useSearchParams(productSearchSchema);
|
| 386 |
+
*
|
| 387 |
+
* // Access parameters directly
|
| 388 |
+
* const page = $derived(params.page); // number (defaults to 1)
|
| 389 |
+
* const sort = $derived(params.sort); // 'newest' | 'oldest' | 'price'
|
| 390 |
+
*
|
| 391 |
+
* // Update parameters directly
|
| 392 |
+
* params.page = 2; // Updates URL to include ?page=2
|
| 393 |
+
* params.sort = 'price'; // Updates URL to include &sort=price
|
| 394 |
+
* ```
|
| 395 |
+
*
|
| 396 |
+
* Example with options:
|
| 397 |
+
* ```typescript
|
| 398 |
+
* // Show default values in URL, debounce updates by 300ms,
|
| 399 |
+
* // don't create new history entries, and compress params
|
| 400 |
+
* const params = useSearchParams(schema, {
|
| 401 |
+
* showDefaults: true,
|
| 402 |
+
* debounce: 300,
|
| 403 |
+
* pushHistory: false,
|
| 404 |
+
* compress: true,
|
| 405 |
+
* compressedParamName: '_compressed' // Custom name to avoid conflicts
|
| 406 |
+
* });
|
| 407 |
+
*
|
| 408 |
+
* // Great for binding to input fields (updates URL without cluttering history)
|
| 409 |
+
* <input type="text" bind:value={params.search} />
|
| 410 |
+
* // Resulting URL will be something like: /?_compressed=N4IgDgTg9g...
|
| 411 |
+
* ```
|
| 412 |
+
* Example with Valibot:
|
| 413 |
+
* ```
|
| 414 |
+
* import * as v from 'valibot';
|
| 415 |
+
*
|
| 416 |
+
* const productSearchSchema = v.object({
|
| 417 |
+
* page: v.optional(v.fallback(v.number(), 1), 1),
|
| 418 |
+
* filter: v.optional(v.fallback(v.string(), ''), ''),
|
| 419 |
+
* sort: v.optional(v.fallback(v.picklist(['newest', 'oldest', 'price']), 'newest'), 'newest'),
|
| 420 |
+
* });
|
| 421 |
+
*
|
| 422 |
+
* const params = useSearchParams(productSearchSchema);
|
| 423 |
+
* ``` * Example with Arktype:
|
| 424 |
+
* ```
|
| 425 |
+
* import { type } from 'arktype';
|
| 426 |
+
*
|
| 427 |
+
* const productSearchSchema = type({
|
| 428 |
+
* page: 'number = 1',
|
| 429 |
+
* filter: 'string = ""',
|
| 430 |
+
* sort: '"newest" | "oldest" | "price" = "newest"',
|
| 431 |
+
* });
|
| 432 |
+
*
|
| 433 |
+
* const params = useSearchParams(productSearchSchema);
|
| 434 |
+
* ```
|
| 435 |
+
* Or with our built-in schema creator (no additional dependencies):
|
| 436 |
+
*
|
| 437 |
+
* ```
|
| 438 |
+
* const productSearchSchema = createSearchParamsSchema({
|
| 439 |
+
* page: { type: 'number', default: 1 },
|
| 440 |
+
* filter: { type: 'string', default: '' },
|
| 441 |
+
* sort: { type: 'string', default: 'newest' }
|
| 442 |
+
* });
|
| 443 |
+
*
|
| 444 |
+
* const params = useSearchParams(productSearchSchema);
|
| 445 |
+
* ```
|
| 446 |
+
*/
|
| 447 |
+
export declare function useSearchParams<Schema extends StandardSchemaV1>(schema: Schema, options?: S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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { SvelteURLSearchParams } from "svelte/reactivity";
|
| 2 |
+
import { dequal } from "dequal/lite";
|
| 3 |
+
import * as lzString from "lz-string";
|
| 4 |
+
import { browser, building } from "$app/environment";
|
| 5 |
+
import { goto } from "$app/navigation";
|
| 6 |
+
import { page } from "$app/state";
|
| 7 |
+
import { IsMounted } from "../is-mounted/is-mounted.svelte.js";
|
| 8 |
+
import { BROWSER } from "esm-env";
|
| 9 |
+
import { untrack } from "svelte";
|
| 10 |
+
/**
|
| 11 |
+
* Extract and pre-process values from URLSearchParams
|
| 12 |
+
*
|
| 13 |
+
* This is a shared utility used by both validateSearchParams and the SearchParams class
|
| 14 |
+
* to ensure consistent conversion of URL string values to JavaScript types.
|
| 15 |
+
*
|
| 16 |
+
* @param searchParams The URLSearchParams object to extract values from
|
| 17 |
+
* @param numberFields Optional set of field names that should be treated as numbers
|
| 18 |
+
* @returns An object with processed parameter values
|
| 19 |
+
* @internal
|
| 20 |
+
*/
|
| 21 |
+
function extractParamValues(searchParams, numberFields = new Set()) {
|
| 22 |
+
const params = {};
|
| 23 |
+
for (const [key, value] of searchParams.entries()) {
|
| 24 |
+
try {
|
| 25 |
+
// Special handling for empty arrays and objects
|
| 26 |
+
if (value === "[]") {
|
| 27 |
+
params[key] = [];
|
| 28 |
+
continue;
|
| 29 |
+
}
|
| 30 |
+
if (value === "{}") {
|
| 31 |
+
params[key] = {};
|
| 32 |
+
continue;
|
| 33 |
+
}
|
| 34 |
+
// Try to parse as JSON for complex objects/arrays
|
| 35 |
+
// This handles cases like ?obj={"foo":"bar"} or ?arr=[1,2,3]
|
| 36 |
+
if (value.startsWith("{") || value.startsWith("[")) {
|
| 37 |
+
params[key] = JSON.parse(value);
|
| 38 |
+
}
|
| 39 |
+
// Boolean values are stored as strings, convert them
|
| 40 |
+
else if (value === "true" || value === "false") {
|
| 41 |
+
params[key] = value === "true";
|
| 42 |
+
}
|
| 43 |
+
// Only convert to number if it looks numeric AND the schema expects a number
|
| 44 |
+
else if (numberFields.has(key) && value.trim() !== "" && !isNaN(Number(value))) {
|
| 45 |
+
params[key] = Number(value);
|
| 46 |
+
}
|
| 47 |
+
// Handle comma-separated values as arrays (fallback format)
|
| 48 |
+
else if (value.includes(",")) {
|
| 49 |
+
params[key] = value.split(",");
|
| 50 |
+
}
|
| 51 |
+
// Keep everything else as strings
|
| 52 |
+
else {
|
| 53 |
+
params[key] = value;
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
catch {
|
| 57 |
+
// If JSON parsing fails, treat as regular string
|
| 58 |
+
// This ensures we don't throw errors during type conversion
|
| 59 |
+
params[key] = value;
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
return params;
|
| 63 |
+
}
|
| 64 |
+
/**
|
| 65 |
+
* Extract schema information by validating an empty object.
|
| 66 |
+
* This consolidates multiple schema validation calls into one for efficiency.
|
| 67 |
+
* Works with any StandardSchemaV1-compatible schema (Zod, Valibot, Arktype, etc.)
|
| 68 |
+
*
|
| 69 |
+
* Note: This function expects schemas used with useSearchParams to have defaults for all fields,
|
| 70 |
+
* which is the recommended pattern since URL parameters are inherently optional.
|
| 71 |
+
*
|
| 72 |
+
* @param schema A StandardSchemaV1-compatible schema
|
| 73 |
+
* @returns Object containing schema keys, number fields, and default values
|
| 74 |
+
* @internal
|
| 75 |
+
*/
|
| 76 |
+
function extractSchemaInfo(schema) {
|
| 77 |
+
const validationResult = schema["~standard"].validate({});
|
| 78 |
+
if (!validationResult || !("value" in validationResult)) {
|
| 79 |
+
return { keys: [], numberFields: new Set(), defaultValues: {} };
|
| 80 |
+
}
|
| 81 |
+
const defaultValues = validationResult.value;
|
| 82 |
+
const keys = Object.keys(defaultValues);
|
| 83 |
+
const numberFields = new Set();
|
| 84 |
+
// Determine which fields are number types by checking default value types
|
| 85 |
+
for (const [key, defaultValue] of Object.entries(defaultValues)) {
|
| 86 |
+
if (typeof defaultValue === "number") {
|
| 87 |
+
numberFields.add(key);
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
return { keys, numberFields, defaultValues };
|
| 91 |
+
}
|
| 92 |
+
/**
|
| 93 |
+
* Extract and pre-process values from URLSearchParams, but only for keys defined in the schema.
|
| 94 |
+
* This enables SvelteKit's fine-grained reactivity by only accessing specific parameters
|
| 95 |
+
* instead of all parameters via searchParams.entries().
|
| 96 |
+
*
|
| 97 |
+
* @param searchParams The URLSearchParams object to extract values from
|
| 98 |
+
* @param schemaKeys Array of parameter keys that are defined in the schema
|
| 99 |
+
* @param numberFields Set of field names that should be treated as numbers
|
| 100 |
+
* @returns An object with processed parameter values for schema-defined keys only
|
| 101 |
+
* @internal
|
| 102 |
+
*/
|
| 103 |
+
function extractSelectiveParamValues(searchParams, schemaKeys, numberFields = new Set()) {
|
| 104 |
+
const params = {};
|
| 105 |
+
// Only access parameters that are defined in the schema
|
| 106 |
+
// This maintains SvelteKit's fine-grained reactivity
|
| 107 |
+
for (const key of schemaKeys) {
|
| 108 |
+
const value = searchParams.get(key);
|
| 109 |
+
if (value === null)
|
| 110 |
+
continue;
|
| 111 |
+
try {
|
| 112 |
+
if (value === "[]") {
|
| 113 |
+
params[key] = [];
|
| 114 |
+
continue;
|
| 115 |
+
}
|
| 116 |
+
if (value === "{}") {
|
| 117 |
+
params[key] = {};
|
| 118 |
+
continue;
|
| 119 |
+
}
|
| 120 |
+
// Try to parse as JSON for complex objects/arrays
|
| 121 |
+
// This handles cases like ?obj={"foo":"bar"} or ?arr=[1,2,3]
|
| 122 |
+
if (value.startsWith("{") || value.startsWith("[")) {
|
| 123 |
+
params[key] = JSON.parse(value);
|
| 124 |
+
}
|
| 125 |
+
// Boolean values are stored as strings, convert them
|
| 126 |
+
else if (value === "true" || value === "false") {
|
| 127 |
+
params[key] = value === "true";
|
| 128 |
+
}
|
| 129 |
+
// Only convert to number if it looks numeric AND the schema expects a number
|
| 130 |
+
// This handles cases like ?page=2 or ?price=19.99
|
| 131 |
+
else if (numberFields.has(key) && value.trim() !== "" && !isNaN(Number(value))) {
|
| 132 |
+
params[key] = Number(value);
|
| 133 |
+
}
|
| 134 |
+
// Handle comma-separated values as arrays (fallback format)
|
| 135 |
+
else if (value.includes(",")) {
|
| 136 |
+
params[key] = value.split(",");
|
| 137 |
+
}
|
| 138 |
+
// Keep everything else as strings
|
| 139 |
+
else {
|
| 140 |
+
params[key] = value;
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
catch {
|
| 144 |
+
// If JSON parsing fails, treat as regular string
|
| 145 |
+
// This ensures we don't throw errors during type conversion
|
| 146 |
+
params[key] = value;
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
return params;
|
| 150 |
+
}
|
| 151 |
+
/**
|
| 152 |
+
* Core class that handles URL search parameter operations with schema validation
|
| 153 |
+
*
|
| 154 |
+
* This class provides the foundation for the useSearchParams hook. It:
|
| 155 |
+
* 1. Validates values against a schema
|
| 156 |
+
* 2. Handles type conversion between URL strings and JavaScript types
|
| 157 |
+
* 3. Updates the URL when values change
|
| 158 |
+
* 4. Maintains a cache of valid schema keys for performance
|
| 159 |
+
*/
|
| 160 |
+
class SearchParams {
|
| 161 |
+
/** The schema used for validation and type conversion */
|
| 162 |
+
#schema;
|
| 163 |
+
/**
|
| 164 |
+
* A lookup object containing all valid keys from the schema
|
| 165 |
+
* Used for fast property existence checking without re-validating
|
| 166 |
+
* Format: { propertyName1: true, propertyName2: true, ... }
|
| 167 |
+
*/
|
| 168 |
+
#schemaShape;
|
| 169 |
+
/**
|
| 170 |
+
* Options that configure behavior
|
| 171 |
+
*/
|
| 172 |
+
#options;
|
| 173 |
+
/**
|
| 174 |
+
* Default values from the schema, used for comparison when showDefaults is false
|
| 175 |
+
*/
|
| 176 |
+
#defaultValues;
|
| 177 |
+
/**
|
| 178 |
+
* Set of field names that expect number types based on schema validation
|
| 179 |
+
* Used to intelligently convert URL string values to numbers only when appropriate
|
| 180 |
+
*/
|
| 181 |
+
#numberFields;
|
| 182 |
+
/**
|
| 183 |
+
* Timer ID for debouncing URL updates
|
| 184 |
+
* @private
|
| 185 |
+
*/
|
| 186 |
+
#debounceTimer = null;
|
| 187 |
+
/**
|
| 188 |
+
* Local cache for immediate reads/writes
|
| 189 |
+
* Used regardless of updateURL setting to prevent input lag
|
| 190 |
+
* When updateURL is true, this cache is synced to the URL (with optional debouncing)
|
| 191 |
+
* When updateURL is false, this cache is the sole source of truth
|
| 192 |
+
* @private
|
| 193 |
+
*/
|
| 194 |
+
#localCache = $state(new URLSearchParams());
|
| 195 |
+
/**
|
| 196 |
+
* Flag to track if local cache has been initialized from URL
|
| 197 |
+
* @private
|
| 198 |
+
*/
|
| 199 |
+
#cacheInitialized = false;
|
| 200 |
+
/**
|
| 201 |
+
* Create a new SearchParams instance with the given schema and options
|
| 202 |
+
*
|
| 203 |
+
* @param schema A StandardSchemaV1-compatible schema
|
| 204 |
+
* @param options Configuration options
|
| 205 |
+
*/
|
| 206 |
+
constructor(schema, options = {}) {
|
| 207 |
+
this.#schema = schema;
|
| 208 |
+
this.#options = {
|
| 209 |
+
showDefaults: false,
|
| 210 |
+
debounce: 0,
|
| 211 |
+
pushHistory: true,
|
| 212 |
+
compress: false,
|
| 213 |
+
compressedParamName: "_data",
|
| 214 |
+
updateURL: true,
|
| 215 |
+
noScroll: false,
|
| 216 |
+
...options,
|
| 217 |
+
};
|
| 218 |
+
// Extract schema information (keys, number fields, defaults) in one pass
|
| 219 |
+
const schemaInfo = extractSchemaInfo(schema);
|
| 220 |
+
// Store schema shape for property checking
|
| 221 |
+
this.#schemaShape = schemaInfo.keys.reduce((acc, key) => {
|
| 222 |
+
acc[key] = true;
|
| 223 |
+
return acc;
|
| 224 |
+
}, {});
|
| 225 |
+
// Store default values and number fields
|
| 226 |
+
this.#defaultValues = { ...schemaInfo.defaultValues };
|
| 227 |
+
this.#numberFields = schemaInfo.numberFields;
|
| 228 |
+
}
|
| 229 |
+
/**
|
| 230 |
+
* Initialize the local cache from the URL on first access
|
| 231 |
+
* @private
|
| 232 |
+
*/
|
| 233 |
+
#initializeCacheFromURL() {
|
| 234 |
+
if (this.#cacheInitialized)
|
| 235 |
+
return;
|
| 236 |
+
this.#cacheInitialized = true;
|
| 237 |
+
// only initialize from URL if updateURL is true and we're in browser
|
| 238 |
+
if (!this.#options.updateURL || !BROWSER || building)
|
| 239 |
+
return;
|
| 240 |
+
const urlParams = page.url.searchParams;
|
| 241 |
+
const compressedParamName = this.#options.compressedParamName || "_data";
|
| 242 |
+
// Handle compressed mode
|
| 243 |
+
if (this.#options.compress && urlParams.has(compressedParamName)) {
|
| 244 |
+
try {
|
| 245 |
+
const compressedData = urlParams.get(compressedParamName) || "";
|
| 246 |
+
const decompressed = lzString.decompressFromEncodedURIComponent(compressedData);
|
| 247 |
+
if (decompressed) {
|
| 248 |
+
const decompressedObj = JSON.parse(decompressed);
|
| 249 |
+
const newCache = new URLSearchParams();
|
| 250 |
+
// populate cache with decompressed values
|
| 251 |
+
for (const [key, value] of Object.entries(decompressedObj)) {
|
| 252 |
+
const stringValue = this.#serializeValue(value);
|
| 253 |
+
newCache.set(key, stringValue);
|
| 254 |
+
}
|
| 255 |
+
untrack(() => (this.#localCache = newCache));
|
| 256 |
+
return;
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
catch (e) {
|
| 260 |
+
console.error("Error initializing cache from compressed URL", e);
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
// Normal mode - copy current URL params to cache
|
| 264 |
+
const newCache = new SvelteURLSearchParams();
|
| 265 |
+
for (const [key, value] of urlParams.entries()) {
|
| 266 |
+
newCache.set(key, value);
|
| 267 |
+
}
|
| 268 |
+
untrack(() => (this.#localCache = newCache));
|
| 269 |
+
}
|
| 270 |
+
/**
|
| 271 |
+
* Get a typed parameter value by key
|
| 272 |
+
* Retrieves the current value from the local cache, runs it through schema validation,
|
| 273 |
+
* and returns the validated, typed result
|
| 274 |
+
*
|
| 275 |
+
* @param key The parameter key to get
|
| 276 |
+
* @returns The typed value after schema validation
|
| 277 |
+
*/
|
| 278 |
+
get(key) {
|
| 279 |
+
this.#initializeCacheFromURL();
|
| 280 |
+
return this.#getTypedValue(key);
|
| 281 |
+
}
|
| 282 |
+
/**
|
| 283 |
+
* Set a parameter value and update the URL
|
| 284 |
+
* Validates the value through the schema before updating the URL
|
| 285 |
+
*
|
| 286 |
+
* @param key The parameter key to set
|
| 287 |
+
* @param value The value to set (will be type-converted and validated)
|
| 288 |
+
*/
|
| 289 |
+
set(key, value) {
|
| 290 |
+
this.#setValue(key, value);
|
| 291 |
+
}
|
| 292 |
+
/**
|
| 293 |
+
* Clean up resources used by this instance
|
| 294 |
+
*
|
| 295 |
+
* IMPORTANT: You only need to call this method when using the debounce option.
|
| 296 |
+
* If you're not using debounce, there's no need to call cleanup.
|
| 297 |
+
*
|
| 298 |
+
* Call this when the component unmounts to prevent memory leaks from debounce timers.
|
| 299 |
+
*
|
| 300 |
+
* @example
|
| 301 |
+
* Example in a Svelte component with Svelte 5 runes:
|
| 302 |
+
* ```svelte
|
| 303 |
+
* <script>
|
| 304 |
+
* import { useSearchParams } from '../../hooks/useSearchParams.svelte';
|
| 305 |
+
*
|
| 306 |
+
* // Using debounce, so we need to handle cleanup
|
| 307 |
+
* const searchParams = useSearchParams(schema, { debounce: 300 });
|
| 308 |
+
*
|
| 309 |
+
* // Register cleanup in a Svelte 5 effect
|
| 310 |
+
* $effect(() => {
|
| 311 |
+
* return () => {
|
| 312 |
+
* // Prevent memory leaks by cleaning up debounce timer
|
| 313 |
+
* searchParams.cleanup();
|
| 314 |
+
* };
|
| 315 |
+
* });
|
| 316 |
+
* </script>
|
| 317 |
+
* ```
|
| 318 |
+
*/
|
| 319 |
+
cleanup() {
|
| 320 |
+
// Clear any debounce timer
|
| 321 |
+
if (this.#debounceTimer) {
|
| 322 |
+
clearTimeout(this.#debounceTimer);
|
| 323 |
+
this.#debounceTimer = null;
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
/**
|
| 327 |
+
* Update multiple parameters at once
|
| 328 |
+
*
|
| 329 |
+
* This is more efficient than setting multiple parameters individually
|
| 330 |
+
* because it only triggers one URL update or one in-memory store update.
|
| 331 |
+
*
|
| 332 |
+
* @param values An object containing parameter key-value pairs to update
|
| 333 |
+
*/
|
| 334 |
+
update(values) {
|
| 335 |
+
this.#initializeCacheFromURL();
|
| 336 |
+
if (!values || typeof values !== "object")
|
| 337 |
+
return;
|
| 338 |
+
// Quick optimization: Filter out non-schema keys upfront
|
| 339 |
+
const filteredValues = {};
|
| 340 |
+
let anyValid = false;
|
| 341 |
+
for (const [key, value] of Object.entries(values)) {
|
| 342 |
+
if (this.has(key)) {
|
| 343 |
+
filteredValues[key] = value;
|
| 344 |
+
anyValid = true;
|
| 345 |
+
}
|
| 346 |
+
}
|
| 347 |
+
// no valid keys to update
|
| 348 |
+
if (!anyValid)
|
| 349 |
+
return;
|
| 350 |
+
// Always use local cache for immediate state
|
| 351 |
+
const paramsObject = this.#extractParamValues(this.#localCache);
|
| 352 |
+
// Check if there are any actual changes
|
| 353 |
+
let hasChanges = false;
|
| 354 |
+
for (const [key, value] of Object.entries(filteredValues)) {
|
| 355 |
+
const currentValue = paramsObject[key];
|
| 356 |
+
// Optimization: For primitives, use direct comparison; use dequal only for objects
|
| 357 |
+
const isPrimitive = typeof currentValue !== "object" &&
|
| 358 |
+
typeof value !== "object" &&
|
| 359 |
+
currentValue !== null &&
|
| 360 |
+
value !== null;
|
| 361 |
+
if (isPrimitive ? currentValue !== value : !dequal(currentValue, value)) {
|
| 362 |
+
hasChanges = true;
|
| 363 |
+
break;
|
| 364 |
+
}
|
| 365 |
+
}
|
| 366 |
+
// no changes, skip update
|
| 367 |
+
if (!hasChanges)
|
| 368 |
+
return;
|
| 369 |
+
// Create a new object with the updated values
|
| 370 |
+
const newParamsObject = { ...paramsObject, ...filteredValues };
|
| 371 |
+
// Validate against schema
|
| 372 |
+
const result = this.validate(newParamsObject);
|
| 373 |
+
if (result && "value" in result) {
|
| 374 |
+
const validatedResult = result.value;
|
| 375 |
+
// Always update local cache immediately (for instant reads)
|
| 376 |
+
const updatedCache = this.#updateParamsWithValidatedValues(this.#localCache, filteredValues, validatedResult, true // always treat as in-memory for cache updates
|
| 377 |
+
);
|
| 378 |
+
this.#localCache = updatedCache;
|
| 379 |
+
// If updateURL is true and we're in browser, sync to URL
|
| 380 |
+
if (this.#options.updateURL && BROWSER && !building) {
|
| 381 |
+
// Handle the compression mode if enabled
|
| 382 |
+
if (this.#options.compress) {
|
| 383 |
+
this.#handleCompressedUpdate(validatedResult);
|
| 384 |
+
}
|
| 385 |
+
else {
|
| 386 |
+
// Normal mode - update the URL
|
| 387 |
+
// Start from the current local cache to preserve all params
|
| 388 |
+
const urlParams = this.#updateParamsWithValidatedValues(this.#localCache, filteredValues, validatedResult, false // use URLSearchParams for URL updates
|
| 389 |
+
);
|
| 390 |
+
this.#navigateWithParams(urlParams);
|
| 391 |
+
}
|
| 392 |
+
}
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
/**
|
| 396 |
+
* Check if a key exists in the schema
|
| 397 |
+
* This is a critical method used by the Proxy handler to determine
|
| 398 |
+
* which properties should be treated as URL parameters
|
| 399 |
+
*
|
| 400 |
+
* @param key The key to check
|
| 401 |
+
* @returns True if the key is defined in the schema
|
| 402 |
+
*/
|
| 403 |
+
has(key) {
|
| 404 |
+
return key in this.#schemaShape;
|
| 405 |
+
}
|
| 406 |
+
/**
|
| 407 |
+
* Reset all parameters to their default values
|
| 408 |
+
*
|
| 409 |
+
* This method removes all current URL parameters or in-memory parameters
|
| 410 |
+
* and optionally sets parameters with non-default values back to their defaults.
|
| 411 |
+
*
|
| 412 |
+
* @param showDefaults Whether to show default values in the URL or in-memory store after reset.
|
| 413 |
+
* If not provided, uses the instance's showDefaults option.
|
| 414 |
+
*/
|
| 415 |
+
reset(showDefaults) {
|
| 416 |
+
this.#initializeCacheFromURL();
|
| 417 |
+
const useShowDefaults = showDefaults !== undefined ? showDefaults : this.#options.showDefaults;
|
| 418 |
+
if (useShowDefaults) {
|
| 419 |
+
// Reuse the filtered default values for both cache and URL updates
|
| 420 |
+
const validDefaultValues = {};
|
| 421 |
+
// Filter out null/undefined values
|
| 422 |
+
for (const [key, defaultValue] of Object.entries(this.#defaultValues)) {
|
| 423 |
+
if (defaultValue !== null && defaultValue !== undefined) {
|
| 424 |
+
validDefaultValues[key] = defaultValue;
|
| 425 |
+
}
|
| 426 |
+
}
|
| 427 |
+
// Always update local cache immediately
|
| 428 |
+
const newCache = new SvelteURLSearchParams();
|
| 429 |
+
for (const [key, value] of Object.entries(validDefaultValues)) {
|
| 430 |
+
const stringValue = this.#serializeValue(value);
|
| 431 |
+
newCache.set(key, stringValue);
|
| 432 |
+
}
|
| 433 |
+
this.#localCache = newCache;
|
| 434 |
+
// If updateURL is true, sync to URL
|
| 435 |
+
if (this.#options.updateURL && BROWSER && !building) {
|
| 436 |
+
const urlParams = new URLSearchParams();
|
| 437 |
+
for (const [key, value] of Object.entries(validDefaultValues)) {
|
| 438 |
+
const stringValue = this.#serializeValue(value);
|
| 439 |
+
urlParams.set(key, stringValue);
|
| 440 |
+
}
|
| 441 |
+
this.#navigateWithParams(urlParams);
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
else {
|
| 445 |
+
// Not showing defaults - just clear everything
|
| 446 |
+
this.#localCache = new SvelteURLSearchParams();
|
| 447 |
+
// If updateURL is true, clear the URL
|
| 448 |
+
if (this.#options.updateURL && BROWSER && !building) {
|
| 449 |
+
goto("?", { replaceState: true, noScroll: this.#options.noScroll });
|
| 450 |
+
}
|
| 451 |
+
}
|
| 452 |
+
}
|
| 453 |
+
/**
|
| 454 |
+
* Validate a value against the schema
|
| 455 |
+
* This is the core method that enforces schema validation
|
| 456 |
+
*
|
| 457 |
+
* @param value The value to validate
|
| 458 |
+
* @returns A StandardSchemaV1.Result containing either the validated value or validation errors
|
| 459 |
+
*/
|
| 460 |
+
validate(value) {
|
| 461 |
+
return this.#schema["~standard"].validate(value);
|
| 462 |
+
}
|
| 463 |
+
/**
|
| 464 |
+
* Helper method to create a new search params object
|
| 465 |
+
* Works with both URLSearchParams and SvelteURLSearchParams
|
| 466 |
+
* @private
|
| 467 |
+
*/
|
| 468 |
+
#createSearchParams(base, isInMemory) {
|
| 469 |
+
if (isInMemory) {
|
| 470 |
+
// For in-memory, always return SvelteURLSearchParams
|
| 471 |
+
return new SvelteURLSearchParams(base.toString());
|
| 472 |
+
}
|
| 473 |
+
else {
|
| 474 |
+
// For URL updates, always return URLSearchParams
|
| 475 |
+
return new URLSearchParams(base.toString());
|
| 476 |
+
}
|
| 477 |
+
}
|
| 478 |
+
/**
|
| 479 |
+
* Helper method to update search params with validated values
|
| 480 |
+
* Works with both URLSearchParams and SvelteURLSearchParams
|
| 481 |
+
* @private
|
| 482 |
+
*/
|
| 483 |
+
#updateParamsWithValidatedValues(searchParams, updates, validatedValues, isInMemory) {
|
| 484 |
+
const newSearchParams = this.#createSearchParams(searchParams, isInMemory);
|
| 485 |
+
for (const key of Object.keys(updates)) {
|
| 486 |
+
// Skip keys not in schema
|
| 487 |
+
if (!this.has(key))
|
| 488 |
+
continue;
|
| 489 |
+
const validatedValue = validatedValues[key];
|
| 490 |
+
// Check if the value should be omitted
|
| 491 |
+
const isDefaultValue = !this.#options.showDefaults && dequal(validatedValue, this.#defaultValues[key]);
|
| 492 |
+
if (validatedValue === undefined || validatedValue === null || isDefaultValue) {
|
| 493 |
+
newSearchParams.delete(key);
|
| 494 |
+
}
|
| 495 |
+
else {
|
| 496 |
+
const stringValue = this.#serializeValue(validatedValue);
|
| 497 |
+
newSearchParams.set(key, stringValue);
|
| 498 |
+
}
|
| 499 |
+
}
|
| 500 |
+
return newSearchParams;
|
| 501 |
+
}
|
| 502 |
+
/**
|
| 503 |
+
* Helper method to handle updates when compression is enabled
|
| 504 |
+
* @private
|
| 505 |
+
*/
|
| 506 |
+
#handleCompressedUpdate(fullParamsObject) {
|
| 507 |
+
try {
|
| 508 |
+
// Convert the entire parameters object to JSON
|
| 509 |
+
const jsonData = JSON.stringify(fullParamsObject);
|
| 510 |
+
// Compress the JSON string
|
| 511 |
+
const compressed = lzString.compressToEncodedURIComponent(jsonData);
|
| 512 |
+
// Create new params with just the compressed data
|
| 513 |
+
const newSearchParams = new URLSearchParams();
|
| 514 |
+
const compressedParamName = this.#options.compressedParamName || "_data";
|
| 515 |
+
newSearchParams.set(compressedParamName, compressed);
|
| 516 |
+
// Update URL
|
| 517 |
+
this.#navigateWithParams(newSearchParams);
|
| 518 |
+
}
|
| 519 |
+
catch (e) {
|
| 520 |
+
console.error("Error compressing data, falling back to normal mode", e);
|
| 521 |
+
// Create new params with all values as fallback
|
| 522 |
+
const newSearchParams = new URLSearchParams();
|
| 523 |
+
for (const [key, value] of Object.entries(fullParamsObject)) {
|
| 524 |
+
if (value === undefined || value === null) {
|
| 525 |
+
continue;
|
| 526 |
+
}
|
| 527 |
+
const stringValue = this.#serializeValue(value);
|
| 528 |
+
newSearchParams.set(key, stringValue);
|
| 529 |
+
}
|
| 530 |
+
this.#navigateWithParams(newSearchParams);
|
| 531 |
+
}
|
| 532 |
+
}
|
| 533 |
+
/**
|
| 534 |
+
* Helper method to navigate with URL parameters
|
| 535 |
+
* Handles debouncing and history state
|
| 536 |
+
* @private
|
| 537 |
+
*/
|
| 538 |
+
#navigateWithParams(params) {
|
| 539 |
+
const navigateToNewUrl = () => {
|
| 540 |
+
if (!BROWSER)
|
| 541 |
+
return;
|
| 542 |
+
// When pushHistory is false, use replaceState to avoid creating a browser history entry
|
| 543 |
+
const gotoOptions = !this.#options.pushHistory
|
| 544 |
+
? { replaceState: true, keepFocus: true }
|
| 545 |
+
: { keepFocus: true };
|
| 546 |
+
goto("?" + params.toString(), { ...gotoOptions, noScroll: this.#options.noScroll });
|
| 547 |
+
};
|
| 548 |
+
// If debounce is set, delay the URL update
|
| 549 |
+
if (this.#options.debounce && this.#options.debounce > 0) {
|
| 550 |
+
// Clear any existing timer
|
| 551 |
+
if (this.#debounceTimer) {
|
| 552 |
+
clearTimeout(this.#debounceTimer);
|
| 553 |
+
}
|
| 554 |
+
// Set a new timer
|
| 555 |
+
this.#debounceTimer = setTimeout(navigateToNewUrl, this.#options.debounce);
|
| 556 |
+
}
|
| 557 |
+
else {
|
| 558 |
+
// No debounce, update immediately
|
| 559 |
+
navigateToNewUrl();
|
| 560 |
+
}
|
| 561 |
+
}
|
| 562 |
+
/**
|
| 563 |
+
* Converts a value to a URL-compatible string representation
|
| 564 |
+
* Handles arrays, objects, and primitive values
|
| 565 |
+
* @private
|
| 566 |
+
*/
|
| 567 |
+
#serializeValue(value) {
|
| 568 |
+
if (Array.isArray(value)) {
|
| 569 |
+
return JSON.stringify(value);
|
| 570 |
+
}
|
| 571 |
+
else if (typeof value === "object" && value !== null) {
|
| 572 |
+
return JSON.stringify(value);
|
| 573 |
+
}
|
| 574 |
+
else {
|
| 575 |
+
return String(value);
|
| 576 |
+
}
|
| 577 |
+
}
|
| 578 |
+
#extractParamValues(searchParams) {
|
| 579 |
+
const compressedParamName = this.#options.compressedParamName || "_data";
|
| 580 |
+
// Check if we're using compression mode and have a compressed parameter
|
| 581 |
+
if (this.#options.compress && searchParams.has(compressedParamName)) {
|
| 582 |
+
try {
|
| 583 |
+
const compressedData = searchParams.get(compressedParamName) || "";
|
| 584 |
+
const decompressed = lzString.decompressFromEncodedURIComponent(compressedData);
|
| 585 |
+
if (decompressed) {
|
| 586 |
+
try {
|
| 587 |
+
// Parse the decompressed JSON
|
| 588 |
+
return JSON.parse(decompressed);
|
| 589 |
+
}
|
| 590 |
+
catch (e) {
|
| 591 |
+
console.error("Failed to parse decompressed data", e);
|
| 592 |
+
return {};
|
| 593 |
+
}
|
| 594 |
+
}
|
| 595 |
+
}
|
| 596 |
+
catch (e) {
|
| 597 |
+
console.error("Error decompressing data", e);
|
| 598 |
+
}
|
| 599 |
+
return {};
|
| 600 |
+
}
|
| 601 |
+
// If not using compression, use the normal extraction with number field detection
|
| 602 |
+
return extractParamValues(searchParams, this.#numberFields);
|
| 603 |
+
}
|
| 604 |
+
/**
|
| 605 |
+
* Get typed values from the local cache using schema validation
|
| 606 |
+
*
|
| 607 |
+
* This method:
|
| 608 |
+
* 1. Gets the current search parameters from the local cache
|
| 609 |
+
* 2. Extracts and processes parameter values
|
| 610 |
+
* 3. Validates them against the schema
|
| 611 |
+
* 4. Returns the typed value for the requested key
|
| 612 |
+
*
|
| 613 |
+
* @param key The parameter key to get
|
| 614 |
+
* @returns The typed value after validation or undefined if invalid
|
| 615 |
+
* @private
|
| 616 |
+
*/
|
| 617 |
+
#getTypedValue(key) {
|
| 618 |
+
// Always read from local cache for immediate state
|
| 619 |
+
const paramsObject = this.#extractParamValues(this.#localCache);
|
| 620 |
+
const result = this.validate(paramsObject);
|
| 621 |
+
if (result instanceof Promise) {
|
| 622 |
+
throw new Error("Async validation is not supported in validateSearchParams");
|
| 623 |
+
}
|
| 624 |
+
if (result && "value" in result) {
|
| 625 |
+
return result.value[key];
|
| 626 |
+
}
|
| 627 |
+
else if (result && "issues" in result) {
|
| 628 |
+
// If validation fails, use defaults
|
| 629 |
+
const emptyResult = this.validate({});
|
| 630 |
+
const defaultValues = emptyResult && "value" in emptyResult ? emptyResult.value : {};
|
| 631 |
+
// find valid params in the paramsObject and use them, do not override all default values
|
| 632 |
+
const validParams = Object.fromEntries(Object.entries(paramsObject).filter(([key]) => !result.issues?.some((issue) => issue.path?.includes(key))));
|
| 633 |
+
return {
|
| 634 |
+
...(typeof defaultValues === "object" && defaultValues !== null ? defaultValues : {}),
|
| 635 |
+
...validParams,
|
| 636 |
+
}[key];
|
| 637 |
+
}
|
| 638 |
+
// If validation failed, return undefined
|
| 639 |
+
return undefined;
|
| 640 |
+
}
|
| 641 |
+
/**
|
| 642 |
+
* Set a parameter value and update the local cache and optionally the URL
|
| 643 |
+
*
|
| 644 |
+
* This method:
|
| 645 |
+
* 1. Gets the current search parameters from the local cache
|
| 646 |
+
* 2. Extracts and processes all current parameters
|
| 647 |
+
* 3. Updates the parameter with the new value
|
| 648 |
+
* 4. Validates the complete parameter object against the schema
|
| 649 |
+
* 5. Updates the local cache immediately (for instant reads)
|
| 650 |
+
* 6. Optionally updates the browser URL if updateURL is true
|
| 651 |
+
*
|
| 652 |
+
* @param key The parameter key to set
|
| 653 |
+
* @param value The value to set
|
| 654 |
+
* @private
|
| 655 |
+
*/
|
| 656 |
+
#setValue(key, value) {
|
| 657 |
+
this.#initializeCacheFromURL();
|
| 658 |
+
// Optimization: Skip if the key is not in schema
|
| 659 |
+
if (!this.has(key))
|
| 660 |
+
return;
|
| 661 |
+
// Always use local cache for immediate state
|
| 662 |
+
const paramsObject = this.#extractParamValues(this.#localCache);
|
| 663 |
+
// Check if the new value is the same as the current value
|
| 664 |
+
// Optimization: For primitives, use direct comparison; use dequal only for objects
|
| 665 |
+
const currentValue = paramsObject[key];
|
| 666 |
+
const isPrimitive = typeof currentValue !== "object" &&
|
| 667 |
+
typeof value !== "object" &&
|
| 668 |
+
currentValue !== null &&
|
| 669 |
+
value !== null;
|
| 670 |
+
if (isPrimitive ? currentValue === value : dequal(currentValue, value)) {
|
| 671 |
+
// Skip the update if values are the same
|
| 672 |
+
return;
|
| 673 |
+
}
|
| 674 |
+
// Create a new object with the updated value
|
| 675 |
+
const newParamsObject = { ...paramsObject, [key]: value };
|
| 676 |
+
// Validate against schema to ensure type correctness
|
| 677 |
+
const result = this.validate(newParamsObject);
|
| 678 |
+
if (result && "value" in result) {
|
| 679 |
+
const validatedResult = result.value;
|
| 680 |
+
const updateObj = { [key]: value };
|
| 681 |
+
// Always update local cache immediately (for instant reads)
|
| 682 |
+
const updatedCache = this.#updateParamsWithValidatedValues(this.#localCache, updateObj, validatedResult, true // always treat as in-memory for cache updates
|
| 683 |
+
);
|
| 684 |
+
this.#localCache = updatedCache;
|
| 685 |
+
// If updateURL is true, sync to URL
|
| 686 |
+
if (this.#options.updateURL && BROWSER && !building) {
|
| 687 |
+
// Handle the compression mode if enabled
|
| 688 |
+
if (this.#options.compress) {
|
| 689 |
+
this.#handleCompressedUpdate(validatedResult);
|
| 690 |
+
}
|
| 691 |
+
else {
|
| 692 |
+
// Normal mode - update the URL
|
| 693 |
+
// Start from the current local cache to preserve all params
|
| 694 |
+
const urlParams = this.#updateParamsWithValidatedValues(this.#localCache, updateObj, validatedResult, false // use URLSearchParams for URL updates
|
| 695 |
+
);
|
| 696 |
+
this.#navigateWithParams(urlParams);
|
| 697 |
+
}
|
| 698 |
+
}
|
| 699 |
+
}
|
| 700 |
+
}
|
| 701 |
+
}
|
| 702 |
+
/**
|
| 703 |
+
* Creates a simple schema compatible with useSearchParams without requiring external validation libraries.
|
| 704 |
+
*
|
| 705 |
+
* This is a lightweight alternative to using full schema validation libraries like Zod, Valibot, or Arktype.
|
| 706 |
+
* Use this when you need basic type conversion and default values without adding dependencies.
|
| 707 |
+
*
|
| 708 |
+
* Limitations:
|
| 709 |
+
* - For 'array' type: supports basic arrays, but doesn't validate array items
|
| 710 |
+
* - For 'object' type: supports generic objects, but doesn't validate nested properties
|
| 711 |
+
* - No custom validation rules or transformations
|
| 712 |
+
* - No granular reactivity: nested property changes require whole-value reassignment
|
| 713 |
+
* (e.g., params.items = [...params.items, newItem] instead of params.items.push(newItem))
|
| 714 |
+
*
|
| 715 |
+
* For complex validation needs (nested validation, refined rules, etc.), use a dedicated
|
| 716 |
+
* validation library instead.
|
| 717 |
+
*
|
| 718 |
+
* Example usage:
|
| 719 |
+
* ```
|
| 720 |
+
* const productSearchSchema = createSearchParamsSchema({
|
| 721 |
+
* // Basic types with defaults
|
| 722 |
+
* page: { type: 'number', default: 1 },
|
| 723 |
+
* filter: { type: 'string', default: '' },
|
| 724 |
+
* sort: { type: 'string', default: 'newest' },
|
| 725 |
+
*
|
| 726 |
+
* // Array type with specific element type
|
| 727 |
+
* tags: {
|
| 728 |
+
* type: 'array',
|
| 729 |
+
* default: ['new'],
|
| 730 |
+
* arrayType: '' // Specify string[] type
|
| 731 |
+
* },
|
| 732 |
+
*
|
| 733 |
+
* // Object type with specific shape
|
| 734 |
+
* config: {
|
| 735 |
+
* type: 'object',
|
| 736 |
+
* default: { theme: 'light' },
|
| 737 |
+
* objectType: { theme: '' } // Specify { theme: string } type
|
| 738 |
+
* }
|
| 739 |
+
* });
|
| 740 |
+
* ```
|
| 741 |
+
*
|
| 742 |
+
* URL storage format:
|
| 743 |
+
* - Arrays are stored as JSON strings: ?tags=["sale","featured"]
|
| 744 |
+
* - Objects are stored as JSON strings: ?config={"theme":"dark","fontSize":14}
|
| 745 |
+
* - Primitive values are stored directly: ?page=2&filter=red
|
| 746 |
+
*/
|
| 747 |
+
export function createSearchParamsSchema(schema) {
|
| 748 |
+
return {
|
| 749 |
+
"~standard": {
|
| 750 |
+
version: 1,
|
| 751 |
+
vendor: "",
|
| 752 |
+
validate: (input) => {
|
| 753 |
+
const output = {};
|
| 754 |
+
const issues = [];
|
| 755 |
+
// Set default values first
|
| 756 |
+
for (const [key, config] of Object.entries(schema)) {
|
| 757 |
+
output[key] =
|
| 758 |
+
config.default !== undefined ? config.default : null;
|
| 759 |
+
}
|
| 760 |
+
if (input && typeof input === "object") {
|
| 761 |
+
for (const [key, config] of Object.entries(schema)) {
|
| 762 |
+
const inputValue = input[key];
|
| 763 |
+
if (inputValue !== undefined) {
|
| 764 |
+
try {
|
| 765 |
+
switch (config.type) {
|
| 766 |
+
case "number": {
|
| 767 |
+
const num = typeof inputValue === "number" ? inputValue : Number(inputValue);
|
| 768 |
+
if (typeof num !== "number" || !Number.isFinite(num)) {
|
| 769 |
+
issues.push({
|
| 770 |
+
message: `Invalid number for "${key}"`,
|
| 771 |
+
path: [key],
|
| 772 |
+
});
|
| 773 |
+
}
|
| 774 |
+
else {
|
| 775 |
+
output[key] = num;
|
| 776 |
+
}
|
| 777 |
+
break;
|
| 778 |
+
}
|
| 779 |
+
case "boolean": {
|
| 780 |
+
if (typeof inputValue === "boolean" ||
|
| 781 |
+
inputValue === "true" ||
|
| 782 |
+
inputValue === "false") {
|
| 783 |
+
output[key] =
|
| 784 |
+
typeof inputValue === "boolean" ? inputValue : inputValue === "true";
|
| 785 |
+
}
|
| 786 |
+
else {
|
| 787 |
+
issues.push({
|
| 788 |
+
message: `Invalid boolean for "${key}"`,
|
| 789 |
+
path: [key],
|
| 790 |
+
});
|
| 791 |
+
}
|
| 792 |
+
break;
|
| 793 |
+
}
|
| 794 |
+
case "array": {
|
| 795 |
+
if (Array.isArray(inputValue)) {
|
| 796 |
+
output[key] = inputValue;
|
| 797 |
+
}
|
| 798 |
+
else {
|
| 799 |
+
issues.push({
|
| 800 |
+
message: `Invalid array for "${key}"`,
|
| 801 |
+
path: [key],
|
| 802 |
+
});
|
| 803 |
+
}
|
| 804 |
+
break;
|
| 805 |
+
}
|
| 806 |
+
case "object": {
|
| 807 |
+
if (typeof inputValue === "object" &&
|
| 808 |
+
inputValue !== null &&
|
| 809 |
+
!Array.isArray(inputValue)) {
|
| 810 |
+
output[key] = inputValue;
|
| 811 |
+
}
|
| 812 |
+
else {
|
| 813 |
+
issues.push({
|
| 814 |
+
message: `Invalid object for "${key}"`,
|
| 815 |
+
path: [key],
|
| 816 |
+
});
|
| 817 |
+
}
|
| 818 |
+
break;
|
| 819 |
+
}
|
| 820 |
+
case "string":
|
| 821 |
+
default: {
|
| 822 |
+
output[key] = String(inputValue);
|
| 823 |
+
}
|
| 824 |
+
}
|
| 825 |
+
}
|
| 826 |
+
catch (e) {
|
| 827 |
+
issues.push({
|
| 828 |
+
message: `Error parsing "${key}": ${e.message}`,
|
| 829 |
+
path: [key],
|
| 830 |
+
});
|
| 831 |
+
}
|
| 832 |
+
}
|
| 833 |
+
}
|
| 834 |
+
}
|
| 835 |
+
if (issues.length > 0) {
|
| 836 |
+
return { issues };
|
| 837 |
+
}
|
| 838 |
+
return { value: output };
|
| 839 |
+
},
|
| 840 |
+
types: {
|
| 841 |
+
input: {},
|
| 842 |
+
output: {},
|
| 843 |
+
},
|
| 844 |
+
},
|
| 845 |
+
};
|
| 846 |
+
}
|
| 847 |
+
/**
|
| 848 |
+
* A utility function to extract, validate and convert URL search parameters to [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
|
| 849 |
+
*
|
| 850 |
+
* This function makes it easy to use the same schema validation in
|
| 851 |
+
* both client-side components (via useSearchParams) and server-side load functions.
|
| 852 |
+
* Unlike useSearchParams, this function doesn't modify the URL - it only validates
|
| 853 |
+
* parameters and returns them as a new URLSearchParams object.
|
| 854 |
+
*
|
| 855 |
+
* **Important for SvelteKit fine-grained reactivity**: This function only accesses URL parameters
|
| 856 |
+
* that are defined in your schema, ensuring that load functions only re-run when schema-defined
|
| 857 |
+
* parameters change, not when any URL parameter changes.
|
| 858 |
+
*
|
| 859 |
+
* Handles both standard URL parameters and compressed parameters (when compression is enabled).
|
| 860 |
+
*
|
| 861 |
+
* @param url The URL object from SvelteKit load function
|
| 862 |
+
* @param schema A validation schema (createSearchParamsSchema, Zod, Valibot, etc.)
|
| 863 |
+
* @param options Optional configuration (like custom compressedParamName)
|
| 864 |
+
* @returns URLSearchParams object with the validated values
|
| 865 |
+
*
|
| 866 |
+
* Example with SvelteKit page or layout load function:
|
| 867 |
+
* ```ts
|
| 868 |
+
* import { validateSearchParams } from '../../hooks/useSearchParams.svelte';
|
| 869 |
+
* import { productSchema } from './schemas';
|
| 870 |
+
*
|
| 871 |
+
* export const load = ({ url }) => {
|
| 872 |
+
* // Get validated search params as URLSearchParams object
|
| 873 |
+
* // Only accesses 'page', 'filter', 'sort' parameters from the URL
|
| 874 |
+
* // Load function will only re-run when these specific parameters change
|
| 875 |
+
* const searchParams = validateSearchParams(url, productSchema, {
|
| 876 |
+
* compressedParamName: '_compressed'
|
| 877 |
+
* });
|
| 878 |
+
*
|
| 879 |
+
* // Use URLSearchParams directly with fetch
|
| 880 |
+
* const response = await fetch(`/api/products?${searchParams.toString()}`);
|
| 881 |
+
* return {
|
| 882 |
+
* products: await response.json()
|
| 883 |
+
* };
|
| 884 |
+
* };
|
| 885 |
+
* ```
|
| 886 |
+
*/
|
| 887 |
+
export function validateSearchParams(url, schema, options = {}) {
|
| 888 |
+
const compressedParamName = options.compressedParamName || "_data";
|
| 889 |
+
let validatedValue = {};
|
| 890 |
+
// Check if we're dealing with compressed data and handle appropriately
|
| 891 |
+
if (url.searchParams.has(compressedParamName)) {
|
| 892 |
+
try {
|
| 893 |
+
// Get and decompress the data
|
| 894 |
+
const compressedData = url.searchParams.get(compressedParamName) || "";
|
| 895 |
+
const decompressed = lzString.decompressFromEncodedURIComponent(compressedData);
|
| 896 |
+
if (decompressed) {
|
| 897 |
+
try {
|
| 898 |
+
// Parse the decompressed JSON
|
| 899 |
+
const decompressedObj = JSON.parse(decompressed);
|
| 900 |
+
// Validate against schema
|
| 901 |
+
const result = schema["~standard"].validate(decompressedObj);
|
| 902 |
+
if (result && "value" in result) {
|
| 903 |
+
validatedValue = result.value;
|
| 904 |
+
}
|
| 905 |
+
else {
|
| 906 |
+
// Use defaults if validation fails
|
| 907 |
+
const emptyResult = schema["~standard"].validate({});
|
| 908 |
+
validatedValue = (emptyResult && "value" in emptyResult ? emptyResult.value : {});
|
| 909 |
+
}
|
| 910 |
+
}
|
| 911 |
+
catch (e) {
|
| 912 |
+
console.error("Failed to parse decompressed data", e);
|
| 913 |
+
// Use defaults if parsing fails
|
| 914 |
+
const emptyResult = schema["~standard"].validate({});
|
| 915 |
+
validatedValue = (emptyResult && "value" in emptyResult ? emptyResult.value : {});
|
| 916 |
+
}
|
| 917 |
+
}
|
| 918 |
+
else {
|
| 919 |
+
// Use defaults if decompression fails
|
| 920 |
+
const emptyResult = schema["~standard"].validate({});
|
| 921 |
+
validatedValue = (emptyResult && "value" in emptyResult ? emptyResult.value : {});
|
| 922 |
+
}
|
| 923 |
+
}
|
| 924 |
+
catch (e) {
|
| 925 |
+
console.error("Error decompressing data", e);
|
| 926 |
+
// Use defaults if decompression errors
|
| 927 |
+
const emptyResult = schema["~standard"].validate({});
|
| 928 |
+
validatedValue = (emptyResult && "value" in emptyResult ? emptyResult.value : {});
|
| 929 |
+
}
|
| 930 |
+
}
|
| 931 |
+
else {
|
| 932 |
+
// Normal (uncompressed) extraction - use selective extraction for fine-grained reactivity
|
| 933 |
+
const schemaInfo = extractSchemaInfo(schema);
|
| 934 |
+
const paramsObject = extractSelectiveParamValues(url.searchParams, schemaInfo.keys, schemaInfo.numberFields);
|
| 935 |
+
// Validate the parameters against the schema
|
| 936 |
+
let result = schema["~standard"].validate(paramsObject);
|
| 937 |
+
if (result instanceof Promise) {
|
| 938 |
+
throw new Error("Async validation is not supported in validateSearchParams");
|
| 939 |
+
}
|
| 940 |
+
if (result && "value" in result) {
|
| 941 |
+
validatedValue = result.value;
|
| 942 |
+
}
|
| 943 |
+
else if (result && "issues" in result) {
|
| 944 |
+
// If validation fails, use defaults
|
| 945 |
+
const emptyResult = schema["~standard"].validate({});
|
| 946 |
+
validatedValue = (emptyResult && "value" in emptyResult ? emptyResult.value : {});
|
| 947 |
+
// find valid params in the paramsObject and use them, do not override all default values
|
| 948 |
+
const validParams = Object.fromEntries(Object.entries(paramsObject).filter(([key]) => !result.issues?.some((issue) => issue.path?.includes(key))));
|
| 949 |
+
validatedValue = { ...validatedValue, ...validParams };
|
| 950 |
+
}
|
| 951 |
+
}
|
| 952 |
+
// Create a new URLSearchParams object with the validated values
|
| 953 |
+
const newSearchParams = new URLSearchParams();
|
| 954 |
+
// Helper function to serialize values
|
| 955 |
+
const serializeValue = (value) => {
|
| 956 |
+
if (Array.isArray(value)) {
|
| 957 |
+
return JSON.stringify(value);
|
| 958 |
+
}
|
| 959 |
+
else if (typeof value === "object" && value !== null) {
|
| 960 |
+
return JSON.stringify(value);
|
| 961 |
+
}
|
| 962 |
+
else {
|
| 963 |
+
return String(value);
|
| 964 |
+
}
|
| 965 |
+
};
|
| 966 |
+
// Add each validated parameter to the URLSearchParams
|
| 967 |
+
for (const [key, value] of Object.entries(validatedValue)) {
|
| 968 |
+
if (value === undefined || value === null)
|
| 969 |
+
continue;
|
| 970 |
+
const stringValue = serializeValue(value);
|
| 971 |
+
newSearchParams.set(key, stringValue);
|
| 972 |
+
}
|
| 973 |
+
return {
|
| 974 |
+
searchParams: newSearchParams,
|
| 975 |
+
data: validatedValue,
|
| 976 |
+
};
|
| 977 |
+
}
|
| 978 |
+
/**
|
| 979 |
+
* Hook to create a reactive search params object with property access
|
| 980 |
+
*
|
| 981 |
+
* This client-side hook automatically updates the URL when parameters change.
|
| 982 |
+
* It provides type-safe access to URL search parameters through direct property access.
|
| 983 |
+
*
|
| 984 |
+
* @param schema A validation schema compatible with StandardSchemaV1
|
| 985 |
+
* @param options Configuration options that affect URL behavior
|
| 986 |
+
* @returns A reactive object for working with typed search parameters
|
| 987 |
+
*
|
| 988 |
+
* Available options:
|
| 989 |
+
* - `showDefaults` (boolean): When true, parameters with default values will be shown in the URL.
|
| 990 |
+
* When false (default), parameters with default values will be omitted from the URL.
|
| 991 |
+
* - `debounce` (number): Milliseconds to delay URL updates when parameters change.
|
| 992 |
+
* Useful to avoid cluttering browser history when values change rapidly (default: 0, no debounce).
|
| 993 |
+
* - `pushHistory` (boolean): Controls whether URL updates create new browser history entries.
|
| 994 |
+
* If true (default), each update adds a new entry to the browser history.
|
| 995 |
+
* If false, updates replace the current URL without creating new history entries.
|
| 996 |
+
* - `compress` (boolean): When true, all parameters are compressed into a single parameter
|
| 997 |
+
* using lz-string compression. This helps reduce URL length and provides basic obfuscation (default: false).
|
| 998 |
+
* Use validateSearchParams with the same compressedParamName option when handling compressed URLs server-side.
|
| 999 |
+
* - `compressedParamName` (string): The name of the parameter used to store compressed data
|
| 1000 |
+
* when compression is enabled. Customize this to avoid conflicts with parameters in your schema.
|
| 1001 |
+
* Default is '_data'.
|
| 1002 |
+
* - `updateURL` (boolean): When true (default), the URL is updated when parameters change.
|
| 1003 |
+
* When false, only in-memory parameters are updated.
|
| 1004 |
+
*
|
| 1005 |
+
* Example with Zod:
|
| 1006 |
+
* ```
|
| 1007 |
+
* import { z } from 'zod';
|
| 1008 |
+
*
|
| 1009 |
+
* const productSearchSchema = z.object({
|
| 1010 |
+
* page: z.number().catch(1),
|
| 1011 |
+
* filter: z.string().catch(''),
|
| 1012 |
+
* sort: z.enum(['newest', 'oldest', 'price']).catch('newest'),
|
| 1013 |
+
* });
|
| 1014 |
+
*
|
| 1015 |
+
* const params = useSearchParams(productSearchSchema);
|
| 1016 |
+
*
|
| 1017 |
+
* // Access parameters directly
|
| 1018 |
+
* const page = $derived(params.page); // number (defaults to 1)
|
| 1019 |
+
* const sort = $derived(params.sort); // 'newest' | 'oldest' | 'price'
|
| 1020 |
+
*
|
| 1021 |
+
* // Update parameters directly
|
| 1022 |
+
* params.page = 2; // Updates URL to include ?page=2
|
| 1023 |
+
* params.sort = 'price'; // Updates URL to include &sort=price
|
| 1024 |
+
* ```
|
| 1025 |
+
*
|
| 1026 |
+
* Example with options:
|
| 1027 |
+
* ```typescript
|
| 1028 |
+
* // Show default values in URL, debounce updates by 300ms,
|
| 1029 |
+
* // don't create new history entries, and compress params
|
| 1030 |
+
* const params = useSearchParams(schema, {
|
| 1031 |
+
* showDefaults: true,
|
| 1032 |
+
* debounce: 300,
|
| 1033 |
+
* pushHistory: false,
|
| 1034 |
+
* compress: true,
|
| 1035 |
+
* compressedParamName: '_compressed' // Custom name to avoid conflicts
|
| 1036 |
+
* });
|
| 1037 |
+
*
|
| 1038 |
+
* // Great for binding to input fields (updates URL without cluttering history)
|
| 1039 |
+
* <input type="text" bind:value={params.search} />
|
| 1040 |
+
* // Resulting URL will be something like: /?_compressed=N4IgDgTg9g...
|
| 1041 |
+
* ```
|
| 1042 |
+
* Example with Valibot:
|
| 1043 |
+
* ```
|
| 1044 |
+
* import * as v from 'valibot';
|
| 1045 |
+
*
|
| 1046 |
+
* const productSearchSchema = v.object({
|
| 1047 |
+
* page: v.optional(v.fallback(v.number(), 1), 1),
|
| 1048 |
+
* filter: v.optional(v.fallback(v.string(), ''), ''),
|
| 1049 |
+
* sort: v.optional(v.fallback(v.picklist(['newest', 'oldest', 'price']), 'newest'), 'newest'),
|
| 1050 |
+
* });
|
| 1051 |
+
*
|
| 1052 |
+
* const params = useSearchParams(productSearchSchema);
|
| 1053 |
+
* ``` * Example with Arktype:
|
| 1054 |
+
* ```
|
| 1055 |
+
* import { type } from 'arktype';
|
| 1056 |
+
*
|
| 1057 |
+
* const productSearchSchema = type({
|
| 1058 |
+
* page: 'number = 1',
|
| 1059 |
+
* filter: 'string = ""',
|
| 1060 |
+
* sort: '"newest" | "oldest" | "price" = "newest"',
|
| 1061 |
+
* });
|
| 1062 |
+
*
|
| 1063 |
+
* const params = useSearchParams(productSearchSchema);
|
| 1064 |
+
* ```
|
| 1065 |
+
* Or with our built-in schema creator (no additional dependencies):
|
| 1066 |
+
*
|
| 1067 |
+
* ```
|
| 1068 |
+
* const productSearchSchema = createSearchParamsSchema({
|
| 1069 |
+
* page: { type: 'number', default: 1 },
|
| 1070 |
+
* filter: { type: 'string', default: '' },
|
| 1071 |
+
* sort: { type: 'string', default: 'newest' }
|
| 1072 |
+
* });
|
| 1073 |
+
*
|
| 1074 |
+
* const params = useSearchParams(productSearchSchema);
|
| 1075 |
+
* ```
|
| 1076 |
+
*/
|
| 1077 |
+
export function useSearchParams(schema, options = {}) {
|
| 1078 |
+
// Create the SearchParams instance to handle validation and URL updates
|
| 1079 |
+
// This is the core class that implements the actual functionality
|
| 1080 |
+
const searchParams = new SearchParams(schema, options);
|
| 1081 |
+
// Wait for hydration to complete before executing browser-specific initialization
|
| 1082 |
+
const isMounted = new IsMounted();
|
| 1083 |
+
// Only run initialization logic after hydration is complete
|
| 1084 |
+
$effect(() => {
|
| 1085 |
+
if (!isMounted.current || !browser || building)
|
| 1086 |
+
return;
|
| 1087 |
+
// Remove incorrect params on initialization (only after hydration)
|
| 1088 |
+
if (options.updateURL !== false) {
|
| 1089 |
+
const schemaInfo = extractSchemaInfo(schema);
|
| 1090 |
+
const currentParams = extractParamValues(page.url.searchParams, schemaInfo.numberFields);
|
| 1091 |
+
const validationResult = schema["~standard"].validate(currentParams);
|
| 1092 |
+
if (validationResult &&
|
| 1093 |
+
"issues" in validationResult &&
|
| 1094 |
+
Array.isArray(validationResult.issues) &&
|
| 1095 |
+
validationResult.issues.length > 0) {
|
| 1096 |
+
// Find all incorrect param keys
|
| 1097 |
+
const invalidKeys = validationResult.issues
|
| 1098 |
+
.map((issue) => Array.isArray(issue.path) && issue.path.length > 0 ? issue.path[0] : null)
|
| 1099 |
+
.filter(Boolean);
|
| 1100 |
+
if (invalidKeys.length > 0) {
|
| 1101 |
+
const newSearchParams = new URLSearchParams(page.url.searchParams.toString());
|
| 1102 |
+
for (const key of invalidKeys) {
|
| 1103 |
+
newSearchParams.delete(String(key));
|
| 1104 |
+
}
|
| 1105 |
+
goto("?" + newSearchParams.toString(), { replaceState: true });
|
| 1106 |
+
}
|
| 1107 |
+
}
|
| 1108 |
+
}
|
| 1109 |
+
// If showDefaults is true, we need to initialize the URL with all default values (only after hydration)
|
| 1110 |
+
if (options.showDefaults) {
|
| 1111 |
+
// Get all the schema information in one pass
|
| 1112 |
+
const schemaInfo = extractSchemaInfo(schema);
|
| 1113 |
+
if (schemaInfo.keys.length > 0) {
|
| 1114 |
+
// If compression is enabled, use SearchParams.update() method which handles compression
|
| 1115 |
+
if (options.compress) {
|
| 1116 |
+
// Call the update method with the default values to properly handle compression
|
| 1117 |
+
searchParams.update(schemaInfo.defaultValues);
|
| 1118 |
+
}
|
| 1119 |
+
else {
|
| 1120 |
+
// For non-compressed mode, use the original approach
|
| 1121 |
+
const currentParams = extractParamValues(page.url.searchParams, schemaInfo.numberFields);
|
| 1122 |
+
const newSearchParams = new URLSearchParams(page.url.searchParams.toString());
|
| 1123 |
+
let needsUpdate = false;
|
| 1124 |
+
// For each default value, add it to the URL if not already present
|
| 1125 |
+
for (const [key, defaultValue] of Object.entries(schemaInfo.defaultValues)) {
|
| 1126 |
+
// Skip if the parameter is already in the URL (don't override user values)
|
| 1127 |
+
if (key in currentParams)
|
| 1128 |
+
continue;
|
| 1129 |
+
needsUpdate = true;
|
| 1130 |
+
if (defaultValue === null || defaultValue === undefined) {
|
| 1131 |
+
continue;
|
| 1132 |
+
}
|
| 1133 |
+
let stringValue;
|
| 1134 |
+
if (Array.isArray(defaultValue)) {
|
| 1135 |
+
stringValue = JSON.stringify(defaultValue);
|
| 1136 |
+
}
|
| 1137 |
+
else if (typeof defaultValue === "object" && defaultValue !== null) {
|
| 1138 |
+
stringValue = JSON.stringify(defaultValue);
|
| 1139 |
+
}
|
| 1140 |
+
else {
|
| 1141 |
+
stringValue = String(defaultValue);
|
| 1142 |
+
}
|
| 1143 |
+
newSearchParams.set(key, stringValue);
|
| 1144 |
+
}
|
| 1145 |
+
// Only update the URL if we added parameters
|
| 1146 |
+
if (needsUpdate) {
|
| 1147 |
+
// Always use replaceState: true for initialization to avoid creating a new history entry
|
| 1148 |
+
// Don't use debouncing for initialization as this is a one-time operation
|
| 1149 |
+
goto("?" + newSearchParams.toString(), { replaceState: true });
|
| 1150 |
+
}
|
| 1151 |
+
}
|
| 1152 |
+
}
|
| 1153 |
+
}
|
| 1154 |
+
});
|
| 1155 |
+
// Only run this logic in the browser and if debounce is enabled
|
| 1156 |
+
if (browser && !building && options.debounce && options.debounce > 0) {
|
| 1157 |
+
$effect(() => {
|
| 1158 |
+
// This effect runs once when the hook is initialized within a component.
|
| 1159 |
+
// It has no dependencies, so it doesn't re-run.
|
| 1160 |
+
return () => {
|
| 1161 |
+
searchParams.cleanup();
|
| 1162 |
+
};
|
| 1163 |
+
});
|
| 1164 |
+
}
|
| 1165 |
+
// Create a proxy to intercept property access/assignment
|
| 1166 |
+
// This enables the direct property syntax: params.page instead of params.get('page')
|
| 1167 |
+
// The proxy pattern is what makes the API feel natural and type-safe
|
| 1168 |
+
//
|
| 1169 |
+
// IMPORTANT LIMITATION: This proxy only provides top-level reactivity
|
| 1170 |
+
// - Direct property access works: params.page, params.filter
|
| 1171 |
+
// - Nested property changes require whole-object updates: params.fields = {...fields, newProp: value}
|
| 1172 |
+
// - Arrays/objects are not granularly reactive: params.items[0].name = 'new' won't trigger URL updates
|
| 1173 |
+
//
|
| 1174 |
+
// For granular nested reactivity, you would need:
|
| 1175 |
+
// 1. Recursive proxy creation for nested objects/arrays
|
| 1176 |
+
// 2. Path tracking system (e.g., "fields.0.name")
|
| 1177 |
+
// 3. Granular URL serialization instead of JSON
|
| 1178 |
+
// 4. Complete rewrite of validation and type systems
|
| 1179 |
+
// This would be a breaking change requiring a new major version
|
| 1180 |
+
const handler = {
|
| 1181 |
+
get: (target, prop) => {
|
| 1182 |
+
// Special methods we want to expose directly with proper binding
|
| 1183 |
+
if (prop === "reset") {
|
| 1184 |
+
// We need to handle each method individually to satisfy TypeScript
|
| 1185 |
+
return function (showDefaults) {
|
| 1186 |
+
return target.reset(showDefaults);
|
| 1187 |
+
};
|
| 1188 |
+
}
|
| 1189 |
+
else if (prop === "update") {
|
| 1190 |
+
return function (values) {
|
| 1191 |
+
return target.update(values);
|
| 1192 |
+
};
|
| 1193 |
+
}
|
| 1194 |
+
else if (prop === "cleanup") {
|
| 1195 |
+
return function () {
|
| 1196 |
+
return target.cleanup();
|
| 1197 |
+
};
|
| 1198 |
+
}
|
| 1199 |
+
else if (prop === "toURLSearchParams") {
|
| 1200 |
+
// Implementation of toURLSearchParams
|
| 1201 |
+
return function () {
|
| 1202 |
+
const newSearchParams = new URLSearchParams();
|
| 1203 |
+
// Get the schema's default values + current values
|
| 1204 |
+
const validationResult = schema["~standard"].validate({});
|
| 1205 |
+
if (validationResult && "value" in validationResult) {
|
| 1206 |
+
const schemaValues = validationResult.value;
|
| 1207 |
+
// Create an object with all the values from the schema
|
| 1208 |
+
// First set the default values
|
| 1209 |
+
const allValues = { ...schemaValues };
|
| 1210 |
+
// Then override with the current values from the proxy
|
| 1211 |
+
// This ensures we get the most up-to-date values that might not yet be in the URL or in-memory store
|
| 1212 |
+
for (const key of Object.keys(schemaValues)) {
|
| 1213 |
+
// Get the current value using the proxy's access
|
| 1214 |
+
if (typeof key === "string" && target.has(key)) {
|
| 1215 |
+
const currentValue = target.get(key);
|
| 1216 |
+
if (currentValue !== undefined) {
|
| 1217 |
+
allValues[key] = currentValue;
|
| 1218 |
+
}
|
| 1219 |
+
}
|
| 1220 |
+
}
|
| 1221 |
+
// Add each parameter to the URLSearchParams
|
| 1222 |
+
for (const [key, value] of Object.entries(allValues)) {
|
| 1223 |
+
// Skip undefined/null values
|
| 1224 |
+
if (value === undefined || value === null) {
|
| 1225 |
+
continue;
|
| 1226 |
+
}
|
| 1227 |
+
// Serialize the value
|
| 1228 |
+
let stringValue;
|
| 1229 |
+
if (Array.isArray(value)) {
|
| 1230 |
+
stringValue = JSON.stringify(value);
|
| 1231 |
+
}
|
| 1232 |
+
else if (typeof value === "object" && value !== null) {
|
| 1233 |
+
stringValue = JSON.stringify(value);
|
| 1234 |
+
}
|
| 1235 |
+
else {
|
| 1236 |
+
stringValue = String(value);
|
| 1237 |
+
}
|
| 1238 |
+
// Set the parameter
|
| 1239 |
+
newSearchParams.set(key, stringValue);
|
| 1240 |
+
}
|
| 1241 |
+
}
|
| 1242 |
+
return newSearchParams;
|
| 1243 |
+
};
|
| 1244 |
+
}
|
| 1245 |
+
// IMPORTANT: We use the has() method to determine if this is a schema parameter
|
| 1246 |
+
// This is why the has() method must be maintained
|
| 1247 |
+
if (typeof prop === "string" && target.has(prop)) {
|
| 1248 |
+
// Type assertion needed here because TypeScript can't infer that our runtime check
|
| 1249 |
+
// with target.has() guarantees that prop is a valid key of our schema output type
|
| 1250 |
+
// NOTE: This returns the raw value (object/array/primitive) without nested proxification
|
| 1251 |
+
// If the value is an object or array, changes to its nested properties won't trigger
|
| 1252 |
+
// URL updates automatically. Users must reassign the entire object/array to trigger updates:
|
| 1253 |
+
// ❌ Won't work: params.config.theme = 'dark'
|
| 1254 |
+
// ✅ Works: params.config = {...params.config, theme: 'dark'}
|
| 1255 |
+
// ❌ Won't work: params.items.push(newItem)
|
| 1256 |
+
// ✅ Works: params.items = [...params.items, newItem]
|
| 1257 |
+
return target.get(prop);
|
| 1258 |
+
}
|
| 1259 |
+
return Reflect.get(target, prop);
|
| 1260 |
+
},
|
| 1261 |
+
set: (target, prop, value) => {
|
| 1262 |
+
// Similar to get(), we use has() to determine if this is a schema parameter
|
| 1263 |
+
if (typeof prop === "string" && target.has(prop)) {
|
| 1264 |
+
// Same type assertion needed here to tell TypeScript that we've verified
|
| 1265 |
+
// this string is a valid key in our schema through the target.has() check
|
| 1266 |
+
// NOTE: This triggers a complete re-serialization of the value to the URL
|
| 1267 |
+
// For objects/arrays, the entire structure is JSON-stringified and stored
|
| 1268 |
+
// This is why nested property mutations don't work - they don't trigger this setter
|
| 1269 |
+
// Only direct assignment to the top-level property triggers URL updates
|
| 1270 |
+
target.set(prop, value);
|
| 1271 |
+
return true;
|
| 1272 |
+
}
|
| 1273 |
+
return Reflect.set(target, prop, value);
|
| 1274 |
+
},
|
| 1275 |
+
};
|
| 1276 |
+
return new Proxy(searchParams, handler);
|
| 1277 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/use-throttle/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-throttle.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-throttle/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./use-throttle.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/use-throttle/use-throttle.svelte.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { MaybeGetter } from "../../internal/types.js";
|
| 2 |
+
type UseThrottleReturn<Args extends unknown[], Return> = ((this: unknown, ...args: Args) => Promise<Return>) & {
|
| 3 |
+
cancel: () => void;
|
| 4 |
+
pending: boolean;
|
| 5 |
+
};
|
| 6 |
+
export declare function useThrottle<Args extends unknown[], Return>(callback: (...args: Args) => Return, interval?: MaybeGetter<number>): UseThrottleReturn<Args, Return>;
|
| 7 |
+
export {};
|
tools/ui/node_modules/runed/dist/utilities/use-throttle/use-throttle.svelte.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { untrack } from "svelte";
|
| 2 |
+
export function useThrottle(callback, interval = 250) {
|
| 3 |
+
let lastCall = 0;
|
| 4 |
+
let timeout = $state();
|
| 5 |
+
let resolve = null;
|
| 6 |
+
let reject = null;
|
| 7 |
+
let promise = null;
|
| 8 |
+
function reset() {
|
| 9 |
+
timeout = undefined;
|
| 10 |
+
promise = null;
|
| 11 |
+
resolve = null;
|
| 12 |
+
reject = null;
|
| 13 |
+
}
|
| 14 |
+
function throttled(...args) {
|
| 15 |
+
return untrack(() => {
|
| 16 |
+
const now = Date.now();
|
| 17 |
+
const intervalValue = typeof interval === "function" ? interval() : interval;
|
| 18 |
+
const nextAllowedTime = lastCall + intervalValue;
|
| 19 |
+
if (!promise) {
|
| 20 |
+
promise = new Promise((res, rej) => {
|
| 21 |
+
resolve = res;
|
| 22 |
+
reject = rej;
|
| 23 |
+
});
|
| 24 |
+
}
|
| 25 |
+
if (now < nextAllowedTime) {
|
| 26 |
+
if (!timeout) {
|
| 27 |
+
timeout = setTimeout(async () => {
|
| 28 |
+
try {
|
| 29 |
+
const result = await callback.apply(this, args);
|
| 30 |
+
resolve?.(result);
|
| 31 |
+
}
|
| 32 |
+
catch (error) {
|
| 33 |
+
reject?.(error);
|
| 34 |
+
}
|
| 35 |
+
finally {
|
| 36 |
+
clearTimeout(timeout);
|
| 37 |
+
reset();
|
| 38 |
+
lastCall = Date.now();
|
| 39 |
+
}
|
| 40 |
+
}, nextAllowedTime - now);
|
| 41 |
+
}
|
| 42 |
+
return promise;
|
| 43 |
+
}
|
| 44 |
+
if (timeout) {
|
| 45 |
+
clearTimeout(timeout);
|
| 46 |
+
timeout = undefined;
|
| 47 |
+
}
|
| 48 |
+
lastCall = now;
|
| 49 |
+
try {
|
| 50 |
+
const result = callback.apply(this, args);
|
| 51 |
+
resolve?.(result);
|
| 52 |
+
}
|
| 53 |
+
catch (error) {
|
| 54 |
+
reject?.(error);
|
| 55 |
+
}
|
| 56 |
+
finally {
|
| 57 |
+
reset();
|
| 58 |
+
}
|
| 59 |
+
return promise;
|
| 60 |
+
});
|
| 61 |
+
}
|
| 62 |
+
throttled.cancel = async () => {
|
| 63 |
+
if (timeout) {
|
| 64 |
+
if (timeout === undefined) {
|
| 65 |
+
// Wait one event loop to see if something triggered the throttled function
|
| 66 |
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
| 67 |
+
if (timeout === undefined)
|
| 68 |
+
return;
|
| 69 |
+
}
|
| 70 |
+
clearTimeout(timeout);
|
| 71 |
+
reject?.("Cancelled");
|
| 72 |
+
reset();
|
| 73 |
+
}
|
| 74 |
+
};
|
| 75 |
+
Object.defineProperty(throttled, "pending", {
|
| 76 |
+
enumerable: true,
|
| 77 |
+
get() {
|
| 78 |
+
return !!timeout;
|
| 79 |
+
},
|
| 80 |
+
});
|
| 81 |
+
return throttled;
|
| 82 |
+
}
|
tools/ui/node_modules/runed/dist/utilities/watch/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./watch.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/watch/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from "./watch.svelte.js";
|
tools/ui/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Getter } from "../../internal/types.js";
|
| 2 |
+
export type WatchOptions = {
|
| 3 |
+
/**
|
| 4 |
+
* If `true`, the effect doesn't run until one of the `sources` changes.
|
| 5 |
+
*
|
| 6 |
+
* @default false
|
| 7 |
+
*/
|
| 8 |
+
lazy?: boolean;
|
| 9 |
+
};
|
| 10 |
+
export declare function watch<T extends Array<unknown>>(sources: {
|
| 11 |
+
[K in keyof T]: Getter<T[K]>;
|
| 12 |
+
}, effect: (values: T, previousValues: {
|
| 13 |
+
[K in keyof T]: T[K] | undefined;
|
| 14 |
+
}) => void | VoidFunction, options?: WatchOptions): void;
|
| 15 |
+
export declare function watch<T>(source: Getter<T>, effect: (value: T, previousValue: T | undefined) => void | VoidFunction, options?: WatchOptions): void;
|
| 16 |
+
export declare namespace watch {
|
| 17 |
+
var pre: typeof watchPre;
|
| 18 |
+
}
|
| 19 |
+
declare function watchPre<T extends Array<unknown>>(sources: {
|
| 20 |
+
[K in keyof T]: Getter<T[K]>;
|
| 21 |
+
}, effect: (values: T, previousValues: {
|
| 22 |
+
[K in keyof T]: T[K] | undefined;
|
| 23 |
+
}) => void | VoidFunction, options?: WatchOptions): void;
|
| 24 |
+
declare function watchPre<T>(source: Getter<T>, effect: (value: T, previousValue: T | undefined) => void | VoidFunction, options?: WatchOptions): void;
|
| 25 |
+
export declare function watchOnce<T extends Array<unknown>>(sources: {
|
| 26 |
+
[K in keyof T]: Getter<T[K]>;
|
| 27 |
+
}, effect: (values: T, previousValues: T) => void | VoidFunction): void;
|
| 28 |
+
export declare function watchOnce<T>(source: Getter<T>, effect: (value: T, previousValue: T) => void | VoidFunction): void;
|
| 29 |
+
export declare namespace watchOnce {
|
| 30 |
+
var pre: typeof watchOncePre;
|
| 31 |
+
}
|
| 32 |
+
declare function watchOncePre<T extends Array<unknown>>(sources: {
|
| 33 |
+
[K in keyof T]: Getter<T[K]>;
|
| 34 |
+
}, effect: (values: T, previousValues: T) => void | VoidFunction): void;
|
| 35 |
+
declare function watchOncePre<T>(source: Getter<T>, effect: (value: T, previousValue: T) => void | VoidFunction): void;
|
| 36 |
+
export {};
|
tools/ui/node_modules/runed/dist/utilities/watch/watch.svelte.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { untrack } from "svelte";
|
| 2 |
+
function runEffect(flush, effect) {
|
| 3 |
+
switch (flush) {
|
| 4 |
+
case "post":
|
| 5 |
+
$effect(effect);
|
| 6 |
+
break;
|
| 7 |
+
case "pre":
|
| 8 |
+
$effect.pre(effect);
|
| 9 |
+
break;
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
function runWatcher(sources, flush, effect, options = {}) {
|
| 13 |
+
const { lazy = false } = options;
|
| 14 |
+
// Run the effect immediately if `lazy` is `false`.
|
| 15 |
+
let active = !lazy;
|
| 16 |
+
// On the first run, if the dependencies are an array, pass an empty array
|
| 17 |
+
// to the previous value instead of `undefined` to allow destructuring.
|
| 18 |
+
//
|
| 19 |
+
// watch(() => [a, b], ([a, b], [prevA, prevB]) => { ... });
|
| 20 |
+
let previousValues = Array.isArray(sources)
|
| 21 |
+
? []
|
| 22 |
+
: undefined;
|
| 23 |
+
runEffect(flush, () => {
|
| 24 |
+
const values = Array.isArray(sources) ? sources.map((source) => source()) : sources();
|
| 25 |
+
if (!active) {
|
| 26 |
+
active = true;
|
| 27 |
+
previousValues = values;
|
| 28 |
+
return;
|
| 29 |
+
}
|
| 30 |
+
const cleanup = untrack(() => effect(values, previousValues));
|
| 31 |
+
previousValues = values;
|
| 32 |
+
return cleanup;
|
| 33 |
+
});
|
| 34 |
+
}
|
| 35 |
+
function runWatcherOnce(sources, flush, effect) {
|
| 36 |
+
const cleanupRoot = $effect.root(() => {
|
| 37 |
+
let stop = false;
|
| 38 |
+
runWatcher(sources, flush, (values, previousValues) => {
|
| 39 |
+
if (stop) {
|
| 40 |
+
cleanupRoot();
|
| 41 |
+
return;
|
| 42 |
+
}
|
| 43 |
+
// Since `lazy` is `true`, `previousValues` is always defined.
|
| 44 |
+
const cleanup = effect(values, previousValues);
|
| 45 |
+
stop = true;
|
| 46 |
+
return cleanup;
|
| 47 |
+
},
|
| 48 |
+
// Running the effect immediately just once makes no sense at all.
|
| 49 |
+
// That's just `onMount` with extra steps.
|
| 50 |
+
{ lazy: true });
|
| 51 |
+
});
|
| 52 |
+
$effect(() => {
|
| 53 |
+
return cleanupRoot;
|
| 54 |
+
});
|
| 55 |
+
}
|
| 56 |
+
export function watch(sources, effect, options) {
|
| 57 |
+
runWatcher(sources, "post", effect, options);
|
| 58 |
+
}
|
| 59 |
+
function watchPre(sources, effect, options) {
|
| 60 |
+
runWatcher(sources, "pre", effect, options);
|
| 61 |
+
}
|
| 62 |
+
watch.pre = watchPre;
|
| 63 |
+
export function watchOnce(source, effect) {
|
| 64 |
+
runWatcherOnce(source, "post", effect);
|
| 65 |
+
}
|
| 66 |
+
function watchOncePre(source, effect) {
|
| 67 |
+
runWatcherOnce(source, "pre", effect);
|
| 68 |
+
}
|
| 69 |
+
watchOnce.pre = watchOncePre;
|
tools/ui/node_modules/runed/package.json
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "runed",
|
| 3 |
+
"version": "0.35.1",
|
| 4 |
+
"type": "module",
|
| 5 |
+
"svelte": "./dist/index.js",
|
| 6 |
+
"types": "./dist/index.d.ts",
|
| 7 |
+
"license": "MIT",
|
| 8 |
+
"keywords": [
|
| 9 |
+
"svelte",
|
| 10 |
+
"svelte5",
|
| 11 |
+
"sveltekit",
|
| 12 |
+
"svelte utilities",
|
| 13 |
+
"svelte helpers",
|
| 14 |
+
"sveltekit utilities",
|
| 15 |
+
"sveltekit helpers",
|
| 16 |
+
"svelte 5 runes",
|
| 17 |
+
"runes",
|
| 18 |
+
"typescript"
|
| 19 |
+
],
|
| 20 |
+
"contributors": [
|
| 21 |
+
{
|
| 22 |
+
"name": "Thomas G. Lopes",
|
| 23 |
+
"url": "https://thomasglopes.com"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"name": "Hunter Johnston",
|
| 27 |
+
"url": "https://x.com/huntabyte"
|
| 28 |
+
}
|
| 29 |
+
],
|
| 30 |
+
"repository": {
|
| 31 |
+
"type": "git",
|
| 32 |
+
"url": "https://github.com/svecosystem/runed",
|
| 33 |
+
"directory": "packages/runed"
|
| 34 |
+
},
|
| 35 |
+
"funding": [
|
| 36 |
+
"https://github.com/sponsors/huntabyte",
|
| 37 |
+
"https://github.com/sponsors/tglide"
|
| 38 |
+
],
|
| 39 |
+
"exports": {
|
| 40 |
+
".": {
|
| 41 |
+
"types": "./dist/index.d.ts",
|
| 42 |
+
"svelte": "./dist/index.js",
|
| 43 |
+
"default": "./dist/index.js"
|
| 44 |
+
},
|
| 45 |
+
"./kit": {
|
| 46 |
+
"types": "./dist/kit/index.d.ts",
|
| 47 |
+
"svelte": "./dist/kit/index.js",
|
| 48 |
+
"default": "./dist/kit/index.js"
|
| 49 |
+
}
|
| 50 |
+
},
|
| 51 |
+
"files": [
|
| 52 |
+
"dist",
|
| 53 |
+
"!dist/**/*.test.*",
|
| 54 |
+
"!dist/**/*.spec.*"
|
| 55 |
+
],
|
| 56 |
+
"peerDependencies": {
|
| 57 |
+
"svelte": "^5.7.0",
|
| 58 |
+
"@sveltejs/kit": "^2.21.0"
|
| 59 |
+
},
|
| 60 |
+
"peerDependenciesMeta": {
|
| 61 |
+
"@sveltejs/kit": {
|
| 62 |
+
"optional": true
|
| 63 |
+
}
|
| 64 |
+
},
|
| 65 |
+
"devDependencies": {
|
| 66 |
+
"@playwright/test": "^1.55.0",
|
| 67 |
+
"@sveltejs/kit": "^2.42.0",
|
| 68 |
+
"@sveltejs/package": "^2.3.0",
|
| 69 |
+
"@sveltejs/vite-plugin-svelte": "^6.2.0",
|
| 70 |
+
"@testing-library/dom": "^10.2.0",
|
| 71 |
+
"@testing-library/jest-dom": "^6.4.6",
|
| 72 |
+
"@testing-library/svelte": "^5.2.0",
|
| 73 |
+
"@testing-library/user-event": "^14.5.2",
|
| 74 |
+
"@types/node": "^20.19.16",
|
| 75 |
+
"@vitest/browser": "^3.2.4",
|
| 76 |
+
"@vitest/coverage-v8": "^3.2.4",
|
| 77 |
+
"@vitest/ui": "^3.2.4",
|
| 78 |
+
"jsdom": "^24.0.0",
|
| 79 |
+
"msw": "^2.7.0",
|
| 80 |
+
"playwright": "^1.55.0",
|
| 81 |
+
"publint": "^0.1.9",
|
| 82 |
+
"resize-observer-polyfill": "^1.5.1",
|
| 83 |
+
"svelte": "^5.39.3",
|
| 84 |
+
"svelte-check": "^4.3.1",
|
| 85 |
+
"tslib": "^2.4.1",
|
| 86 |
+
"typescript": "^5.9.2",
|
| 87 |
+
"vite": "^7.1.5",
|
| 88 |
+
"vitest": "^3.2.4"
|
| 89 |
+
},
|
| 90 |
+
"dependencies": {
|
| 91 |
+
"dequal": "^2.0.3",
|
| 92 |
+
"esm-env": "^1.0.0",
|
| 93 |
+
"lz-string": "^1.5.0"
|
| 94 |
+
},
|
| 95 |
+
"scripts": {
|
| 96 |
+
"dev": "pnpm sync && pnpm watch",
|
| 97 |
+
"build": "pnpm package",
|
| 98 |
+
"package": "svelte-kit sync && svelte-package && publint",
|
| 99 |
+
"test": "vitest --run && playwright test",
|
| 100 |
+
"test:watch": "vitest --watch",
|
| 101 |
+
"test:ui": "vitest --watch --ui",
|
| 102 |
+
"test:integration": "playwright test",
|
| 103 |
+
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
| 104 |
+
"watch": "svelte-kit sync && svelte-package --watch"
|
| 105 |
+
}
|
| 106 |
+
}
|
tools/ui/node_modules/rw/.eslintrc
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
env:
|
| 2 |
+
node: true
|
| 3 |
+
|
| 4 |
+
extends:
|
| 5 |
+
"eslint:recommended"
|
tools/ui/node_modules/rw/.npmignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.DS_Store
|
| 2 |
+
node_modules
|
| 3 |
+
test/input.txt
|
tools/ui/node_modules/rw/LICENSE
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2014-2016, Michael Bostock
|
| 2 |
+
All rights reserved.
|
| 3 |
+
|
| 4 |
+
Redistribution and use in source and binary forms, with or without
|
| 5 |
+
modification, are permitted provided that the following conditions are met:
|
| 6 |
+
|
| 7 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 8 |
+
list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 11 |
+
this list of conditions and the following disclaimer in the documentation
|
| 12 |
+
and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
* The name Michael Bostock may not be used to endorse or promote products
|
| 15 |
+
derived from this software without specific prior written permission.
|
| 16 |
+
|
| 17 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 18 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 19 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 20 |
+
DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
|
| 21 |
+
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 22 |
+
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 23 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
| 24 |
+
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 25 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
|
| 26 |
+
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
tools/ui/node_modules/rw/README.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# rw - Now stdin and stdout are files.
|
| 2 |
+
|
| 3 |
+
How do you read a file from stdin? If you thought,
|
| 4 |
+
|
| 5 |
+
```js
|
| 6 |
+
var contents = fs.readFileSync("/dev/stdin", "utf8");
|
| 7 |
+
```
|
| 8 |
+
|
| 9 |
+
you’d be wrong, because Node only reads up to the size of the file reported by fs.stat rather than reading until it receives an EOF. So, if you redirect a file to your program (`cat file | program`), you’ll only read the first 65,536 bytes of your file. Oops.
|
| 10 |
+
|
| 11 |
+
What about writing a file to stdout? If you thought,
|
| 12 |
+
|
| 13 |
+
```js
|
| 14 |
+
fs.writeFileSync("/dev/stdout", contents, "utf8");
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
you’d also be wrong, because this tries to close stdout, so you get this error:
|
| 18 |
+
|
| 19 |
+
```
|
| 20 |
+
Error: UNKNOWN, unknown error
|
| 21 |
+
at Object.fs.writeSync (fs.js:528:18)
|
| 22 |
+
at Object.fs.writeFileSync (fs.js:975:21)
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
(Also, this doesn’t work on Windows, because Windows doesn’t support /dev/stdout, /dev/stdin and /dev/stderr!)
|
| 26 |
+
|
| 27 |
+
Shucks. So what should you do?
|
| 28 |
+
|
| 29 |
+
You could use a different pattern for reading from stdin:
|
| 30 |
+
|
| 31 |
+
```js
|
| 32 |
+
var chunks = [];
|
| 33 |
+
|
| 34 |
+
process.stdin
|
| 35 |
+
.on("data", function(chunk) { chunks.push(chunk); })
|
| 36 |
+
.on("end", function() { console.log(chunks.join("").length); })
|
| 37 |
+
.setEncoding("utf8");
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
But that’s a pain, since now your code has two different code paths for reading inputs depending on whether you’re reading a real file or stdin. And the code gets even more complex if you want to [read that file synchronously](https://github.com/mbostock/rw/blob/master/lib/rw/read-file-sync.js).
|
| 41 |
+
|
| 42 |
+
You could also try a different pattern for writing to stdout:
|
| 43 |
+
|
| 44 |
+
```js
|
| 45 |
+
process.stdout.write(contents);
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
Or even:
|
| 49 |
+
|
| 50 |
+
```js
|
| 51 |
+
console.log(contents);
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
But if you try to pipe your output to `head`, you’ll get this error:
|
| 55 |
+
|
| 56 |
+
```
|
| 57 |
+
Error: write EPIPE
|
| 58 |
+
at errnoException (net.js:904:11)
|
| 59 |
+
at Object.afterWrite (net.js:720:19)
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Huh.
|
| 63 |
+
|
| 64 |
+
The **rw** module fixes these problems. It provides an interface just like readFile, readFileSync, writeFile and writeFileSync, but with implementations that work the way you expect on stdin and stdout. If you use these methods on files other than /dev/stdin or /dev/stdout, they simply delegate to the fs methods, so you can trust that they behave identically to the methods you’re used to.
|
| 65 |
+
|
| 66 |
+
For example, now you can read stdin synchronously like so:
|
| 67 |
+
|
| 68 |
+
```js
|
| 69 |
+
var contents = rw.readFileSync("/dev/stdin", "utf8");
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
Or to write to stdout:
|
| 73 |
+
|
| 74 |
+
```js
|
| 75 |
+
rw.writeFileSync("/dev/stdout", contents, "utf8");
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
And rw automatically squashes EPIPE errors, so you can pipe the output of your program to `head` and you won’t get a spurious stack trace.
|
| 79 |
+
|
| 80 |
+
To install, `npm install rw`.
|
| 81 |
+
|
| 82 |
+
### Note
|
| 83 |
+
|
| 84 |
+
If you want to read synchronously from stdin using [readFileSync](#readFileSync), you cannot also use process.stdin in the same program. Likewise, if you want to write synchronously to stdout or stderr using [writeFileSync](#writeFileSync), you cannot use process.stdout or process.stderr, respectively. (This includes using console.log and the like!) Failure to heed this warning may result in error: EAGAIN, resource temporarily unavailable. Unfortunately, it does not appear possible for this library to fix this issue automatically, so please use caution.
|
| 85 |
+
|
| 86 |
+
Only the asynchronous methods [readFile](#readFile) and [writeFile](#writeFile) are supported on Windows. Node has no synchronous API for reading from process.[stdin](https://nodejs.org/api/process.html#process_process_stdin) or writing to process.[stdout](https://nodejs.org/api/process.html#process_process_stdout) or process.[stderr](https://nodejs.org/api/process.html#process_process_stderr), so you’re out of luck!
|
| 87 |
+
|
| 88 |
+
## API Reference
|
| 89 |
+
|
| 90 |
+
<a name="readFile" href="#readFile">#</a> rw.<b>readFile</b>(<i>path</i>[, <i>options</i>], <i>callback</i>)
|
| 91 |
+
|
| 92 |
+
Reads the file at the specified *path* completely into memory, invoking the specified *callback* once the data is available and the file is closed. The *callback* is invoked with two arguments: the *error* that occurred during read (hopefully null), and the read data. If *options* is a string, it specifies the encoding to use, in which case the read data will be a string; otherwise *options* is an object, and may specify encoding and flag properties. This method is a drop-in replacement for [fs.readFile](https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback) and fixes the behavior of special files such as /dev/stdin.
|
| 93 |
+
|
| 94 |
+
<a name="readFileSync" href="#readFileSync">#</a> rw.<b>readFileSync</b>(<i>path</i>[, <i>options</i>])
|
| 95 |
+
|
| 96 |
+
Reads the file at the specified *path* completely into memory, synchronously, returning the data. If an error occurred during read, this function throws an error instead. If *options* is a string, it specifies the encoding to use, in which case the read data will be a string; otherwise *options* is an object, and may specify encoding and flag properties. This method is a drop-in replacement for [fs.readFileSync](https://nodejs.org/api/fs.html#fs_fs_readfilesync_file_options) and fixes the behavior of special files such as /dev/stdin.
|
| 97 |
+
|
| 98 |
+
<a name="writeFile" href="#writeFile">#</a> rw.<b>writeFile</b>(<i>path</i>, <i>data</i>[, <i>options</i>], <i>callback</i>)
|
| 99 |
+
|
| 100 |
+
Writes the specified *data* (completely in memory) to a file at the specified *path*, invoking the specified *callback* once the data is completely written and the file is closed. The *callback* is invoked with a single argument: the *error* that occurred during write (hopefully null). If *options* is a string, it specifies the encoding to use, in which case the *data* must be a string; otherwise *options* is an object, and may specify encoding, mode and flag properties. This method is a drop-in replacement for [fs.writeFile](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) and fixes the behavior of special files such as /dev/stdout.
|
| 101 |
+
|
| 102 |
+
<a name="writeFileSync" href="#writeFileSync">#</a> rw.<b>writeFileSync</b>(<i>path</i>, <i>data</i>[, <i>options</i>])
|
| 103 |
+
|
| 104 |
+
Writes the specified *data* (completely in memory) to a file at the specified *path*, synchronously, returning once the data is completely written and the file is closed. Throws an *error* if one occurs during write. If *options* is a string, it specifies the encoding to use, in which case the *data* must be a string; otherwise *options* is an object, and may specify encoding, mode and flag properties. This method is a drop-in replacement for [fs.writeFileSync](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) and fixes the behavior of special files such as /dev/stdout.
|
| 105 |
+
|
| 106 |
+
<a name="dash_readFile" href="#dash_readFile">#</a> rw.dash.<b>readFile</b>(<i>path</i>[, <i>options</i>], <i>callback</i>)
|
| 107 |
+
|
| 108 |
+
Equivalent to [rw.readFile](#readFile), except treats a *path* of `-` as `/dev/stdin`. Useful for command-line arguments.
|
| 109 |
+
|
| 110 |
+
<a name="dash_readFileSync" href="#dash_readFileSync">#</a> rw.dash.<b>readFileSync</b>(<i>path</i>[, <i>options</i>])
|
| 111 |
+
|
| 112 |
+
Equivalent to [rw.readFileSync](#readFileSync), except treats a *path* of `-` as `/dev/stdin`. Useful for command-line arguments.
|
| 113 |
+
|
| 114 |
+
<a name="dash_writeFile" href="#dash_writeFile">#</a> rw.dash.<b>writeFile</b>(<i>path</i>, <i>data</i>[, <i>options</i>], <i>callback</i>)
|
| 115 |
+
|
| 116 |
+
Equivalent to [rw.writeFile](#writeFile), except treats a *path* of `-` as `/dev/stdout`. Useful for command-line arguments.
|
| 117 |
+
|
| 118 |
+
<a name="dash_writeFileSync" href="#dash_writeFileSync">#</a> rw.dash.<b>writeFileSync</b>(<i>path</i>, <i>data</i>[, <i>options</i>])
|
| 119 |
+
|
| 120 |
+
Equivalent to [rw.writeFileSync](#writeFileSync), except treats a *path* of `-` as `/dev/stdout`. Useful for command-line arguments.
|
tools/ui/node_modules/rw/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
exports.dash = require("./lib/rw/dash");
|
| 2 |
+
exports.readFile = require("./lib/rw/read-file");
|
| 3 |
+
exports.readFileSync = require("./lib/rw/read-file-sync");
|
| 4 |
+
exports.writeFile = require("./lib/rw/write-file");
|
| 5 |
+
exports.writeFileSync = require("./lib/rw/write-file-sync");
|
tools/ui/node_modules/rw/lib/rw/dash.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var slice = Array.prototype.slice;
|
| 2 |
+
|
| 3 |
+
function dashify(method, file) {
|
| 4 |
+
return function(path) {
|
| 5 |
+
var argv = arguments;
|
| 6 |
+
if (path == "-") (argv = slice.call(argv)).splice(0, 1, file);
|
| 7 |
+
return method.apply(null, argv);
|
| 8 |
+
};
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
exports.readFile = dashify(require("./read-file"), "/dev/stdin");
|
| 12 |
+
exports.readFileSync = dashify(require("./read-file-sync"), "/dev/stdin");
|
| 13 |
+
exports.writeFile = dashify(require("./write-file"), "/dev/stdout");
|
| 14 |
+
exports.writeFileSync = dashify(require("./write-file-sync"), "/dev/stdout");
|
tools/ui/node_modules/rw/lib/rw/decode.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module.exports = function(options) {
|
| 2 |
+
if (options) {
|
| 3 |
+
if (typeof options === "string") return encoding(options);
|
| 4 |
+
if (options.encoding !== null) return encoding(options.encoding);
|
| 5 |
+
}
|
| 6 |
+
return identity();
|
| 7 |
+
};
|
| 8 |
+
|
| 9 |
+
function identity() {
|
| 10 |
+
var chunks = [];
|
| 11 |
+
return {
|
| 12 |
+
push: function(chunk) { chunks.push(chunk); },
|
| 13 |
+
value: function() { return Buffer.concat(chunks); }
|
| 14 |
+
};
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
function encoding(encoding) {
|
| 18 |
+
var chunks = [];
|
| 19 |
+
return {
|
| 20 |
+
push: function(chunk) { chunks.push(chunk); },
|
| 21 |
+
value: function() { return Buffer.concat(chunks).toString(encoding); }
|
| 22 |
+
};
|
| 23 |
+
}
|
tools/ui/node_modules/rw/lib/rw/encode.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module.exports = function(data, options) {
|
| 2 |
+
return typeof data === "string"
|
| 3 |
+
? new Buffer(data, typeof options === "string" ? options
|
| 4 |
+
: options && options.encoding !== null ? options.encoding
|
| 5 |
+
: "utf8")
|
| 6 |
+
: data;
|
| 7 |
+
};
|
tools/ui/node_modules/rw/lib/rw/read-file-sync.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var fs = require("fs"),
|
| 2 |
+
decode = require("./decode");
|
| 3 |
+
|
| 4 |
+
module.exports = function(filename, options) {
|
| 5 |
+
if (fs.statSync(filename).isFile()) {
|
| 6 |
+
return fs.readFileSync(filename, options);
|
| 7 |
+
} else {
|
| 8 |
+
var fd = fs.openSync(filename, options && options.flag || "r"),
|
| 9 |
+
decoder = decode(options);
|
| 10 |
+
|
| 11 |
+
while (true) { // eslint-disable-line no-constant-condition
|
| 12 |
+
try {
|
| 13 |
+
var buffer = new Buffer(bufferSize),
|
| 14 |
+
bytesRead = fs.readSync(fd, buffer, 0, bufferSize);
|
| 15 |
+
} catch (e) {
|
| 16 |
+
if (e.code === "EOF") break;
|
| 17 |
+
fs.closeSync(fd);
|
| 18 |
+
throw e;
|
| 19 |
+
}
|
| 20 |
+
if (bytesRead === 0) break;
|
| 21 |
+
decoder.push(buffer.slice(0, bytesRead));
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
fs.closeSync(fd);
|
| 25 |
+
return decoder.value();
|
| 26 |
+
}
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
var bufferSize = 1 << 16;
|
tools/ui/node_modules/rw/lib/rw/read-file.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var fs = require("fs"),
|
| 2 |
+
decode = require("./decode");
|
| 3 |
+
|
| 4 |
+
module.exports = function(path, options, callback) {
|
| 5 |
+
if (arguments.length < 3) callback = options, options = null;
|
| 6 |
+
|
| 7 |
+
switch (path) {
|
| 8 |
+
case "/dev/stdin": return readStream(process.stdin, options, callback);
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
fs.stat(path, function(error, stat) {
|
| 12 |
+
if (error) return callback(error);
|
| 13 |
+
if (stat.isFile()) return fs.readFile(path, options, callback);
|
| 14 |
+
readStream(fs.createReadStream(path, options ? {flags: options.flag || "r"} : {}), options, callback); // N.B. flag / flags
|
| 15 |
+
});
|
| 16 |
+
};
|
| 17 |
+
|
| 18 |
+
function readStream(stream, options, callback) {
|
| 19 |
+
var decoder = decode(options);
|
| 20 |
+
stream.on("error", callback);
|
| 21 |
+
stream.on("data", function(d) { decoder.push(d); });
|
| 22 |
+
stream.on("end", function() { callback(null, decoder.value()); });
|
| 23 |
+
}
|
tools/ui/node_modules/rw/lib/rw/write-file-sync.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var fs = require("fs"),
|
| 2 |
+
encode = require("./encode");
|
| 3 |
+
|
| 4 |
+
module.exports = function(filename, data, options) {
|
| 5 |
+
var stat;
|
| 6 |
+
|
| 7 |
+
try {
|
| 8 |
+
stat = fs.statSync(filename);
|
| 9 |
+
} catch (error) {
|
| 10 |
+
if (error.code !== "ENOENT") throw error;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
if (!stat || stat.isFile()) {
|
| 14 |
+
fs.writeFileSync(filename, data, options);
|
| 15 |
+
} else {
|
| 16 |
+
var fd = fs.openSync(filename, options && options.flag || "w"),
|
| 17 |
+
bytesWritten = 0,
|
| 18 |
+
bytesTotal = (data = encode(data, options)).length;
|
| 19 |
+
|
| 20 |
+
while (bytesWritten < bytesTotal) {
|
| 21 |
+
try {
|
| 22 |
+
bytesWritten += fs.writeSync(fd, data, bytesWritten, bytesTotal - bytesWritten, null);
|
| 23 |
+
} catch (error) {
|
| 24 |
+
if (error.code === "EPIPE") break; // ignore broken pipe, e.g., | head
|
| 25 |
+
fs.closeSync(fd);
|
| 26 |
+
throw error;
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
fs.closeSync(fd);
|
| 31 |
+
}
|
| 32 |
+
};
|
tools/ui/node_modules/rw/lib/rw/write-file.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var fs = require("fs"),
|
| 2 |
+
encode = require("./encode");
|
| 3 |
+
|
| 4 |
+
module.exports = function(path, data, options, callback) {
|
| 5 |
+
if (arguments.length < 4) callback = options, options = null;
|
| 6 |
+
|
| 7 |
+
switch (path) {
|
| 8 |
+
case "/dev/stdout": return writeStream(process.stdout, "write", data, options, callback);
|
| 9 |
+
case "/dev/stderr": return writeStream(process.stderr, "write", data, options, callback);
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
fs.stat(path, function(error, stat) {
|
| 13 |
+
if (error && error.code !== "ENOENT") return callback(error);
|
| 14 |
+
if (stat && stat.isFile()) return fs.writeFile(path, data, options, callback);
|
| 15 |
+
writeStream(fs.createWriteStream(path, options ? {flags: options.flag || "w"} : {}), "end", data, options, callback); // N.B. flag / flags
|
| 16 |
+
});
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
function writeStream(stream, send, data, options, callback) {
|
| 20 |
+
stream.on("error", function(error) { callback(error.code === "EPIPE" ? null : error); }); // ignore broken pipe, e.g., | head
|
| 21 |
+
stream[send](encode(data, options), function(error) { callback(error && error.code === "EPIPE" ? null : error); });
|
| 22 |
+
}
|
tools/ui/node_modules/rw/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "rw",
|
| 3 |
+
"version": "1.3.3",
|
| 4 |
+
"description": "Now stdin and stdout are files.",
|
| 5 |
+
"keywords": [
|
| 6 |
+
"fs",
|
| 7 |
+
"readFile",
|
| 8 |
+
"writeFile",
|
| 9 |
+
"stdin",
|
| 10 |
+
"stdout"
|
| 11 |
+
],
|
| 12 |
+
"homepage": "https://github.com/mbostock/rw",
|
| 13 |
+
"license": "BSD-3-Clause",
|
| 14 |
+
"author": {
|
| 15 |
+
"name": "Mike Bostock",
|
| 16 |
+
"url": "http://bost.ocks.org/mike"
|
| 17 |
+
},
|
| 18 |
+
"main": "index.js",
|
| 19 |
+
"repository": {
|
| 20 |
+
"type": "git",
|
| 21 |
+
"url": "http://github.com/mbostock/rw.git"
|
| 22 |
+
},
|
| 23 |
+
"scripts": {
|
| 24 |
+
"test": "test/run-tests && eslint index.js lib",
|
| 25 |
+
"prepublish": "npm test",
|
| 26 |
+
"postpublish": "git push && git push --tags"
|
| 27 |
+
},
|
| 28 |
+
"devDependencies": {
|
| 29 |
+
"d3-queue": "3",
|
| 30 |
+
"eslint": "3"
|
| 31 |
+
}
|
| 32 |
+
}
|
tools/ui/node_modules/rw/test/cat-async
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
|
| 3 |
+
var rw = require("../").dash;
|
| 4 |
+
|
| 5 |
+
rw.readFile(process.argv[2] || "-", "utf8", function(error, contents) {
|
| 6 |
+
if (error) throw error;
|
| 7 |
+
rw.writeFile("-", contents, "utf8", function(error) {
|
| 8 |
+
if (error) throw error;
|
| 9 |
+
});
|
| 10 |
+
});
|
tools/ui/node_modules/rw/test/cat-sync
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
|
| 3 |
+
var rw = require("../").dash;
|
| 4 |
+
|
| 5 |
+
rw.writeFileSync("-", rw.readFileSync(process.argv[2] || "-", "utf8"), "utf8");
|