All files / packages/value/src index.ts

66.92% Statements 85/127
77.52% Branches 69/89
33.33% Functions 3/9
69.74% Lines 83/119

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346                                                                                                          1201x   654x 654x       2x     654x                                                                       547x 13x     534x                                                       924x       5x   314x   2x   387x   216x 2x       214x             34x     180x       180x       180x 132x     48x       48x       48x       48x       48x       48x                   48x 46x 46x   46x 117x         110x   110x 110x 418x 418x     110x 110x     7x     46x 43x 43x 43x 43x   43x 110x   110x 418x   418x 160x 160x   160x     418x     110x     43x 43x 110x       46x     2x 2x 4x     2x           1221x   664x   4x                 223x     44x   293x     86x     5x   2x   2x   2x   3x                     538x 538x       2x                     3x   3x 6x     3x     14x              
import {
	isBigInt64Array,
	isBigUint64Array,
	isDate,
	isFloat32Array,
	isFloat64Array,
	isMap,
	isSet,
	isUint8Array,
} from 'node:util/types'
 
import { TZDate } from '@date-fns/tz'
import * as Ydb from '@ydbjs/api/value'
 
import { Dict } from './dict.js'
import { List } from './list.js'
import { Null } from './null.js'
import { Optional } from './optional.js'
import {
	Bool,
	Bytes,
	Datetime,
	Double,
	Float,
	Int32,
	Int64,
	Primitive,
	PrimitiveType,
	Text,
	TzDatetime,
	Uint64,
	Uuid,
} from './primitive.js'
import { Struct, StructType } from './struct.js'
import { Tuple } from './tuple.js'
import { type Type, TypeKind } from './type.js'
import { uuidFromBigInts } from './uuid.js'
import type { Value } from './value.js'
 
export type JSValue =
	| null
	| boolean
	| number
	| bigint
	| string
	| Date
	| Uint8Array
	| JSValue[]
	| Set<JSValue>
	| Map<JSValue, JSValue>
	| { [key: string]: JSValue }
 
export function fromYdb(value: Ydb.Value, type: Ydb.Type): Value {
	switch (type.type.case) {
		case 'typeId':
			let pValue = new Primitive({ value: value.value }, new PrimitiveType(type.type.value))
			if (value.high128) {
				//@ts-expect-error
				// Not all primitive types have a high128 property.
				// Do not use this property unless you are sure it exists.
				pValue.high128 = value.high128
			}
 
			return pValue
		case 'listType':
			return new List(
				...value.items.map((v) =>
					fromYdb(v, (type.type.value as unknown as Ydb.ListType).item!)
				)
			)
		case 'tupleType':
			return new Tuple(
				...value.items.map((v, i) =>
					fromYdb(v, (type.type.value as unknown as Ydb.TupleType).elements[i]!)
				)
			)
		case 'dictType': {
			let dict: [Value, Value][] = []
			for (let i = 0; i < value.pairs.length; i++) {
				let pair = value.pairs[i]!
				dict.push([
					fromYdb(pair.key!, type.type.value.key!),
					fromYdb(pair.payload!, (type.type.value as unknown as Ydb.DictType).payload!),
				])
			}
			return new Dict(...dict)
		}
		case 'structType': {
			let struct: { [key: string]: Value } = {}
			for (let i = 0; i < value.items.length; i++) {
				let member = (type.type.value as unknown as Ydb.StructType).members[i]!
				struct[member.name] = fromYdb(value.items[i]!, member.type!)
			}
 
			return new Struct(struct)
		}
		case 'nullType':
			return new Null()
		case 'optionalType':
			if (value.value.case === 'nullFlagValue') {
				return new Null()
			}
 
			return new Optional(fromYdb(value, type.type.value.item!))
	}
 
	throw new Error('Unsupported value.')
}
 
/**
 * Convert a native JavaScript value into a YDB `Value`. Types are inferred from
 * the input structure.
 *
 * Note: when converting an array of plain objects (`[{}, ...]`), every struct
 * field is wrapped in `Optional`. This keeps the conversion single-pass and
 * lets heterogeneous arrays (objects with different key sets) produce a single
 * unified struct type. As a consequence, the resulting type never matches
 * `NOT NULL` columns on the YDB side.
 *
 * If you target a schema with `NOT NULL` columns, construct values explicitly:
 *
 * ```ts
 * new List(
 *   new Struct({ key: new Text('a'), n: new Uint8(1) })
 * )
 * ```
 *
 * or build a `StructType` and pass it to `new Struct(obj, type)` to pin the
 * field types.
 */
