better-call 0.0.0-experimental.06264e12

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.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +254 -0
  3. package/dist/error.cjs +67 -0
  4. package/dist/error.cjs.map +1 -0
  5. package/dist/error.d.cts +46 -0
  6. package/dist/error.d.mts +46 -0
  7. package/dist/error.mjs +64 -0
  8. package/dist/error.mjs.map +1 -0
  9. package/dist/fn.cjs +335 -0
  10. package/dist/fn.cjs.map +1 -0
  11. package/dist/fn.d.cts +312 -0
  12. package/dist/fn.d.mts +312 -0
  13. package/dist/fn.mjs +335 -0
  14. package/dist/fn.mjs.map +1 -0
  15. package/dist/index.cjs +37 -0
  16. package/dist/index.cjs.map +1 -0
  17. package/dist/index.d.cts +46 -0
  18. package/dist/index.d.mts +46 -0
  19. package/dist/index.mjs +24 -0
  20. package/dist/index.mjs.map +1 -0
  21. package/dist/module.cjs +111 -0
  22. package/dist/module.cjs.map +1 -0
  23. package/dist/module.d.cts +249 -0
  24. package/dist/module.d.mts +249 -0
  25. package/dist/module.mjs +102 -0
  26. package/dist/module.mjs.map +1 -0
  27. package/dist/plugins/http.cjs +185 -0
  28. package/dist/plugins/http.cjs.map +1 -0
  29. package/dist/plugins/http.d.cts +1261 -0
  30. package/dist/plugins/http.d.mts +1261 -0
  31. package/dist/plugins/http.mjs +175 -0
  32. package/dist/plugins/http.mjs.map +1 -0
  33. package/dist/plugins/read-only.cjs +19 -0
  34. package/dist/plugins/read-only.cjs.map +1 -0
  35. package/dist/plugins/read-only.d.cts +17 -0
  36. package/dist/plugins/read-only.d.mts +17 -0
  37. package/dist/plugins/read-only.mjs +19 -0
  38. package/dist/plugins/read-only.mjs.map +1 -0
  39. package/dist/schema.cjs +167 -0
  40. package/dist/schema.cjs.map +1 -0
  41. package/dist/schema.d.cts +225 -0
  42. package/dist/schema.d.mts +225 -0
  43. package/dist/schema.mjs +159 -0
  44. package/dist/schema.mjs.map +1 -0
  45. package/dist/scope.d.cts +18 -0
  46. package/dist/scope.d.mts +18 -0
  47. package/dist/storage.cjs +256 -0
  48. package/dist/storage.cjs.map +1 -0
  49. package/dist/storage.d.cts +195 -0
  50. package/dist/storage.d.mts +195 -0
  51. package/dist/storage.mjs +253 -0
  52. package/dist/storage.mjs.map +1 -0
  53. package/dist/types.d.cts +8 -0
  54. package/dist/types.d.mts +8 -0
  55. package/dist/var.cjs +162 -0
  56. package/dist/var.cjs.map +1 -0
  57. package/dist/var.d.cts +36 -0
  58. package/dist/var.d.mts +36 -0
  59. package/dist/var.mjs +154 -0
  60. package/dist/var.mjs.map +1 -0
  61. package/package.json +92 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.mjs","names":[],"sources":["../src/schema.ts"],"sourcesContent":["import { type Issue, ValidationError } from \"./error\";\nimport type { LiteralString, Prettify } from \"./types\";\n\nexport type Rules = {\n\t/** Strings: length. Numbers: value. */\n\tmin?: number;\n\t/** Strings: length. Numbers: value. */\n\tmax?: number;\n\t/** Strings only: exact length. */\n\tlength?: number;\n\tregex?: RegExp;\n\temail?: boolean;\n\turl?: boolean;\n\tstartsWith?: string;\n\tendsWith?: string;\n\t/** Numbers only. */\n\tint?: boolean;\n\t/** Allowed values. */\n\tenum?: readonly unknown[];\n\t/** Escape hatch - return true, or a message to fail with. */\n\tcheck?: (value: any) => boolean | string;\n};\n\nexport interface TypeDefination<T, O, D = never> extends Rules {\n\tname: LiteralString;\n\ttype?: T;\n\toutput?: O;\n\tshape?: unknown;\n\t/** `function` types only: the declared input of the expected fn -\n\t * plain closures get it validated at their door on every call. */\n\tfnInput?: unknown;\n\t/** Used when the incoming value is `undefined`. */\n\tdefault?: D;\n\t/** When true, `undefined` passes straight through unvalidated. */\n\toptional?: boolean;\n\ttransform?: (value: any) => O;\n}\n\nexport type TypeOptions<T, O> = {\n\ttransform?: (value: T) => O;\n};\n\ntype WithDefault<D> = { default?: D };\n\ntype WithOptional<Opt> = { optional?: Opt };\n\n/**\n * `optional` widens the output; `default` keeps it narrow because a value\n * is always produced. Declaring both means optional to send, never absent.\n */\ntype OutOf<O, D, Opt> = [Opt] extends [true]\n\t? [D] extends [never]\n\t\t? O | undefined\n\t\t: O\n\t: O;\n\n/** Either marker makes the key omittable in `InferArgs`. */\ntype DefOf<D, Opt> = [Opt] extends [true]\n\t? [D] extends [never]\n\t\t? undefined\n\t\t: D\n\t: D;\n\ntype StringOptions<E extends string, O> = TypeOptions<E, O> &\n\tPick<\n\t\tRules,\n\t\t| \"min\"\n\t\t| \"max\"\n\t\t| \"length\"\n\t\t| \"regex\"\n\t\t| \"email\"\n\t\t| \"url\"\n\t\t| \"startsWith\"\n\t\t| \"endsWith\"\n\t\t| \"check\"\n\t> & { enum?: readonly E[] };\n\ntype ArrayOptions<E, O> = TypeOptions<FieldOut<E>[], O> &\n\tPick<Rules, \"min\" | \"max\" | \"length\" | \"check\">;\n\ntype NumberOptions<O> = TypeOptions<number, O> &\n\tPick<Rules, \"min\" | \"max\" | \"int\" | \"check\"> & {\n\t\tenum?: readonly number[];\n\t};\n\nexport type InferType<T> =\n\tT extends TypeDefination<infer T2, any, any> ? T2 : never;\n\nexport type InferOutput<T> =\n\tT extends TypeDefination<any, infer O, any> ? O : never;\n\nexport type DefineInput<I> = Prettify<{\n\t[K in keyof I]: FieldIn<I[K]>;\n}>;\n\n/** Keys whose field is OPTIONAL with no default: absent from the output\n * too, so they mark `?`. A defaulted field always produces a value and\n * stays required. */\ntype OutOptional<O> = {\n\t[K in keyof O]: [DefaultOf<O[K]>] extends [never]\n\t\t? never\n\t\t: [DefaultOf<O[K]>] extends [undefined]\n\t\t\t? K\n\t\t\t: never;\n}[keyof O];\n\nexport type DefineOutput<O> = Prettify<\n\t{ [K in keyof O as K extends OutOptional<O> ? never : K]: FieldOut<O[K]> } & {\n\t\t[K in keyof O as K extends OutOptional<O> ? K : never]?: FieldOut<O[K]>;\n\t}\n>;\n\n/**\n * A handler-less `v.fn({ input, output })` used as a schema describes\n * \"a fn from `input` to `output`\" - the VALUE is the fn itself. Two\n * views of the same signature:\n *\n * `SchemaFnIn` is the PROVIDER's side - what a caller must hand over.\n * Like any handler, their fn receives the PARSED input (validation runs\n * at its door) and returns the declared output, sync or async.\n *\n * `SchemaFnOut` is the CONSUMER's side (`c.input.x`) - the handler calls\n * it with RAW args, exactly like calling the fn it stands in for.\n *\n * No declared input means the signature is UNSPECIFIED, not zero-arg -\n * any fn fits (`create: v.fn`), so the args stay open.\n */\ntype SchemaFnIn<FI, FO> = (\n\t...args: unknown extends FI ? any[] : [input: InferInput<FI>]\n) => unknown extends FO\n\t? any\n\t: InferInput<OutputSchemaOf<FO>> | Promise<InferInput<OutputSchemaOf<FO>>>;\n\ntype SchemaFnOut<FI, FO> = (\n\t...args: unknown extends FI ? any[] : [input: InferArgs<FI>]\n) => unknown extends FO\n\t? any\n\t: InferInput<OutputSchemaOf<FO>> | Promise<InferInput<OutputSchemaOf<FO>>>;\n\n/**\n * A fn schema whose input IS a var carries that var's name as an optional\n * phantom (`$fnVar`, tuple-wrapped so a plain fn can never false-match).\n * Scope resolution reads it to WIDEN the fn's args with everything the\n * scope mounts on that var - see `WidenSchemaFns`. Optional, so any plain\n * closure still satisfies the type.\n */\nexport type FnVarBrand<FI> = FI extends {\n\t$var: true;\n\tname: infer N extends string;\n}\n\t? { readonly $fnVar?: [N] }\n\t: unknown;\n\n/**\n * A declared `output` comes in two forms: a bare schema (the signature\n * AND the exit check), or the wrapper `{ def?, validation? }` splitting\n * what the fn PROMISES from what gets CHECKED - `{ def }` documents\n * without paying runtime validation, `{ def, validation }` checks with a\n * different (usually looser) schema than it documents. The wrapper is\n * recognized by its keys, so an output that IS an object with only\n * `def`/`validation` fields must be written `v.object({...})`.\n *\n * `OutputSchemaOf` is the type-level unwrap - the schema the fn's return\n * type (and its rendered signature) comes from.\n */\nexport type OutputSchemaOf<O> =\n\tExclude<keyof O, \"def\" | \"validation\"> extends never\n\t\t? O extends { def: infer D }\n\t\t\t? D\n\t\t\t: O extends { validation: infer Vl }\n\t\t\t\t? Vl\n\t\t\t\t: O\n\t\t: O;\n\n/** The runtime unwrap: `def` is the documented schema (falls back to\n * `validation`), `validation` is what the exit check runs - undefined\n * means no check. A bare schema is both. */\nexport const outputContract = (\n\toutput: unknown,\n): { def?: unknown; validation?: unknown } => {\n\tif (output === undefined) return {};\n\tif (\n\t\toutput !== null &&\n\t\ttypeof output === \"object\" &&\n\t\t!Array.isArray(output) &&\n\t\t!isType(output) &&\n\t\t!isVar(output) &&\n\t\t!isFnSchema(output)\n\t) {\n\t\tconst keys = Object.keys(output);\n\t\tif (\n\t\t\tkeys.length > 0 &&\n\t\t\tkeys.every((k) => k === \"def\" || k === \"validation\")\n\t\t) {\n\t\t\tconst { def, validation } = output as {\n\t\t\t\tdef?: unknown;\n\t\t\t\tvalidation?: unknown;\n\t\t\t};\n\t\t\treturn { def: def ?? validation, validation };\n\t\t}\n\t}\n\treturn { def: output, validation: output };\n};\n\n/**\n * One input field, in four flavours:\n * - a `v.var()`, whose shape comes from the var's own `schema`\n * - a handler-less `v.fn(...)` builder, which types the field as a FN\n * - a type from `v.string()` / `v.object()` / ...\n * - a bare nested record, which recurses\n *\n * The record case has to come last: a TypeDefination is itself a record,\n * and so is a builder.\n */\ntype FieldOut<F> = F extends { $var: true; schema?: infer S }\n\t? InferInput<NonNullable<S>>\n\t: F extends { $fnSchema: { input?: infer FI; output?: infer FO } }\n\t\t? SchemaFnOut<FI, FO> & FnVarBrand<FI>\n\t\t: F extends TypeDefination<any, infer O, any>\n\t\t\t? O\n\t\t\t: F extends Record<string, unknown>\n\t\t\t\t? Prettify<{ [K in keyof F]: FieldOut<F[K]> }>\n\t\t\t\t: never;\n\ntype FieldIn<F> = F extends { $var: true; schema?: infer S }\n\t? InferArgs<NonNullable<S>>\n\t: F extends { $fnSchema: { input?: infer FI; output?: infer FO } }\n\t\t? SchemaFnIn<FI, FO> & FnVarBrand<FI>\n\t\t: F extends TypeDefination<infer T, any, any>\n\t\t\t? T\n\t\t\t: F extends Record<string, unknown>\n\t\t\t\t? ArgsShape<F>\n\t\t\t\t: never;\n\n/**\n * A field's declared default, looked through a var to its schema. Only a\n * TYPE's default counts - a var's own default is its initial value, not a\n * licence to omit the input. The `$fnSchema` guard mirrors `asType`'s\n * ordering: a bare `v.fn` is CALLABLE, and any callable duck-matches\n * TypeDefination (`.name` comes with every function), which would read a\n * phantom default off it and wrongly mark the field optional.\n */\ntype DefaultOf<F> = F extends { $var: true; schema?: infer S }\n\t? NonNullable<S> extends TypeDefination<any, any, infer D>\n\t\t? D\n\t\t: never\n\t: F extends { $fnSchema: unknown }\n\t\t? never\n\t\t: F extends TypeDefination<any, any, infer D>\n\t\t\t? D\n\t\t\t: never;\n\ntype Defaulted<I> = {\n\t[K in keyof I]: [DefaultOf<I[K]>] extends [never] ? never : K;\n}[keyof I];\n\n/** Defaulted keys are optional to send, but always present in the handler. */\ntype ArgsShape<I> = Prettify<\n\t{ [K in keyof I as K extends Defaulted<I> ? never : K]: FieldIn<I[K]> } & {\n\t\t[K in keyof I as K extends Defaulted<I> ? K : never]?: FieldIn<I[K]>;\n\t}\n>;\n\n/**\n * Post-transform shape - what a handler sees. The `$var` branch must come\n * first: a var's `name` property duck-matches TypeDefination, and falling\n * into that branch reads the var's VALUE type instead of its schema. A\n * TUPLE input maps position by position - the fn takes that many args.\n */\nexport type InferInput<I> = I extends { $var: true; schema?: infer S }\n\t? InferInput<NonNullable<S>>\n\t: I extends { $fnSchema: { input?: infer FI; output?: infer FO } }\n\t\t? SchemaFnOut<FI, FO> & FnVarBrand<FI>\n\t\t: I extends readonly unknown[]\n\t\t\t? { -readonly [K in keyof I]: InferInput<I[K]> }\n\t\t\t: I extends TypeDefination<any, infer O, any>\n\t\t\t\t? O\n\t\t\t\t: Prettify<{ [K in keyof I]: FieldOut<I[K]> }>;\n\n/** Pre-transform shape - what a caller sends. Same branch order. */\nexport type InferArgs<I> = I extends { $var: true; schema?: infer S }\n\t? InferArgs<NonNullable<S>>\n\t: I extends { $fnSchema: { input?: infer FI; output?: infer FO } }\n\t\t? SchemaFnIn<FI, FO> & FnVarBrand<FI>\n\t\t: I extends readonly unknown[]\n\t\t\t? { -readonly [K in keyof I]: InferArgs<I[K]> }\n\t\t\t: I extends TypeDefination<infer T, any, any>\n\t\t\t\t? T\n\t\t\t\t: ArgsShape<I>;\n\nexport const isType = (value: any): value is TypeDefination<any, any> =>\n\ttypeof value?.name === \"string\";\n\n/** A handler-less `v.fn(...)` builder doubles as a schema: the value it\n * describes is a FN with the declared signature. The builder FN itself is\n * branded too, so bare `v.fn` reads as \"any function\". */\nexport const isFnSchema = (\n\tvalue: any,\n): value is { $fnSchema: { input?: unknown; output?: unknown } } =>\n\ttypeof value?.$fnSchema === \"object\" && value.$fnSchema !== null;\n\nexport const asType = (value: any): TypeDefination<any, any> =>\n\t// A var's own `name` (\"user\") would duck-match isType, so unwrap first -\n\t// and a builder is a record, so it must be caught before the fallback.\n\tisVar(value)\n\t\t? asType(value.schema ?? {})\n\t\t: isFnSchema(value)\n\t\t\t? { name: \"function\", fnInput: value.$fnSchema.input }\n\t\t\t: isType(value)\n\t\t\t\t? value\n\t\t\t\t: { name: \"object\", shape: value };\n\nexport const typeOf = (value: unknown) =>\n\tvalue === null\n\t\t? \"null\"\n\t\t: Array.isArray(value)\n\t\t\t? \"array\"\n\t\t\t: Number.isNaN(value)\n\t\t\t\t? \"NaN\"\n\t\t\t\t: typeof value;\n\nexport const isVar = (value: any): boolean => value?.$var === true;\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst fail = (path: string, message: string): never => {\n\tthrow new ValidationError(path, message);\n};\n\n/** Constraint checks, run after the value's type is known to be right. */\nconst applyRules = (def: Rules, value: any, path: string) => {\n\tif (def.enum && !def.enum.includes(value)) {\n\t\tfail(path, `expected one of ${def.enum.join(\", \")}, received ${value}`);\n\t}\n\tif (typeof value === \"string\") {\n\t\tif (def.length !== undefined && value.length !== def.length) {\n\t\t\tfail(path, `expected length ${def.length}, received ${value.length}`);\n\t\t}\n\t\tif (def.min !== undefined && value.length < def.min) {\n\t\t\tfail(\n\t\t\t\tpath,\n\t\t\t\t`expected at least ${def.min} characters, received ${value.length}`,\n\t\t\t);\n\t\t}\n\t\tif (def.max !== undefined && value.length > def.max) {\n\t\t\tfail(\n\t\t\t\tpath,\n\t\t\t\t`expected at most ${def.max} characters, received ${value.length}`,\n\t\t\t);\n\t\t}\n\t\tif (def.regex && !def.regex.test(value)) {\n\t\t\tfail(path, `does not match ${def.regex}`);\n\t\t}\n\t\tif (def.email && !EMAIL.test(value))\n\t\t\tfail(path, \"expected an email address\");\n\t\tif (def.url) {\n\t\t\ttry {\n\t\t\t\tnew URL(value);\n\t\t\t} catch {\n\t\t\t\tfail(path, \"expected a URL\");\n\t\t\t}\n\t\t}\n\t\tif (def.startsWith !== undefined && !value.startsWith(def.startsWith)) {\n\t\t\tfail(path, `expected to start with \"${def.startsWith}\"`);\n\t\t}\n\t\tif (def.endsWith !== undefined && !value.endsWith(def.endsWith)) {\n\t\t\tfail(path, `expected to end with \"${def.endsWith}\"`);\n\t\t}\n\t}\n\tif (Array.isArray(value)) {\n\t\tif (def.length !== undefined && value.length !== def.length) {\n\t\t\tfail(path, `expected length ${def.length}, received ${value.length}`);\n\t\t}\n\t\tif (def.min !== undefined && value.length < def.min) {\n\t\t\tfail(\n\t\t\t\tpath,\n\t\t\t\t`expected at least ${def.min} items, received ${value.length}`,\n\t\t\t);\n\t\t}\n\t\tif (def.max !== undefined && value.length > def.max) {\n\t\t\tfail(path, `expected at most ${def.max} items, received ${value.length}`);\n\t\t}\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (def.int && !Number.isInteger(value)) {\n\t\t\tfail(path, `expected an integer, received ${value}`);\n\t\t}\n\t\tif (def.min !== undefined && value < def.min) {\n\t\t\tfail(path, `expected >= ${def.min}, received ${value}`);\n\t\t}\n\t\tif (def.max !== undefined && value > def.max) {\n\t\t\tfail(path, `expected <= ${def.max}, received ${value}`);\n\t\t}\n\t}\n\tif (def.check) {\n\t\tconst result = def.check(value);\n\t\tif (result !== true) {\n\t\t\tfail(path, typeof result === \"string\" ? result : \"failed check\");\n\t\t}\n\t}\n};\n\nexport const validate = (\n\tdef: TypeDefination<any, any, any>,\n\tvalue: unknown,\n\tpath: string,\n): any => {\n\t// `undefined` falls back to the declared default before anything else,\n\t// then to `optional`, which passes it through untouched.\n\tif (value === undefined) {\n\t\tif (def.default !== undefined) value = def.default;\n\t\telse if (def.optional) return undefined;\n\t}\n\t// A var used as an input field validates against its own schema. An\n\t// absent value is left alone so the var keeps its default.\n\tif (isVar(def)) {\n\t\tif (value === undefined) return undefined;\n\t\tconst schema = (def as any).schema;\n\t\treturn schema === undefined ? value : validate(schema, value, path);\n\t}\n\tif (def.name === \"any\") {\n\t\treturn def.transform ? def.transform(value) : value;\n\t}\n\tif (def.name === \"date\") {\n\t\tif (!(value instanceof Date)) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tpath,\n\t\t\t\t`expected date, received ${typeOf(value)}`,\n\t\t\t);\n\t\t}\n\t\treturn def.transform ? def.transform(value) : value;\n\t}\n\tif (def.name === \"function\") {\n\t\tif (typeof value !== \"function\") {\n\t\t\tthrow new ValidationError(\n\t\t\t\tpath,\n\t\t\t\t`expected function, received ${typeOf(value)}`,\n\t\t\t);\n\t\t}\n\t\t// A branded fn (`$fn`) validates its own declared input at its own\n\t\t// door; a plain closure gets THIS schema's input validated for it.\n\t\tconst inner = def.fnInput;\n\t\tif (inner === undefined || (value as { $fn?: boolean }).$fn === true) {\n\t\t\treturn value;\n\t\t}\n\t\tconst innerType = asType(inner);\n\t\treturn (input?: unknown, parent?: unknown) =>\n\t\t\t(value as (i: unknown, p: unknown) => unknown)(\n\t\t\t\tvalidate(innerType, input, `${path}()`),\n\t\t\t\tparent,\n\t\t\t);\n\t}\n\tif (def.name === \"array\") {\n\t\tif (!Array.isArray(value)) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tpath,\n\t\t\t\t`expected array, received ${typeOf(value)}`,\n\t\t\t);\n\t\t}\n\t\tapplyRules(def, value, path);\n\t\t// No declared element (`v.array()`): ANY array - passed through\n\t\t// as-is, elements untouched.\n\t\tif (def.shape === undefined) {\n\t\t\treturn def.transform ? def.transform(value) : value;\n\t\t}\n\t\t// Every element validates - ALL failures report together, not\n\t\t// just the first, mirroring object fields.\n\t\tconst elementType = asType(def.shape);\n\t\tconst items: unknown[] = [];\n\t\tconst problems: Issue[] = [];\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\ttry {\n\t\t\t\titems.push(validate(elementType, value[index], `${path}[${index}]`));\n\t\t\t} catch (thrown) {\n\t\t\t\tif (!(thrown instanceof ValidationError)) throw thrown;\n\t\t\t\tproblems.push(...thrown.issues);\n\t\t\t}\n\t\t}\n\t\tconst firstProblem = problems[0];\n\t\tif (firstProblem) {\n\t\t\tthrow new ValidationError(\n\t\t\t\tfirstProblem.path,\n\t\t\t\tfirstProblem.message,\n\t\t\t\tproblems,\n\t\t\t);\n\t\t}\n\t\treturn def.transform ? def.transform(items) : items;\n\t}\n\tif (def.name === \"object\") {\n\t\tif (typeOf(value) !== \"object\") {\n\t\t\tthrow new ValidationError(\n\t\t\t\tpath,\n\t\t\t\t`expected object, received ${typeOf(value)}`,\n\t\t\t);\n\t\t}\n\t\t// No declared shape (`v.object()`): ANY object - passed through\n\t\t// as-is, nothing stripped.\n\t\tif (def.shape === undefined) {\n\t\t\treturn def.transform ? def.transform(value) : value;\n\t\t}\n\t\t// Every field validates - ALL failures report together, not just\n\t\t// the first. Three bad fields is one error with three issues.\n\t\tconst parsed: Record<string, unknown> = {};\n\t\tconst issues: Issue[] = [];\n\t\tfor (const [field, child] of Object.entries(\n\t\t\tdef.shape as Record<string, unknown>,\n\t\t)) {\n\t\t\ttry {\n\t\t\t\tconst parsedField = validate(\n\t\t\t\t\tasType(child),\n\t\t\t\t\t(value as Record<string, unknown>)[field],\n\t\t\t\t\t`${path}.${field}`,\n\t\t\t\t);\n\t\t\t\t// An absent optional field stays ABSENT - materializing the key\n\t\t\t\t// as `undefined` would clobber values it gets spread over.\n\t\t\t\tif (parsedField !== undefined) parsed[field] = parsedField;\n\t\t\t} catch (thrown) {\n\t\t\t\tif (!(thrown instanceof ValidationError)) throw thrown;\n\t\t\t\tissues.push(...thrown.issues);\n\t\t\t}\n\t\t}\n\t\tconst firstIssue = issues[0];\n\t\tif (firstIssue) {\n\t\t\tthrow new ValidationError(firstIssue.path, firstIssue.message, issues);\n\t\t}\n\t\treturn def.transform ? def.transform(parsed) : parsed;\n\t}\n\tif (typeOf(value) !== def.name) {\n\t\tthrow new ValidationError(\n\t\t\tpath,\n\t\t\t`expected ${def.name}, received ${typeOf(value)}`,\n\t\t);\n\t}\n\tapplyRules(def, value, path);\n\treturn def.transform ? def.transform(value) : value;\n};\n\n/** Builds the runtime object; the declared return type is the contract. */\nconst build = (name: string, options: any, extra?: any): any => ({\n\tname,\n\t...extra,\n\t...options,\n});\n\nexport const vTypes = {\n\t/** An `enum` narrows both sides to the literal union: `v.string({\n\t * enum: [\"a\", \"b\"] })` types as `\"a\" | \"b\"`, not `string`. */\n\tstring: <\n\t\tconst E extends string = string,\n\t\tO = E,\n\t\tD = never,\n\t\tOpt extends boolean = false,\n\t>(\n\t\toptions?: StringOptions<E, O> & WithDefault<D> & WithOptional<Opt>,\n\t): TypeDefination<E, OutOf<O, D, Opt>, DefOf<D, Opt>> =>\n\t\tbuild(\"string\", options),\n\tnumber: <O = number, D = never, Opt extends boolean = false>(\n\t\toptions?: NumberOptions<O> & WithDefault<D> & WithOptional<Opt>,\n\t): TypeDefination<number, OutOf<O, D, Opt>, DefOf<D, Opt>> =>\n\t\tbuild(\"number\", options),\n\tboolean: <O = boolean, D = never, Opt extends boolean = false>(\n\t\toptions?: TypeOptions<boolean, O> & WithDefault<D> & WithOptional<Opt>,\n\t): TypeDefination<boolean, OutOf<O, D, Opt>, DefOf<D, Opt>> =>\n\t\tbuild(\"boolean\", options),\n\t/** A Date INSTANCE - checked with `instanceof`, never parsed. */\n\tdate: <O = Date, D = never, Opt extends boolean = false>(\n\t\toptions?: TypeOptions<Date, O> & WithDefault<D> & WithOptional<Opt>,\n\t): TypeDefination<Date, OutOf<O, D, Opt>, DefOf<D, Opt>> =>\n\t\tbuild(\"date\", options),\n\t/** Passthrough - validated as-is, never coerced or stripped. */\n\tany: <T = unknown, D = never, Opt extends boolean = false>(\n\t\toptions?: TypeOptions<T, T> & WithDefault<D> & WithOptional<Opt>,\n\t): TypeDefination<T, OutOf<T, D, Opt>, DefOf<D, Opt>> =>\n\t\tbuild(\"any\", options),\n\t/** With a SHAPE every field validates; with NO shape (`v.object()`)\n\t * any object passes, as-is. */\n\tobject: <\n\t\tS = undefined,\n\t\tO = DefineOutput<S>,\n\t\tD = never,\n\t\tOpt extends boolean = false,\n\t>(\n\t\tshape?: S,\n\t\toptions?: TypeOptions<DefineOutput<S>, O> &\n\t\t\tWithDefault<D> &\n\t\t\tWithOptional<Opt>,\n\t\t// Args use ArgsShape, not DefineInput, so a defaulted field inside\n\t\t// an object is optional to send there too.\n\t): [S] extends [undefined]\n\t\t? TypeDefination<Record<string, any>, Record<string, any>>\n\t\t: TypeDefination<ArgsShape<S>, OutOf<O, D, Opt>, DefOf<D, Opt>> =>\n\t\tbuild(\"object\", options, shape === undefined ? {} : { shape }),\n\t/** With an ELEMENT every item validates - all failures report\n\t * together, like object fields; with NO element (`v.array()`) any\n\t * array passes, as-is. `min`/`max`/`length` count items. */\n\tarray: <\n\t\tE = undefined,\n\t\tO = FieldOut<E>[],\n\t\tD = never,\n\t\tOpt extends boolean = false,\n\t>(\n\t\telement?: E,\n\t\toptions?: ArrayOptions<E, O> & WithDefault<D> & WithOptional<Opt>,\n\t): [E] extends [undefined]\n\t\t? TypeDefination<any[], OutOf<any[], D, Opt>, DefOf<D, Opt>>\n\t\t: TypeDefination<FieldIn<E>[], OutOf<O, D, Opt>, DefOf<D, Opt>> =>\n\t\tbuild(\"array\", options, element === undefined ? {} : { shape: element }),\n} satisfies Record<string, (...args: any[]) => TypeDefination<any, any>>;\n"],"mappings":";;;;;AAiLA,MAAa,kBACZ,WAC6C;CAC7C,IAAI,WAAW,KAAA,GAAW,OAAO,CAAC;CAClC,IACC,WAAW,QACX,OAAO,WAAW,YAClB,CAAC,MAAM,QAAQ,MAAM,KACrB,CAAC,OAAO,MAAM,KACd,CAAC,MAAM,MAAM,KACb,CAAC,WAAW,MAAM,GACjB;EACD,MAAM,OAAO,OAAO,KAAK,MAAM;EAC/B,IACC,KAAK,SAAS,KACd,KAAK,OAAO,MAAM,MAAM,SAAS,MAAM,YAAY,GAClD;GACD,MAAM,EAAE,KAAK,eAAe;GAI5B,OAAO;IAAE,KAAK,OAAO;IAAY;GAAW;EAC7C;CACD;CACA,OAAO;EAAE,KAAK;EAAQ,YAAY;CAAO;AAC1C;AAwFA,MAAa,UAAU,UACtB,OAAO,OAAO,SAAS;;;;AAKxB,MAAa,cACZ,UAEA,OAAO,OAAO,cAAc,YAAY,MAAM,cAAc;AAE7D,MAAa,UAAU,UAGtB,MAAM,KAAK,IACR,OAAO,MAAM,UAAU,CAAC,CAAC,IACzB,WAAW,KAAK,IACf;CAAE,MAAM;CAAY,SAAS,MAAM,UAAU;AAAM,IACnD,OAAO,KAAK,IACX,QACA;CAAE,MAAM;CAAU,OAAO;AAAM;AAErC,MAAa,UAAU,UACtB,UAAU,OACP,SACA,MAAM,QAAQ,KAAK,IAClB,UACA,OAAO,MAAM,KAAK,IACjB,QACA,OAAO;AAEb,MAAa,SAAS,UAAwB,OAAO,SAAS;AAE9D,MAAM,QAAQ;AAEd,MAAM,QAAQ,MAAc,YAA2B;CACtD,MAAM,IAAI,gBAAgB,MAAM,OAAO;AACxC;;AAGA,MAAM,cAAc,KAAY,OAAY,SAAiB;CAC5D,IAAI,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,KAAK,GACvC,KAAK,MAAM,m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G,OACZ;GAGA,IAAI,gBAAgB,KAAA,GAAW,OAAO,SAAS;EAChD,SAAS,QAAQ;GAChB,IAAI,EAAE,kBAAkB,kBAAkB,MAAM;GAChD,OAAO,KAAK,GAAG,OAAO,MAAM;EAC7B;EAED,MAAM,aAAa,OAAO;EAC1B,IAAI,YACH,MAAM,IAAI,gBAAgB,WAAW,MAAM,WAAW,SAAS,MAAM;EAEtE,OAAO,IAAI,YAAY,IAAI,UAAU,MAAM,IAAI;CAChD;CACA,IAAI,OAAO,KAAK,MAAM,IAAI,MACzB,MAAM,IAAI,gBACT,MACA,YAAY,IAAI,KAAK,aAAa,OAAO,KAAK,GAC/C;CAED,WAAW,KAAK,OAAO,IAAI;CAC3B,OAAO,IAAI,YAAY,IAAI,UAAU,KAAK,IAAI;AAC/C;;AAGA,MAAM,SAAS,MAAc,SAAc,WAAsB;CAChE;CACA,GAAG;CACH,GAAG;AACJ;AAEA,MAAa,SAAS;;;CAGrB,SAMC,YAEA,MAAM,UAAU,OAAO;CACxB,SACC,YAEA,MAAM,UAAU,OAAO;CACxB,UACC,YAEA,MAAM,WAAW,OAAO;;CAEzB,OACC,YAEA,MAAM,QAAQ,OAAO;;CAEtB,MACC,YAEA,MAAM,OAAO,OAAO;;;CAGrB,SAMC,OACA,YAQA,MAAM,UAAU,SAAS,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,CAAC;;;;CAI9D,QAMC,SACA,YAIA,MAAM,SAAS,SAAS,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,CAAC;AACzE"}
