|
| 1 | +import type { DurableObject } from "cloudflare:workers"; |
| 2 | +import { type SnapshotPolicy, state } from "./index.js"; |
| 3 | +import { unreachable } from "./util.js"; |
| 4 | + |
| 5 | +type FieldDecoratorFactoryReturn<T> = ( |
| 6 | + value: T, |
| 7 | + metadata: { kind: string; name: string }, |
| 8 | +) => FieldDecoratorReturn<T>; |
| 9 | + |
| 10 | +type FieldDecoratorReturn<T> = (this: DurableObject, initialValue: T) => T; |
| 11 | + |
| 12 | +type DiffableArgs = |
| 13 | + | [] |
| 14 | + | [DiffableOpts] |
| 15 | + | [name?: string] |
| 16 | + | [_: any, { kind: string; name: string }]; |
| 17 | + |
| 18 | +type DiffableOpts = { |
| 19 | + name?: string; |
| 20 | + snapshotPolicy?: SnapshotPolicy; |
| 21 | +}; |
| 22 | + |
| 23 | +export function diffable( |
| 24 | + _: any, |
| 25 | + { kind, name }: { kind: string; name: string }, |
| 26 | +): FieldDecoratorReturn<any>; |
| 27 | +export function diffable(name?: string): FieldDecoratorFactoryReturn<any>; |
| 28 | +export function diffable( |
| 29 | + options: DiffableOpts, |
| 30 | +): FieldDecoratorFactoryReturn<any>; |
| 31 | +export function diffable(): |
| 32 | + | FieldDecoratorReturn<any> |
| 33 | + | FieldDecoratorFactoryReturn<any> { |
| 34 | + // biome-ignore lint/style/noArguments: <explanation> |
| 35 | + const args = arguments as unknown as DiffableArgs; |
| 36 | + const fn = |
| 37 | + (opts: DiffableOpts = {}) => |
| 38 | + (_: any, { kind, name: fieldName }: { kind: string; name: string }) => { |
| 39 | + if (kind === "field") { |
| 40 | + return function (this: DurableObject, initialValue: any) { |
| 41 | + const fieldNameNonPrivate = fieldName.replace(/^#/, ""); |
| 42 | + return state( |
| 43 | + this.ctx, |
| 44 | + opts.name ?? fieldNameNonPrivate, |
| 45 | + initialValue, |
| 46 | + { |
| 47 | + snapshotPolicy: opts.snapshotPolicy ?? { changes: 10 }, |
| 48 | + }, |
| 49 | + ); |
| 50 | + }; |
| 51 | + } |
| 52 | + |
| 53 | + throw new Error("Only fields can be persistable"); |
| 54 | + }; |
| 55 | + |
| 56 | + if (args.length === 0) { |
| 57 | + return fn(); |
| 58 | + } |
| 59 | + |
| 60 | + if (args.length === 1) { |
| 61 | + const [optsOrName] = args; |
| 62 | + |
| 63 | + if (typeof optsOrName === "object") { |
| 64 | + return fn(optsOrName); |
| 65 | + } |
| 66 | + |
| 67 | + return fn(optsOrName ? { name: optsOrName } : {}); |
| 68 | + } |
| 69 | + |
| 70 | + const [value, metadata] = args; |
| 71 | + return fn()(value, metadata ?? unreachable()); |
| 72 | +} |
0 commit comments