cross-state 0.53.3 → 0.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-CUT6urMc.cjs +30 -0
- package/dist/diff-BQ8bB3Wk.d.cts +22 -0
- package/dist/diff-gZezL04N.d.ts +22 -0
- package/dist/extendedJson-BZkQBXEv.js +29 -0
- package/dist/extendedJson-BZkQBXEv.js.map +1 -0
- package/dist/extendedJson-Dn2F7Edo.cjs +53 -0
- package/dist/extendedJson-Dn2F7Edo.cjs.map +1 -0
- package/dist/hash-BV06P7va.js +19 -0
- package/dist/hash-BV06P7va.js.map +1 -0
- package/dist/hash-CJPl7SRj.cjs +30 -0
- package/dist/hash-CJPl7SRj.cjs.map +1 -0
- package/dist/index.cjs +49 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +59 -0
- package/dist/index.d.ts +59 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/mutative/index.cjs +3 -0
- package/dist/mutative/index.d.cts +3 -0
- package/dist/mutative/index.d.ts +3 -0
- package/dist/mutative/index.js +3 -0
- package/dist/mutative/register.cjs +10 -0
- package/dist/mutative/register.cjs.map +1 -0
- package/dist/mutative/register.d.cts +11 -0
- package/dist/mutative/register.d.ts +9 -0
- package/dist/mutative/register.js +10 -0
- package/dist/mutative/register.js.map +1 -0
- package/dist/mutativeMethods-6QzygG3W.d.cts +13 -0
- package/dist/mutativeMethods-Br3xN2Iq.d.ts +13 -0
- package/dist/mutativeMethods-CZKeRIDL.js +27 -0
- package/dist/mutativeMethods-CZKeRIDL.js.map +1 -0
- package/dist/mutativeMethods-CgXk_bMt.cjs +33 -0
- package/dist/mutativeMethods-CgXk_bMt.cjs.map +1 -0
- package/dist/patchMethods-C3L7Kh8T.d.cts +48 -0
- package/dist/patchMethods-D5YJwcpn.cjs +264 -0
- package/dist/patchMethods-D5YJwcpn.cjs.map +1 -0
- package/dist/patchMethods-DRPfkhAe.js +241 -0
- package/dist/patchMethods-DRPfkhAe.js.map +1 -0
- package/dist/patchMethods-Dxad6HF6.d.ts +48 -0
- package/dist/patches/index.cjs +5 -0
- package/dist/patches/index.d.cts +4 -0
- package/dist/patches/index.d.ts +4 -0
- package/dist/patches/index.js +5 -0
- package/dist/patches/register.cjs +11 -0
- package/dist/patches/register.cjs.map +1 -0
- package/dist/patches/register.d.cts +12 -0
- package/dist/patches/register.d.ts +10 -0
- package/dist/patches/register.js +11 -0
- package/dist/patches/register.js.map +1 -0
- package/dist/persist/register.cjs +13 -0
- package/dist/persist/register.cjs.map +1 -0
- package/dist/persist/register.d.cts +15 -0
- package/dist/persist/register.d.ts +13 -0
- package/dist/persist/register.js +13 -0
- package/dist/persist/register.js.map +1 -0
- package/dist/persist-BluRVcW6.js +258 -0
- package/dist/persist-BluRVcW6.js.map +1 -0
- package/dist/persist-CPjpg6D0.d.ts +61 -0
- package/dist/persist-CztClydq.cjs +263 -0
- package/dist/persist-CztClydq.cjs.map +1 -0
- package/dist/persist-D7MAsyyW.d.cts +61 -0
- package/dist/propAccess-ByqBjC19.cjs +173 -0
- package/dist/propAccess-ByqBjC19.cjs.map +1 -0
- package/dist/propAccess-DGchzVfy.js +113 -0
- package/dist/propAccess-DGchzVfy.js.map +1 -0
- package/dist/react/index.cjs +610 -0
- package/dist/react/index.cjs.map +1 -0
- package/dist/react/index.d.cts +305 -0
- package/dist/react/index.d.ts +305 -0
- package/dist/react/index.js +590 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/register.cjs +16 -0
- package/dist/react/register.cjs.map +1 -0
- package/dist/react/register.d.cts +16 -0
- package/dist/react/register.d.ts +14 -0
- package/dist/react/register.js +16 -0
- package/dist/react/register.js.map +1 -0
- package/dist/scope-DI1OFHcr.d.ts +167 -0
- package/dist/scope-DO5vpLPV.d.cts +167 -0
- package/dist/scope-DU5dFP1T.js +322 -0
- package/dist/scope-DU5dFP1T.js.map +1 -0
- package/dist/scope-DvqvkIHB.cjs +369 -0
- package/dist/scope-DvqvkIHB.cjs.map +1 -0
- package/dist/store-BEsiS8y7.d.cts +242 -0
- package/dist/store-BWMWEUpu.cjs +819 -0
- package/dist/store-BWMWEUpu.cjs.map +1 -0
- package/dist/store-DKaeE840.d.ts +242 -0
- package/dist/store-Dr8gM3lq.js +730 -0
- package/dist/store-Dr8gM3lq.js.map +1 -0
- package/dist/storeMethods-AIJSwxHz.js +315 -0
- package/dist/storeMethods-AIJSwxHz.js.map +1 -0
- package/dist/storeMethods-BQwU2Uia.d.cts +107 -0
- package/dist/storeMethods-C4luym7C.d.ts +107 -0
- package/dist/storeMethods-DVVsmUg1.cjs +375 -0
- package/dist/storeMethods-DVVsmUg1.cjs.map +1 -0
- package/package.json +92 -135
- package/dist/cjs/hash.cjs +0 -30
- package/dist/cjs/hash.cjs.map +0 -1
- package/dist/cjs/index.cjs +0 -56
- package/dist/cjs/index.cjs.map +0 -1
- package/dist/cjs/index2.cjs +0 -300
- package/dist/cjs/index2.cjs.map +0 -1
- package/dist/cjs/mutative/index.cjs +0 -10
- package/dist/cjs/mutative/index.cjs.map +0 -1
- package/dist/cjs/mutative/register.cjs +0 -8
- package/dist/cjs/mutative/register.cjs.map +0 -1
- package/dist/cjs/mutativeMethods.cjs +0 -29
- package/dist/cjs/mutativeMethods.cjs.map +0 -1
- package/dist/cjs/patches/index.cjs +0 -10
- package/dist/cjs/patches/index.cjs.map +0 -1
- package/dist/cjs/patches/register.cjs +0 -8
- package/dist/cjs/patches/register.cjs.map +0 -1
- package/dist/cjs/persist/register.cjs +0 -11
- package/dist/cjs/persist/register.cjs.map +0 -1
- package/dist/cjs/persist.cjs +0 -302
- package/dist/cjs/persist.cjs.map +0 -1
- package/dist/cjs/propAccess.cjs +0 -162
- package/dist/cjs/propAccess.cjs.map +0 -1
- package/dist/cjs/react/index.cjs +0 -628
- package/dist/cjs/react/index.cjs.map +0 -1
- package/dist/cjs/react/register.cjs +0 -13
- package/dist/cjs/react/register.cjs.map +0 -1
- package/dist/cjs/scope.cjs +0 -400
- package/dist/cjs/scope.cjs.map +0 -1
- package/dist/cjs/store.cjs +0 -829
- package/dist/cjs/store.cjs.map +0 -1
- package/dist/cjs/storeMethods.cjs +0 -856
- package/dist/cjs/storeMethods.cjs.map +0 -1
- package/dist/cjs/urlStore.cjs +0 -120
- package/dist/cjs/urlStore.cjs.map +0 -1
- package/dist/es/hash.mjs +0 -27
- package/dist/es/hash.mjs.map +0 -1
- package/dist/es/index.mjs +0 -20
- package/dist/es/index.mjs.map +0 -1
- package/dist/es/index2.mjs +0 -291
- package/dist/es/index2.mjs.map +0 -1
- package/dist/es/mutative/index.mjs +0 -2
- package/dist/es/mutative/index.mjs.map +0 -1
- package/dist/es/mutative/register.mjs +0 -6
- package/dist/es/mutative/register.mjs.map +0 -1
- package/dist/es/mutativeMethods.mjs +0 -27
- package/dist/es/mutativeMethods.mjs.map +0 -1
- package/dist/es/patches/index.mjs +0 -2
- package/dist/es/patches/index.mjs.map +0 -1
- package/dist/es/patches/register.mjs +0 -6
- package/dist/es/patches/register.mjs.map +0 -1
- package/dist/es/persist/register.mjs +0 -9
- package/dist/es/persist/register.mjs.map +0 -1
- package/dist/es/persist.mjs +0 -300
- package/dist/es/persist.mjs.map +0 -1
- package/dist/es/propAccess.mjs +0 -151
- package/dist/es/propAccess.mjs.map +0 -1
- package/dist/es/react/index.mjs +0 -611
- package/dist/es/react/index.mjs.map +0 -1
- package/dist/es/react/register.mjs +0 -11
- package/dist/es/react/register.mjs.map +0 -1
- package/dist/es/scope.mjs +0 -391
- package/dist/es/scope.mjs.map +0 -1
- package/dist/es/store.mjs +0 -812
- package/dist/es/store.mjs.map +0 -1
- package/dist/es/storeMethods.mjs +0 -845
- package/dist/es/storeMethods.mjs.map +0 -1
- package/dist/es/urlStore.mjs +0 -116
- package/dist/es/urlStore.mjs.map +0 -1
- package/dist/types/core/cache.d.ts +0 -119
- package/dist/types/core/commonTypes.d.ts +0 -76
- package/dist/types/core/index.d.ts +0 -6
- package/dist/types/core/resourceGroup.d.ts +0 -16
- package/dist/types/core/scope.d.ts +0 -5
- package/dist/types/core/store.d.ts +0 -86
- package/dist/types/core/urlStore.d.ts +0 -21
- package/dist/types/index.d.ts +0 -14
- package/dist/types/lib/applyPatches.d.ts +0 -2
- package/dist/types/lib/autobind.d.ts +0 -1
- package/dist/types/lib/cacheState.d.ts +0 -20
- package/dist/types/lib/calcDuration.d.ts +0 -2
- package/dist/types/lib/calculatedValue.d.ts +0 -9
- package/dist/types/lib/castArray.d.ts +0 -1
- package/dist/types/lib/clone.d.ts +0 -1
- package/dist/types/lib/constrain.d.ts +0 -1
- package/dist/types/lib/debounce.d.ts +0 -12
- package/dist/types/lib/deferred.d.ts +0 -5
- package/dist/types/lib/diff.d.ts +0 -17
- package/dist/types/lib/disposable.d.ts +0 -3
- package/dist/types/lib/equals.d.ts +0 -3
- package/dist/types/lib/extendedJson.d.ts +0 -5
- package/dist/types/lib/forwardError.d.ts +0 -1
- package/dist/types/lib/hash.d.ts +0 -5
- package/dist/types/lib/helpers.d.ts +0 -2
- package/dist/types/lib/instanceCache.d.ts +0 -18
- package/dist/types/lib/isPromise.d.ts +0 -1
- package/dist/types/lib/makeSelector.d.ts +0 -2
- package/dist/types/lib/maybePromise.d.ts +0 -1
- package/dist/types/lib/path.d.ts +0 -41
- package/dist/types/lib/promiseChain.d.ts +0 -5
- package/dist/types/lib/promiseWithCancel.d.ts +0 -8
- package/dist/types/lib/promiseWithState.d.ts +0 -9
- package/dist/types/lib/propAccess.d.ts +0 -7
- package/dist/types/lib/queue.d.ts +0 -11
- package/dist/types/lib/standardMethods.d.ts +0 -20
- package/dist/types/lib/throttle.d.ts +0 -2
- package/dist/types/lib/trackingProxy.d.ts +0 -2
- package/dist/types/lib/trie.d.ts +0 -11
- package/dist/types/lib/typeHelpers.d.ts +0 -12
- package/dist/types/lib/unwrapPromise.d.ts +0 -1
- package/dist/types/lib/updateHelpers.d.ts +0 -1
- package/dist/types/lib/wildcardMatch.d.ts +0 -3
- package/dist/types/mutative/index.d.ts +0 -1
- package/dist/types/mutative/mutativeMethods.d.ts +0 -11
- package/dist/types/mutative/register.d.ts +0 -7
- package/dist/types/patches/index.d.ts +0 -1
- package/dist/types/patches/patchMethods.d.ts +0 -44
- package/dist/types/patches/register.d.ts +0 -7
- package/dist/types/persist/index.d.ts +0 -3
- package/dist/types/persist/persist.d.ts +0 -40
- package/dist/types/persist/persistPathHelpers.d.ts +0 -6
- package/dist/types/persist/persistStorage.d.ts +0 -17
- package/dist/types/persist/register.d.ts +0 -9
- package/dist/types/react/cacheMethods.d.ts +0 -5
- package/dist/types/react/form/customInput.d.ts +0 -6
- package/dist/types/react/form/form.d.ts +0 -98
- package/dist/types/react/form/formField.d.ts +0 -68
- package/dist/types/react/form/formForEach.d.ts +0 -19
- package/dist/types/react/form/index.d.ts +0 -3
- package/dist/types/react/form/useFormAutosave.d.ts +0 -9
- package/dist/types/react/index.d.ts +0 -11
- package/dist/types/react/loadingBoundary.d.ts +0 -21
- package/dist/types/react/register.d.ts +0 -15
- package/dist/types/react/scope.d.ts +0 -24
- package/dist/types/react/scopeMethods.d.ts +0 -20
- package/dist/types/react/storeMethods.d.ts +0 -15
- package/dist/types/react/useCache.d.ts +0 -34
- package/dist/types/react/useDecoupledState.d.ts +0 -7
- package/dist/types/react/useProp.d.ts +0 -8
- package/dist/types/react/useStore.d.ts +0 -16
- package/dist/types/react/useUrlParamScope.d.ts +0 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["matches: Record<KeyType, any>","value","form","name","options","errors","options: FormOptions<TDraft, TOriginal>","form","lastDraft: TDraft | undefined","context: FormContext<TDraft, TOriginal>","Form","Component","UrlContext: Context<UrlContextType | undefined>","value","url","location","params","update","options: UrlOptions<T>","update","value","delayedUpdate: (value: T) => void"],"sources":["../../src/react/form/customInput.tsx","../../src/lib/wildcardMatch.ts","../../src/react/form/formField.tsx","../../src/react/form/formForEach.tsx","../../src/react/form/useFormAutosave.ts","../../src/react/form/form.tsx","../../src/react/url/urlContext.tsx","../../src/react/url/urlOptions.ts","../../src/react/url/urlHelpers.ts","../../src/react/url/useUrlParam.ts","../../src/react/url/urlStore.ts","../../src/react/useDecoupledState.ts"],"sourcesContent":["import type { ReactNode } from 'react';\n\nexport interface CustomInputProps extends React.HTMLAttributes<HTMLDivElement> {\n name: string;\n children?: ReactNode;\n}\n\nexport function CustomInput({ name, children, ...props }: CustomInputProps): React.JSX.Element {\n return (\n <div\n {...props}\n style={{\n position: 'relative',\n ...props.style,\n }}\n >\n {children}\n\n <input\n name={name}\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n opacity: 0,\n width: '100%',\n height: '100%',\n pointerEvents: 'none',\n }}\n />\n </div>\n );\n}\n","import { isObject } from '@lib/helpers';\nimport { type KeyType } from './path';\nimport { castArrayPath } from './propAccess';\n\nexport function wildcardMatch(s: KeyType[] | string, w: KeyType[] | string): boolean {\n if (typeof s === 'string') {\n s = castArrayPath(s);\n }\n\n if (typeof w === 'string') {\n w = castArrayPath(w);\n }\n\n return s.length === w.length && s.every((s, i) => w[i] === '*' || s === w[i]);\n}\n\nexport function getWildCardMatches(\n object: any,\n path: [KeyType, ...KeyType[]] | string,\n): Record<KeyType, any> {\n const matches: Record<KeyType, any> = {};\n const [first, second, ...rest] = castArrayPath(path);\n\n if (first === undefined) {\n throw new Error('Path is empty');\n }\n\n if (!Array.isArray(object) && !isObject(object)) {\n object = {};\n }\n\n for (const [key, value] of first !== '*' ? [[first, object[first]]] : Object.entries(object)) {\n if (first !== '*' && first !== key) {\n continue;\n }\n\n if (second === undefined) {\n matches[key] = value;\n continue;\n }\n\n for (const [subKey, subValue] of Object.entries(getWildCardMatches(value, [second, ...rest]))) {\n matches[`${key}.${subKey}`] = subValue;\n }\n }\n\n return matches;\n}\n","import { type PathAsString, type Value } from '@lib/path';\nimport {\n createElement,\n useEffect,\n useState,\n type Component,\n type ComponentPropsWithoutRef,\n type ReactNode,\n} from 'react';\nimport {\n getDerivedState,\n type Field,\n type Form,\n type FormContext,\n type FormInstance,\n} from './form';\n\nexport interface FormFieldComponentProps<TValue, TPath> {\n name: TPath;\n value: TValue;\n onChange: (event: { target: { value: TValue } } | TValue | undefined, ...args: any[]) => void;\n onBlur: (...args: any[]) => void;\n}\n\nexport type FormFieldInfos<TDraft, TOriginal, TPath extends string> = Field<\n TDraft,\n TOriginal,\n TPath\n> & {\n hasTriggeredValidations: boolean;\n};\n\ntype NativeInputType = 'input' | 'select' | 'textarea';\n\ntype PartialComponentType<P> =\n | (new (props: P, context?: any) => Component<P, any>)\n | ((props: P, context?: any) => ReactNode);\n\nexport type FormFieldComponent = NativeInputType | PartialComponentType<any>;\n\ntype FieldValue<T extends FormFieldComponent> = ComponentPropsWithoutRef<T>['value'];\n\ntype FieldChangeValue<T extends FormFieldComponent> =\n ComponentPropsWithoutRef<T> extends {\n onChange?: (update: infer U) => void;\n }\n ? U extends { target: { value: infer V } }\n ? V\n : U\n : never;\n\ntype MakeOptional<T, Keys extends string> = Omit<T, Keys> & Partial<Pick<T, Keys & keyof T>>;\n\nexport type FormFieldProps<TPath, TDraft> = {\n name: TPath & PathAsString<TDraft>;\n commitOnBlur?: boolean;\n commitDebounce?: number;\n};\n\nexport type FormFieldPropsWithRender<TDraft, TOriginal, TPath extends string> = FormFieldProps<\n TPath,\n TDraft\n> &\n NoInfer<{\n component?: undefined;\n render: (\n props: FormFieldComponentProps<Value<TDraft, TPath>, TPath>,\n info: FormFieldInfos<TDraft, TOriginal, TPath>,\n form: FormContext<TDraft, TOriginal>,\n ) => ReactNode;\n inputFilter?: undefined;\n defaultValue?: undefined;\n serialize?: undefined;\n deserialize?: undefined;\n onChange?: undefined;\n onBlur?: undefined;\n }>;\n\ntype Serialize<TDraft, TOriginal, TPath, TComponent extends FormFieldComponent> = (\n value: Value<TDraft, TPath>,\n formState: FormInstance<TDraft, TOriginal>,\n) => FieldValue<TComponent>;\n\ntype Deserialize<TDraft, TOriginal, TPath, TComponent extends FormFieldComponent> = (\n value: FieldChangeValue<TComponent>,\n formState: FormInstance<TDraft, TOriginal>,\n) => Value<TDraft, TPath>;\n\nexport type FormFieldPropsWithComponent<\n TDraft,\n TOriginal,\n TPath extends string,\n TComponent extends FormFieldComponent,\n> = FormFieldProps<TPath, TDraft> & {\n component?: TComponent;\n render?: undefined;\n} & NoInfer<\n {\n inputFilter?: (value: FieldChangeValue<TComponent>) => boolean;\n } & MakeOptional<\n Omit<ComponentPropsWithoutRef<TComponent>, 'id' | 'name' | 'value' | 'defaultValue'>,\n 'onChange' | 'onBlur'\n > &\n (Value<TDraft, TPath> extends Exclude<FieldValue<TComponent>, undefined>\n ? {\n defaultValue?: FieldValue<TComponent>;\n serialize?: Serialize<TDraft, TOriginal, TPath, TComponent>;\n }\n : Value<TDraft, TPath> extends FieldValue<TComponent>\n ?\n | {\n defaultValue: FieldValue<TComponent>;\n serialize?: Serialize<TDraft, TOriginal, TPath, TComponent>;\n }\n | {\n defaultValue?: FieldValue<TComponent>;\n serialize: Serialize<TDraft, TOriginal, TPath, TComponent>;\n }\n : {\n serialize: Serialize<TDraft, TOriginal, TPath, TComponent>;\n }) &\n (FieldChangeValue<TComponent> extends Value<TDraft, TPath>\n ? {\n deserialize?: Deserialize<TDraft, TOriginal, TPath, TComponent>;\n }\n : {\n deserialize: Deserialize<TDraft, TOriginal, TPath, TComponent>;\n })\n >;\n\nexport function FormField<\n TDraft,\n TOriginal,\n TPath extends string,\n TComponent extends FormFieldComponent,\n>(\n this: Form<TDraft, any>,\n {\n // id,\n name = '' as any,\n component,\n commitOnBlur,\n commitDebounce,\n render,\n inputFilter,\n defaultValue,\n serialize,\n deserialize = (x) => x as Value<TDraft, TPath>,\n onChange,\n onBlur,\n ...restProps\n }:\n | FormFieldPropsWithRender<TDraft, TOriginal, TPath>\n | FormFieldPropsWithComponent<TDraft, TOriginal, TPath, TComponent>,\n): React.JSX.Element | null {\n type T = FieldChangeValue<TComponent>;\n\n const form = this.useForm();\n const getFormState = () => ({ ...form, ...getDerivedState(form) });\n const [localValue, setLocalValue] = useState<T>();\n\n const value = this.useFormState((form) => {\n const value = form.getField(name as any).value;\n if (serialize) {\n return serialize(value as any, getFormState());\n }\n if (value !== undefined) {\n return value;\n }\n return defaultValue;\n });\n\n const setValue = (x: FieldChangeValue<TComponent>) =>\n form.getField(name as any).setValue(deserialize(x, getFormState()));\n\n const hasTriggeredValidations = this.useFormState((form) => form.hasTriggeredValidations);\n\n useEffect(() => {\n if (localValue === undefined || !commitDebounce) {\n return;\n }\n\n const timeout = setTimeout(() => {\n setValue(localValue);\n setLocalValue(undefined);\n }, commitDebounce);\n\n return () => clearTimeout(timeout);\n }, [localValue, commitDebounce]);\n\n const props = {\n name,\n value: localValue ?? value,\n onChange: (event: { target: { value: T } } | T, ...moreArgs: any[]) => {\n const value =\n typeof event === 'object' && event !== null && 'target' in event\n ? event.target.value\n : event;\n\n if (inputFilter && !inputFilter(value)) {\n return;\n }\n\n if (commitOnBlur || commitDebounce) {\n setLocalValue(value);\n } else {\n setValue(value);\n }\n\n onChange?.(event, ...moreArgs);\n },\n onBlur(...args: any[]) {\n if (localValue !== undefined) {\n setValue(localValue);\n setLocalValue(undefined);\n }\n\n onBlur?.(...args);\n },\n } as FormFieldComponentProps<Value<TDraft, TPath>, TPath>;\n\n if (render) {\n return (\n <>\n {render(props, { ...form.getField(name as any), hasTriggeredValidations } as any, form) ??\n null}\n </>\n );\n }\n\n if (component) {\n return createElement(component, { ...restProps, ...props });\n }\n\n return null;\n}\n","import { type GetKeys, type Join, type PathAsString, type Value } from '@lib/path';\nimport { Fragment, useCallback, type ReactNode } from 'react';\nimport { type FieldHelperMethods, type Form } from './form';\n\nexport type ElementName<TDraft, TPath extends string> = keyof {\n [Path in TPath as Join<Path, GetKeys<NonNullable<Value<TDraft, Path>>> & (string | number)>]: 1;\n};\n\nexport interface FormForEachProps<TDraft, TPath extends string> {\n name: TPath & PathAsString<TDraft>;\n renderElement?: (props: {\n name: ElementName<TDraft, TPath>;\n key: `${GetKeys<NonNullable<Value<TDraft, TPath>>> & (string | number)}`;\n index: number;\n remove: () => void;\n }) => ReactNode;\n children?: (\n props: {\n setValue: (\n value: Value<TDraft, TPath> | ((value: Value<TDraft, TPath>) => Value<TDraft, TPath>),\n ) => void;\n } & FieldHelperMethods<TDraft, TPath>,\n ) => ReactNode;\n}\n\nexport function FormForEach<TDraft, TPath extends string>(\n this: Form<TDraft, any>,\n { name, renderElement, children }: FormForEachProps<TDraft, TPath>,\n): React.JSX.Element {\n const form = this.useForm();\n\n const names = this.useFormState(() => {\n const field = form.getField(name as any) as any;\n return field.names as any[];\n });\n\n const add = useCallback(\n (...args: any[]) => {\n const field = form.getField(name as any) as any;\n field.add(...args);\n },\n [form],\n );\n\n const remove = useCallback(\n (key: any) => {\n const field = form.getField(name as any) as any;\n field.remove(key);\n },\n [form],\n );\n\n const setValue = useCallback(\n (value: Value<TDraft, TPath> | ((value: Value<TDraft, TPath>) => Value<TDraft, TPath>)) => {\n const field = form.getField(name as any) as any;\n field.setValue(value);\n },\n [form],\n );\n\n return (\n <>\n {renderElement &&\n names.map((name, index) => {\n const key = name.split('.').pop();\n\n return (\n <Fragment key={key}>\n {renderElement({\n name,\n key,\n index,\n remove: () => remove(key),\n })}\n </Fragment>\n );\n })}\n\n {children?.({\n names,\n add,\n remove,\n setValue,\n } as any)}\n </>\n );\n}\n","import type { Duration } from '@core';\nimport { calcDuration } from '@lib/calcDuration';\nimport { debounce } from '@lib/debounce';\nimport { deepEqual } from '@lib/equals';\nimport type { MaybePromise } from '@lib/maybePromise';\nimport { queue } from '@lib/queue';\nimport { useEffect, useMemo, useRef } from 'react';\nimport type { FormContext } from './form';\n\nexport interface FormAutosaveOptions<TDraft, TOriginal> {\n save: (draft: TDraft, form: FormContext<TDraft, TOriginal>) => MaybePromise<void>;\n debounce?: Duration;\n resetAfterSave?: boolean;\n}\n\nexport function useFormAutosave<TDraft, TOriginal extends TDraft>(\n form: FormContext<TDraft, TOriginal>,\n): void {\n const { formState, options, getDraft } = form;\n const debounceTime = calcDuration(options.autoSave?.debounce ?? 2_000);\n const latestRef = useRef({ options });\n const lastValue = useRef<TDraft | undefined>(undefined);\n const q = useMemo(() => queue(), []);\n\n const run = useMemo(\n () =>\n debounce(async () => {\n const { options } = latestRef.current;\n const save = options.autoSave?.save;\n const draft = getDraft();\n\n lastValue.current = draft;\n\n q.clear();\n\n q(async () => {\n try {\n formState.set('saveInProgress', true);\n await save?.(draft, form);\n\n if (q.size === 0 && options.autoSave?.resetAfterSave) {\n form.reset();\n }\n } finally {\n formState.set('saveInProgress', false);\n\n if (q.size === 0) {\n formState.set('saveScheduled', false);\n }\n }\n });\n }, debounceTime),\n [formState, debounceTime],\n );\n\n useEffect(() => {\n if (!options.autoSave?.save) {\n return;\n }\n\n return formState\n .map((state) => state.draft)\n .subscribe(\n () => {\n if (deepEqual(getDraft(), lastValue.current)) {\n return;\n }\n\n run();\n formState.set('saveScheduled', true);\n },\n { runNow: false },\n );\n }, [formState]);\n\n useEffect(() => {\n latestRef.current = { options };\n });\n}\n","import { createStore, type Store, type Update } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { deepEqual } from '@lib/equals';\nimport { isObject } from '@lib/helpers';\nimport {\n type Path,\n type PathAsString,\n type Value,\n type WildcardPathAsString,\n type WildcardValue,\n} from '@lib/path';\nimport { get, join, set } from '@lib/propAccess';\nimport type { Object_ } from '@lib/typeHelpers';\nimport { getWildCardMatches } from '@lib/wildcardMatch';\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n type Context,\n type FormEvent,\n type FunctionComponent,\n type HTMLProps,\n type ReactNode,\n} from 'react';\nimport { useStore, type UseStoreOptions } from '../useStore';\nimport {\n FormField,\n type FormFieldComponent,\n type FormFieldPropsWithComponent,\n type FormFieldPropsWithRender,\n} from './formField';\nimport { FormForEach, type ElementName, type FormForEachProps } from './formForEach';\nimport { useFormAutosave, type FormAutosaveOptions } from './useFormAutosave';\n\n/// /////////////////////////////////////////////////////////////////////////////\n// Form types\n/// /////////////////////////////////////////////////////////////////////////////\n\nexport type Transform<TDraft> = Path<TDraft> | '' extends infer TPath\n ? TPath extends TPath\n ? {\n update: (value: Value<TDraft, TPath>, store: Store<TDraft>) => void | TDraft;\n } & (TPath extends '' ? { trigger?: '' } : { trigger: TPath })\n : never\n : never;\n\nexport interface FormOptions<TDraft, TOriginal> {\n defaultValue: TDraft;\n validations?: Validations<TDraft, TOriginal>;\n localizeError?: (error: string, field: string) => string | undefined;\n autoSave?: FormAutosaveOptions<TDraft, TOriginal>;\n transform?: Transform<TDraft>[];\n validatedClass?: string;\n}\n\nexport type Validations<TDraft, TOriginal> = {\n [TPath in WildcardPathAsString<TDraft>]?: Record<string, Validation<TDraft, TOriginal, TPath>>;\n} & Record<string, Record<string, Validation<TDraft, TOriginal, any>>>;\n\nexport type Validation<TDraft, TOriginal, TPath> = (\n value: WildcardValue<TDraft, TPath>,\n context: {\n draft: TDraft;\n original: TOriginal;\n field: PathAsString<TDraft> | '';\n },\n) => boolean;\n\nexport type Field<TDraft, TOriginal, TPath extends string> = {\n originalValue: Value<TOriginal, TPath> | undefined;\n value: Value<TDraft, TPath>;\n setValue: (value: Update<Value<TDraft, TPath>>) => void;\n hasChange: boolean;\n errors: string[];\n} & (Value<TDraft, TPath> extends Object_ ? FieldHelperMethods<TDraft, TPath> : {});\n\nexport type FieldHelperMethods<TDraft, TPath extends string> = {\n names: ElementName<TDraft, TPath>[];\n add: NonNullable<Value<TDraft, TPath>> extends readonly (infer T)[]\n ? (element: T) => void\n : NonNullable<Value<TDraft, TPath>> extends Record<infer K, infer V>\n ? (key: K, value: V) => void\n : never;\n remove: Value<TDraft, TPath> extends readonly any[]\n ? (index: number) => void\n : (key: string) => void;\n};\n\nexport interface FormState<TDraft> {\n draft: TDraft | undefined;\n hasTriggeredValidations: boolean;\n saveScheduled: boolean;\n saveInProgress: boolean;\n}\n\nexport interface FormDerivedState<TDraft> {\n draft: TDraft;\n hasTriggeredValidations: boolean;\n saveScheduled: boolean;\n saveInProgress: boolean;\n hasChanges: boolean;\n errors: Map<string, string[]>;\n isValid: boolean;\n}\n\nexport interface FormContext<TDraft, TOriginal> {\n formState: Store<FormState<TDraft>>;\n options: FormOptions<TDraft, TOriginal>;\n original: TOriginal | undefined;\n getField: <TPath extends string>(path: TPath) => Field<TDraft, TOriginal, TPath>;\n getDraft: () => TDraft;\n hasTriggeredValidations: () => boolean;\n saveScheduled: () => boolean;\n saveInProgress: () => boolean;\n hasChanges: () => boolean;\n getErrors: () => Map<string, string[]>;\n isValid: () => boolean;\n validate: () => boolean;\n reset: () => void;\n}\n\nexport interface FormInstance<TDraft, TOriginal>\n extends FormDerivedState<TDraft>,\n Pick<\n FormContext<TDraft, TOriginal>,\n 'options' | 'original' | 'getField' | 'validate' | 'reset'\n > {}\n\n/// /////////////////////////////////////////////////////////////////////////////\n// Implementation\n/// /////////////////////////////////////////////////////////////////////////////\n\nfunction FormContainer({\n form,\n ...formProps\n}: {\n form: Form<any, any>;\n onSubmit?: (\n event: FormEvent<HTMLFormElement>,\n form: FormInstance<any, any>,\n ) => void | Promise<void>;\n} & Omit<HTMLProps<HTMLFormElement>, 'form' | 'onSubmit'>) {\n const formInstance = form.useForm();\n const hasTriggeredValidations = form.useFormState((state) => state.hasTriggeredValidations);\n\n const formRef = useRef<HTMLFormElement>(null);\n\n function updateValidity(errors: Map<string, string[]>, buttonElement?: HTMLButtonElement) {\n const formElement = formRef.current;\n if (!formElement) {\n return;\n }\n\n const localizedErrors = new Map(\n [...errors.entries()].map(\n ([field, errors]) =>\n [\n field,\n errors.map((error) => formInstance.options.localizeError?.(error, field) ?? error),\n ] as const,\n ),\n );\n\n for (const element of Array.from(formElement.elements)) {\n if ('name' in element && 'setCustomValidity' in element) {\n (element as HTMLObjectElement).setCustomValidity(\n localizedErrors.get((element as HTMLObjectElement).name)?.join('\\n') ?? '',\n );\n }\n }\n\n if (buttonElement && 'setCustomValidity' in buttonElement) {\n const errorString = [...errors.values()].flat().join('\\n');\n\n buttonElement.setCustomValidity(errorString);\n }\n }\n\n useEffect(() => {\n return formInstance.formState\n .map(() => formInstance.getErrors())\n .subscribe((errors) => updateValidity(errors));\n }, []);\n\n return (\n <form\n ref={formRef}\n noValidate\n {...formProps}\n className={[\n formProps.className,\n hasTriggeredValidations ? (formInstance.options.validatedClass ?? 'validated') : undefined,\n ]\n .filter(Boolean)\n .join(' ')}\n onSubmit={async (event) => {\n if (formInstance.saveInProgress()) {\n return;\n }\n\n try {\n formInstance.formState.set('saveInProgress', true);\n event.preventDefault();\n\n const formElement = event.currentTarget;\n const buttonElement =\n event.nativeEvent instanceof SubmitEvent &&\n event.nativeEvent.submitter instanceof HTMLButtonElement\n ? event.nativeEvent.submitter\n : undefined;\n\n updateValidity(formInstance.getErrors(), buttonElement);\n\n formElement.reportValidity();\n\n const isValid = formInstance.validate();\n if (isValid) {\n await formProps.onSubmit?.(event, {\n ...formInstance,\n ...getDerivedState(formInstance),\n });\n }\n } finally {\n formInstance.formState.set('saveInProgress', false);\n }\n }}\n />\n );\n}\n\nfunction getField<TDraft, TOriginal extends TDraft, TPath extends string>(\n form: FormContext<TDraft, TOriginal>,\n path: TPath,\n): Field<TDraft, TOriginal, TPath> {\n const field = {\n get originalValue() {\n return form.original !== undefined ? get(form.original as any, path as any) : undefined;\n },\n\n get value() {\n const draft = form.getDraft();\n return get(draft ?? form.original ?? form.options.defaultValue, path as any);\n },\n\n setValue(update: Update<Value<TDraft, TPath>>) {\n form.formState.set('draft', (draft = form.original ?? form.options.defaultValue) => {\n if (update instanceof Function) {\n update = update(get(draft, path as any) as Value<TDraft, TPath>);\n }\n\n return set(draft, path as any, update as any);\n });\n },\n\n get hasChange() {\n return !deepEqual(this.originalValue, this.value);\n },\n\n get errors() {\n const errors = form.getErrors();\n return errors.get(path) ?? [];\n },\n\n get names(): any {\n const { value } = this;\n\n if (Array.isArray(value)) {\n return value.map((_, index) => join(path, String(index)));\n }\n\n if (isObject(value)) {\n return Object.keys(value).map((key) => join(path, key));\n }\n\n return [];\n },\n\n add(...args: any[]) {\n this.setValue((value): any => {\n if (!value) {\n throw new Error(`Cannot add element to ${JSON.stringify(value)}`);\n }\n\n if (Array.isArray(value)) {\n return [...(value ?? []), args[0]];\n }\n\n if (isObject(value)) {\n return {\n ...value,\n [args[0]]: args[1],\n };\n }\n\n throw new Error(`Cannot add element to ${JSON.stringify(value)}`);\n });\n },\n\n remove(key: string | number) {\n this.setValue((value): any => {\n if (!value) {\n throw new Error(`Cannot remove element from ${JSON.stringify(value)}`);\n }\n\n if (Array.isArray(value)) {\n return value.filter((_, index) => index !== Number(key));\n }\n\n if (isObject(value)) {\n const { [key]: _, ...rest } = value as Record<string | number, unknown>;\n return rest;\n }\n\n throw new Error(`Cannot remove element from ${JSON.stringify(value)}`);\n });\n },\n };\n\n return field as any;\n}\n\nfunction getErrors<TDraft, TOriginal>(\n draft: TDraft,\n original: TOriginal | undefined,\n validations: FormOptions<TDraft, TOriginal>['validations'],\n) {\n const errors = new Map<string, string[]>();\n\n for (const [path, block] of Object.entries(validations ?? {})) {\n for (const [validationName, validate] of Object.entries(\n block as Record<string, Validation<any, any, any>>,\n )) {\n let matched = false;\n\n for (const [field, value] of Object.entries(getWildCardMatches(draft, path))) {\n matched = true;\n if (!validate(value, { draft, original, field })) {\n const fieldErrors = errors.get(field) ?? [];\n fieldErrors.push(validationName);\n errors.set(field, fieldErrors);\n }\n }\n\n if (!matched && !path.includes('*')) {\n if (!validate(undefined, { draft, original, field: path })) {\n const fieldErrors = errors.get(path) ?? [];\n fieldErrors.push(validationName);\n errors.set(path, fieldErrors);\n }\n }\n }\n }\n\n return errors;\n}\n\nexport function getDerivedState<TDraft>(\n instance: FormContext<TDraft, any>,\n): FormDerivedState<TDraft> {\n return {\n draft: instance.getDraft(),\n hasTriggeredValidations: instance.hasTriggeredValidations(),\n saveScheduled: instance.saveScheduled(),\n saveInProgress: instance.saveInProgress(),\n hasChanges: instance.hasChanges(),\n errors: instance.getErrors(),\n isValid: instance.isValid(),\n };\n}\n\nexport class Form<TDraft, TOriginal extends TDraft = TDraft> {\n context: Context<FormContext<TDraft, TOriginal> | null> = createContext<FormContext<\n TDraft,\n TOriginal\n > | null>(null);\n\n constructor(public readonly options: FormOptions<TDraft, TOriginal>) {\n autobind(Form);\n }\n\n useForm(): FormContext<TDraft, TOriginal> {\n const context = useContext(this.context);\n\n if (!context) {\n throw new Error('Form context not found');\n }\n\n return context;\n }\n\n useFormState<S>(\n selector: (state: FormInstance<TDraft, TOriginal>) => S,\n useStoreOptions?: UseStoreOptions<S>,\n ): S {\n const form = this.useForm();\n\n return useStore(\n form.formState,\n () =>\n selector({\n ...form,\n ...getDerivedState(form),\n }),\n\n useStoreOptions,\n );\n }\n\n useField<TPath extends string>(\n path: TPath,\n useStoreOptions?: UseStoreOptions<any>,\n ): Field<TDraft, TOriginal, TPath> {\n const form = this.useForm();\n this.useFormState((form) => [form.getField(path).value, form.original], useStoreOptions);\n return form.getField(path);\n }\n\n // ///////////////////////////////////////////////////////////////////////////\n // React Components\n // ///////////////////////////////////////////////////////////////////////////\n\n Form({\n original,\n defaultValue,\n validations,\n localizeError,\n autoSave,\n transform,\n validatedClass,\n ...formProps\n }: {\n original?: TOriginal;\n onSubmit?: (event: FormEvent<HTMLFormElement>, form: FormInstance<TDraft, TOriginal>) => void;\n } & Partial<FormOptions<TDraft, TOriginal>> &\n Omit<HTMLProps<HTMLFormElement>, 'defaultValue' | 'autoSave' | 'onSubmit'>): React.JSX.Element {\n const options: FormOptions<TDraft, TOriginal> = {\n defaultValue: { ...this.options.defaultValue, ...defaultValue },\n validations: { ...this.options.validations, ...validations } as Validations<\n TDraft,\n TOriginal\n >,\n localizeError: localizeError ?? this.options.localizeError,\n autoSave: autoSave ?? this.options.autoSave,\n transform: transform ?? this.options.transform,\n validatedClass: validatedClass ?? this.options.validatedClass,\n };\n\n const formState = useMemo(() => {\n return createStore<FormState<TDraft>>({\n draft: undefined,\n hasTriggeredValidations: false,\n saveScheduled: false,\n saveInProgress: false,\n });\n }, []);\n\n let lastDraft: TDraft | undefined;\n const cache = new Map<string, unknown>();\n function lazy<T>(key: string, fn: () => T): T {\n if (lastDraft !== formState.get().draft) {\n cache.clear();\n lastDraft = formState.get().draft;\n }\n\n let value = cache.get(key);\n if (!cache.has(key)) {\n value = fn();\n cache.set(key, value);\n }\n\n return value as T;\n }\n\n const context: FormContext<TDraft, TOriginal> = {\n formState,\n options,\n original,\n\n getField() {\n throw new Error('Not implemented');\n },\n\n getDraft() {\n return formState.get().draft ?? original ?? options.defaultValue;\n },\n\n hasTriggeredValidations() {\n return formState.get().hasTriggeredValidations;\n },\n\n saveScheduled() {\n return formState.get().saveScheduled;\n },\n\n saveInProgress() {\n return formState.get().saveInProgress;\n },\n\n hasChanges() {\n return lazy(\n 'hasChanges',\n () => !deepEqual(this.getDraft(), original ?? options.defaultValue),\n );\n },\n\n getErrors() {\n return lazy('getErrors', () => getErrors(this.getDraft(), original, options.validations));\n },\n\n isValid() {\n return lazy('isValid', () => this.getErrors().size === 0);\n },\n\n validate() {\n formState.set('hasTriggeredValidations', true);\n return this.isValid();\n },\n\n reset() {\n formState.set('draft', undefined);\n formState.set('hasTriggeredValidations', false);\n },\n };\n\n context.getField = (path) => lazy(path, () => getField(context, path));\n\n // useEffect(() => {\n // const handles = options.transform?.map(({ trigger, update }) => {\n // const draft = derivedState.map('draft');\n // const triggerStore = trigger ? draft.map(trigger as any) : draft;\n\n // return triggerStore.subscribe(() => {\n // const value = trigger ? get(draft.get(), trigger as any) : draft.get();\n // const result = update(value as any, draft);\n\n // if (result !== undefined) {\n // draft.set(result);\n // }\n // });\n // });\n\n // return () => {\n // handles?.forEach((handle) => handle());\n // };\n // }, [original,options.transform]);\n\n useFormAutosave(context);\n\n return (\n <this.context.Provider value={context}>\n <FormContainer {...formProps} form={this} />\n </this.context.Provider>\n );\n }\n\n FormState<S>({\n selector,\n children,\n }: {\n selector: (form: FormInstance<TDraft, TOriginal>) => S;\n children: (selectedState: S) => ReactNode;\n }): React.JSX.Element {\n const selectedState = this.useFormState(selector);\n return <>{children(selectedState)}</>;\n }\n\n Field<const TPath extends string>(\n props: FormFieldPropsWithRender<TDraft, TOriginal, TPath>,\n ): React.JSX.Element;\n\n Field<const TPath extends string, const TComponent extends FormFieldComponent = 'input'>(\n props: FormFieldPropsWithComponent<TDraft, TOriginal, TPath, TComponent>,\n ): React.JSX.Element;\n\n Field(props: any): React.JSX.Element {\n return Reflect.apply(FormField, this, [{ component: 'input', ...props }]);\n }\n\n ForEach<const TPath extends string>(props: FormForEachProps<TDraft, TPath>): React.JSX.Element {\n return Reflect.apply(FormForEach, this, [props]);\n }\n\n withForm<TProps extends Record<string, unknown>>(\n Component: React.ComponentType<TProps>,\n formProps?: Parameters<this['Form']>[0],\n ): FunctionComponent<TProps> {\n const { Form } = this;\n return function FormWrapper(props: TProps) {\n return (\n <Form {...formProps}>\n <Component {...props} />\n </Form>\n );\n };\n }\n}\n\nexport function createForm<TDraft, TOriginal extends TDraft = TDraft>(\n options: FormOptions<TDraft, TOriginal>,\n): Form<TDraft, TOriginal> {\n return new Form(options);\n}\n","import React, { createContext, useContext, type Context, type ReactNode } from 'react';\n\nexport type Location = string | { pathname: string; search: string; hash: string };\n\nexport interface UrlContextType {\n location: Location;\n navigate: (navigate: (from: Location) => string) => void;\n}\n\nexport type UrlContextProviderProps = { children?: ReactNode } & (\n | { location: UrlContextType['location'] }\n | { locationHook: () => UrlContextType['location'] }\n) &\n ({ navigate: UrlContextType['navigate'] } | { navigateHook: () => UrlContextType['navigate'] });\n\nexport const UrlContext: Context<UrlContextType | undefined> = createContext<\n UrlContextType | undefined\n>(undefined);\n\nexport function UrlProvider({ children, ...props }: UrlContextProviderProps): React.JSX.Element {\n const location = 'location' in props ? props.location : props.locationHook();\n const navigate = 'navigate' in props ? props.navigate : props.navigateHook();\n\n return <UrlContext.Provider value={{ location, navigate }}>{children}</UrlContext.Provider>;\n}\n\nexport function useUrlContext(): UrlContextType {\n const context = useContext(UrlContext);\n if (!context) {\n throw new Error('useUrlContext must be used within a UrlContextProvider');\n }\n return context;\n}\n","export interface UrlOptions<T> {\n key: string;\n type?: 'search' | 'hash';\n serialize?: (value: T) => string;\n deserialize?: (value: string) => T;\n defaultValue: T;\n writeDefaultValue?: boolean;\n onCommit?: (value: T) => void;\n persist?: { id: string };\n}\n\nexport interface UrlOptionsWithoutDefaults<T>\n extends Omit<UrlOptions<T | undefined>, 'defaultValue'> {\n defaultValue?: T | undefined;\n}\n\nexport function createUrlOptions<T>(options: UrlOptions<T>): UrlOptions<T>;\nexport function createUrlOptions<T>(\n options: UrlOptionsWithoutDefaults<T>,\n): UrlOptions<T | undefined>;\nexport function createUrlOptions<T>(options: UrlOptionsWithoutDefaults<T>) {\n return {\n ...options,\n defaultValue: options.defaultValue as T,\n };\n}\n","import { fromExtendedJsonString, toExtendedJsonString } from '@lib/extendedJson';\nimport type { Location } from '@react/url/urlContext';\n\nexport function defaultDeserializer<T>(value: string): T {\n if (value === undefined) {\n return undefined as T;\n }\n\n try {\n return fromExtendedJsonString(value) as T;\n } catch {\n return undefined as T;\n }\n}\n\nexport function defaultSerializer<T>(value: T): string {\n return toExtendedJsonString(value);\n}\n\nexport function parseLocation(location: Location): URL {\n if (typeof location !== 'string') {\n location = `${location.pathname}${location.search}${location.hash}`;\n }\n\n return new URL(location, window.location.origin);\n}\n\nexport function createStorageKey(id: string, key: string) {\n return `cross-state:url:${id}:${key}`;\n}\n","import type { Update, UpdateFunction } from '@core';\nimport { useUrlContext } from '@react/url/urlContext';\nimport {\n createStorageKey,\n defaultDeserializer,\n defaultSerializer,\n parseLocation,\n} from '@react/url/urlHelpers';\nimport type { UrlOptions, UrlOptionsWithoutDefaults } from '@react/url/urlOptions';\nimport type { UrlStore } from '@react/url/urlStore';\nimport { useEffect, useMemo } from 'react';\n\nexport function useUrlParam<T>(store: UrlStore<T>): [T, update: UpdateFunction<T>];\nexport function useUrlParam<T>(options: UrlOptions<T>): [T, update: UpdateFunction<T>];\nexport function useUrlParam<T>(\n options: UrlOptionsWithoutDefaults<T>,\n): [T | undefined, update: UpdateFunction<T | undefined>];\nexport function useUrlParam<T>(\n input: UrlStore<T> | UrlOptionsWithoutDefaults<T>,\n): [T, update: UpdateFunction<T>] {\n const {\n key,\n type = 'hash',\n serialize = defaultSerializer,\n deserialize = defaultDeserializer,\n defaultValue,\n writeDefaultValue,\n onCommit,\n persist,\n } = 'options' in input ? input.options : (input as UrlOptions<T>);\n\n const { location, navigate } = useUrlContext();\n const url = parseLocation(location);\n const params = new URLSearchParams(url[type].slice(1));\n const urlValue = params.get(key);\n\n const storageKey = persist && createStorageKey(persist.id, key);\n const storageValue = storageKey ? localStorage.getItem(storageKey) : null;\n\n const value = useMemo(\n () =>\n urlValue !== null\n ? deserialize(urlValue)\n : storageValue !== null\n ? deserialize(storageValue)\n : defaultValue,\n [urlValue],\n );\n\n function commit(value: T) {\n const serializedValue = serialize(value);\n\n navigate((location) => {\n const url = parseLocation(location);\n const params = new URLSearchParams(url[type].slice(1));\n\n if (!writeDefaultValue && serializedValue === serialize(defaultValue)) {\n params.delete(key);\n } else {\n params.set(key, serializedValue);\n }\n\n url[type] = params.toString();\n return url.toString().replace(window.location.origin, '');\n });\n\n if (storageKey) {\n localStorage.setItem(storageKey, serializedValue);\n }\n\n onCommit?.(value);\n }\n\n function update(update: Update<T>) {\n if (update instanceof Function) {\n update = update(value);\n }\n\n commit(update);\n }\n\n useEffect(() => {\n if (urlValue !== null) {\n commit(deserialize(urlValue));\n }\n }, [urlValue]);\n\n useEffect(() => {\n if (urlValue === null && storageValue !== null) {\n commit(deserialize(storageValue));\n } else if (urlValue === null && writeDefaultValue) {\n commit(defaultValue);\n }\n }, []);\n\n return [value, update];\n}\n","import {\n createUrlOptions,\n type UrlOptions,\n type UrlOptionsWithoutDefaults,\n} from '@react/url/urlOptions';\nimport { useUrlParam } from '@react/url/useUrlParam';\n\nexport class UrlStore<T> {\n constructor(public readonly options: UrlOptions<T>) {}\n\n useStore(): T {\n return useUrlParam(this)[0];\n }\n\n useProp(): [T, update: (value: T) => void] {\n return useUrlParam(this);\n }\n}\nexport function createUrlStore<T>(options: UrlOptions<T>): UrlStore<T>;\nexport function createUrlStore<T>(options: UrlOptionsWithoutDefaults<T>): UrlStore<T | undefined>;\nexport function createUrlStore<T>(options: UrlOptionsWithoutDefaults<T>) {\n return new UrlStore(createUrlOptions(options));\n}\n","import { startTransition, useEffect, useMemo, useRef, useState } from 'react';\nimport { type Duration } from '@core';\nimport { debounce } from '@lib/debounce';\nimport { simpleHash } from '@lib/hash';\nimport { throttle } from '@lib/throttle';\n\nexport interface UseDecoupledStateOptions<T> {\n debounce?: Duration;\n throttle?: Duration;\n onCommit?: (value: T) => void;\n}\n\nexport function useDecoupledState<T>(\n value: T,\n onChange: (value: T) => void,\n options: UseDecoupledStateOptions<T> = {},\n): [state: T, setState: (value: T) => void] {\n const [dirty, setDirty] = useState<{ v: T }>();\n const ref = useRef({ onChange, onCommit: options.onCommit });\n\n useEffect(() => {\n ref.current = { onChange, onCommit: options.onCommit };\n }, [onChange]);\n\n const update = useMemo(() => {\n const { onChange, onCommit } = ref.current;\n\n const update = (value: T) => {\n onChange(value);\n setDirty(undefined);\n onCommit?.(value);\n };\n\n let delayedUpdate: (value: T) => void;\n\n if (options.debounce) {\n delayedUpdate = debounce(update, options.debounce);\n } else if (options.throttle) {\n delayedUpdate = throttle(update, options.throttle);\n } else {\n delayedUpdate = (value) => startTransition(() => update(value));\n }\n\n return (value: T) => {\n setDirty({ v: value });\n delayedUpdate(value);\n };\n }, [simpleHash([options.debounce, options.throttle])]);\n\n return [dirty ? dirty.v : value, update];\n}\n"],"mappings":";;;;;;;;;AAOA,SAAgB,YAAY,EAAE,MAAM,SAAU,GAAG,SAA8C;AAC7F,QACE,qBAAC;EACC,GAAI;EACJ,OAAO;GACL,UAAU;GACV,GAAG,MAAM;;aAGV,UAED,oBAAC;GACO;GACN,OAAO;IACL,UAAU;IACV,KA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,YAAY;CAC1B,MAAM,MAAM,OAAO;EAAE;EAAU,UAAU,QAAQ;;AAEjD,iBAAgB;AACd,MAAI,UAAU;GAAE;GAAU,UAAU,QAAQ;;IAC3C,CAAC;CAEJ,MAAM,SAAS,cAAc;EAC3B,MAAM,EAAE,sBAAU,aAAa,IAAI;EAEnC,MAAMC,YAAU,YAAa;AAC3B,cAASC;AACT,YAAS;AACT,cAAWA;;EAGb,IAAIC;AAEJ,MAAI,QAAQ,SACV,iBAAgB,SAASF,UAAQ,QAAQ;WAChC,QAAQ,SACjB,iBAAgB,SAASA,UAAQ,QAAQ;MAEzC,kBAAiB,YAAU,sBAAsBA,SAAOC;AAG1D,UAAQ,YAAa;AACnB,YAAS,EAAE,GAAGA;AACd,iBAAcA;;IAEf,CAAC,WAAW,CAAC,QAAQ,UAAU,QAAQ;AAE1C,QAAO,CAAC,QAAQ,MAAM,IAAI,OAAO"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const require_store = require('../store-BWMWEUpu.cjs');
|
|
2
|
+
require('../propAccess-ByqBjC19.cjs');
|
|
3
|
+
require('../hash-CJPl7SRj.cjs');
|
|
4
|
+
const require_scope = require('../scope-DvqvkIHB.cjs');
|
|
5
|
+
const require_storeMethods = require('../storeMethods-DVVsmUg1.cjs');
|
|
6
|
+
|
|
7
|
+
//#region src/react/register.ts
|
|
8
|
+
Object.assign(require_store.Store.prototype, require_storeMethods.storeMethods);
|
|
9
|
+
require_store.autobind(require_store.Store);
|
|
10
|
+
Object.assign(require_scope.Cache.prototype, require_storeMethods.cacheMethods);
|
|
11
|
+
require_store.autobind(require_scope.Cache);
|
|
12
|
+
Object.assign(require_scope.Scope.prototype, require_storeMethods.scopeMethods);
|
|
13
|
+
require_store.autobind(require_scope.Scope);
|
|
14
|
+
|
|
15
|
+
//#endregion
|
|
16
|
+
//# sourceMappingURL=register.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"register.cjs","names":["Store","storeMethods","autobind","Cache","cacheMethods","Scope","scopeMethods"],"sources":["../../src/react/register.ts"],"sourcesContent":["import { Cache, Scope, Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { cacheMethods } from '@react/cacheMethods';\nimport { scopeMethods } from '@react/scopeMethods';\nimport { storeMethods } from './storeMethods';\n\ntype StoreMethods = typeof storeMethods;\ntype CacheMethods = typeof cacheMethods;\ntype ScopeMethods = typeof scopeMethods;\n\ndeclare module '@core' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends StoreMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Cache<T> extends CacheMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Scope<T> extends ScopeMethods {}\n}\n\nObject.assign(Store.prototype, storeMethods);\nautobind(Store);\n\nObject.assign(Cache.prototype, cacheMethods);\nautobind(Cache);\n\nObject.assign(Scope.prototype, scopeMethods);\nautobind(Scope);\n"],"mappings":";;;;;;;AAqBA,OAAO,OAAOA,oBAAM,WAAWC;AAC/BC,uBAASF;AAET,OAAO,OAAOG,oBAAM,WAAWC;AAC/BF,uBAASC;AAET,OAAO,OAAOE,oBAAM,WAAWC;AAC/BJ,uBAASG"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import "../scope-DO5vpLPV.cjs";
|
|
2
|
+
import "../store-BEsiS8y7.cjs";
|
|
3
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-BQwU2Uia.cjs";
|
|
4
|
+
|
|
5
|
+
//#region src/react/register.d.ts
|
|
6
|
+
type StoreMethods = typeof storeMethods;
|
|
7
|
+
type CacheMethods = typeof cacheMethods;
|
|
8
|
+
type ScopeMethods = typeof scopeMethods;
|
|
9
|
+
declare module "@core" {
|
|
10
|
+
interface Store<T> extends StoreMethods {}
|
|
11
|
+
interface Cache<T> extends CacheMethods {}
|
|
12
|
+
interface Scope<T> extends ScopeMethods {}
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export {};
|
|
16
|
+
//# sourceMappingURL=register.d.cts.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import "../scope-DI1OFHcr.js";
|
|
2
|
+
import "../store-DKaeE840.js";
|
|
3
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-C4luym7C.js";
|
|
4
|
+
|
|
5
|
+
//#region src/react/register.d.ts
|
|
6
|
+
type StoreMethods = typeof storeMethods;
|
|
7
|
+
type CacheMethods = typeof cacheMethods;
|
|
8
|
+
type ScopeMethods = typeof scopeMethods;
|
|
9
|
+
declare module "@core" {
|
|
10
|
+
interface Store<T> extends StoreMethods {}
|
|
11
|
+
interface Cache<T> extends CacheMethods {}
|
|
12
|
+
interface Scope<T> extends ScopeMethods {}
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=register.d.ts.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Store, autobind } from "../store-Dr8gM3lq.js";
|
|
2
|
+
import "../propAccess-DGchzVfy.js";
|
|
3
|
+
import "../hash-BV06P7va.js";
|
|
4
|
+
import { Cache, Scope } from "../scope-DU5dFP1T.js";
|
|
5
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-AIJSwxHz.js";
|
|
6
|
+
|
|
7
|
+
//#region src/react/register.ts
|
|
8
|
+
Object.assign(Store.prototype, storeMethods);
|
|
9
|
+
autobind(Store);
|
|
10
|
+
Object.assign(Cache.prototype, cacheMethods);
|
|
11
|
+
autobind(Cache);
|
|
12
|
+
Object.assign(Scope.prototype, scopeMethods);
|
|
13
|
+
autobind(Scope);
|
|
14
|
+
|
|
15
|
+
//#endregion
|
|
16
|
+
//# sourceMappingURL=register.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"register.js","names":[],"sources":["../../src/react/register.ts"],"sourcesContent":["import { Cache, Scope, Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { cacheMethods } from '@react/cacheMethods';\nimport { scopeMethods } from '@react/scopeMethods';\nimport { storeMethods } from './storeMethods';\n\ntype StoreMethods = typeof storeMethods;\ntype CacheMethods = typeof cacheMethods;\ntype ScopeMethods = typeof scopeMethods;\n\ndeclare module '@core' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends StoreMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Cache<T> extends CacheMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Scope<T> extends ScopeMethods {}\n}\n\nObject.assign(Store.prototype, storeMethods);\nautobind(Store);\n\nObject.assign(Cache.prototype, cacheMethods);\nautobind(Cache);\n\nObject.assign(Scope.prototype, scopeMethods);\nautobind(Scope);\n"],"mappings":";;;;;;;AAqBA,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS;AAET,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS;AAET,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS"}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { AnyPath, Calculate, Constrain, Duration, MaybePromise, Path, Selector, Store, StoreOptions, Value } from "./store-DKaeE840.js";
|
|
2
|
+
|
|
3
|
+
//#region src/lib/cacheState.d.ts
|
|
4
|
+
type ValueState<T> = {
|
|
5
|
+
status: "value";
|
|
6
|
+
value: T;
|
|
7
|
+
error?: undefined;
|
|
8
|
+
};
|
|
9
|
+
type ErrorState = {
|
|
10
|
+
status: "error";
|
|
11
|
+
value?: undefined;
|
|
12
|
+
error: unknown;
|
|
13
|
+
};
|
|
14
|
+
type PendingState = {
|
|
15
|
+
status: "pending";
|
|
16
|
+
value?: undefined;
|
|
17
|
+
error?: undefined;
|
|
18
|
+
};
|
|
19
|
+
type CacheState<T> = (ValueState<T> | ErrorState | PendingState) & {
|
|
20
|
+
isStale: boolean;
|
|
21
|
+
isUpdating: boolean;
|
|
22
|
+
isConnected: boolean;
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/core/resourceGroup.d.ts
|
|
26
|
+
interface Resource {
|
|
27
|
+
invalidateAll(): void;
|
|
28
|
+
clearAll(): void;
|
|
29
|
+
}
|
|
30
|
+
declare class ResourceGroup {
|
|
31
|
+
readonly name?: string | undefined;
|
|
32
|
+
private refMap;
|
|
33
|
+
private refSet;
|
|
34
|
+
constructor(name?: string | undefined);
|
|
35
|
+
add(resource: Resource): void;
|
|
36
|
+
delete(resource: Resource): void;
|
|
37
|
+
invalidateAll(): void;
|
|
38
|
+
clearAll(): void;
|
|
39
|
+
}
|
|
40
|
+
declare const allResources: ResourceGroup;
|
|
41
|
+
declare function createResourceGroup(name?: string): ResourceGroup;
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/core/cache.d.ts
|
|
44
|
+
interface CacheGetOptions {
|
|
45
|
+
/**
|
|
46
|
+
* How to handle the cache when getting the value.
|
|
47
|
+
* - `whenMissing`: Only fetch a new value if there is no cached value.
|
|
48
|
+
* - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.
|
|
49
|
+
* - `force`: Always fetch a new value, regardless of the cache state.
|
|
50
|
+
*/
|
|
51
|
+
update?: "whenMissing" | "whenStale" | "force";
|
|
52
|
+
/**
|
|
53
|
+
* If set to `true`, the cache will be updated in the background.
|
|
54
|
+
* This means that a stale value will be returned immediately, if available, while the new value is being fetched.
|
|
55
|
+
*/
|
|
56
|
+
backgroundUpdate?: boolean;
|
|
57
|
+
}
|
|
58
|
+
interface CacheFunction<T, Args extends any[] = []> {
|
|
59
|
+
(...args: Args): Promise<T> | Calculate<Promise<T>>;
|
|
60
|
+
}
|
|
61
|
+
interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {
|
|
62
|
+
/**
|
|
63
|
+
* How long to keep the cache entry before it is considered stale.
|
|
64
|
+
* If set to `undefined` or `null`, the cache entry will never be invalidated automatically.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```typescript
|
|
68
|
+
* createCache(fetchData, {
|
|
69
|
+
* invalidateAfter: { seconds: 10 },
|
|
70
|
+
* });
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;
|
|
74
|
+
/**
|
|
75
|
+
* If set, the cache will be invalidated when the window gets focused.
|
|
76
|
+
* This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.
|
|
77
|
+
*/
|
|
78
|
+
invalidateOnWindowFocus?: boolean;
|
|
79
|
+
/**
|
|
80
|
+
* If set, the cached value will be cleared when the cache is invalidated.
|
|
81
|
+
* Without this option, the cache will keep the last value as stale until a new value becomes available.
|
|
82
|
+
*/
|
|
83
|
+
clearOnInvalidate?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* If set, cache entries will be cleared after approximately the specified duration.
|
|
86
|
+
* This is useful for long lived pages or applications and helps to prevent memory leaks.
|
|
87
|
+
* The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.
|
|
88
|
+
*/
|
|
89
|
+
clearUnusedAfter?: Duration | null;
|
|
90
|
+
/**
|
|
91
|
+
* Add the cache to the specified resource group(s).
|
|
92
|
+
* This allows you to invalidate or clear multiple caches that belong to the same group.
|
|
93
|
+
* All caches are always added to the `allResources` group.
|
|
94
|
+
*/
|
|
95
|
+
resourceGroup?: ResourceGroup | ResourceGroup[];
|
|
96
|
+
/**
|
|
97
|
+
* Function to generate a custom cache key based on the provided arguments.
|
|
98
|
+
* This allows you to control how cache entries are identified and reused.
|
|
99
|
+
* By default, the arguments array is used as the cache key.
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.
|
|
104
|
+
* createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {
|
|
105
|
+
* getCacheKey: (filter?) => ({
|
|
106
|
+
* num: filter?.num ?? 0,
|
|
107
|
+
* bool: filter?.bool ?? false,
|
|
108
|
+
* }),
|
|
109
|
+
* });
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
getCacheKey?: (...args: NoInfer<Args>) => unknown;
|
|
113
|
+
}
|
|
114
|
+
declare class Cache<T, Args extends any[] = unknown[]> extends Store<Promise<T>> {
|
|
115
|
+
readonly args: Args;
|
|
116
|
+
readonly options: CacheOptions<T, Args>;
|
|
117
|
+
readonly derivedFromCache?: {
|
|
118
|
+
cache: Cache<any, any>;
|
|
119
|
+
selectors: (Selector<any, any> | AnyPath)[];
|
|
120
|
+
} | undefined;
|
|
121
|
+
readonly state: Store<CacheState<T>>;
|
|
122
|
+
protected stalePromise?: Promise<T>;
|
|
123
|
+
protected invalidationTimer?: ReturnType<typeof setTimeout>;
|
|
124
|
+
constructor(getter: Calculate<Promise<T>>, args: Args, options?: CacheOptions<T, Args>, derivedFromCache?: {
|
|
125
|
+
cache: Cache<any, any>;
|
|
126
|
+
selectors: (Selector<any, any> | AnyPath)[];
|
|
127
|
+
} | undefined);
|
|
128
|
+
get({
|
|
129
|
+
update,
|
|
130
|
+
backgroundUpdate
|
|
131
|
+
}?: CacheGetOptions): Promise<T>;
|
|
132
|
+
updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void;
|
|
133
|
+
updateError(error: unknown): void;
|
|
134
|
+
invalidate(recursive?: boolean): void;
|
|
135
|
+
clear(recursive?: boolean): void;
|
|
136
|
+
mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;
|
|
137
|
+
mapValue<const P extends AnyPath>(selector: P extends Path<T> ? P : Path<T>): Cache<Value<T, P>, Args>;
|
|
138
|
+
protected watchPromise(): void;
|
|
139
|
+
protected setTimers(): void;
|
|
140
|
+
protected watchFocus(): void;
|
|
141
|
+
}
|
|
142
|
+
type CreateCacheResult<T, Args extends any[]> = [] extends Args ? CacheBundle<T, Args> & Cache<T, Args> : CacheBundle<T, Args>;
|
|
143
|
+
interface InvalidationOptions<T, Args extends any[]> {
|
|
144
|
+
filter?: (cache: Cache<T, Args>) => boolean;
|
|
145
|
+
}
|
|
146
|
+
type CacheBundle<T, Args extends any[]> = {
|
|
147
|
+
(...args: Args): Cache<T, Args>;
|
|
148
|
+
mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;
|
|
149
|
+
mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;
|
|
150
|
+
invalidateAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
151
|
+
clearAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
152
|
+
getInstances: () => Cache<T, Args>[];
|
|
153
|
+
};
|
|
154
|
+
declare function create<T, Args extends any[] = []>(cacheFunction: CacheFunction<T, Args>, options?: CacheOptions<T, Args>): CreateCacheResult<T, Args>;
|
|
155
|
+
declare const createCache: typeof create & {
|
|
156
|
+
defaultOptions: CacheOptions<any, any>;
|
|
157
|
+
};
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/core/scope.d.ts
|
|
160
|
+
declare class Scope<T> {
|
|
161
|
+
readonly defaultValue: T;
|
|
162
|
+
constructor(defaultValue: T);
|
|
163
|
+
}
|
|
164
|
+
declare function createScope<T>(defaultValue: T): Scope<T>;
|
|
165
|
+
//#endregion
|
|
166
|
+
export { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope };
|
|
167
|
+
//# sourceMappingURL=scope-DI1OFHcr.d.ts.map
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { AnyPath, Calculate, Constrain, Duration, MaybePromise, Path, Selector, Store, StoreOptions, Value } from "./store-BEsiS8y7.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/lib/cacheState.d.ts
|
|
4
|
+
type ValueState<T> = {
|
|
5
|
+
status: "value";
|
|
6
|
+
value: T;
|
|
7
|
+
error?: undefined;
|
|
8
|
+
};
|
|
9
|
+
type ErrorState = {
|
|
10
|
+
status: "error";
|
|
11
|
+
value?: undefined;
|
|
12
|
+
error: unknown;
|
|
13
|
+
};
|
|
14
|
+
type PendingState = {
|
|
15
|
+
status: "pending";
|
|
16
|
+
value?: undefined;
|
|
17
|
+
error?: undefined;
|
|
18
|
+
};
|
|
19
|
+
type CacheState<T> = (ValueState<T> | ErrorState | PendingState) & {
|
|
20
|
+
isStale: boolean;
|
|
21
|
+
isUpdating: boolean;
|
|
22
|
+
isConnected: boolean;
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/core/resourceGroup.d.ts
|
|
26
|
+
interface Resource {
|
|
27
|
+
invalidateAll(): void;
|
|
28
|
+
clearAll(): void;
|
|
29
|
+
}
|
|
30
|
+
declare class ResourceGroup {
|
|
31
|
+
readonly name?: string | undefined;
|
|
32
|
+
private refMap;
|
|
33
|
+
private refSet;
|
|
34
|
+
constructor(name?: string | undefined);
|
|
35
|
+
add(resource: Resource): void;
|
|
36
|
+
delete(resource: Resource): void;
|
|
37
|
+
invalidateAll(): void;
|
|
38
|
+
clearAll(): void;
|
|
39
|
+
}
|
|
40
|
+
declare const allResources: ResourceGroup;
|
|
41
|
+
declare function createResourceGroup(name?: string): ResourceGroup;
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/core/cache.d.ts
|
|
44
|
+
interface CacheGetOptions {
|
|
45
|
+
/**
|
|
46
|
+
* How to handle the cache when getting the value.
|
|
47
|
+
* - `whenMissing`: Only fetch a new value if there is no cached value.
|
|
48
|
+
* - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.
|
|
49
|
+
* - `force`: Always fetch a new value, regardless of the cache state.
|
|
50
|
+
*/
|
|
51
|
+
update?: "whenMissing" | "whenStale" | "force";
|
|
52
|
+
/**
|
|
53
|
+
* If set to `true`, the cache will be updated in the background.
|
|
54
|
+
* This means that a stale value will be returned immediately, if available, while the new value is being fetched.
|
|
55
|
+
*/
|
|
56
|
+
backgroundUpdate?: boolean;
|
|
57
|
+
}
|
|
58
|
+
interface CacheFunction<T, Args extends any[] = []> {
|
|
59
|
+
(...args: Args): Promise<T> | Calculate<Promise<T>>;
|
|
60
|
+
}
|
|
61
|
+
interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {
|
|
62
|
+
/**
|
|
63
|
+
* How long to keep the cache entry before it is considered stale.
|
|
64
|
+
* If set to `undefined` or `null`, the cache entry will never be invalidated automatically.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```typescript
|
|
68
|
+
* createCache(fetchData, {
|
|
69
|
+
* invalidateAfter: { seconds: 10 },
|
|
70
|
+
* });
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;
|
|
74
|
+
/**
|
|
75
|
+
* If set, the cache will be invalidated when the window gets focused.
|
|
76
|
+
* This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.
|
|
77
|
+
*/
|
|
78
|
+
invalidateOnWindowFocus?: boolean;
|
|
79
|
+
/**
|
|
80
|
+
* If set, the cached value will be cleared when the cache is invalidated.
|
|
81
|
+
* Without this option, the cache will keep the last value as stale until a new value becomes available.
|
|
82
|
+
*/
|
|
83
|
+
clearOnInvalidate?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* If set, cache entries will be cleared after approximately the specified duration.
|
|
86
|
+
* This is useful for long lived pages or applications and helps to prevent memory leaks.
|
|
87
|
+
* The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.
|
|
88
|
+
*/
|
|
89
|
+
clearUnusedAfter?: Duration | null;
|
|
90
|
+
/**
|
|
91
|
+
* Add the cache to the specified resource group(s).
|
|
92
|
+
* This allows you to invalidate or clear multiple caches that belong to the same group.
|
|
93
|
+
* All caches are always added to the `allResources` group.
|
|
94
|
+
*/
|
|
95
|
+
resourceGroup?: ResourceGroup | ResourceGroup[];
|
|
96
|
+
/**
|
|
97
|
+
* Function to generate a custom cache key based on the provided arguments.
|
|
98
|
+
* This allows you to control how cache entries are identified and reused.
|
|
99
|
+
* By default, the arguments array is used as the cache key.
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.
|
|
104
|
+
* createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {
|
|
105
|
+
* getCacheKey: (filter?) => ({
|
|
106
|
+
* num: filter?.num ?? 0,
|
|
107
|
+
* bool: filter?.bool ?? false,
|
|
108
|
+
* }),
|
|
109
|
+
* });
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
getCacheKey?: (...args: NoInfer<Args>) => unknown;
|
|
113
|
+
}
|
|
114
|
+
declare class Cache<T, Args extends any[] = unknown[]> extends Store<Promise<T>> {
|
|
115
|
+
readonly args: Args;
|
|
116
|
+
readonly options: CacheOptions<T, Args>;
|
|
117
|
+
readonly derivedFromCache?: {
|
|
118
|
+
cache: Cache<any, any>;
|
|
119
|
+
selectors: (Selector<any, any> | AnyPath)[];
|
|
120
|
+
} | undefined;
|
|
121
|
+
readonly state: Store<CacheState<T>>;
|
|
122
|
+
protected stalePromise?: Promise<T>;
|
|
123
|
+
protected invalidationTimer?: ReturnType<typeof setTimeout>;
|
|
124
|
+
constructor(getter: Calculate<Promise<T>>, args: Args, options?: CacheOptions<T, Args>, derivedFromCache?: {
|
|
125
|
+
cache: Cache<any, any>;
|
|
126
|
+
selectors: (Selector<any, any> | AnyPath)[];
|
|
127
|
+
} | undefined);
|
|
128
|
+
get({
|
|
129
|
+
update,
|
|
130
|
+
backgroundUpdate
|
|
131
|
+
}?: CacheGetOptions): Promise<T>;
|
|
132
|
+
updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void;
|
|
133
|
+
updateError(error: unknown): void;
|
|
134
|
+
invalidate(recursive?: boolean): void;
|
|
135
|
+
clear(recursive?: boolean): void;
|
|
136
|
+
mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;
|
|
137
|
+
mapValue<const P extends AnyPath>(selector: P extends Path<T> ? P : Path<T>): Cache<Value<T, P>, Args>;
|
|
138
|
+
protected watchPromise(): void;
|
|
139
|
+
protected setTimers(): void;
|
|
140
|
+
protected watchFocus(): void;
|
|
141
|
+
}
|
|
142
|
+
type CreateCacheResult<T, Args extends any[]> = [] extends Args ? CacheBundle<T, Args> & Cache<T, Args> : CacheBundle<T, Args>;
|
|
143
|
+
interface InvalidationOptions<T, Args extends any[]> {
|
|
144
|
+
filter?: (cache: Cache<T, Args>) => boolean;
|
|
145
|
+
}
|
|
146
|
+
type CacheBundle<T, Args extends any[]> = {
|
|
147
|
+
(...args: Args): Cache<T, Args>;
|
|
148
|
+
mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args>;
|
|
149
|
+
mapValue<const P>(selector: Constrain<P, Path<T>>): CreateCacheResult<Value<T, P>, Args>;
|
|
150
|
+
invalidateAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
151
|
+
clearAll: (options?: InvalidationOptions<T, Args>) => void;
|
|
152
|
+
getInstances: () => Cache<T, Args>[];
|
|
153
|
+
};
|
|
154
|
+
declare function create<T, Args extends any[] = []>(cacheFunction: CacheFunction<T, Args>, options?: CacheOptions<T, Args>): CreateCacheResult<T, Args>;
|
|
155
|
+
declare const createCache: typeof create & {
|
|
156
|
+
defaultOptions: CacheOptions<any, any>;
|
|
157
|
+
};
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/core/scope.d.ts
|
|
160
|
+
declare class Scope<T> {
|
|
161
|
+
readonly defaultValue: T;
|
|
162
|
+
constructor(defaultValue: T);
|
|
163
|
+
}
|
|
164
|
+
declare function createScope<T>(defaultValue: T): Scope<T>;
|
|
165
|
+
//#endregion
|
|
166
|
+
export { Cache, CacheBundle, CacheFunction, CacheGetOptions, CacheOptions, CacheState, CreateCacheResult, ErrorState, PendingState, Resource, ResourceGroup, Scope, ValueState, allResources, createCache, createResourceGroup, createScope };
|
|
167
|
+
//# sourceMappingURL=scope-DO5vpLPV.d.cts.map
|