@@ -0,0 +1,18 @@
1
+ import { Prettify } from "./types.cjs";
2
+ import { ModuleVars, VarArgsInScope, VarExtensionsFor } from "./module.cjs";
3
+ //#region src/scope.d.ts
4
+ type MergeExtension<T, E> = T extends object ? Prettify<T & E> : T;
5
+ type Merged<PL, Base> = ModuleVars<PL> & Base;
6
+ type WidenSchemaFn<T, PL> = T extends {
7
+ $fnVar?: [infer N extends string];
8
+ } ? T extends ((input: infer A) => infer R) ? unknown extends VarArgsInScope<PL, N> ? T : ((input: Prettify<A & VarArgsInScope<PL, N>>) => R) & {
9
+ readonly $fnVar?: [N];
10
+ } : T : T;
11
+ type WidenSchemaFns<T, PL> = T extends ((...args: any[]) => any) ? WidenSchemaFn<T, PL> : T extends readonly unknown[] ? { [K in keyof T]: WidenSchemaFns<T[K], PL>; } : T extends Date | RegExp | Promise<unknown> | Map<any, any> | Set<any> ? T : T extends object ? { [K in keyof T]: WidenSchemaFns<T[K], PL>; } : T;
12
+ type ScopeOf<PL, Base = unknown, ExtPL = PL> = { [K in keyof Merged<PL, Base>]: WidenSchemaFns<MergeExtension<Merged<PL, Base>[K], VarExtensionsFor<ExtPL, K & string>>, ExtPL>; };
13
+ type ResolvedVars<PL> = { [K in keyof ModuleVars<PL>]: MergeExtension<ModuleVars<PL>[K], VarExtensionsFor<PL, K & string>>; };
14
+ type VarScope<RV, Required, RO extends boolean = false> = RO extends true ? { readonly [K in keyof RV]: K extends Required ? NonNullable<RV[K]> : RV[K]; } : Prettify<{ [K in keyof RV]: K extends Required ? NonNullable<RV[K]> : RV[K]; }>;
15
+ type VarName<RV> = keyof RV & string;
16
+ //#endregion
17
+ export { ResolvedVars, ScopeOf, VarName, VarScope, WidenSchemaFns };
18
+ //# sourceMappingURL=scope.d.cts.map
@@ -0,0 +1,18 @@
1
+ import { Prettify } from "./types.mjs";
2
+ import { ModuleVars, VarArgsInScope, VarExtensionsFor } from "./module.mjs";
3
+ //#region src/scope.d.ts
4
+ type MergeExtension<T, E> = T extends object ? Prettify<T & E> : T;
5
+ type Merged<PL, Base> = ModuleVars<PL> & Base;
6
+ type WidenSchemaFn<T, PL> = T extends {
7
+ $fnVar?: [infer N extends string];
8
+ } ? T extends ((input: infer A) => infer R) ? unknown extends VarArgsInScope<PL, N> ? T : ((input: Prettify<A & VarArgsInScope<PL, N>>) => R) & {
9
+ readonly $fnVar?: [N];
10
+ } : T : T;
11
+ type WidenSchemaFns<T, PL> = T extends ((...args: any[]) => any) ? WidenSchemaFn<T, PL> : T extends readonly unknown[] ? { [K in keyof T]: WidenSchemaFns<T[K], PL>; } : T extends Date | RegExp | Promise<unknown> | Map<any, any> | Set<any> ? T : T extends object ? { [K in keyof T]: WidenSchemaFns<T[K], PL>; } : T;
12
+ type ScopeOf<PL, Base = unknown, ExtPL = PL> = { [K in keyof Merged<PL, Base>]: WidenSchemaFns<MergeExtension<Merged<PL, Base>[K], VarExtensionsFor<ExtPL, K & string>>, ExtPL>; };
13
+ type ResolvedVars<PL> = { [K in keyof ModuleVars<PL>]: MergeExtension<ModuleVars<PL>[K], VarExtensionsFor<PL, K & string>>; };
14
+ type VarScope<RV, Required, RO extends boolean = false> = RO extends true ? { readonly [K in keyof RV]: K extends Required ? NonNullable<RV[K]> : RV[K]; } : Prettify<{ [K in keyof RV]: K extends Required ? NonNullable<RV[K]> : RV[K]; }>;
15
+ type VarName<RV> = keyof RV & string;
16
+ //#endregion
17
+ export { ResolvedVars, ScopeOf, VarName, VarScope, WidenSchemaFns };
18
+ //# sourceMappingURL=scope.d.mts.map
@@ -0,0 +1,256 @@
1
+ const require_schema = require("./schema.cjs");
2
+ const require_module = require("./module.cjs");
3
+ //#region src/storage.ts
4
+ const WHERE_OPS = {
5
+ eq: true,
6
+ ne: true,
7
+ lt: true,
8
+ lte: true,
9
+ gt: true,
10
+ gte: true,
11
+ in: true,
12
+ notIn: true,
13
+ contains: true,
14
+ startsWith: true,
15
+ endsWith: true
16
+ };
17
+ /** An operator object is a plain record whose keys are ALL operator names.
18
+ * Anything else - a Date, an array, an empty object - is a value. */
19
+ const isOps = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date) && Object.keys(value).length > 0 && Object.keys(value).every((key) => key in WHERE_OPS);
20
+ /** Flatten a where to normalized conditions - the adapter author's
21
+ * translation seam: map each condition onto your query language, AND them. */
22
+ const conditionsOf = (where = {}) => Object.entries(where).flatMap(([field, spec]) => isOps(spec) ? Object.entries(spec).map(([op, value]) => ({
23
+ field,
24
+ op,
25
+ value
26
+ })) : [{
27
+ field,
28
+ op: "eq",
29
+ value: spec
30
+ }]);
31
+ /** Dates equate and order by their instant. */
32
+ const rawValue = (value) => value instanceof Date ? value.getTime() : value;
33
+ const equals = (a, b) => rawValue(a) === rawValue(b);
34
+ const compare = (a, b) => {
35
+ const left = rawValue(a);
36
+ const right = rawValue(b);
37
+ return left < right ? -1 : left > right ? 1 : 0;
38
+ };
39
+ const holds = (row, { field, op, value }) => {
40
+ const current = row[field];
41
+ switch (op) {
42
+ case "eq": return equals(current, value);
43
+ case "ne": return !equals(current, value);
44
+ case "lt":
45
+ case "lte":
46
+ case "gt":
47
+ case "gte": {
48
+ if (current == null || value == null) return false;
49
+ const order = compare(current, value);
50
+ if (op === "lt") return order < 0;
51
+ if (op === "lte") return order <= 0;
52
+ if (op === "gt") return order > 0;
53
+ return order >= 0;
54
+ }
55
+ case "in": return value.some((member) => equals(current, member));
56
+ case "notIn": return !value.some((member) => equals(current, member));
57
+ case "contains": return typeof current === "string" && current.includes(value);
58
+ case "startsWith": return typeof current === "string" && current.startsWith(value);
59
+ case "endsWith": return typeof current === "string" && current.endsWith(value);
60
+ }
61
+ };
62
+ /** Does a row satisfy a where? The in-memory evaluator - the dummy adapter
63
+ * runs on it, and any adapter over an unqueryable backend can too. */
64
+ const matchesWhere = (row, where = {}) => conditionsOf(where).every((condition) => holds(row, condition));
65
+ /** The DUMMY adapter: rows in arrays, one per model. Implements the whole
66
+ * surface - the optional verbs by mutation (single-threaded, so "atomic"),
67
+ * transactions by snapshot-and-restore. */
68
+ const memoryAdapter = () => {
69
+ let tables = /* @__PURE__ */ new Map();
70
+ const rows = (model) => {
71
+ let list = tables.get(model);
72
+ if (!list) {
73
+ list = [];
74
+ tables.set(model, list);
75
+ }
76
+ return list;
77
+ };
78
+ const self = {
79
+ create: (model, data) => {
80
+ const row = { ...data };
81
+ rows(model).push(row);
82
+ return row;
83
+ },
84
+ findOne: (model, where) => rows(model).find((row) => matchesWhere(row, where)) ?? null,
85
+ findMany: (model, where, options) => {
86
+ let list = rows(model).filter((row) => matchesWhere(row, where));
87
+ const sort = options?.sortBy;
88
+ if (sort) {
89
+ const direction = sort.direction === "desc" ? -1 : 1;
90
+ list = [...list].sort((a, b) => direction * compare(a[sort.field], b[sort.field]));
91
+ }
92
+ const start = options?.offset ?? 0;
93
+ const end = options?.limit === void 0 ? void 0 : start + options.limit;
94
+ return start === 0 && end === void 0 ? list : list.slice(start, end);
95
+ },
96
+ update: (model, where, patch) => {
97
+ const row = rows(model).find((r) => matchesWhere(r, where));
98
+ return row ? Object.assign(row, patch) : null;
99
+ },
100
+ delete: (model, where) => {
101
+ const list = rows(model);
102
+ const keep = list.filter((row) => !matchesWhere(row, where));
103
+ tables.set(model, keep);
104
+ return list.length - keep.length;
105
+ },
106
+ count: (model, where) => rows(model).filter((row) => matchesWhere(row, where)).length,
107
+ consumeOne: (model, where) => {
108
+ const list = rows(model);
109
+ const index = list.findIndex((row) => matchesWhere(row, where));
110
+ return index === -1 ? null : list.splice(index, 1)[0];
111
+ },
112
+ incrementOne: (model, where, increments) => {
113
+ const row = rows(model).find((r) => matchesWhere(r, where));
114
+ if (!row) return null;
115
+ for (const [field, by] of Object.entries(increments)) row[field] = (row[field] ?? 0) + by;
116
+ return row;
117
+ },
118
+ transaction: async (run) => {
119
+ const snapshot = new Map([...tables].map(([model, list]) => [model, list.map((row) => ({ ...row }))]));
120
+ try {
121
+ return await run(self);
122
+ } catch (thrown) {
123
+ tables = snapshot;
124
+ throw thrown;
125
+ }
126
+ }
127
+ };
128
+ return self;
129
+ };
130
+ const OPS = [
131
+ "create",
132
+ "findOne",
133
+ "findMany",
134
+ "update",
135
+ "delete",
136
+ "count",
137
+ "consumeOne",
138
+ "incrementOne"
139
+ ];
140
+ /** The op against the backend, optional verbs falling back to the required
141
+ * six: find-then-write - correct alone, racy under contention. The comment
142
+ * every fallback deserves lives on `StorageAdapter`. */
143
+ const rawOp = (adapter, name, op, args) => {
144
+ if (op === "consumeOne" && !adapter.consumeOne) return (async () => {
145
+ const where = args[0];
146
+ const row = await adapter.findOne(name, where);
147
+ if (!row) return null;
148
+ await adapter.delete(name, row);
149
+ return row;
150
+ })();
151
+ if (op === "incrementOne" && !adapter.incrementOne) return (async () => {
152
+ const [where, increments] = args;
153
+ const row = await adapter.findOne(name, where);
154
+ if (!row) return null;
155
+ const patch = Object.fromEntries(Object.entries(increments).map(([field, by]) => [field, (row[field] ?? 0) + by]));
156
+ return adapter.update(name, where, patch);
157
+ })();
158
+ return adapter[op](name, ...args);
159
+ };
160
+ const buildStorage = (state, models) => {
161
+ const run = (key, name, op, args) => {
162
+ const base = () => Promise.resolve(rawOp(state.adapter, name, op, args));
163
+ return state.hooks.filter((entry) => require_module.matchesTarget(entry.target, `${key}.${op}`)).reduceRight((next, entry) => () => Promise.resolve(entry.hook({
164
+ model: key,
165
+ op,
166
+ args
167
+ }, next)), base)();
168
+ };
169
+ const storage = {};
170
+ for (const [key, input] of Object.entries(models)) {
171
+ const name = (require_schema.isVar(input) ? input : input.schema).name;
172
+ const collection = {
173
+ create: (data) => run(key, name, "create", [data]),
174
+ findOne: (where) => run(key, name, "findOne", [where]),
175
+ findMany: (where, options) => run(key, name, "findMany", [where, options]),
176
+ update: (where, patch) => run(key, name, "update", [where, patch]),
177
+ delete: (where) => run(key, name, "delete", [where]),
178
+ count: (where) => run(key, name, "count", [where]),
179
+ consumeOne: (where) => run(key, name, "consumeOne", [where]),
180
+ incrementOne: (where, increments) => run(key, name, "incrementOne", [where, increments])
181
+ };
182
+ storage[key] = collection;
183
+ if (require_schema.isVar(input)) continue;
184
+ for (const op of OPS) {
185
+ const declared = input[op];
186
+ if (!declared) continue;
187
+ const cacheKey = `${key}.${op}`;
188
+ let entries = state.subscriptions.get(cacheKey);
189
+ if (!entries) {
190
+ const produced = typeof declared === "function" ? declared(collection[op]) : declared;
191
+ entries = Array.isArray(produced) ? produced : [produced];
192
+ state.subscriptions.set(cacheKey, entries);
193
+ }
194
+ entries.forEach((entry, index) => {
195
+ storage[`${key}$${op}${index === 0 ? "" : index}`] = entry;
196
+ });
197
+ }
198
+ }
199
+ const self = Object.assign(storage, {
200
+ $adapter: (adapter) => {
201
+ state.adapter = adapter;
202
+ return self;
203
+ },
204
+ $on: (target, hook) => {
205
+ state.hooks.push({
206
+ target,
207
+ hook
208
+ });
209
+ return self;
210
+ },
211
+ $omit: (...keys) => buildStorage(state, Object.fromEntries(Object.entries(models).filter(([key]) => !keys.includes(key)))),
212
+ $pick: (...keys) => buildStorage(state, Object.fromEntries(keys.map((key) => [key, models[key]]))),
213
+ $extend: (more) => buildStorage(state, {
214
+ ...models,
215
+ ...more
216
+ }),
217
+ $transaction: (fn) => {
218
+ const inside = (adapter) => Promise.resolve(fn(buildStorage({
219
+ ...state,
220
+ adapter
221
+ }, models)));
222
+ return state.adapter.transaction ? state.adapter.transaction((tx) => inside(tx)) : inside(state.adapter);
223
+ },
224
+ $models: models
225
+ });
226
+ return self;
227
+ };
228
+ /**
229
+ * MANY instances of a var: each model is a collection of rows shaped like
230
+ * the var's VALUE, addressed by the var's NAME - the var stays what it
231
+ * always was (the scope's one current instance), the storage holds every
232
+ * other one, and the query API is how rows move between the two.
233
+ *
234
+ * The returned storage is CUSTOMIZABLE through its `$` surface: `$adapter`
235
+ * swaps the backend in place, `$on` mounts hooks around ops,
236
+ * `$omit`/`$pick`/`$extend` derive model views over the same state, and
237
+ * `$transaction` scopes ops to one adapter transaction.
238
+ *
239
+ * A model can also DECLARE its persistence: pass `{ schema, create: ... }`
240
+ * instead of the bare var, and the op subscriptions ride on the storage as
241
+ * mountable `v.on` entries - `use: [db]` wires them into the app. The same
242
+ * config carries `fields` metadata (unique, index, references) for schema
243
+ * generators to consume.
244
+ */
245
+ const makeStorage = (adapter, models) => buildStorage({
246
+ adapter,
247
+ hooks: [],
248
+ subscriptions: /* @__PURE__ */ new Map()
249
+ }, models);
250
+ //#endregion
251
+ exports.conditionsOf = conditionsOf;
252
+ exports.makeStorage = makeStorage;
253
+ exports.matchesWhere = matchesWhere;
254
+ exports.memoryAdapter = memoryAdapter;
255
+
256
+ //# sourceMappingURL=storage.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.cjs","names":["matchesTarget","isVar"],"sources":["../src/storage.ts"],"sourcesContent":["import { matchesTarget, type OnEntry } from \"./module\";\nimport { isVar } from \"./schema\";\nimport type { ValueOfVar, VarDefination } from \"./var\";\n\n/* ---------------------------------- where ---------------------------------- */\n\n/** Per-field operators, for everything equality can't say: expiry sweeps\n * (`lt`), revocation lists (`in`), guarded counters (`lt` as the guard).\n * A bare value stays plain equality - the common case reads like data. */\nexport type WhereOps<V> = {\n\teq?: V;\n\tne?: V;\n\tlt?: V;\n\tlte?: V;\n\tgt?: V;\n\tgte?: V;\n\tin?: readonly V[];\n\tnotIn?: readonly V[];\n\tcontains?: string;\n\tstartsWith?: string;\n\tendsWith?: string;\n};\n\nexport type WhereOp = keyof WhereOps<unknown>;\n\n/** AND across fields; each field a bare value (equality) or operators. */\nexport type Where<R> = { [K in keyof R]?: R[K] | WhereOps<R[K]> };\n\n/** One normalized clause: `{ tag: \"a\" }` -> `{ field: \"tag\", op: \"eq\" }`. */\nexport type Condition = { field: string; op: WhereOp; value: unknown };\n\nconst WHERE_OPS: Record<WhereOp, true> = {\n\teq: true,\n\tne: true,\n\tlt: true,\n\tlte: true,\n\tgt: true,\n\tgte: true,\n\tin: true,\n\tnotIn: true,\n\tcontains: true,\n\tstartsWith: true,\n\tendsWith: true,\n};\n\n/** An operator object is a plain record whose keys are ALL operator names.\n * Anything else - a Date, an array, an empty object - is a value. */\nconst isOps = (value: unknown): value is WhereOps<unknown> =>\n\ttypeof value === \"object\" &&\n\tvalue !== null &&\n\t!Array.isArray(value) &&\n\t!(value instanceof Date) &&\n\tObject.keys(value).length > 0 &&\n\tObject.keys(value).every((key) => key in WHERE_OPS);\n\n/** Flatten a where to normalized conditions - the adapter author's\n * translation seam: map each condition onto your query language, AND them. */\nexport const conditionsOf = (\n\twhere: Record<string, unknown> = {},\n): Condition[] =>\n\tObject.entries(where).flatMap(([field, spec]) =>\n\t\tisOps(spec)\n\t\t\t? Object.entries(spec).map(([op, value]) => ({\n\t\t\t\t\tfield,\n\t\t\t\t\top: op as WhereOp,\n\t\t\t\t\tvalue,\n\t\t\t\t}))\n\t\t\t: [{ field, op: \"eq\" as const, value: spec }],\n\t);\n\n/** Dates equate and order by their instant. */\nconst rawValue = (value: unknown) =>\n\tvalue instanceof Date ? value.getTime() : value;\n\nconst equals = (a: unknown, b: unknown) => rawValue(a) === rawValue(b);\n\nconst compare = (a: unknown, b: unknown): number => {\n\tconst left = rawValue(a) as number;\n\tconst right = rawValue(b) as number;\n\treturn left < right ? -1 : left > right ? 1 : 0;\n};\n\nconst holds = (\n\trow: Record<string, unknown>,\n\t{ field, op, value }: Condition,\n): boolean => {\n\tconst current = row[field];\n\tswitch (op) {\n\t\tcase \"eq\":\n\t\t\treturn equals(current, value);\n\t\tcase \"ne\":\n\t\t\treturn !equals(current, value);\n\t\tcase \"lt\":\n\t\tcase \"lte\":\n\t\tcase \"gt\":\n\t\tcase \"gte\": {\n\t\t\tif (current == null || value == null) return false;\n\t\t\tconst order = compare(current, value);\n\t\t\tif (op === \"lt\") return order < 0;\n\t\t\tif (op === \"lte\") return order <= 0;\n\t\t\tif (op === \"gt\") return order > 0;\n\t\t\treturn order >= 0;\n\t\t}\n\t\tcase \"in\":\n\t\t\treturn (value as readonly unknown[]).some((member) =>\n\t\t\t\tequals(current, member),\n\t\t\t);\n\t\tcase \"notIn\":\n\t\t\treturn !(value as readonly unknown[]).some((member) =>\n\t\t\t\tequals(current, member),\n\t\t\t);\n\t\tcase \"contains\":\n\t\t\treturn typeof current === \"string\" && current.includes(value as string);\n\t\tcase \"startsWith\":\n\t\t\treturn typeof current === \"string\" && current.startsWith(value as string);\n\t\tcase \"endsWith\":\n\t\t\treturn typeof current === \"string\" && current.endsWith(value as string);\n\t}\n};\n\n/** Does a row satisfy a where? The in-memory evaluator - the dummy adapter\n * runs on it, and any adapter over an unqueryable backend can too. */\nexport const matchesWhere = (\n\trow: Record<string, unknown>,\n\twhere: Record<string, unknown> = {},\n): boolean => conditionsOf(where).every((condition) => holds(row, condition));\n\n/* ----------------------------------- ops ----------------------------------- */\n\n/** Shaping for `findMany`: sort, then window. */\nexport type FindManyOptions<R> = {\n\tlimit?: number;\n\toffset?: number;\n\tsortBy?: { field: keyof R & string; direction?: \"asc\" | \"desc\" };\n};\n\n/** One model's CRUD surface. `create` is generic so a row EXTENDED by a\n * mounted module (an account with a password field) keeps its extra\n * fields through the round-trip. */\nexport type Collection<R> = {\n\tcreate: <T extends R>(data: T) => Promise<T>;\n\tfindOne: (where: Where<R>) => Promise<R | null>;\n\tfindMany: (where?: Where<R>, options?: FindManyOptions<R>) => Promise<R[]>;\n\t/** Merge `patch` into the FIRST match - null when nothing matched. */\n\tupdate: (where: Where<R>, patch: Partial<R>) => Promise<R | null>;\n\t/** Remove every match; how many is the answer. */\n\tdelete: (where: Where<R>) => Promise<number>;\n\tcount: (where?: Where<R>) => Promise<number>;\n\t/** Claim the FIRST match: the row comes back and is GONE, atomically -\n\t * two racing consumers never both get it. Single-use credentials\n\t * (verification tokens, one-time codes) hang off this. */\n\tconsumeOne: (where: Where<R>) => Promise<R | null>;\n\t/** Add to numeric fields of the FIRST match, atomically; the where is\n\t * also the GUARD (`count: { lt: max }`), so check-and-bump is one op -\n\t * null means no row passed it. Rate limiting hangs off this. */\n\tincrementOne: (\n\t\twhere: Where<R>,\n\t\tincrements: Partial<Record<keyof R & string, number>>,\n\t) => Promise<R | null>;\n};\n\n/**\n * What a real database implements: six required verbs, models addressed by\n * NAME, `where` as bare-equality fields and/or operator objects\n * (`conditionsOf` normalizes either form). The storage API above never\n * changes - adapters translate it, sync or async.\n *\n * The optional verbs are ATOMICITY upgrades: without `consumeOne` /\n * `incrementOne` the storage falls back to find-then-write - correct alone,\n * racy under contention - and without `transaction` a `$transaction` block\n * runs plainly. Implement them where the backend has the primitive.\n */\nexport type StorageAdapter = {\n\tcreate: (model: string, data: Record<string, unknown>) => unknown;\n\tfindOne: (model: string, where: Record<string, unknown>) => unknown;\n\tfindMany: (\n\t\tmodel: string,\n\t\twhere?: Record<string, unknown>,\n\t\toptions?: FindManyOptions<Record<string, unknown>>,\n\t) => unknown;\n\tupdate: (\n\t\tmodel: string,\n\t\twhere: Record<string, unknown>,\n\t\tpatch: Record<string, unknown>,\n\t) => unknown;\n\tdelete: (model: string, where: Record<string, unknown>) => unknown;\n\tcount: (model: string, where?: Record<string, unknown>) => unknown;\n\t/** Atomic find-and-delete of the first match. */\n\tconsumeOne?: (model: string, where: Record<string, unknown>) => unknown;\n\t/** Atomic guarded add to numeric fields of the first match. */\n\tincrementOne?: (\n\t\tmodel: string,\n\t\twhere: Record<string, unknown>,\n\t\tincrements: Record<string, number>,\n\t) => unknown;\n\t/** Run `run` against a transaction-bound view of this adapter:\n\t * committed when it resolves, rolled back when it throws. */\n\ttransaction?: <T>(run: (tx: StorageAdapter) => Promise<T>) => Promise<T>;\n};\n\n/** The DUMMY adapter: rows in arrays, one per model. Implements the whole\n * surface - the optional verbs by mutation (single-threaded, so \"atomic\"),\n * transactions by snapshot-and-restore. */\nexport const memoryAdapter = (): StorageAdapter => {\n\tlet tables = new Map<string, Record<string, unknown>[]>();\n\tconst rows = (model: string) => {\n\t\tlet list = tables.get(model);\n\t\tif (!list) {\n\t\t\tlist = [];\n\t\t\ttables.set(model, list);\n\t\t}\n\t\treturn list;\n\t};\n\tconst self: StorageAdapter = {\n\t\tcreate: (model, data) => {\n\t\t\tconst row = { ...data };\n\t\t\trows(model).push(row);\n\t\t\treturn row;\n\t\t},\n\t\tfindOne: (model, where) =>\n\t\t\trows(model).find((row) => matchesWhere(row, where)) ?? null,\n\t\tfindMany: (model, where, options) => {\n\t\t\tlet list = rows(model).filter((row) => matchesWhere(row, where));\n\t\t\tconst sort = options?.sortBy;\n\t\t\tif (sort) {\n\t\t\t\tconst direction = sort.direction === \"desc\" ? -1 : 1;\n\t\t\t\tlist = [...list].sort(\n\t\t\t\t\t(a, b) => direction * compare(a[sort.field], b[sort.field]),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst start = options?.offset ?? 0;\n\t\t\tconst end =\n\t\t\t\toptions?.limit === undefined ? undefined : start + options.limit;\n\t\t\treturn start === 0 && end === undefined ? list : list.slice(start, end);\n\t\t},\n\t\tupdate: (model, where, patch) => {\n\t\t\tconst row = rows(model).find((r) => matchesWhere(r, where));\n\t\t\treturn row ? Object.assign(row, patch) : null;\n\t\t},\n\t\tdelete: (model, where) => {\n\t\t\tconst list = rows(model);\n\t\t\tconst keep = list.filter((row) => !matchesWhere(row, where));\n\t\t\ttables.set(model, keep);\n\t\t\treturn list.length - keep.length;\n\t\t},\n\t\tcount: (model, where) =>\n\t\t\trows(model).filter((row) => matchesWhere(row, where)).length,\n\t\tconsumeOne: (model, where) => {\n\t\t\tconst list = rows(model);\n\t\t\tconst index = list.findIndex((row) => matchesWhere(row, where));\n\t\t\treturn index === -1 ? null : list.splice(index, 1)[0];\n\t\t},\n\t\tincrementOne: (model, where, increments) => {\n\t\t\tconst row = rows(model).find((r) => matchesWhere(r, where));\n\t\t\tif (!row) return null;\n\t\t\tfor (const [field, by] of Object.entries(increments)) {\n\t\t\t\trow[field] = ((row[field] as number) ?? 0) + by;\n\t\t\t}\n\t\t\treturn row;\n\t\t},\n\t\ttransaction: async (run) => {\n\t\t\tconst snapshot = new Map(\n\t\t\t\t[...tables].map(([model, list]) => [\n\t\t\t\t\tmodel,\n\t\t\t\t\tlist.map((row) => ({ ...row })),\n\t\t\t\t]),\n\t\t\t);\n\t\t\ttry {\n\t\t\t\treturn await run(self);\n\t\t\t} catch (thrown) {\n\t\t\t\ttables = snapshot;\n\t\t\t\tthrow thrown;\n\t\t\t}\n\t\t},\n\t};\n\treturn self;\n};\n\n/* ---------------------------------- models ---------------------------------- */\n\ntype AnyVar = VarDefination<any, any, any, any>;\n\n/** Persistence facts about one field the ROW SHAPE can't say - consumed by\n * schema generators and adapters, never acted on by the runtime. (Read\n * shaping like redaction is a `$on` hook, not metadata.) */\nexport type FieldMeta = {\n\t/** No two rows share a value. */\n\tunique?: boolean;\n\t/** Worth an index. */\n\tindex?: boolean;\n\t/** Foreign key: this field holds `model.field` values. */\n\treferences?: {\n\t\tmodel: string;\n\t\tfield: string;\n\t\tonDelete?: \"cascade\" | \"set null\" | \"restrict\";\n\t};\n};\n\n/** What an op subscription hands back: `v.on` entries to mount. */\ntype SubscriptionEntries = OnEntry<string> | readonly OnEntry<string>[];\n\n/**\n * A model declared WITH its persistence: `schema` is the var (the shape),\n * `fields` carries per-field storage metadata, and each op key SUBSCRIBES\n * that op to app events - handed the bound collection op, it returns `v.on`\n * entries that mount wherever the storage does (`use: [db]`). An\n * already-built entry works in place of the fn.\n */\nexport type ModelConfig<SV extends AnyVar = AnyVar> = {\n\tschema: SV;\n\tfields?: {\n\t\t[F in keyof NonNullable<ValueOfVar<SV>>]?: FieldMeta;\n\t};\n} & {\n\t[Op in StorageOp]?:\n\t\t| ((\n\t\t\t\taction: Collection<NonNullable<ValueOfVar<SV>>>[Op],\n\t\t ) => SubscriptionEntries)\n\t\t| SubscriptionEntries;\n};\n\n/** A model is a bare var, or a config carrying the var as `schema`. */\ntype ModelInput = AnyVar | ModelConfig;\n\n/** The var behind a model input. Checked through `$var`, never `schema` -\n * a bare var also HAS a `schema` property (its type shape). */\ntype SchemaOf<T> = T extends { $var: true }\n\t? T\n\t: T extends { schema: infer SV }\n\t\t? SV\n\t\t: never;\n\ntype RowOf<T> = NonNullable<ValueOfVar<SchemaOf<T>>>;\n\nexport type StorageModels = Record<string, ModelInput>;\n\nexport type StorageOp =\n\t| \"create\"\n\t| \"findOne\"\n\t| \"findMany\"\n\t| \"update\"\n\t| \"delete\"\n\t| \"count\"\n\t| \"consumeOne\"\n\t| \"incrementOne\";\n\n/** What a storage hook sees: which model and op, with the op's arguments\n * positionally (`create` -> [data], `update` -> [where, patch], `findMany`\n * -> [where, options], `incrementOne` -> [where, increments], ...). */\nexport type StorageHookContext = {\n\t/** The model KEY being addressed (the storage's property name). */\n\tmodel: string;\n\top: StorageOp;\n\targs: readonly unknown[];\n};\n\n/** `next()` runs the op (hooks below it included) and resolves its result;\n * the hook's own return value IS the op's result - wrap, veto, transform. */\nexport type StorageHook = (\n\tc: StorageHookContext,\n\tnext: () => Promise<unknown>,\n) => unknown;\n\n/** Every target a storage hook can name - a flat union, so editors offer\n * the whole surface: exact (\"user.create\"), per-model (\"user.*\"), per-op\n * (\"*.create\"), everything (\"*\"). */\nexport type StorageTarget<M> =\n\t| \"*\"\n\t| `${keyof M & string}.${StorageOp | \"*\"}`\n\t| `*.${StorageOp}`;\n\nexport type Storage<M extends StorageModels> = {\n\t[K in keyof M]: Collection<RowOf<M[K]>>;\n} & StorageApi<M>;\n\n/** The customization surface, `$`-prefixed so model keys never collide. */\nexport type StorageApi<M extends StorageModels> = {\n\t/** Swap the backend IN PLACE: every view of this storage - and every\n\t * module that captured it - starts hitting the new adapter. */\n\t$adapter: (adapter: StorageAdapter) => Storage<M>;\n\t/** Intercept ops: hooks stack in mount order and apply to every view\n\t * sharing this storage's state. */\n\t$on: (target: StorageTarget<M>, hook: StorageHook) => Storage<M>;\n\t/** A view WITHOUT these models - same adapter, same hooks. */\n\t$omit: <K extends keyof M & string>(...keys: K[]) => Storage<Omit<M, K>>;\n\t/** A view of ONLY these models - same adapter, same hooks. */\n\t$pick: <K extends keyof M & string>(...keys: K[]) => Storage<Pick<M, K>>;\n\t/** A view with MORE models - same adapter, same hooks. */\n\t$extend: <M2 extends StorageModels>(models: M2) => Storage<M & M2>;\n\t/** Run `fn` against a view whose ops share ONE adapter transaction -\n\t * committed when it resolves, rolled back when it throws. Same models,\n\t * same hooks (they run inside). An adapter without `transaction` runs\n\t * `fn` plainly - no atomicity, same answer. */\n\t$transaction: <T>(fn: (tx: Storage<M>) => Promise<T> | T) => Promise<T>;\n\t/** The model definitions this view exposes. */\n\t$models: M;\n};\n\n/** Adapter, hooks and produced subscription entries live HERE, shared by\n * every view of one storage - a `$pick`ed slice still writes through the\n * same backend and hook stack, and a subscription materializes ONCE (same\n * entry object across views, so double-mounting dedups by identity). */\ntype StorageState = {\n\tadapter: StorageAdapter;\n\thooks: { target: string; hook: StorageHook }[];\n\tsubscriptions: Map<string, readonly OnEntry<string>[]>;\n};\n\nconst OPS: readonly StorageOp[] = [\n\t\"create\",\n\t\"findOne\",\n\t\"findMany\",\n\t\"update\",\n\t\"delete\",\n\t\"count\",\n\t\"consumeOne\",\n\t\"incrementOne\",\n];\n\n/** The op against the backend, optional verbs falling back to the required\n * six: find-then-write - correct alone, racy under contention. The comment\n * every fallback deserves lives on `StorageAdapter`. */\nconst rawOp = (\n\tadapter: StorageAdapter,\n\tname: string,\n\top: StorageOp,\n\targs: unknown[],\n) => {\n\tif (op === \"consumeOne\" && !adapter.consumeOne) {\n\t\treturn (async () => {\n\t\t\tconst where = args[0] as Record<string, unknown>;\n\t\t\tconst row = (await adapter.findOne(name, where)) as Record<\n\t\t\t\tstring,\n\t\t\t\tunknown\n\t\t\t> | null;\n\t\t\tif (!row) return null;\n\t\t\t// Delete THE row by its own fields, not the where - an operator\n\t\t\t// where (`expiresAt: { lt }`) must not sweep other matches.\n\t\t\tawait adapter.delete(name, row);\n\t\t\treturn row;\n\t\t})();\n\t}\n\tif (op === \"incrementOne\" && !adapter.incrementOne) {\n\t\treturn (async () => {\n\t\t\tconst [where, increments] = args as [\n\t\t\t\tRecord<string, unknown>,\n\t\t\t\tRecord<string, number>,\n\t\t\t];\n\t\t\tconst row = (await adapter.findOne(name, where)) as Record<\n\t\t\t\tstring,\n\t\t\t\tunknown\n\t\t\t> | null;\n\t\t\tif (!row) return null;\n\t\t\tconst patch = Object.fromEntries(\n\t\t\t\tObject.entries(increments).map(([field, by]) => [\n\t\t\t\t\tfield,\n\t\t\t\t\t((row[field] as number) ?? 0) + by,\n\t\t\t\t]),\n\t\t\t);\n\t\t\treturn adapter.update(name, where, patch);\n\t\t})();\n\t}\n\treturn (adapter[op] as (...a: unknown[]) => unknown)(name, ...args);\n};\n\nconst buildStorage = <M extends StorageModels>(\n\tstate: StorageState,\n\tmodels: M,\n): Storage<M> => {\n\t// Every op funnels here: matching hooks compose around the adapter\n\t// call, first mounted outermost - the `v.on` rules, one layer down.\n\tconst run = (key: string, name: string, op: StorageOp, args: unknown[]) => {\n\t\tconst base = () => Promise.resolve(rawOp(state.adapter, name, op, args));\n\t\treturn state.hooks\n\t\t\t.filter((entry) => matchesTarget(entry.target, `${key}.${op}`))\n\t\t\t.reduceRight<() => Promise<unknown>>(\n\t\t\t\t(next, entry) => () =>\n\t\t\t\t\tPromise.resolve(entry.hook({ model: key, op, args }, next)),\n\t\t\t\tbase,\n\t\t\t)();\n\t};\n\n\tconst storage: Record<string, unknown> = {};\n\tfor (const [key, input] of Object.entries(models)) {\n\t\tconst def = isVar(input) ? input : (input as ModelConfig).schema;\n\t\tconst name = (def as { name: string }).name;\n\t\tconst collection = {\n\t\t\tcreate: (data: unknown) => run(key, name, \"create\", [data]),\n\t\t\tfindOne: (where: unknown) => run(key, name, \"findOne\", [where]),\n\t\t\tfindMany: (where?: unknown, options?: unknown) =>\n\t\t\t\trun(key, name, \"findMany\", [where, options]),\n\t\t\tupdate: (where: unknown, patch: unknown) =>\n\t\t\t\trun(key, name, \"update\", [where, patch]),\n\t\t\tdelete: (where: unknown) => run(key, name, \"delete\", [where]),\n\t\t\tcount: (where?: unknown) => run(key, name, \"count\", [where]),\n\t\t\tconsumeOne: (where: unknown) => run(key, name, \"consumeOne\", [where]),\n\t\t\tincrementOne: (where: unknown, increments: unknown) =>\n\t\t\t\trun(key, name, \"incrementOne\", [where, increments]),\n\t\t} satisfies Record<StorageOp, unknown>;\n\t\tstorage[key] = collection;\n\n\t\t// Op subscriptions become PROPERTIES of the storage, so mounting it\n\t\t// as a module (`use: [db]`) mounts the persistence it declared.\n\t\t// Materialized once per state - views share entry identity.\n\t\tif (isVar(input)) continue;\n\t\tfor (const op of OPS) {\n\t\t\tconst declared = (input as Record<string, unknown>)[op];\n\t\t\tif (!declared) continue;\n\t\t\tconst cacheKey = `${key}.${op}`;\n\t\t\tlet entries = state.subscriptions.get(cacheKey);\n\t\t\tif (!entries) {\n\t\t\t\tconst produced =\n\t\t\t\t\ttypeof declared === \"function\"\n\t\t\t\t\t\t? declared(collection[op])\n\t\t\t\t\t\t: (declared as SubscriptionEntries);\n\t\t\t\tentries = Array.isArray(produced) ? produced : [produced];\n\t\t\t\tstate.subscriptions.set(cacheKey, entries as OnEntry<string>[]);\n\t\t\t}\n\t\t\tentries.forEach((entry, index) => {\n\t\t\t\tstorage[`${key}$${op}${index === 0 ? \"\" : index}`] = entry;\n\t\t\t});\n\t\t}\n\t}\n\n\tconst self: Storage<M> = Object.assign(storage, {\n\t\t$adapter: (adapter: StorageAdapter) => {\n\t\t\tstate.adapter = adapter;\n\t\t\treturn self;\n\t\t},\n\t\t$on: (target: StorageTarget<M>, hook: StorageHook) => {\n\t\t\tstate.hooks.push({ target, hook });\n\t\t\treturn self;\n\t\t},\n\t\t$omit: (...keys: string[]) =>\n\t\t\tbuildStorage(\n\t\t\t\tstate,\n\t\t\t\tObject.fromEntries(\n\t\t\t\t\tObject.entries(models).filter(([key]) => !keys.includes(key)),\n\t\t\t\t) as StorageModels,\n\t\t\t),\n\t\t$pick: (...keys: string[]) =>\n\t\t\tbuildStorage(\n\t\t\t\tstate,\n\t\t\t\tObject.fromEntries(\n\t\t\t\t\tkeys.map((key) => [key, models[key]]),\n\t\t\t\t) as StorageModels,\n\t\t\t),\n\t\t$extend: (more: StorageModels) =>\n\t\t\tbuildStorage(state, { ...models, ...more }),\n\t\t$transaction: <T>(fn: (tx: Storage<M>) => Promise<T> | T) => {\n\t\t\t// The tx view is this storage with only the adapter swapped:\n\t\t\t// hooks and subscriptions stay the SHARED arrays, so they apply\n\t\t\t// (and mount) inside exactly as outside.\n\t\t\tconst inside = (adapter: StorageAdapter) =>\n\t\t\t\tPromise.resolve(fn(buildStorage({ ...state, adapter }, models)));\n\t\t\treturn state.adapter.transaction\n\t\t\t\t? state.adapter.transaction((tx) => inside(tx))\n\t\t\t\t: inside(state.adapter);\n\t\t},\n\t\t$models: models,\n\t} as StorageApi<M>) as Storage<M>;\n\treturn self;\n};\n\n/**\n * MANY instances of a var: each model is a collection of rows shaped like\n * the var's VALUE, addressed by the var's NAME - the var stays what it\n * always was (the scope's one current instance), the storage holds every\n * other one, and the query API is how rows move between the two.\n *\n * The returned storage is CUSTOMIZABLE through its `$` surface: `$adapter`\n * swaps the backend in place, `$on` mounts hooks around ops,\n * `$omit`/`$pick`/`$extend` derive model views over the same state, and\n * `$transaction` scopes ops to one adapter transaction.\n *\n * A model can also DECLARE its persistence: pass `{ schema, create: ... }`\n * instead of the bare var, and the op subscriptions ride on the storage as\n * mountable `v.on` entries - `use: [db]` wires them into the app. The same\n * config carries `fields` metadata (unique, index, references) for schema\n * generators to consume.\n */\nexport const makeStorage = <const M extends StorageModels>(\n\tadapter: StorageAdapter,\n\tmodels: M,\n): Storage<M> =>\n\tbuildStorage({ adapter, hooks: [], subscriptions: new Map() }, models);\n"],"mappings":";;;AA+BA,MAAM,YAAmC;CACxC,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,KAAK;CACL,IAAI;CACJ,KAAK;CACL,IAAI;CACJ,OAAO;CACP,UAAU;CACV,YAAY;CACZ,UAAU;AACX;;;AAIA,MAAM,SAAS,UACd,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK,KACpB,EAAE,iBAAiB,SACnB,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,KAC5B,OAAO,KAAK,KAAK,CAAC,CAAC,OAAO,QAAQ,OAAO,SAAS;;;AAInD,MAAa,gBACZ,QAAiC,CAAC,MAElC,OAAO,QAAQ,KAAK,CAAC,CAAC,SAAS,CAAC,OAAO,UACtC,MAA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ACC,OACA,OAAO,YACN,KAAK,KAAK,QAAQ,CAAC,KAAK,OAAO,IAAI,CAAC,CACrC,CACD;EACD,UAAU,SACT,aAAa,OAAO;GAAE,GAAG;GAAQ,GAAG;EAAK,CAAC;EAC3C,eAAkB,OAA2C;GAI5D,MAAM,UAAU,YACf,QAAQ,QAAQ,GAAG,aAAa;IAAE,GAAG;IAAO;GAAQ,GAAG,MAAM,CAAC,CAAC;GAChE,OAAO,MAAM,QAAQ,cAClB,MAAM,QAAQ,aAAa,OAAO,OAAO,EAAE,CAAC,IAC5C,OAAO,MAAM,OAAO;EACxB;EACA,SAAS;CACV,CAAkB;CAClB,OAAO;AACR;;;;;;;;;;;;;;;;;;AAmBA,MAAa,eACZ,SACA,WAEA,aAAa;CAAE;CAAS,OAAO,CAAC;CAAG,+BAAe,IAAI,IAAI;AAAE,GAAG,MAAM"}
@@ -0,0 +1,195 @@
1
+ import { ValueOfVar, VarDefination } from "./var.cjs";
2
+ import { OnEntry } from "./module.cjs";
3
+ //#region src/storage.d.ts
4
+ /** Per-field operators, for everything equality can't say: expiry sweeps
5
+ * (`lt`), revocation lists (`in`), guarded counters (`lt` as the guard).
6
+ * A bare value stays plain equality - the common case reads like data. */
7
+ type WhereOps<V> = {
8
+ eq?: V;
9
+ ne?: V;
10
+ lt?: V;
11
+ lte?: V;
12
+ gt?: V;
13
+ gte?: V;
14
+ in?: readonly V[];
15
+ notIn?: readonly V[];
16
+ contains?: string;
17
+ startsWith?: string;
18
+ endsWith?: string;
19
+ };
20
+ type WhereOp = keyof WhereOps<unknown>;
21
+ /** AND across fields; each field a bare value (equality) or operators. */
22
+ type Where<R> = { [K in keyof R]?: R[K] | WhereOps<R[K]>; };
23
+ /** One normalized clause: `{ tag: "a" }` -> `{ field: "tag", op: "eq" }`. */
24
+ type Condition = {
25
+ field: string;
26
+ op: WhereOp;
27
+ value: unknown;
28
+ };
29
+ /** Flatten a where to normalized conditions - the adapter author's
30
+ * translation seam: map each condition onto your query language, AND them. */
31
+ declare const conditionsOf: (where?: Record<string, unknown>) => Condition[];
32
+ /** Does a row satisfy a where? The in-memory evaluator - the dummy adapter
33
+ * runs on it, and any adapter over an unqueryable backend can too. */
34
+ declare const matchesWhere: (row: Record<string, unknown>, where?: Record<string, unknown>) => boolean;
35
+ /** Shaping for `findMany`: sort, then window. */
36
+ type FindManyOptions<R> = {
37
+ limit?: number;
38
+ offset?: number;
39
+ sortBy?: {
40
+ field: keyof R & string;
41
+ direction?: "asc" | "desc";
42
+ };
43
+ };
44
+ /** One model's CRUD surface. `create` is generic so a row EXTENDED by a
45
+ * mounted module (an account with a password field) keeps its extra
46
+ * fields through the round-trip. */
47
+ type Collection<R> = {
48
+ create: <T extends R>(data: T) => Promise<T>;
49
+ findOne: (where: Where<R>) => Promise<R | null>;
50
+ findMany: (where?: Where<R>, options?: FindManyOptions<R>) => Promise<R[]>;
51
+ /** Merge `patch` into the FIRST match - null when nothing matched. */
52
+ update: (where: Where<R>, patch: Partial<R>) => Promise<R | null>;
53
+ /** Remove every match; how many is the answer. */
54
+ delete: (where: Where<R>) => Promise<number>;
55
+ count: (where?: Where<R>) => Promise<number>;
56
+ /** Claim the FIRST match: the row comes back and is GONE, atomically -
57
+ * two racing consumers never both get it. Single-use credentials
58
+ * (verification tokens, one-time codes) hang off this. */
59
+ consumeOne: (where: Where<R>) => Promise<R | null>;
60
+ /** Add to numeric fields of the FIRST match, atomically; the where is
61
+ * also the GUARD (`count: { lt: max }`), so check-and-bump is one op -
62
+ * null means no row passed it. Rate limiting hangs off this. */
63
+ incrementOne: (where: Where<R>, increments: Partial<Record<keyof R & string, number>>) => Promise<R | null>;
64
+ };
65
+ /**
66
+ * What a real database implements: six required verbs, models addressed by
67
+ * NAME, `where` as bare-equality fields and/or operator objects
68
+ * (`conditionsOf` normalizes either form). The storage API above never
69
+ * changes - adapters translate it, sync or async.
70
+ *
71
+ * The optional verbs are ATOMICITY upgrades: without `consumeOne` /
72
+ * `incrementOne` the storage falls back to find-then-write - correct alone,
73
+ * racy under contention - and without `transaction` a `$transaction` block
74
+ * runs plainly. Implement them where the backend has the primitive.
75
+ */
76
+ type StorageAdapter = {
77
+ create: (model: string, data: Record<string, unknown>) => unknown;
78
+ findOne: (model: string, where: Record<string, unknown>) => unknown;
79
+ findMany: (model: string, where?: Record<string, unknown>, options?: FindManyOptions<Record<string, unknown>>) => unknown;
80
+ update: (model: string, where: Record<string, unknown>, patch: Record<string, unknown>) => unknown;
81
+ delete: (model: string, where: Record<string, unknown>) => unknown;
82
+ count: (model: string, where?: Record<string, unknown>) => unknown;
83
+ /** Atomic find-and-delete of the first match. */
84
+ consumeOne?: (model: string, where: Record<string, unknown>) => unknown;
85
+ /** Atomic guarded add to numeric fields of the first match. */
86
+ incrementOne?: (model: string, where: Record<string, unknown>, increments: Record<string, number>) => unknown;
87
+ /** Run `run` against a transaction-bound view of this adapter:
88
+ * committed when it resolves, rolled back when it throws. */
89
+ transaction?: <T>(run: (tx: StorageAdapter) => Promise<T>) => Promise<T>;
90
+ };
91
+ /** The DUMMY adapter: rows in arrays, one per model. Implements the whole
92
+ * surface - the optional verbs by mutation (single-threaded, so "atomic"),
93
+ * transactions by snapshot-and-restore. */
94
+ declare const memoryAdapter: () => StorageAdapter;
95
+ type AnyVar = VarDefination<any, any, any, any>;
96
+ /** Persistence facts about one field the ROW SHAPE can't say - consumed by
97
+ * schema generators and adapters, never acted on by the runtime. (Read
98
+ * shaping like redaction is a `$on` hook, not metadata.) */
99
+ type FieldMeta = {
100
+ /** No two rows share a value. */
101
+ unique?: boolean;
102
+ /** Worth an index. */
103
+ index?: boolean;
104
+ /** Foreign key: this field holds `model.field` values. */
105
+ references?: {
106
+ model: string;
107
+ field: string;
108
+ onDelete?: "cascade" | "set null" | "restrict";
109
+ };
110
+ };
111
+ /** What an op subscription hands back: `v.on` entries to mount. */
112
+ type SubscriptionEntries = OnEntry<string> | readonly OnEntry<string>[];
113
+ /**
114
+ * A model declared WITH its persistence: `schema` is the var (the shape),
115
+ * `fields` carries per-field storage metadata, and each op key SUBSCRIBES
116
+ * that op to app events - handed the bound collection op, it returns `v.on`
117
+ * entries that mount wherever the storage does (`use: [db]`). An
118
+ * already-built entry works in place of the fn.
119
+ */
120
+ type ModelConfig<SV extends AnyVar = AnyVar> = {
121
+ schema: SV;
122
+ fields?: { [F in keyof NonNullable<ValueOfVar<SV>>]?: FieldMeta; };
123
+ } & { [Op in StorageOp]?: ((action: Collection<NonNullable<ValueOfVar<SV>>>[Op]) => SubscriptionEntries) | SubscriptionEntries; };
124
+ /** A model is a bare var, or a config carrying the var as `schema`. */
125
+ type ModelInput = AnyVar | ModelConfig;
126
+ /** The var behind a model input. Checked through `$var`, never `schema` -
127
+ * a bare var also HAS a `schema` property (its type shape). */
128
+ type SchemaOf<T> = T extends {
129
+ $var: true;
130
+ } ? T : T extends {
131
+ schema: infer SV;
132
+ } ? SV : never;
133
+ type RowOf<T> = NonNullable<ValueOfVar<SchemaOf<T>>>;
134
+ type StorageModels = Record<string, ModelInput>;
135
+ type StorageOp = "create" | "findOne" | "findMany" | "update" | "delete" | "count" | "consumeOne" | "incrementOne";
136
+ /** What a storage hook sees: which model and op, with the op's arguments
137
+ * positionally (`create` -> [data], `update` -> [where, patch], `findMany`
138
+ * -> [where, options], `incrementOne` -> [where, increments], ...). */
139
+ type StorageHookContext = {
140
+ /** The model KEY being addressed (the storage's property name). */
141
+ model: string;
142
+ op: StorageOp;
143
+ args: readonly unknown[];
144
+ };
145
+ /** `next()` runs the op (hooks below it included) and resolves its result;
146
+ * the hook's own return value IS the op's result - wrap, veto, transform. */
147
+ type StorageHook = (c: StorageHookContext, next: () => Promise<unknown>) => unknown;
148
+ /** Every target a storage hook can name - a flat union, so editors offer
149
+ * the whole surface: exact ("user.create"), per-model ("user.*"), per-op
150
+ * ("*.create"), everything ("*"). */
151
+ type StorageTarget<M> = "*" | `${keyof M & string}.${StorageOp | "*"}` | `*.${StorageOp}`;
152
+ type Storage<M extends StorageModels> = { [K in keyof M]: Collection<RowOf<M[K]>>; } & StorageApi<M>;
153
+ /** The customization surface, `$`-prefixed so model keys never collide. */
154
+ type StorageApi<M extends StorageModels> = {
155
+ /** Swap the backend IN PLACE: every view of this storage - and every
156
+ * module that captured it - starts hitting the new adapter. */
157
+ $adapter: (adapter: StorageAdapter) => Storage<M>;
158
+ /** Intercept ops: hooks stack in mount order and apply to every view
159
+ * sharing this storage's state. */
160
+ $on: (target: StorageTarget<M>, hook: StorageHook) => Storage<M>;
161
+ /** A view WITHOUT these models - same adapter, same hooks. */
162
+ $omit: <K extends keyof M & string>(...keys: K[]) => Storage<Omit<M, K>>;
163
+ /** A view of ONLY these models - same adapter, same hooks. */
164
+ $pick: <K extends keyof M & string>(...keys: K[]) => Storage<Pick<M, K>>;
165
+ /** A view with MORE models - same adapter, same hooks. */
166
+ $extend: <M2 extends StorageModels>(models: M2) => Storage<M & M2>;
167
+ /** Run `fn` against a view whose ops share ONE adapter transaction -
168
+ * committed when it resolves, rolled back when it throws. Same models,
169
+ * same hooks (they run inside). An adapter without `transaction` runs
170
+ * `fn` plainly - no atomicity, same answer. */
171
+ $transaction: <T>(fn: (tx: Storage<M>) => Promise<T> | T) => Promise<T>;
172
+ /** The model definitions this view exposes. */
173
+ $models: M;
174
+ };
175
+ /**
176
+ * MANY instances of a var: each model is a collection of rows shaped like
177
+ * the var's VALUE, addressed by the var's NAME - the var stays what it
178
+ * always was (the scope's one current instance), the storage holds every
179
+ * other one, and the query API is how rows move between the two.
180
+ *
181
+ * The returned storage is CUSTOMIZABLE through its `$` surface: `$adapter`
182
+ * swaps the backend in place, `$on` mounts hooks around ops,
183
+ * `$omit`/`$pick`/`$extend` derive model views over the same state, and
184
+ * `$transaction` scopes ops to one adapter transaction.
185
+ *
186
+ * A model can also DECLARE its persistence: pass `{ schema, create: ... }`
187
+ * instead of the bare var, and the op subscriptions ride on the storage as
188
+ * mountable `v.on` entries - `use: [db]` wires them into the app. The same
189
+ * config carries `fields` metadata (unique, index, references) for schema
190
+ * generators to consume.
191
+ */
192
+ declare const makeStorage: <const M extends StorageModels>(adapter: StorageAdapter, models: M) => Storage<M>;
193
+ //#endregion
194
+ export { Collection, Condition, FieldMeta, FindManyOptions, ModelConfig, Storage, StorageAdapter, StorageApi, StorageHook, StorageHookContext, StorageModels, StorageOp, StorageTarget, Where, WhereOp, WhereOps, conditionsOf, makeStorage, matchesWhere, memoryAdapter };
195
+ //# sourceMappingURL=storage.d.cts.map