Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Avoid derived() store updates on invalid upstream state. #9458

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 116 additions & 22 deletions documentation/docs/03-runtime/02-svelte-store.md
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ title: 'svelte/store'

The `svelte/store` module exports functions for creating [readable](/docs/svelte-store#readable), [writable](/docs/svelte-store#writable) and [derived](/docs/svelte-store#derived) stores.

Keep in mind that you don't _have_ to use these functions to enjoy the [reactive `$store` syntax](/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values) in your components. Any object that correctly implements `.subscribe`, unsubscribe, and (optionally) `.set` is a valid store, and will work both with the special syntax, and with Svelte's built-in [`derived` stores](/docs/svelte-store#derived).
Keep in mind that you don't _have_ to use these functions to enjoy the [reactive `$store` syntax](/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values) in your components. Any object that correctly implements the `subscribe` (including returning unsubscribe functions) and (optionally) `set` methods is a valid store, and will work both with the special syntax and with Svelte's built-in [derived stores](/docs/svelte-store#derived).

This makes it possible to wrap almost any other reactive state handling library for use in Svelte. Read more about the [store contract](/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values) to see what a correct implementation looks like.

@@ -18,8 +18,7 @@ Function that creates a store which has values that can be set from 'outside' co

`update` is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.

```js
/// file: store.js
```ts
import { writable } from 'svelte/store';

const count = writable(0);
@@ -35,8 +34,7 @@ count.update((n) => n + 1); // logs '2'

If a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a `set` function which changes the value of the store, and an `update` function which works like the `update` method on the store, taking a callback to calculate the store's new value from its old value. It must return a `stop` function that is called when the subscriber count goes from one to zero.

```js
/// file: store.js
```ts
import { writable } from 'svelte/store';

const count = writable(0, () => {
@@ -59,27 +57,60 @@ Note that the value of a `writable` is lost when it is destroyed, for example wh

> EXPORT_SNIPPET: svelte/store#readable

Creates a store whose value cannot be set from 'outside', the first argument is the store's initial value, and the second argument to `readable` is the same as the second argument to `writable`.
Creates a store which can be subscribed to, but does not have the `set` and `update` methods that a writable store has. The value of a readable store is instead set by the `initial_value` argument at creation and then updated internally by an `on_start` function. This function is called when the store receives its first subscriber.

The `on_start` function allows the creation of stores whose value changes automatically based on application-specific logic. It's passed `set` and `update` functions that behave like the methods available on writable stores.

The `on_start` function can optionally return an `on_stop` function which will be called when the store loses its last subscriber. This allows stores to go dormant when not being used by any other code.

```ts
import { readable } from 'svelte/store';

const time = readable(new Date(), (set) => {
set(new Date());
const lastPressedSimpleKey = readable('', (set) => {
const handleEvent = (event: KeyboardEvent) => {
if (event.key.length === 1) {
set(event.key);
}
};

const interval = setInterval(() => {
set(new Date());
}, 1000);
window.addEventListener('keypress', handleEvent, { passive: true });

return function onStop() {
window.removeEventListener('keypress', handleEvent);
};
});

return () => clearInterval(interval);
lastPressedSimpleKey.subscribe((value) => {
console.log(`Most recently pressed simple key is "${value}".`);
});
```

const ticktock = readable('tick', (set, update) => {
`on_start` could also set up a timer to poll an API for data which changes frequently, or even establish a WebSocket connection. The following example creates a store which polls [Open Notify's public ISS position API](http://open-notify.org/Open-Notify-API/ISS-Location-Now/) every 3 seconds.

> If `set` or `update` are called after the store has lost its last subscriber, they will have no effect. You should still take care to clean up any asynchronous callbacks registered in `on_start` by providing a suitable `on_stop` function, but a few accidental late calls will not negatively affect the store.
>
> For instance, in the example below `set` may be called late if the `issPosition` store loses its last subscriber after a `fetch` call is made but before the corresponding HTTP response is received.

```ts
import { readable } from 'svelte/store';

const issPosition = readable({ latitude: 0, longitude: 0 }, (set) => {
const interval = setInterval(() => {
update((sound) => (sound === 'tick' ? 'tock' : 'tick'));
}, 1000);
fetch('http://api.open-notify.org/iss-now.json')
.then((response) => response.json())
.then((payload) => set(payload.iss_position));
}, 3000);

return function onStop() {
clearInterval(interval);
};
});

return () => clearInterval(interval);
issPosition.subscribe(({ latitude, longitude }) => {
console.log(
`The ISS is currently above ${latitude}°, ${longitude}°` +
` in the ${latitude > 0 ? 'northern' : 'southern'} hemisphere.`
);
});
```

@@ -108,7 +139,9 @@ import { derived } from 'svelte/store';
const doubled = derived(a, ($a) => $a * 2);
```

The callback can set a value asynchronously by accepting a second argument, `set`, and an optional third argument, `update`, calling either or both of them when appropriate.
The `derive_value` function can set values asynchronously by accepting a second argument, `set`, and an optional third argument, `update`, and calling either or both of these functions when appropriate.

> If `set` and `update` are, in combination, called multiple times synchronously, only the last change will cause the store's subscribers to be notified. For instance, calling `update` and then `set` synchronously in a `derive_value` function will only cause the value passed to `set` to be sent to subscribers.

In this case, you can also pass a third argument to `derived` — the initial value of the derived store before `set` or `update` is first called. If no initial value is specified, the store's initial value will be `undefined`.

@@ -123,7 +156,7 @@ declare global {
export {};

// @filename: index.ts
// @errors: 18046 2769 7006
// @errors: 18046 2769 7006 2722
// ---cut---
import { derived } from 'svelte/store';

@@ -143,7 +176,7 @@ const delayedIncrement = derived(a, ($a, set, update) => {
});
```

If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.
If you return a function from the `derive_value` function, it will be called a) before the function runs again, or b) after the last subscriber unsubscribes.

```ts
// @filename: ambient.d.ts
@@ -188,7 +221,6 @@ declare global {
export {};

// @filename: index.ts

// ---cut---
import { derived } from 'svelte/store';

@@ -199,13 +231,75 @@ const delayed = derived([a, b], ([$a, $b], set) => {
});
```

### TypeScript type inference

If a multi-argument `derive_value` function is passed to `derive`, TypeScript may not be able to infer the type of the derived store, yielding a store of type `Readable<unknown>`. Set an initial value for the store to resolve this; `undefined` with a type assertion is sufficient. Alternatively, you may use type arguments, although this requires specifying the types of the dependency stores, too.

```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';

declare global {
const a: Writable<number>;
}

export {};

// @filename: index.ts
// ---cut---
import { derived } from 'svelte/store';

// @errors: 2769
const aInc = derived(
a,
($a, set) => setTimeout(() => set($a + 1), 1000),
undefined as unknown as number
);

const concatenated = derived<[number, number], string>([a, aInc], ([$a, $aInc], set) =>
setTimeout(() => set(`${$a}${$aInc}`), 1000)
);
```

`derived` can derive new stores from stores not created by Svelte, including from RxJS `Observable`s. In this case, TypeScript may not be able to infer the types of data held by the dependency stores. Use a type assertion to `ExternalStore` or a type argument to provide the missing context.

Until TypeScript gains support for [partial type argument inference](https://github.com/microsoft/TypeScript/issues/26242), the latter option requires also specifying the return type of `derive_store`.

```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';

declare global {
const a: Writable<number>;
const observable: {
subscribe: (fn: (value: unknown) => void) => { unsubscribe: () => void };
};
}

export {};

// @filename: index.ts
// ---cut---
import { derived, type ExternalStore } from 'svelte/store';

const sum = derived(
[a, observable as ExternalStore<number>],
([$a, $observable]) => $a + $observable
);

const sumMore = derived<[number, number], number>(
[sum, observable],
([$sum, $observable]) => $sum + $observable
);
```

## `readonly`

> EXPORT_SNIPPET: svelte/store#readonly

This simple helper function makes a store readonly. You can still subscribe to the changes from the original one using this new readable store.

```js
```ts
import { readonly, writable } from 'svelte/store';

const writableStore = writable(1);
@@ -224,7 +318,7 @@ readableStore.set(2); // ERROR

Generally, you should read the value of a store by subscribing to it and using the value as it changes over time. Occasionally, you may need to retrieve the value of a store to which you're not subscribed. `get` allows you to do so.

> This works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.
> By default, `get` subscribes to the given store, makes note of its value, then unsubscribes again. Passing `true` as a second argument causes `get` to directly read the internal state of the store instead, which, in the case of a derived store, may be outdated or `undefined`. Where performance is important, it's recommended to set `allow_stale` to `true` or not use `get`.

```ts
// @filename: ambient.d.ts
593 changes: 428 additions & 165 deletions packages/svelte/src/store/index.js

Large diffs are not rendered by default.

37 changes: 27 additions & 10 deletions packages/svelte/src/store/private.d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
import { Readable, Subscriber } from './public.js';
import { Updater, Subscriber, ExternalReadable, Readable, Writable } from './public.js';

/** Cleanup logic callback. */
export type Invalidator<T> = (value?: T) => void;
/** An object with `set` and `update` methods that only work if the object's `enabled` property is
* `true` */
export type DisableableSetterUpdater<T> = {
enabled: boolean;
set: (value: T) => void;
update: (fn: Updater<T>) => void;
};

/** Pair of subscriber and invalidator. */
export type SubscribeInvalidateTuple<T> = [Subscriber<T>, Invalidator<T>];
/** A tuple of a function which is called when a store's value changes and a function which is
* called shortly before the first to enable proper order of evaluation. */
export type SubscriberInvalidator<T> = [(value: T, isChanged?: boolean) => void, () => void];

/** One or more `Readable`s. */
/** An `Array` of all subscribers to a store. */
export type Subscribers<T> = Array<Subscriber<T> | SubscriberInvalidator<T>>;

/** One or more `Readable` or `ExternalReadable` stores. The spread syntax is important for
* `StoresValues` to work. */
export type Stores =
| Readable<any>
| [Readable<any>, ...Array<Readable<any>>]
| Array<Readable<any>>;
| ExternalReadable<any>
| [Readable<any> | ExternalReadable<any>, ...Array<Readable<any> | ExternalReadable<any>>];

/** One or more values from `Readable` stores. */
export type StoresValues<T> =
T extends Readable<infer U> ? U : { [K in keyof T]: T[K] extends Readable<infer U> ? U : never };
export type StoresValues<T> = T extends Readable<infer U> | ExternalReadable<infer U>
? U
: {
[K in keyof T]: T[K] extends Readable<infer U> | ExternalReadable<infer U> ? U : never;
};

/** A special case of `OnStart` created by `derived` when subscribing to other stores created by
* this module. */
export type DerivedOnStart<T> = (store: Writable<T>) => () => void;
80 changes: 36 additions & 44 deletions packages/svelte/src/store/public.d.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,43 @@
import type { Invalidator } from './private.js';
import { SubscriberInvalidator, Stores, StoresValues } from './private.js';

/** Callback to inform of a value updates. */
export type Subscriber<T> = (value: T) => void;

/** Unsubscribes from value updates. */
export type Unsubscriber = () => void;
/** A function which sets a store's value. */
export type Setter<T> = (value: T) => void;

/** Callback to update a value. */
/** A function which returns a new value for a store derived from its current value. */
export type Updater<T> = (value: T) => T;

/**
* Start and stop notification callbacks.
* This function is called when the first subscriber subscribes.
*
* @param {(value: T) => void} set Function that sets the value of the store.
* @param {(value: Updater<T>) => void} update Function that sets the value of the store after passing the current value to the update function.
* @returns {void | (() => void)} Optionally, a cleanup function that is called when the last remaining
* subscriber unsubscribes.
*/
export type StartStopNotifier<T> = (
set: (value: T) => void,
/** A function which is called when a store's value changes. */
export type Subscriber<T> = (value: T) => void;

/** A store not created by this module, e.g., an RxJS `Observable`. */
export type ExternalReadable<T = unknown> = {
subscribe: (subscriber: Subscriber<T>) => (() => void) | { unsubscribe: () => void };
};

/** A store created by this module which can be subscribed to. */
export type Readable<T> = {
subscribe: (subscriber: Subscriber<T> | SubscriberInvalidator<T>) => () => void;
};

/** A store which can be subscribed to and has `set` and `update` methods. */
export type Writable<T> = Readable<T> & {
set: Setter<T>;
update: (fn: Updater<T>) => void;
};

/** A function which is called whenever a store receives its first subscriber, and whose return
* value, if a function, is called when the same store loses its last subscriber. */
export type OnStart<T> = (set: Setter<T>, update: (fn: Updater<T>) => void) => void | (() => void);

/** A function which derives a value from the dependency stores' values and optionally calls the
* passed `set` or `update` functions to change the store. */
export type ComplexDeriveValue<S, T> = (
values: S extends Stores ? StoresValues<S> : S,
set: Setter<T>,
update: (fn: Updater<T>) => void
) => void | (() => void);

/** Readable interface for subscribing. */
export interface Readable<T> {
/**
* Subscribe on value changes.
* @param run subscription callback
* @param invalidate cleanup callback
*/
subscribe(this: void, run: Subscriber<T>, invalidate?: Invalidator<T>): Unsubscriber;
}

/** Writable interface for both updating and subscribing. */
export interface Writable<T> extends Readable<T> {
/**
* Set value and inform subscribers.
* @param value to set
*/
set(this: void, value: T): void;

/**
* Update value using callback and inform subscribers.
* @param updater callback
*/
update(this: void, updater: Updater<T>): void;
}

export * from './index.js';
/** A function which derives a value from the dependency stores' values and returns it. */
export type SimpleDeriveValue<S, T> = (values: S extends Stores ? StoresValues<S> : S) => T;

export { writable, readable, derived, readonly, get } from './index.js';
338 changes: 278 additions & 60 deletions packages/svelte/tests/store/test.ts
Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@ describe('writable', () => {
assert.deepEqual(values, [0, 1, 2]);
});

it('creates an undefined writable store', () => {
it('creates an `undefined` writable store', () => {
const store = writable();

const values: unknown[] = [];
@@ -41,7 +41,9 @@ describe('writable', () => {

const store = writable(0, () => {
called += 1;
return () => (called -= 1);
return () => {
called -= 1;
};
});

const unsubscribe1 = store.subscribe(() => {});
@@ -81,22 +83,43 @@ describe('writable', () => {
let count1 = 0;
let count2 = 0;

store.subscribe(() => (count1 += 1))();
store.subscribe(() => {
count1 += 1;
})();
assert.equal(count1, 1);

const unsubscribe = store.subscribe(() => (count2 += 1));
const unsubscribe = store.subscribe(() => {
count2 += 1;
});
assert.equal(count2, 1);

unsubscribe();
});

it('no error even if unsubscribe calls twice', () => {
it('does not throw an error if `unsubscribe` is called more than once', () => {
let num = 0;
const store = writable(num, (set) => set((num += 1)));
const unsubscribe = store.subscribe(() => {});
unsubscribe();
assert.doesNotThrow(() => unsubscribe());
});

it('allows multiple subscriptions of one handler', () => {
let call_count = 0;

const value = writable(1);

const handle_new_value = () => {
call_count += 1;
};
const unsubscribers = [1, 2, 3].map((_) => value.subscribe(handle_new_value));

assert.equal(call_count, 3);
value.set(2);
assert.equal(call_count, 6);

for (const unsubscribe of unsubscribers) unsubscribe();
});
});

describe('readable', () => {
@@ -139,7 +162,7 @@ describe('readable', () => {
assert.deepEqual(values, [0, 1, 2]);
});

it('passes an optional update function', () => {
it('passes an optional `update` function', () => {
let running;

let tick = (value: any) => {};
@@ -186,7 +209,7 @@ describe('readable', () => {
assert.deepEqual(values, [0, 1, 2, 5, 9, 5, 11]);
});

it('creates an undefined readable store', () => {
it('creates an `undefined` readable store', () => {
const store = readable();

const values: unknown[] = [];
@@ -228,7 +251,6 @@ const fake_observable = {
describe('derived', () => {
it('maps a single store', () => {
const a = writable(1);

const b = derived(a, (n) => n * 2);

const values: number[] = [];
@@ -249,7 +271,6 @@ describe('derived', () => {
it('maps multiple stores', () => {
const a = writable(2);
const b = writable(3);

const c = derived([a, b], ([a, b]) => a * b);

const values: number[] = [];
@@ -268,11 +289,46 @@ describe('derived', () => {
assert.deepEqual(values, [6, 12, 20]);
});

it('passes optional set function', () => {
it('allows derived with different types', () => {
const a = writable('one');
const b = writable(1);
const c = derived([a, b], ([a, b]) => `${a} ${b}`);

assert.deepEqual(get(c), 'one 1');

a.set('two');
b.set(2);
assert.deepEqual(get(c), 'two 2');
});

it('errors on undefined stores #1', () => {
assert.throws(() => {
// @ts-expect-error `null` and `undefined` should create type errors, but this code is testing
// that the implementation also throws an error.
derived(null, (n) => n);
});
});

it('errors on undefined stores #2', () => {
assert.throws(() => {
const a = writable(1);
// @ts-expect-error `null` and `undefined` should create type errors, but this code is testing
// that the implementation also throws an error.
derived([a, null, undefined], ([n]) => {
return n * 2;
});
});
});

it('works with RxJS-style observables', () => {
const d = derived(fake_observable, (_) => _);
assert.equal(get(d), 42);
});

it('passes optional `set` function', () => {
const number = writable(1);
const evens = derived(
number,
// @ts-expect-error TODO feels like inference should work here
(n, set) => {
if (n % 2 === 0) set(n);
},
@@ -299,22 +355,20 @@ describe('derived', () => {
assert.deepEqual(values, [0, 2, 4]);
});

it('passes optional set and update functions', () => {
it('passes optional `set` and `update` functions', () => {
const number = writable(1);
const evensAndSquaresOf4 = derived(
const evens_and_squares_of_4 = derived(
number,
// @ts-expect-error TODO feels like inference should work here
(n, set, update) => {
if (n % 2 === 0) set(n);
// @ts-expect-error TODO feels like inference should work here
if (n % 4 === 0) update((n) => n * n);
},
0
);

const values: number[] = [];

const unsubscribe = evensAndSquaresOf4.subscribe((value) => {
const unsubscribe = evens_and_squares_of_4.subscribe((value) => {
values.push(value);
});

@@ -323,44 +377,62 @@ describe('derived', () => {
number.set(4);
number.set(5);
number.set(6);
assert.deepEqual(values, [0, 2, 4, 16, 6]);
assert.deepEqual(values, [0, 2, 16, 6]);

number.set(7);
number.set(8);
number.set(9);
number.set(10);
assert.deepEqual(values, [0, 2, 4, 16, 6, 8, 64, 10]);
assert.deepEqual(values, [0, 2, 16, 6, 64, 10]);

unsubscribe();

number.set(11);
number.set(12);
assert.deepEqual(values, [0, 2, 4, 16, 6, 8, 64, 10]);
assert.deepEqual(values, [0, 2, 16, 6, 64, 10]);
});

it('prevents glitches', () => {
const lastname = writable('Jekyll');

const firstname = derived(lastname, (n) => (n === 'Jekyll' ? 'Henry' : 'Edward'));

const fullname = derived([firstname, lastname], (names) => names.join(' '));
const last_name = writable('Jekyll');
const first_name = derived(last_name, (n) => (n === 'Jekyll' ? 'Henry' : 'Edward'));
const full_name = derived([first_name, last_name], (names) => names.join(' '));

const values: string[] = [];

const unsubscribe = fullname.subscribe((value) => {
const unsubscribe = full_name.subscribe((value) => {
values.push(value as string);
});

lastname.set('Hyde');
last_name.set('Hyde');

assert.deepEqual(values, ['Henry Jekyll', 'Edward Hyde']);

unsubscribe();
});

it('only calls `derive_value` when necessary', () => {
let call_count = 0;

const sequence = writable(['a', 'b']);
const length = derived(sequence, ($sequence) => {
call_count += 1;
return $sequence.length;
});

assert.equal(call_count, 0);

const unsubscribes = [
length.subscribe(() => {}),
length.subscribe(() => {}),
length.subscribe(() => {})
];
assert.equal(call_count, 1);

for (const unsubscribe of unsubscribes) unsubscribe();
});

it('prevents diamond dependency problem', () => {
const count = writable(0);

const values: string[] = [];

const a = derived(count, ($count) => {
@@ -387,6 +459,169 @@ describe('derived', () => {
unsubscribe();
});

it('avoids premature updates of dependent stores on invalid state', () => {
const values: number[] = [];

const sequence = writable(['a', 'b']);
const length = derived(sequence, ($sequence) => $sequence.length);
const lengths_sum = derived(
[sequence, length],
([$sequence, $length]) => $sequence.length + $length
);

const unsubscribe = lengths_sum.subscribe((value) => values.push(value));

assert.deepEqual(values, [4]);
sequence.set(['a', 'b', 'c']);
assert.deepEqual(values, [4, 6]);

unsubscribe();
});

it('avoids premature updates of dependent stores on invalid state', () => {
const values: number[] = [];

const sequence = writable(['a', 'b']);
const length = derived(sequence, ($sequence) => $sequence.length);
const length_dec = derived(length, ($length) => $length - 1);
const lengths_sum = derived(
[sequence, length_dec],
([$sequence, $length_dec]) => $sequence.length + $length_dec
);

const unsubscribe = lengths_sum.subscribe((value) => values.push(value));

assert.deepEqual(values, [3]);
sequence.set(['a', 'b', 'c']);
assert.deepEqual(values, [3, 5]);

unsubscribe();
});

it('avoids premature updates of dependent stores on invalid state', () => {
const values: string[] = [];

const length = writable(2);
const length_dec = derived(length, ($length) => $length - 1);
const length_dec_inc = derived(length_dec, ($length_dec) => $length_dec + 1);
const sequence = derived(length_dec_inc, ($length_dec_inc) =>
[...Array($length_dec_inc)].map((_, i) => i)
);
const last_as_string = derived([length_dec_inc, sequence], ([$length_dec_inc, $sequence]) =>
$sequence[$length_dec_inc - 1].toString()
);

const unsubscribe = last_as_string.subscribe((value) => values.push(value));

assert.deepEqual(values, ['1']);
length.set(3);
assert.deepEqual(values, ['1', '2']);

unsubscribe();
});

it('does not freeze when depending on an asynchronous store', () => {
const values: number[] = [];

const noop = () => {};
// `do_later` allows deferring store updates in `length_delayed` without having to handle
// strictly asynchronous execution.
let do_later = noop;

const length = writable(1);
const length_delayed = derived(
length,
($length, set) => {
do_later = () => {
set($length);
};
return () => {
do_later = noop;
};
},
0
);
const lengths_derivative = derived(
[length, length_delayed],
([$length, $length_delayed]) => $length * 3 - $length_delayed
);

const unsubscribe = lengths_derivative.subscribe((value) => values.push(value));

if (typeof do_later === 'function') do_later();
length.set(2);
length.set(3);
length.set(4);
if (typeof do_later === 'function') do_later();
if (typeof do_later === 'function') do_later();
assert.deepEqual(values, [3, 2, 5, 8, 11, 8]);

unsubscribe();
});

it('disables `set` and `update` functions during `on_start` clean-up (`on_stop`)', () => {
const noop = () => {};
// `do_later()` allows deferring store updates in `length_delayed` without having to handle
// strictly asynchronous execution.
let do_later = noop;

const length = readable(0, (set) => {
if (do_later === noop) do_later = () => set(1);
// No clean-up function is returned, so `do_later()` remains set even after it should.
});

assert.equal(get(length, true), 0);

const unsubscribe = length.subscribe(noop);
unsubscribe();

assert.equal(get(length, true), 0);
if (typeof do_later === 'function') do_later();
assert.equal(get(length, true), 0);

// The original `set()` is still disabled even after re-subscribing, since `set` and `update`
// are created anew each time.
const unsubscribe_2 = length.subscribe(noop);
if (typeof do_later === 'function') do_later();
assert.equal(get(length, true), 0);

unsubscribe_2();
});

it('disables `set` and `update` functions during `derived` clean-up', () => {
const noop = () => {};
// `do_later()` allows deferring store updates in `length_delayed` without having to handle
// strictly asynchronous execution.
let do_later = noop;

const length = writable(1);
const length_delayed = derived(
length,
($length, _, update) => {
if (do_later === noop) do_later = () => update((_) => $length);
// No clean-up function is returned, so `do_later()` remains set even after it should.
},
0
);

assert.equal(get(length_delayed, true), 0);

const unsubscribe = length_delayed.subscribe(noop);
unsubscribe();

assert.equal(get(length_delayed, true), 0);
if (typeof do_later === 'function') do_later();
assert.equal(get(length_delayed, true), 0);

// The original `update()` is still disabled even after re-subscribing, since `set` and `update`
// are created anew each time.
const unsubscribe_2 = length.subscribe(noop);
if (typeof do_later === 'function') do_later();
assert.equal(get(length_delayed, true), 0);

unsubscribe_2();
});

it('derived dependency does not update and shared ancestor updates', () => {
const root = writable({ a: 0, b: 0 });

@@ -412,7 +647,7 @@ describe('derived', () => {
unsubscribe();
});

it('is updated with safe_not_equal logic', () => {
it('is updated with `safe_not_equal` logic', () => {
const arr = [0];

const number = writable(1);
@@ -436,17 +671,16 @@ describe('derived', () => {
unsubscribe();
});

it('calls a cleanup function', () => {
it('calls an `on_stop` function', () => {
const num = writable(1);

const values: number[] = [];
const cleaned_up: number[] = [];

// @ts-expect-error TODO feels like inference should work here
const d = derived(num, ($num, set) => {
set($num * 2);

return function cleanup() {
return function on_stop() {
cleaned_up.push($num);
};
});
@@ -473,7 +707,10 @@ describe('derived', () => {

const values: number[] = [];

// @ts-expect-error TODO feels like inference should work here
// @ts-expect-error Returning a non-function value from `derive_value` forces TypeScript to
// assume the function is a `SimpleDeriveValue<S, T>` as opposed to a `ComplexDeriveValue<S,
// T>`. Since the value will be discarded by the implementation, showing a type error is
// justified.
const d = derived(num, ($num, set) => {
set($num * 2);
return {};
@@ -507,7 +744,6 @@ describe('derived', () => {
});

it('works with RxJS-style observables', () => {
// @ts-expect-error TODO feels like inference should work here
const d = derived(fake_observable, (_) => _);
assert.equal(get(d), 42);
});
@@ -516,7 +752,6 @@ describe('derived', () => {
const a = writable(true);
let b_started = false;

// @ts-expect-error TODO feels like inference should work here
const b = derived(a, (_, __) => {
b_started = true;
return () => {
@@ -525,7 +760,6 @@ describe('derived', () => {
};
});

// @ts-expect-error TODO feels like inference should work here
const c = derived(a, ($a, set) => {
if ($a) return b.subscribe(set);
});
@@ -534,23 +768,6 @@ describe('derived', () => {
a.set(false);
assert.equal(b_started, false);
});

it('errors on undefined stores #1', () => {
assert.throws(() => {
// @ts-expect-error TODO feels like inference should work here
derived(null, (n) => n);
});
});

it('errors on undefined stores #2', () => {
assert.throws(() => {
const a = writable(1);
// @ts-expect-error TODO feels like inference should work here
derived([a, null, undefined], ([n]) => {
return n * 2;
});
});
});
});

describe('get', () => {
@@ -566,17 +783,18 @@ describe('get', () => {

describe('readonly', () => {
it('makes a store readonly', () => {
const writableStore = writable(1);
const readableStore = readonly(writableStore);
const writable_store = writable(1);
const readable_store = readonly(writable_store);

assert.equal(get(readableStore), get(writableStore));
assert.equal(get(readable_store), get(writable_store));

writableStore.set(2);
writable_store.set(2);

assert.equal(get(readableStore), 2);
assert.equal(get(readableStore), get(writableStore));
assert.equal(get(readable_store), 2);
assert.equal(get(readable_store), get(writable_store));

// @ts-ignore
assert.throws(() => readableStore.set(3));
// @ts-expect-error This should create a type errors, but this code is testing that the
// implementation also throws an error.
assert.throws(() => readable_store.set(3));
});
});