npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@svetlokit/cookie-manager

v1.0.4

Published

Cookie manager for SvelteKit

Downloads

2

Readme

@svetlokit/cookie-manager

Library for simple management cookies in your SvelteKit app

Getting Started

1. Types

Add to your App.d.ts cookieManager fields - ServerCookieManager for server side and BrowserCookieManager for browser

declare namespace App {
	 interface Locals {
		userid: string;
		cookieManager: import('@svetlokit/cookie-manager').ServerCookieManager;
	}

	interface Platform {}

	interface Session {}

	interface Stuff {
		cookieManager: import('@svetlokit/cookie-manager').BrowserCookieManager;
	}
}

2. Hooks

Add cookieManagerHook

import type { Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
import { cookieManagerHook } from  '@svetlokit/cookie-manager';

export const handle: Handle = sequence(cookieManagerHook, ...);

3. Create adapter

Create adapter for your cookie. You can do it by extending `CookieAdapter'

import { CookieAdapter } from  '@svetlokit/cookie-manager';

export class DateAdapter extends CookieAdapter<Date> {
    public static serialize(value: Date): string {
        return value.toISOString();
    }
    public static parse(serializedValue: string): Date {
        return new Date(serializedValue);
    }

    public get isFuture(): boolean {
        return this.value?.getTime() > Date.now();
    }
}

4. Use adapters

import { CookieManager, CookieTextAdapter } from '@svetlokit/cookie-manager';
import type { RequestEvent, RequestHandler } from '@sveltejs/kit';
import { DateAdapter } from './date.adapter.ts';

export const get: RequestHandler = async (event: RequestEvent) => {
    const userAuthorizedAt: DateAdapter = event.locals.cookieManager.getAdapter(DateAdapter, 'date-authorize');
    ...
    userAuthorizedAt.update(new Date());
    ...
    ...
    ...
    const userRegisteredAt: DateAdapter = event.locals.cookieManager.getAdapter(DateAdapter, 'date-register');
    ...
};

5. Use in browser

Add to __layout.svelte

<script lang="ts" context="module">
	import type { Load } from '@sveltejs/kit';
	import { BrowserCookieManager } from '@svetlokit/cookie-manager';

	// see https://kit.svelte.dev/docs#loading
	export const load: Load = async ({ fetch }) => {
		return { 
			stuff: {
				cookieManager: new BrowserCookieManager()
			}
		}
	};
</script>

And in ither files you can get manager from page store

<script lang="ts">
	import { page } from '$app/stores';

	import { onMount } from 'svelte';

	onMount(() =>{
		console.log($page.stuff.cookieManager);
	})
</script>

Entities

CookieManager<Options>

Mediator between cookies and adapters.

Members

| Fields | Descripton | |------------------------------|----------------| | public get(name: string): string | undefined | Get cookie by name |

| Methods | Descripton | |------------------------------|----------------| | protected cookies: Map<string, string> | Initial cookies values | | public set(name: string, value: string, options?: Options): void | Set cookie value | | public remove(name: string): void | Remove cookie |; | public getAdapter<...>(ctor: CookieAdapterCtor, name: string, defaultValue?: any): T | Get adapter instance |;

CookieAdapter<T>

Adapter for cookie, that keep value of some type (default - string). You can create it with CookieManager#getAdapter, or by new ... (in this case don't forget CookieAdapter#setManager. By defalut implementented CookieJSONAdapter<D> and CookieTextAdapter.
Example of implementing adapter:

interface ParsedUserInfo {
    name: string;
    endOfTrial: string;
}

export interface UserInfo {
    name: string;
    endOfTrial: Date;
}

export class UserInfo extends CookieAdapter<Date> {
    public static serialize(value: UserInfo): string {
        return JSON.stringify(value);
    }
    public static parse(serializedValue: string): UserInfo {
        try {
            const info = JSON.parse(serializedValue);
            if (typeof info === 'object') {
                return {
                    ...info,
                    endOfTrial: new Date(info.endOfTrial)
                };
            }
        } catch (e) { }

        return null;
    }

    public get trialEnded(): boolean {
        return this.value?.endOfTrial?.getTime() > Date.now();
    }

    public extendTrial(): void {
        if (this.value) {
            const endOfTrial: Date = new Date(this.value.endOfTrial);
            endOfTrial.setDate(endOfTrial.getDate() + 1);
            
            this.update({ ...this.value, endOfTrial });
        }
    }
}

public static serialize<T>(value: T): string

Function for serialization value of adapter to cookie string value

...
public static serialize(value: Date): string {
    return value.toISOString();
}
...

public static parse<T>(serializedValue: string): T

Function for pasring adapter value from cookie value

...
public static parse(serializedValue: string): Date {
    return new Date(serializedValue);
}
...

Members

| Fields | Descripton | |------------------------------|----------------| | public readonly name: string | Name of cookie | | public initialValue?: string | Initial cookie value on adapter create moment | | public get serializedValue(): string | Serialized current adapter value | | public value: D = null | Current adapter value | | protected manager?: CookieManager | Manager, that gives initial value and saves updated value of this adapter |

| Methods | Descripton | |------------------------------|----------------| | public setManager(manager: CookieManager): void | Set manager | | public update(value: D, options?: CookieOptions): void | Update value |