export function fromJs(native: JSValue): Value {
	switch (typeof native) {
		case 'undefined':
			throw new Error('Cannot convert undefined to YDBValue.')
		case 'boolean':
			return new Bool(native)
		case 'number':
			return Number.isInteger(native) ? new Int32(native) : new Double(native)
		case 'bigint':
			return new Int64(native)
		case 'string':
			return new Text(native)
		case 'object': {
			if (native === null) {
				return new Null()
			}
 
			// Check if the object is already a YDB Value
			if (
				typeof native === 'object' &&
				native !== null &&
				'type' in native &&
				'encode' in native &&
				typeof (native as any).encode === 'function'
			) {
				return native as unknown as Value
			}
 
			Iif (isDate(native)) {
				return new Datetime(native)
			}
 
			Iif (native instanceof TZDate) {
				return new TzDatetime(native)
			}
 
			if (isUint8Array(native)) {
				return new Bytes(native)
			}
 
			Iif (isFloat32Array(native)) {
				return new List(...Array.from(native, (v) => new Float(v)))
			}
 
			Iif (isFloat64Array(native)) {
				return new List(...Array.from(native, (v) => new Float(v)))
			}
 
			Iif (isBigInt64Array(native)) {
				return new List(...Array.from(native, (v) => new Int64(v)))
			}
 
			Iif (isBigUint64Array(native)) {
				return new List(...Array.from(native, (v) => new Uint64(v)))
			}
 
			Iif (isSet(native)) {
				return new Tuple(...Array.from(native, fromJs))
			}
 
			Iif (isMap(native)) {
				let pairs: [Value, Value][] = []
 
				for (let [key, value] of native.entries()) {
					pairs.push([fromJs(key as JSValue), fromJs(value as JSValue)])
				}
 
				return new Dict(...pairs)
			}
 
			if (Array.isArray(native)) {
				let values: Value[] = []
				let structs: [string, Value][][] = []
 
				for (let i = 0; i < native.length; i++) {
					if (
						typeof native[i] === 'object' &&
						!Array.isArray(native[i]) &&
						native[i] !== null
					) {
						let element = native[i] as { [key: string]: JSValue }
 
						let struct: [string, Value][] = []
						for (let key in element) {
							let value = fromJs(element[key]!)
							struct.push([key, value])
						}
 
						structs.push(struct)
						continue
					}
 
					values.push(fromJs(native[i]!))
				}
 
				if (structs.length > 0) {
					let structNames: string[] = []
					let structNamesSet: Set<string> = new Set()
					let structTypes: Type[] = []
					let structValues: { [key: string]: Value }[] = []
 
					for (let struct of structs) {
						let record: { [key: string]: Value } = {}
 
						for (let [key, value] of struct) {
							value = new Optional(value)
 
							if (!structNamesSet.has(key)) {
								structNames.push(key)
								structTypes.push(value.type)
 
								structNamesSet.add(key)
							}
 
							record[key] = value
						}
 
						structValues.push(record)
					}
 
					let structTypeDef = new StructType(structNames, structTypes)
					for (let struct of structValues) {
						values.push(new Struct(struct, structTypeDef))
					}
				}
 
				return new List(...values)
			}
 
			let struct: { [key: string]: Value } = {}
			for (let [k, v] of Object.entries(native)) {
				struct[k] = fromJs(v)
			}
 
			return new Struct(struct)
		}
	}
}
 
export function toJs(value: Value): JSValue {
	switch (value.type.kind) {
		case TypeKind.PRIMITIVE:
			switch ((value.type as PrimitiveType).id) {
				case Ydb.Type_PrimitiveTypeId.BOOL:
					return (value as Primitive).value as boolean
				case Ydb.Type_PrimitiveTypeId.INT8:
				case Ydb.Type_PrimitiveTypeId.INT16:
				case Ydb.Type_PrimitiveTypeId.INT32:
				case Ydb.Type_PrimitiveTypeId.UINT8:
				case Ydb.Type_PrimitiveTypeId.UINT16:
				case Ydb.Type_PrimitiveTypeId.UINT32:
				case Ydb.Type_PrimitiveTypeId.FLOAT:
				case Ydb.Type_PrimitiveTypeId.DOUBLE:
					return (value as Primitive).value as number
				case Ydb.Type_PrimitiveTypeId.INT64:
				case Ydb.Type_PrimitiveTypeId.UINT64:
					return (value as Primitive).value as bigint
				case Ydb.Type_PrimitiveTypeId.UTF8:
					return (value as Primitive).value as string
				case Ydb.Type_PrimitiveTypeId.JSON:
				case Ydb.Type_PrimitiveTypeId.JSON_DOCUMENT:
					return JSON.parse((value as Primitive).value as string) as JSValue
				case Ydb.Type_PrimitiveTypeId.STRING:
				case Ydb.Type_PrimitiveTypeId.YSON:
					return (value as Primitive).value as Uint8Array
				case Ydb.Type_PrimitiveTypeId.UUID:
					return uuidFromBigInts((value as Uuid).value as bigint, (value as Uuid).high128)
				case Ydb.Type_PrimitiveTypeId.DATE:
					return new Date(((value as Primitive).value as number) * 24 * 60 * 60 * 1000)
				case Ydb.Type_PrimitiveTypeId.DATETIME:
					return new Date(((value as Primitive).value as number) * 1000)
				case Ydb.Type_PrimitiveTypeId.TIMESTAMP:
					return new Date(Number(((value as Primitive).value as bigint) / 1000n))
				case Ydb.Type_PrimitiveTypeId.TZ_DATE:
				case Ydb.Type_PrimitiveTypeId.TZ_DATETIME:
				case Ydb.Type_PrimitiveTypeId.TZ_TIMESTAMP: {
					let [dateStr, tz] = ((value as Primitive).value as string).split(',')
 
					return new TZDate(dateStr!, tz!)
				}
			}
			break
		case TypeKind.OPTIONAL: {
			let { item } = value as Optional<Type>
			return item === null ? null : toJs(item)
		}
		case TypeKind.LIST:
		case TypeKind.TUPLE:
			return (value as List).items.map(toJs)
		case TypeKind.DICT: {
			let dict: Map<JSValue, JSValue> = new Map()
 
			for (let [k, v] of (value as Dict).pairs) {
				dict.set(toJs(k), toJs(v))
			}
 
			return dict
		}
		case TypeKind.STRUCT: {
			let struct: { [key: string]: JSValue } = {}
 
			for (let i = 0; i < (value as Struct).type.names.length; i++) {
				struct[(value as Struct).type.names[i]!] = toJs((value as Struct).items[i]!)
			}
 
			return struct
		}
		case TypeKind.NULL:
			return null
	}
 
	throw new Error('Unsupported value.')
}
export * from './type.js'
export * from './value.js'