function isArray(value: any): value is readonly unknown[] { // See: https://github.com/microsoft/TypeScript/issues/17002 return Array.isArray(value); } function isSet(value: any): value is ReadonlySet { return value instanceof Set; } import type { PickDeferred, Expanded, Resource, } from '@balena/abstract-sql-to-typescript' with { 'resolution-mode': 'import', }; export type { Resource }; type ResourceName = `${Letter | Digit}${string}`; export type AnyResourceObject = { [key: ResourceName]: any; }; export type AnyResource = { Read: AnyObject; Write: AnyObject; }; type StringKeyOf = keyof T & string; export type ExpandableStringKeyOf = StringKeyOf< ResourceExpand >; type ExtractExpand = NonNullable< Extract>[number] >; type SelectPropsOf< T extends Resource['Read'], U extends ODataOptions, > = U['$select'] extends | ReadonlyArray> | ReadonlySet> ? X : U['$select'] extends StringKeyOf ? U['$select'] : // If no $select is provided, all properties that are not $expanded are selected Exclude, ExpandPropsOf>; type ExpandPropsOf< T extends Resource['Read'], U extends ODataOptions, > = U['$expand'] extends { [key in StringKeyOf]?: any } ? StringKeyOf : U['$expand'] extends ReadonlyArray> ? X : // If no $expand is provided, no properties are expanded never; type ExpandToResponse< T extends Resource['Read'], U extends ODataOptions, > = U['$expand'] extends { [key in infer X extends StringKeyOf]?: any } ? { [P in X]-?: OptionsToResponse< Expanded[number], U['$expand'][P], undefined >; } : U['$expand'] extends ReadonlyArray> ? { [P in X]-?: Array[number]>>; } : // If no $expand is provided, no properties are expanded // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- We do want an empty object but `Record` doesn't work because things breaks after it's used in a union, needs investigation {}; type MaybeGetKey = K extends keyof T ? T[K] : undefined; // Check if two types are exactly equal, useful for checking against eg exactly `any` type Equals = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; export type OptionsToResponse< T extends Resource['Read'], U extends ODataOptions, ID extends ResourceId | undefined, > = U extends { $count: ODataOptions['$count']; } ? number : Equals extends true ? | (PickDeferred> & ExpandToResponse) | undefined : ID extends ResourceId ? | (PickDeferred> & ExpandToResponse) | undefined : Array> & ExpandToResponse>; // TODO-Major: remove this export export type Dictionary = Record; type LowerLetter = | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'; type UpperLetter = | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'; type Letter = LowerLetter | UpperLetter; type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; // This allowsdisabling the expandFilter error when inside a lambda expr because we need to allow `alias: field: ...` let disableExpandFilterError = false; const mapObj = , R>( obj: T, fn: (value: T[StringKeyOf], key: StringKeyOf) => R, ): R[] => Object.keys(obj).map((key: StringKeyOf) => fn(obj[key], key)); const NumberIsFinite: (v: any) => v is number = (Number as any).isFinite ?? ((v) => typeof v === 'number' && isFinite(v)); const isString = (v: any): v is string => typeof v === 'string'; const isBoolean = (v: any): v is boolean => v === true || v === false; const isDate = (v: any): v is Date => Object.prototype.toString.call(v) === '[object Date]'; const isObject = (v: unknown): v is object => v != null && typeof v === 'object'; const isValidOption = ( key: string, ): key is StringKeyOf> => { return ( key === '$select' || key === '$filter' || key === '$expand' || key === '$orderby' || key === '$top' || key === '$skip' || key === '$format' ); }; const encodedSlash = encodeURIComponent('/'); const encodedCount = encodeURIComponent('$count'); const trailingCountRegex = new RegExp( `(?:(?:${encodedSlash})|/)${encodedCount}$`, ); const ODataOptionCodeExampleMap = { $filter: '$filter: a: $op: [b: $count: ... ]', $expand: '$expand: a: $count: ...', $orderby: "$orderby: { a: { $count: ... }, $dir: 'asc' }", }; const durationTimepartFlagEntries = [ ['hours', 'H'], ['minutes', 'M'], ['seconds', 'S'], ] as const; /** * It is expected that errors thrown by `_request` will be instances of this class/a subclass of it. */ export class StatusError extends Error { constructor( message: string, public statusCode: number, ) { super(message); } } interface PollOnObj { unsubscribe: () => void; } class Poll { private subscribers: { error: Array<(err: any) => void>; data: Array<(response: T) => void>; } = { error: [], data: [], }; private stopped = false; private pollInterval?: ReturnType; private requestFn: null | (() => Promise); constructor( requestFn: () => Promise, private intervalTime = 10000, ) { this.requestFn = requestFn; this.start(); } public setPollInterval(intervalTime: number): void { this.intervalTime = intervalTime; this.restartTimeout(); } public async runRequest(): Promise { if (this.stopped || this.requestFn == null) { return; } try { const response = await this.requestFn(); if (this.stopped) { return; } this.restartTimeout(); // Catch errors in event subscribers so that they don't trigger // the 'catch' below, and that subsequent subscribers will still // be called for (const fn of this.subscribers.data) { try { fn(response); } catch (error) { console.error( 'pinejs-client error: Caught error in data event subscription:', error, ); } } } catch (err: any) { if (this.stopped) { return; } this.restartTimeout(); for (const fn of this.subscribers.error) { try { fn(err); } catch (error) { console.error( 'pinejs-client error: Caught error in error event subscription:', error, ); } } } } public on(name: 'data', fn: (response: T) => void): PollOnObj; public on(name: 'error', fn: (err: any) => void): PollOnObj; public on( name: keyof Poll['subscribers'], fn: (value: any) => void, ): PollOnObj { const subscribers = this.subscribers[name] as Array<(value: any) => void>; const index = subscribers.push(fn) - 1; return { // we use the index of the subscriber as a key to unsubscribe // we can't use splice as this would change the index of the other subscribers // so currently it creates a hole in the array ([undefined]) where once a subscriber was // eslint-disable-next-line @typescript-eslint/no-array-delete unsubscribe: () => delete this.subscribers[name][index], }; } public start(): void { this.stopped = false; void this.runRequest(); } public stop(): void { if (this.pollInterval) { clearTimeout(this.pollInterval); } this.stopped = true; } public destroy(): void { this.stop(); this.requestFn = null; this.subscribers.error.length = 0; this.subscribers.data.length = 0; } private restartTimeout(): void { if (this.stopped) { return; } if (this.pollInterval) { clearTimeout(this.pollInterval); } this.pollInterval = setTimeout(() => this.runRequest(), this.intervalTime); } } const isPrimitive = (value?: unknown): value is Primitive => { return ( value === null || isString(value) || NumberIsFinite(value) || isBoolean(value) || isDate(value) ); }; // Escape a resource name (string), or resource path (array) const escapeResource = (resource: string | string[]): string => { if (isString(resource)) { resource = encodeURIComponent(resource); } else if (isArray(resource)) { resource = resource.map(encodeURIComponent).join('/'); } else { throw new Error('Not a valid resource: ' + typeof resource); } return resource.replace(trailingCountRegex, '/$count'); }; // Escape a primitive value const escapeValue = (value: Primitive): string | number | boolean | null => { if (isString(value)) { value = value.replace(/'/g, "''"); return `'${encodeURIComponent(value)}'`; } else if (isDate(value)) { return `datetime'${value.toISOString()}'`; } else if (value === null || NumberIsFinite(value) || isBoolean(value)) { return value; } else { throw new Error('Not a valid value: ' + typeof value); } }; const escapeParameterAlias = (value: unknown): string => { if (!isString(value)) { throw new Error( `Parameter alias reference must be a string, got: ${typeof value}`, ); } return `@${encodeURIComponent(value)}`; }; const join = (strOrArray: string | string[], separator = ','): string => { if (isString(strOrArray)) { return strOrArray; } else if (isArray(strOrArray)) { return strOrArray.join(separator); } else { throw new Error('Expected a string or array, got: ' + typeof strOrArray); } }; type RemoveDollarPrefix = T extends `$${infer Rest}` ? Rest : T; const stripDollarPrefix = ( key: T, ): RemoveDollarPrefix => key.slice(1) as RemoveDollarPrefix; // Every separator `bracketJoin` is ever called with: `,` for `$in` lists, the // logical `$and`/`$or` joins, and the comparison/arithmetic operators. type FilterSeparator = ',' | ' and ' | ' or ' | ` ${RemoveDollarPrefix} `; // Join together a bunch of statements making sure the whole lot is correctly parenthesised const bracketJoin = (arr: string[][], separator: FilterSeparator): string[] => { if (arr.length === 1) { return arr[0]; } if (separator === ' or ' || separator === ' and ') { const otherSeparator = separator === ' or ' ? ' and ' : ' or '; const $resultArr: string[] = []; for (let i = 0; i < arr.length; i++) { if (i !== 0) { $resultArr.push(separator); } const subArr = arr[i]; if (subArr.includes(otherSeparator)) { $resultArr.push(`(${subArr.join('')})`); } else { $resultArr.push(...subArr); } } return $resultArr; } const resultArr: string[] = []; for (let i = 0; i < arr.length; i++) { if (i !== 0) { resultArr.push(separator); } const subArr = arr[i]; if (subArr.length > 1) { resultArr.push(`(${subArr.join('')})`); } else { resultArr.push(subArr[0]); } } return resultArr; }; // Add the parentKey + operator if it exists. const addParentKey = ( filter: string[] | string | boolean | number | null, parentKey?: string[], operator = ' eq ', ): string[] => { if (parentKey != null) { if (isArray(filter)) { if (filter.length === 1) { filter = filter[0]; } else { filter = `(${filter.join('')})`; } } else { filter = `${filter}`; } return [escapeResource(parentKey), operator, filter]; } if (isArray(filter)) { return filter; } return [`${filter}`]; }; const applyBinds = ( filter: string, params: Record>, parentKey?: string[], ): string[] => { for (const index of Object.keys(params)) { const param = params[index]; let paramStr = `(${buildFilter(param).join('')})`; // Escape $ for filter.replace paramStr = paramStr.replace(/\$/g, '$$$$'); filter = filter.replace( new RegExp(`\\$${index}([^a-zA-Z0-9]|$)`, 'g'), `${paramStr}$1`, ); } filter = `(${filter})`; return addParentKey(filter, parentKey); }; const filterOperation = ( filter: FilterOperationValue, operator: FilterOperationKey, parentKey?: string[], ): string[] => { const op = ` ${stripDollarPrefix(operator)} ` as const; if (isPrimitive(filter)) { const filterStr = escapeValue(filter); return addParentKey(filterStr, parentKey, op); } else if (isArray(filter)) { const filterArr = handleFilterArray(filter); const filterStr = bracketJoin(filterArr, op); return addParentKey(filterStr, parentKey); } else if (isObject(filter)) { const result = handleFilterObject(filter); if (result.length < 1) { throw new Error( `${operator} objects must have at least 1 property, got: ${JSON.stringify( filter, )}`, ); } if (result.length === 1) { return addParentKey(result[0], parentKey, op); } else { const filterStr = bracketJoin(result, op); return addParentKey(filterStr, parentKey); } } else { throw new Error( 'Expected null/string/number/bool/obj/array, got: ' + typeof filter, ); } }; const filterFunction = ( filter: FilterFunctionValue, fnIdentifier: FilterFunctionKey, parentKey?: string[], ): string[] => { const fnName = fnIdentifier.slice(1); if (isPrimitive(filter)) { const operands = []; if (parentKey != null) { operands.push(escapeResource(parentKey)); } operands.push(escapeValue(filter)); return [`${fnName}(${operands.join()})`]; } else if (isArray(filter)) { const filterArr = handleFilterArray(filter); let filterStr = filterArr.map((subArr) => subArr.join('')).join(','); filterStr = `${fnName}(${filterStr})`; return addParentKey(filterStr, parentKey); } else if (isObject(filter)) { const filterArr = handleFilterObject(filter); let filterStr = filterArr.map((subArr) => subArr.join('')).join(','); filterStr = `${fnName}(${filterStr})`; return addParentKey(filterStr, parentKey); } else { throw new Error( `Expected null/string/number/obj/array, got: ${typeof filter}`, ); } }; type FilterType< Operator extends keyof AllFilterOperations, T extends Resource['Read'], > = NonNullable[Operator]>; // Handle special cases for all the different $ operators. const handleFilterOperator = < T extends Resource['Read'], U extends AllFilterOperations, >( filter: AllFilterOperations[keyof AllFilterOperations], operator: keyof AllFilterOperations, parentKey?: string[], ): string[] => { switch (operator) { case '$ne': case '$eq': case '$gt': case '$ge': case '$lt': case '$le': case '$add': case '$sub': case '$mul': case '$div': case '$mod': return filterOperation( filter as FilterType, operator, parentKey, ); // break case '$contains': case '$endswith': case '$startswith': case '$length': case '$indexof': case '$substring': case '$tolower': case '$toupper': case '$trim': case '$concat': case '$year': case '$month': case '$day': case '$hour': case '$minute': case '$second': case '$fractionalseconds': case '$date': case '$time': case '$totaloffsetminutes': case '$now': case '$maxdatetime': case '$mindatetime': case '$totalseconds': case '$round': case '$floor': case '$ceiling': case '$isof': case '$cast': return filterFunction( filter as FilterType, operator, parentKey, ); case '$duration': { const durationValue = filter as DurationValue; if (!isObject(durationValue)) { throw new Error(`Expected type for ${operator}, got: ${typeof filter}`); } let durationString = 'P'; if (durationValue.days) { durationString += `${durationValue.days}D`; } let timePart = ''; for (const [partKey, partFlag] of durationTimepartFlagEntries) { if (durationValue[partKey]) { timePart += `${durationValue[partKey]}${partFlag}`; } } if (timePart.length > 0) { durationString += `T${timePart}`; } if (durationString.length <= 1) { throw new Error( `Expected ${operator} to include duration properties, got: ${typeof filter}`, ); } if (durationValue.negative) { durationString = `-${durationString}`; } return addParentKey(`duration'${durationString}'`, parentKey); } // break case '$raw': { const filterx = filter as U[typeof operator]; if (isString(filterx)) { return addParentKey(`(${filterx})`, parentKey); } else if (!isPrimitive(filterx)) { // This needs to use the mutable version `Array.isArray` or otherwise the destructuring gets the wrong types? if (Array.isArray(filterx)) { const [rawFilter, ...params] = filterx; if (!isString(rawFilter)) { throw new Error( `First element of array for ${operator} must be a string, got: ${typeof rawFilter}`, ); } const mappedParams: Record> = {}; for (let index = 0; index < params.length; index++) { mappedParams[index + 1] = params[index]; } return applyBinds(rawFilter, mappedParams, parentKey); } else if (isObject(filterx)) { const filterStr = filterx.$string; if (!isString(filterStr)) { throw new Error( `$string element of object for ${operator} must be a string, got: ${typeof filterStr}`, ); } const mappedParams: Record> = {}; for (const index of Object.keys(filterx)) { if (index !== '$string') { if (!/^[a-zA-Z0-9]+$/.test(index)) { throw new Error( `${operator} param names must contain only [a-zA-Z0-9], got: ${index}`, ); } mappedParams[index] = filterx[index as ResourceName]; } } return applyBinds(filterStr, mappedParams, parentKey); } } throw new Error( `Expected string/array/object for ${operator}, got: ${typeof filterx}`, ); } // break case '$': { const resource = escapeResource(filter as FilterType); return addParentKey(resource, parentKey); } case '$count': { if ( parentKey != null && isObject(filter) && // Handles the `$filter: $op: [ {a: {$count: {'...'}}}, value]`` case. (Object.keys(filter).length === 0 || Object.prototype.hasOwnProperty.call(filter, '$filter')) ) { const keys = parentKey.slice(0, parentKey.length - 1); keys.push( handleOptions( '$filter', { $count: filter as { $filter?: Filter } }, parentKey[parentKey.length - 1], ), ); return [keys.join('/')]; } throw new Error( '`$filter: { a: { $count: { $op: number } } }` has been removed, please use `$filter: { $eq: [ { a: { $count: {} } }, number ] }` instead.', ); } // break case '$and': case '$or': { const filterStr = buildFilter( filter as FilterType, undefined, ` ${stripDollarPrefix(operator)} `, ); return addParentKey(filterStr, parentKey); } // break case '$in': { if (isPrimitive(filter)) { const filterStr = escapeValue(filter); return addParentKey(filterStr, parentKey, ' eq '); } else if (isArray(filter)) { if (filter.every(isPrimitive)) { const filterStr = handleFilterArray(filter, undefined, 1); const inStr = bracketJoin(filterStr, ',').join(''); return addParentKey(`(${inStr})`, parentKey, ' in '); } else { const filterStr = handleFilterArray(filter, parentKey, 1); return bracketJoin(filterStr, ' or '); } } else if (isObject(filter)) { const filterArr = handleFilterObject(filter, parentKey); if (filterArr.length < 1) { throw new Error( `${operator} objects must have at least 1 property, got: ${JSON.stringify( filter, )}`, ); } return bracketJoin(filterArr, ' or '); } else { throw new Error( `Expected null/string/number/bool/obj/array, got: ${typeof filter}`, ); } } // break case '$not': { const filterStr = `not(${buildFilter( filter as FilterType, ).join('')})`; return addParentKey(filterStr, parentKey); } // break case '$any': case '$all': { const filterx = filter as FilterType; const alias = filterx.$alias; const expr = filterx.$expr; if (alias == null) { throw new Error( `Lambda expression (${operator}) has no alias defined.`, ); } if (expr == null) { throw new Error(`Lambda expression (${operator}) has no expr defined.`); } let filterStr; const prevDisableExpandFilterError = disableExpandFilterError; try { // Disable the expandFilter error when inside a lambda expr because we need to allow `alias: field: ...` disableExpandFilterError = true; filterStr = buildFilter(expr).join(''); } finally { disableExpandFilterError = prevDisableExpandFilterError; } filterStr = `${operator.slice(1)}(${alias}:${filterStr})`; return addParentKey(filterStr, parentKey, '/'); } case '$fn': { const filterx = filter as FilterType; if (typeof filterx.$scope !== 'string') { throw new Error( `Function expression (${operator}) $scope must be a string.`, ); } const scope = escapeResource(filterx.$scope); if (typeof filterx.$method !== 'string') { throw new Error( `Function expression (${operator}) $method must be a string.`, ); } const method = escapeResource(filterx.$method); const args = filterx.$args?.map((v) => `${escapeValue(v)}`) ?? []; const filterStr = `${scope}.${method}(` + args.join(',') + ')'; return addParentKey(filterStr, parentKey, '/'); } // break default: throw new Error(`Unrecognised operator: '${operator}'`); } }; const handleFilterObject = ( filter: FilterObj, parentKey?: string[], ): string[][] => { return mapObj(filter, (value, key) => { if (value === undefined) { throw new Error( `'${key}' was present on a filter object but undefined, did you mean to use null instead?`, ); } if (key.startsWith('$')) { return handleFilterOperator( value, key as keyof AllFilterOperations, parentKey, ); } else if (key.startsWith('@')) { const parameterAlias = escapeParameterAlias(value); return addParentKey(parameterAlias, parentKey); } else { let keys: string[] = [key]; if (parentKey != null) { if (disableExpandFilterError === false && parentKey.length > 0) { throw new Error( '`$filter: a: b: ...` has been removed, please use `$filter: a: $any: { $alias: "x", $expr: x: b: ... }` instead.', ); } keys = parentKey.concat(keys); } return buildFilter(value, keys); } }); }; const handleFilterArray = ( filter: FilterArray, parentKey?: string[], minElements = 2, ): string[][] => { if (filter.length < minElements) { throw new Error( `Filter arrays must have at least ${minElements} elements, got: ${JSON.stringify( filter, )}`, ); } return filter.map((value) => { return buildFilter(value, parentKey); }); }; // Turn a filter query object into an OData $filter string const buildFilter = ( filter: Filter, parentKey?: string[], joinStr?: FilterSeparator, ): string[] => { if (isPrimitive(filter)) { const filterStr = escapeValue(filter); return addParentKey(filterStr, parentKey); } else if (isArray(filter)) { const filterArr = handleFilterArray(filter); const filterStr = bracketJoin(filterArr, joinStr ?? ' or '); return addParentKey(filterStr, parentKey); } else if (isObject(filter)) { const filterArr = handleFilterObject(filter, parentKey); return bracketJoin(filterArr, joinStr ?? ' and '); } else { throw new Error( `Expected null/string/number/obj/array, got: ${typeof filter}`, ); } }; const buildOrderBy = ( orderby: OrderBy, ): string => { if (isString(orderby)) { if (/\/\$count\b/.test(orderby)) { throw new Error( "`$orderby: 'a/$count'` has been removed, please use `$orderby: { a: { $count: {...} } }` instead.", ); } return orderby; } else if (isArray(orderby)) { if (orderby.length === 0) { throw new Error(`'$orderby' arrays have to have at least 1 element`); } const result = orderby.map((value) => { if (isArray(value)) { throw new Error(`'$orderby' cannot have nested arrays`); } return buildOrderBy(value); }); return join(result); } else if (isObject(orderby)) { const { $dir, ...$orderby } = orderby; const result = mapObj($orderby as typeof orderby, (dirOrOptions, key) => { let propertyPath: string = key; let dir = $dir; if (dirOrOptions == null) { throw new Error( `Orderby object values must not be null, got null for ${key}`, ); } if (typeof dirOrOptions === 'string') { dir = dirOrOptions; } else { const keys = Object.keys(dirOrOptions); if ( !Object.prototype.hasOwnProperty.call(dirOrOptions, '$count') || keys.length > 1 ) { throw new Error( `When using '${ ODataOptionCodeExampleMap['$orderby'] }' you can only specify $count, got: '${JSON.stringify(keys)}'`, ); } propertyPath = handleOptions('$orderby', dirOrOptions, propertyPath); } if (dir == null) { throw new Error( `'$orderby' objects should either use the '{ a: 'asc' }' or the ${ODataOptionCodeExampleMap.$orderby} notation`, ); } if (dir !== 'asc' && dir !== 'desc') { throw new Error(`'$orderby' direction must be 'asc' or 'desc'`); } return `${propertyPath} ${dir}`; }); if (result.length !== 1) { throw new Error( `'$orderby' objects must have exactly one element, got ${result.length} elements`, ); } return result[0]; } else { throw new Error( `'$orderby' option has to be either a string, array, or object`, ); } }; const buildOption = ( option: string, value: ODataOptionsWithoutCount[string], ): string => { let compiledValue: string; switch (option) { case '$filter': compiledValue = buildFilter(value as Filter).join(''); break; case '$expand': compiledValue = buildExpand(value as Expand); break; case '$orderby': compiledValue = buildOrderBy(value as OrderBy); break; case '$top': case '$skip': { const num = value; if (!NumberIsFinite(num)) { throw new Error(`'${option}' option has to be a number`); } compiledValue = '' + num; break; } case '$select': { const select = value; if (isString(select)) { compiledValue = join(select); } else if (isArray(select)) { if (select.length === 0) { throw new Error(`'${option}' arrays have to have at least 1 element`); } compiledValue = join(select as string[]); } else if (isSet(select)) { if (select.size === 0) { throw new Error(`'${option}' sets have to have at least 1 element`); } compiledValue = join(Array.from(select)); } else { throw new Error( `'${option}' option has to be either a string or array`, ); } break; } default: // Escape parameter aliases as primitives if (option.startsWith('@')) { if (!isPrimitive(value)) { throw new Error( `Unknown type for parameter alias option '${option}': ${typeof value}`, ); } compiledValue = '' + escapeValue(value); } // Unknown values are left as-is else if (isArray(value)) { compiledValue = join(value as string[]); } else if (isString(value)) { compiledValue = value; } else if (isBoolean(value) || NumberIsFinite(value)) { compiledValue = value.toString(); } else { throw new Error(`Unknown type for option ${typeof value}`); } } return `${option}=${compiledValue}`; }; const handleOptions = ( optionOperation: keyof typeof ODataOptionCodeExampleMap, options: ODataOptions, parentKey: string, ): string => { if (Object.prototype.hasOwnProperty.call(options, '$count')) { const keys = Object.keys(options); if (keys.length > 1) { throw new Error( `When using '${ ODataOptionCodeExampleMap[optionOperation] }' you can only specify $count, got: '${JSON.stringify(keys)}'`, ); } options = options.$count!; parentKey += '/$count'; // Check whether there is anything else other than $filter in the $count // and error b/c it's invalid. if ( Object.keys(options).length > (Object.prototype.hasOwnProperty.call(options, '$filter') ? 1 : 0) ) { throw new Error( `When using '${ ODataOptionCodeExampleMap[optionOperation] }' you can only specify $filter in the $count, got: '${JSON.stringify( Object.keys(options), )}'`, ); } } const optionsArray = mapObj(options, (value, key) => { if (key.startsWith('$')) { if (!isValidOption(key)) { throw new Error(`Unknown key option '${key}'`); } return buildOption(key, value); } if (optionOperation === '$expand') { throw new Error( `'$expand: ${parentKey}: ${key}: ...' is invalid, use '$expand: ${parentKey}: $expand: ${key}: ...' instead.`, ); } throw new Error( `'${optionOperation}: ${parentKey}: ${key}: ...' is invalid.`, ); }); let optionsStr = optionsArray.join(';'); if (optionsStr.length > 0) { optionsStr = `(${optionsStr})`; } optionsStr = escapeResource(parentKey) + optionsStr; return optionsStr; }; const handleExpandObject = ( expand: ResourceExpand, ): string[] => { const expands = mapObj(expand, (value, key) => { if (key.startsWith('$')) { throw new Error( 'Cannot have expand options without first expanding something!', ); } if (value == null) { throw new Error( `Expand object values must not be null, got null for ${key}`, ); } if (isPrimitive(value)) { const jsonValue = JSON.stringify(value); throw new Error( `'$expand: ${key}: ${jsonValue}' is invalid, use '$expand: ${key}: $expand: ${jsonValue}' instead.`, ); } if (isArray(value)) { throw new Error( `'$expand: ${key}: [...]' is invalid, use '$expand: ${key}: {...}' instead.`, ); } if (key.endsWith('/$count')) { throw new Error( "`$expand: { 'a/$count': {...} }` has been removed, please use `$expand: { a: { $count: {...} } }` instead.", ); } return handleOptions('$expand', value, key); }); return expands; }; const handleExpandArray = ( expands: ReadonlyArray>, ): string[] => { if (expands.length < 1) { throw new Error( `Expand arrays must have at least 1 elements, got: ${JSON.stringify( expands, )}`, ); } return expands.map((expand) => { return buildExpand(expand); }); }; const buildExpand = (expand: Expand): string => { if (isPrimitive(expand)) { return escapeResource(expand); } else if (isArray(expand)) { const expandStr = handleExpandArray(expand); return join(expandStr); } else if (isObject(expand)) { const expandStr = handleExpandObject(expand); return join(expandStr); } else { throw new Error(`Unknown type for expand '${typeof expand}'`); } }; const getRetryAfterHeaderDelayMs = ( getRetryAfterHeader: RetryParametersObj['getRetryAfterHeader'], err: unknown, ) => { const retryAfterRaw = getRetryAfterHeader?.(err); if (typeof retryAfterRaw !== 'string') { return; } // TODO: Add support for parsing and converting HTTP date format values to delay. const retryAfterSeconds = parseInt(retryAfterRaw, 10); if (!Number.isInteger(retryAfterSeconds) || retryAfterSeconds < 0) { return; } return retryAfterSeconds * 1000; }; const validParams = [ 'apiPrefix', 'passthrough', 'passthroughByMethod', 'retry', ] as const; export type PreparedFn< T extends Record, U, TResource extends Resource = AnyResource, > = ( parameterAliases?: T, body?: Params['body'], passthrough?: Params['passthrough'], ) => U; export type RetryParametersObj = { canRetry?: (err: any) => boolean; onRetry?: ( prevErr: any, delayMs: number, attempt: number, maxAttempts: number, ) => void; getRetryAfterHeader?: (err: unknown) => string | undefined; minDelayMs?: number; maxDelayMs?: number; maxAttempts?: number; }; export type RetryParameters = RetryParametersObj | false; export abstract class PinejsClientCore< Model extends { [key in keyof Model]: Resource } = { [key in string]: AnyResource; }, > { public apiPrefix = '/'; public passthrough: AnyObject = {}; public passthroughByMethod: AnyObject = {}; public backendParams?: AnyObject; public retry: RetryParameters = false; // `backendParams` must be used by a backend for any additional parameters it may have. constructor(params: string | ConstructorParams) { if (isString(params)) { params = { apiPrefix: params }; } if (isObject(params)) { for (const validParam of validParams) { const value = params[validParam]; if (value != null) { (this[validParam] satisfies PinejsClientCore[typeof validParam]) = value; } } } } private canRetryDefaultHandler(err: any) { let statusCode: number | undefined; if (err instanceof StatusError) { statusCode = err.statusCode; } else if ( isObject(err) && 'statusCode' in err && NumberIsFinite(err.statusCode) ) { // TODO-MAJOR: enforce throwing a subclass of StatusError statusCode = err.statusCode; } return ( statusCode == null || statusCode === 429 || (statusCode >= 500 && statusCode < 600) ); } protected async callWithRetry( fnCall: () => Promise, retry?: RetryParameters, ): Promise { // Explicitly passing retry as false disables retrying for this call. if (retry === false || (retry == null && this.retry === false)) { return await fnCall(); } const retryDefaultParameters = this.retry || {}; const retryParameters = retry ?? {}; const minDelayMs = retryParameters.minDelayMs ?? retryDefaultParameters.minDelayMs; const maxDelayMs = retryParameters.maxDelayMs ?? retryDefaultParameters.maxDelayMs; const maxAttempts = retryParameters.maxAttempts ?? retryDefaultParameters.maxAttempts; if (minDelayMs == null || minDelayMs <= 0) { throw new Error( `pinejs-client minDelayMs must be a positive integer, got: '${minDelayMs}'`, ); } if (maxDelayMs == null || maxDelayMs <= 0) { throw new Error( `pinejs-client maxDelayMs must be a positive integer, got: '${maxDelayMs}'`, ); } if (maxAttempts == null || maxAttempts <= 0) { throw new Error( `pinejs-client maxAttempts must be a positive integer, got: '${maxAttempts}'`, ); } if (minDelayMs > maxDelayMs) { throw new Error( 'pinejs-client maxDelayMs must be greater than or equal to minDelayMs', ); } const onRetryHandler = retryParameters.onRetry ?? retryDefaultParameters.onRetry; const getRetryAfterHeader = retryParameters.getRetryAfterHeader ?? retryDefaultParameters.getRetryAfterHeader; let attempt = 1; const canRetryHandler = retryParameters.canRetry ?? retryDefaultParameters.canRetry ?? this.canRetryDefaultHandler; while (true) { try { return await fnCall(); } catch (err) { if (attempt >= maxAttempts || !canRetryHandler(err)) { throw err; } let delayMs = Math.min(2 ** (attempt - 1) * minDelayMs, maxDelayMs); // note that attempt is incremented before calling onRetryHandler because // retries effectively begin with attempt number 2. attempt++; const retryAfterDelayMs = getRetryAfterHeaderDelayMs( getRetryAfterHeader, err, ); if (retryAfterDelayMs != null && retryAfterDelayMs > delayMs) { delayMs = retryAfterDelayMs; } onRetryHandler?.(err, delayMs, attempt, maxAttempts); await new Promise((resolve) => { setTimeout(resolve, delayMs); }); } } } // `backendParams` must be used by a backend for any additional parameters it may have. public clone( params: string | ConstructorParams, backendParams?: AnyObject, ): this { if (isString(params)) { params = { apiPrefix: params }; } const cloneParams: typeof params = {}; for (const validParam of validParams) { if (this[validParam] != null) { (cloneParams[validParam] as PinejsClientCore[typeof validParam]) = this[validParam]; } const paramValue = params?.[validParam]; if (paramValue != null) { (cloneParams[validParam] as PinejsClientCore[typeof validParam]) = paramValue; } } let cloneBackendParams: typeof backendParams = {}; if (isObject(this.backendParams)) { cloneBackendParams = { ...this.backendParams }; } if (isObject(backendParams)) { cloneBackendParams = { ...cloneBackendParams, ...backendParams }; } return new ( this.constructor as new ( $params: ConstructorParams, $backendParams: AnyObject, ) => this )(cloneParams, cloneBackendParams); } public async get< TResource extends StringKeyOf, TParams extends Params & { resource: TResource; }, >( params: { resource: TResource } & TParams, ): Promise< NoInfer< OptionsToResponse< Model[TResource]['Read'], NonNullable, MaybeGetKey > > > { if ('url' in params && params.url != null) { throw new Error( 'Passing `url` to `get` has been removed, please use a query object instead or use `request` directly.', ); } const result = await this.request({ ...params, method: 'GET' }); return this.transformGetResult(params, result); } protected transformGetResult< TResource extends StringKeyOf, TParams extends Params & { resource: TResource; }, >( params: TParams, data: AnyObject, ): NoInfer< OptionsToResponse< Model[TResource]['Read'], NonNullable, MaybeGetKey > >; protected transformGetResult( params: Params & { options: { $count: NonNullable['$count']> }; }, data: AnyObject, ): number; protected transformGetResult( params: Params & { id: NonNullable['id']> }, data: AnyObject, ): AnyObject | undefined; protected transformGetResult( params: Omit, 'id'>, data: AnyObject, ): AnyObject[]; protected transformGetResult( params: Params, data: AnyObject, ): PromiseResultTypes { if (!isObject(data)) { throw new Error(`Response was not a JSON object: '${typeof data}'`); } if (data.d == null) { throw new Error( "Invalid response received, the 'd' property is missing.", ); } if (params.id != null) { // singular if (data.d.length > 1) { throw new Error( 'Returned multiple results when only one was expected.', ); } return data.d[0]; } return data.d; } public subscribe< TResource extends StringKeyOf, TParams extends SubscribeParams & { resource: TResource; }, >( params: TParams & { resource: TResource; }, ): Poll< NoInfer< OptionsToResponse< Model[TResource]['Read'], NonNullable, MaybeGetKey > > > { if (!isObject(params)) { throw new Error('Params must be an object.'); } const { pollInterval } = params; const requestFn = this.prepare(params, {}); return new Poll(requestFn, pollInterval); } public put>( params: { resource: TResource } & Params, ): Promise { if ('url' in params && params.url != null) { throw new Error( 'Passing `url` to `put` has been removed, please use a query object instead or use `request` directly.', ); } return this.request({ ...params, method: 'PUT' }); } public patch>( params: { resource: TResource } & Params, ): Promise { if ('url' in params && params.url != null) { throw new Error( 'Passing `url` to `patch` has been removed, please use a query object instead or use `request` directly.', ); } return this.request({ ...params, method: 'PATCH' }); } public post>( params: { resource: TResource; } & ActionParams & Omit, 'method' | 'url' | 'body'>, ): Promise; public post>( params: { resource: TResource } & Params, ): Promise>; public post>( params: { resource: TResource } & ActionParams & Params, ): Promise> { if ('url' in params && params.url != null) { throw new Error( 'Passing `url` to `post` has been removed, please use a query object instead or use `request` directly.', ); } return this.request({ ...params, method: 'POST' }) as Promise< PickDeferred >; } public delete>( params: { resource: TResource } & Params, ): Promise { if ('url' in params && params.url != null) { throw new Error( 'Passing `url` to `delete` has been removed, please use a query object instead or use `request` directly.', ); } return this.request({ ...params, method: 'DELETE' }); } public async getOrCreate< TResource extends StringKeyOf, TParams extends GetOrCreateParams & { resource: TResource; }, >( params: { resource: TResource } & TParams, ): Promise< NoInfer< OptionsToResponse< Model[TResource]['Read'], NonNullable, TParams['id'] > > > { if ('url' in params && params.url != null) { throw new Error( 'Passing `url` to `getOrCreate` has been removed, please use a query object instead.', ); } const { id, body, ...restParams } = params; if (params.resource.endsWith('/$count')) { throw new Error('getOrCreate does not support $count on resources'); } if (body == null) { throw new Error('The body property is missing'); } if ( !isObject(id) || isDate(id) || Object.keys(id).length === 0 || // `{ '@': alias }` is an aliased primary key, not a natural key '@' in id ) { throw new Error( 'The id property must be an object with the natural key of the model', ); } // The id is used to create the resource, so parameter aliases have to be resolved // to the values they refer to in the options const resolvedId: AnyObject = {}; for (const [key, idValue] of Object.entries(id as AnyObject)) { if (isObject(idValue) && '@' in idValue) { const alias: unknown = idValue['@']; if (!isString(alias)) { throw new Error( `Parameter alias reference must be a string, got: ${typeof alias}`, ); } const aliasOption = `@${alias}`; if ( params.options == null || !Object.prototype.hasOwnProperty.call(params.options, aliasOption) ) { throw new Error( `The parameter alias '${aliasOption}' for the id property '${key}' must be set in the options`, ); } resolvedId[key] = (params.options as AnyObject)[aliasOption]; } else { resolvedId[key] = idValue; } } // The body is spread over the id when creating, so a differing value would create a // resource that doesn't match the natural key that we looked up for (const key of Object.keys(resolvedId)) { if (!Object.prototype.hasOwnProperty.call(body, key)) { continue; } const idValue: unknown = resolvedId[key]; const bodyValue: unknown = (body as AnyObject)[key]; const isSameValue = isDate(idValue) && isDate(bodyValue) ? idValue.getTime() === bodyValue.getTime() : idValue === bodyValue; if (!isSameValue) { throw new Error( `The body property '${key}' conflicts with the natural key in the id property`, ); } } const result = await this.get>({ ...restParams, id, } as Omit); if (result != null) { return result as OptionsToResponse< Model[TResource]['Read'], NonNullable, TParams['id'] >; } return (await this.post({ ...restParams, body: { ...resolvedId, ...body, }, })) as OptionsToResponse< Model[TResource]['Read'], NonNullable, TParams['id'] >; } public async upsert>( params: { resource: TResource } & UpsertParams, ): Promise> { if ('url' in params && params.url != null) { throw new Error( 'Passing `url` to `upsert` has been removed, please use a query object instead.', ); } const { id, body, ...restParams } = params; if (!isObject(id)) { throw new Error('The id property must be an object'); } const naturalKeyProps = Object.keys(params.id); if (naturalKeyProps.length === 0) { throw new Error( 'The id property must be an object with the natural key of the model', ); } if (body == null) { throw new Error('The body property is missing'); } const postParams = { ...restParams, body: { ...body, ...id, }, }; try { return await this.post(postParams); } catch (err: any) { // Backends such as pinejs-client-fetch/request pass the response body as the message const isUniqueKeyViolationResponse = err.statusCode === 409 && /unique/i.test(err.body ?? err.message); if (!isUniqueKeyViolationResponse) { throw err; } const { options } = restParams; const $filter = options?.$filter == null ? id : { $and: [options.$filter, id] }; const patchParams = { ...restParams, options: { ...options, $filter, }, body, }; await this.patch(patchParams); } } public prepare< TAliases extends Record< string, Array<'null' | 'string' | 'number' | 'boolean' | 'Date'> >, TResource extends StringKeyOf, TParams extends Params & { resource: TResource; }, >( params: { resource: TResource; method?: 'GET'; } & TParams, /** * If this is passed then all the listed aliases are expected to be used in params and passed to the returned prepared function. */ expectedAliases: TAliases, ): PreparedFn< StringDictionaryToDictType, Promise< NoInfer< OptionsToResponse< Model[TResource]['Read'], NonNullable, MaybeGetKey > > >, Model[TResource] >; public prepare< TAliases extends Record< string, Array<'null' | 'string' | 'number' | 'boolean' | 'Date'> >, TResource extends StringKeyOf, >( params: Params & { resource: TResource; method: 'PUT' | 'PATCH' | 'DELETE'; }, /** * If this is passed then all the listed aliases are expected to be used in params and passed to the returned prepared function. */ expectedAliases: TAliases, ): PreparedFn< StringDictionaryToDictType, Promise, Model[TResource] >; public prepare< TAliases extends Record< string, Array<'null' | 'string' | 'number' | 'boolean' | 'Date'> >, TResource extends StringKeyOf, >( params: Params & { resource: TResource; method: 'POST'; }, /** * If this is passed then all the listed aliases are expected to be used in params and passed to the returned prepared function. */ expectedAliases: TAliases, ): PreparedFn< StringDictionaryToDictType, Promise, Model[TResource] >; public prepare>( params: Params, ): PreparedFn> { if (!isObject(params)) { throw new Error('Params must be an object.'); } // precompile the URL string to improve performance const compiledUrl = params.url ?? this.compile(params); const urlQueryParamsStr = !compiledUrl.includes('?') ? '?' : '&'; const method = (params.method ?? 'GET').toUpperCase() as ODataMethod; const { body: defaultBody, passthrough: defaultPassthrough } = params; return async (parameterAliases, body, passthrough) => { // Build fresh params for every call so that we never mutate the caller's // params and concurrent calls cannot interfere with each other const requestParams: Params = { ...params, method }; if (body != null) { requestParams.body = { ...defaultBody, ...body, }; } else if (defaultBody != null) { requestParams.body = { ...defaultBody }; } if (passthrough != null) { requestParams.passthrough = { ...defaultPassthrough, ...passthrough, }; } else if (defaultPassthrough != null) { requestParams.passthrough = { ...defaultPassthrough }; } if (parameterAliases != null) { requestParams.url = compiledUrl + urlQueryParamsStr + mapObj(parameterAliases, (value, option) => { if (!isPrimitive(value)) { throw new Error( `Unknown type for parameter alias option '${option}': ${typeof value}`, ); } return `@${option}=${escapeValue(value)}`; }).join('&'); } else { requestParams.url = compiledUrl; } const result = await this.request(requestParams); if (method === 'GET') { return this.transformGetResult(requestParams, result as AnyObject); } return result; }; } public compile>( params: { resource: TResource } & Partial & Params, ): string; public compile(params: Params & Partial): string; public compile(params: Params & Partial): string { if (!isObject(params)) { throw new Error('Params must be an object.'); } if (params.url != null) { throw new Error( 'Passing `url` to `compile` has been removed, please use a query object or the url directly instead.', ); } else { if (params.resource == null) { throw new Error('The resource must be specified.'); } if (params.resource.endsWith('/$count')) { throw new Error( "`resource: 'a/$count'` has been removed, please use `options: { $count: { ... } }` instead.", ); } let url = escapeResource(params.resource); let { options } = params; if ( options != null && Object.prototype.hasOwnProperty.call(options, '$count') ) { const keys = Object.keys(options); if (keys.length > 1) { throw new Error( `When using 'options: { $count: ... }' you can only specify $count, got: '${JSON.stringify( keys, )}'`, ); } // A single resource cannot be counted, and pine accepts neither `a(1)/$count` nor `a/$count(1)` if (params.id != null) { throw new Error( '`options: { $count: ... }` cannot be combined with `id`, please use `options: { $count: { $filter: { id: ... } } }` instead.', ); } url += '/$count'; options = options.$count; } if (Object.prototype.hasOwnProperty.call(params, 'id')) { const { id } = params; if (id == null) { throw new Error('If the id property is set it must be non-null'); } let value: string; if (isObject(id) && !isDate(id)) { if (Object.keys(id).length === 0) { throw new Error( 'If the id property is an object it must not be empty', ); } if ('@' in id) { value = escapeParameterAlias(id['@']); } else { value = mapObj(id, (v, k) => { const escapedValue = isObject(v) && '@' in v ? escapeParameterAlias(v['@']) : escapeValue(v!); return `${k}=${escapedValue}`; }).join(','); } } else { value = '' + escapeValue(id); } url += `(${value})`; } if (Object.prototype.hasOwnProperty.call(params, 'action')) { if (params.action == null) { throw new Error('If the action property is set it must be non-null'); } url += `/${params.action}`; } let queryOptions: string[] = []; if (options != null) { queryOptions = mapObj(options, (value, option) => { if (option.startsWith('$') && !isValidOption(option)) { throw new Error(`Unknown odata option '${option}'`); } return buildOption(option, value); }); } if ((params as any).customOptions != null) { throw new Error( '`customOptions` has been removed, use `options` instead.', ); } if (queryOptions.length > 0) { url += '?' + queryOptions.join('&'); } return url; } } public request( params: Params & { method?: 'GET'; options: { $count: NonNullable['$count']> }; }, ): Promise<{ d: number }>; public request( params: Params & { method?: 'GET'; id: NonNullable['id']> }, ): Promise<{ d: AnyObject | undefined }>; public request( params: Omit, 'id'> & { method?: 'GET' }, ): Promise<{ d: AnyObject[] }>; public request( params: Params & { method?: 'GET' }, ): Promise<{ d: PromiseResultTypes }>; public request( params: Params & { method: 'PUT' | 'PATCH' | 'DELETE'; }, ): Promise; public request( params: Params & { method: 'POST'; }, ): Promise; public request( params: Params, ): Promise; public request( params: Params, ): Promise { if (!isObject(params)) { throw new Error('Params must be an object.'); } let { method, apiPrefix } = params; const { body, passthrough = {}, retry } = params; apiPrefix = apiPrefix ?? this.apiPrefix; const url = apiPrefix + (params.url ?? this.compile(params)); method = method ?? 'GET'; method = method.toUpperCase() as typeof method; // Filter to prevent accidental parameter passthrough. const opts = { ...this.passthrough, ...(this.passthroughByMethod[method] ?? {}), ...passthrough, url, body, method, }; // Do not await this._request result, so that we can preserve // the potentially enhanced promise-like result. return this.callWithRetry(() => this._request(opts), retry); } public abstract _request( params: { method: string; url: string; body?: AnyObject; } & AnyObject, ): Promise>; } export type PromiseResultTypes = number | AnyObject | AnyObject[] | undefined; type FilterOperationKey = | '$ne' | '$eq' | '$gt' | '$ge' | '$lt' | '$le' | '$add' | '$sub' | '$mul' | '$div' | '$mod'; type FilterOperationValue = Filter; type FilterFunctionKey = | '$contains' | '$endswith' | '$startswith' | '$length' | '$indexof' | '$substring' | '$tolower' | '$toupper' | '$trim' | '$concat' | '$year' | '$month' | '$day' | '$hour' | '$minute' | '$second' | '$fractionalseconds' | '$date' | '$time' | '$totaloffsetminutes' | '$now' | '$maxdatetime' | '$mindatetime' | '$totalseconds' | '$round' | '$floor' | '$ceiling' | '$isof' | '$cast'; type FilterFunctionValue = Filter; type DurationValue = { negative?: boolean; days?: number; hours?: number; minutes?: number; seconds?: number; }; export type NestedFilterOperations< T extends Resource['Read'], NestedKey extends StringKeyOf = ExpandableStringKeyOf, > = { $count?: NestedKey extends ExpandableStringKeyOf ? | Filter> | ODataCountOptions> : never; $in?: Filter; $any?: NestedKey extends ExpandableStringKeyOf ? Lambda> : never; $all?: NestedKey extends ExpandableStringKeyOf ? Lambda> : never; }; type FilterOperations = { '@'?: string; $raw?: RawFilter; $?: StringKeyOf | string[]; $and?: Filter; $or?: Filter; $not?: Filter; // Filter operations $ne?: FilterOperationValue; $eq?: FilterOperationValue; $gt?: FilterOperationValue; $ge?: FilterOperationValue; $lt?: FilterOperationValue; $le?: FilterOperationValue; $add?: FilterOperationValue; $sub?: FilterOperationValue; $mul?: FilterOperationValue; $div?: FilterOperationValue; $mod?: FilterOperationValue; // Filter functions $contains?: FilterFunctionValue; $endswith?: FilterFunctionValue; $startswith?: FilterFunctionValue; $length?: FilterFunctionValue; $indexof?: FilterFunctionValue; $substring?: FilterFunctionValue; $tolower?: FilterFunctionValue; $toupper?: FilterFunctionValue; $trim?: FilterFunctionValue; $concat?: FilterFunctionValue; $year?: FilterFunctionValue; $month?: FilterFunctionValue; $day?: FilterFunctionValue; $hour?: FilterFunctionValue; $minute?: FilterFunctionValue; $second?: FilterFunctionValue; $fractionalseconds?: FilterFunctionValue; $date?: FilterFunctionValue; $time?: FilterFunctionValue; $totaloffsetminutes?: FilterFunctionValue; $now?: FilterFunctionValue; $duration?: DurationValue; $maxdatetime?: FilterFunctionValue; $mindatetime?: FilterFunctionValue; $totalseconds?: FilterFunctionValue; $round?: FilterFunctionValue; $floor?: FilterFunctionValue; $ceiling?: FilterFunctionValue; $isof?: FilterFunctionValue; $cast?: FilterFunctionValue; $fn?: { $scope: string; $method: string; $args?: Primitive[]; }; }; type AllFilterOperations = FilterOperations & NestedFilterOperations; export type FilterObj = { [key in StringKeyOf]?: Filter | NestedFilterOperations | undefined; } & FilterOperations; export type FilterArray = ReadonlyArray>; export type FilterBaseType = string | number | null | boolean | Date; export type RawFilter = | string | [string, ...Array>] | { $string: string; [index: ResourceName]: Filter; }; export interface Lambda< T extends Resource['Read'] = AnyResourceObject, Alias extends string = string, > { // This alias can only be inferred when we are not passing any generic parameters so in // practice it has limited use but if/when typescript supports partial inference of generic // parameters it will become significantly more useful $alias: Alias; $expr: Filter]: T }>; } export type Filter = FilterObj | FilterArray | FilterBaseType; export type ResourceExpand = { [ resource in StringKeyOf as ExtractExpand extends never ? never : resource ]?: ODataOptions>; }; export type BaseExpand = ExpandableStringKeyOf | ResourceExpand; export type Expand = BaseExpand | ReadonlyArray>; /** * This can interact poorly with generics because `field: 'desc'` would be treated as `field: string` which doesn't match */ type OrderByDirection = 'asc' | 'desc'; type BaseOrderBy = | StringKeyOf | { [k in StringKeyOf]?: OrderByDirection } | ({ [k in ExpandableStringKeyOf & ResourceName]?: { $count: ODataCountOptions>; }; } & { $dir: OrderByDirection; }); // Arrays of orderbys cannot be nested export type OrderBy = BaseOrderBy | ReadonlyArray>; type StringPrimitiveToType< T extends 'null' | 'string' | 'number' | 'boolean' | 'Date', > = | ('null' extends T ? null : never) | ('number' extends T ? number : never) | ('string' extends T ? string : never) | ('boolean' extends T ? boolean : never) | ('Date' extends T ? Date : never); type StringDictionaryToDictType< T extends Record< string, Array<'null' | 'string' | 'number' | 'boolean' | 'Date'> >, > = keyof T extends never ? Record : { [key in keyof T]: StringPrimitiveToType; }; export type Primitive = null | string | number | boolean | Date; export type ParameterAlias = Primitive; export interface ODataOptionsWithoutCount< T extends Resource['Read'] = AnyResourceObject, > { $filter?: Filter; $expand?: Expand; $orderby?: OrderBy; $top?: number; $skip?: number; $select?: | StringKeyOf | ReadonlyArray> | ReadonlySet>; $format?: string; [index: string]: | undefined | ParameterAlias | string[] | Filter | Expand | OrderBy | ReadonlySet>; } export type ODataCountOptions = Pick, '$filter'>; export interface ODataOptions< T extends Resource['Read'] = AnyResourceObject, > extends ODataOptionsWithoutCount> { $count?: ODataCountOptions>; [index: string]: | ODataOptionsWithoutCount>[string] | ODataCountOptions>; } export type OptionsObject = ODataOptions; export type ODataMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; export type BaseResourceId = | string | number | Date | { '@': string; }; export type ResourceAlternateKey = { [key in StringKeyOf]?: BaseResourceId; }; export type ResourceId = BaseResourceId | ResourceAlternateKey; export type AnyObject = Record; export interface ActionParams { action: string; body?: unknown; } export interface Params { apiPrefix?: string; method?: ODataMethod; resource?: string; id?: ResourceId; url?: string; body?: Partial; passthrough?: AnyObject; options?: ODataOptions; retry?: RetryParameters; } export interface ConstructorParams extends Pick< Params, 'apiPrefix' | 'passthrough' | 'retry' > { // Only supported on the client, as a request already has a single method for `passthrough` passthroughByMethod?: { [method in ODataMethod]?: AnyObject }; } export interface SubscribeParams< T extends Resource = AnyResource, > extends Params { method?: 'GET'; pollInterval?: number; } export interface GetOrCreateParams< T extends Resource = AnyResource, > extends Omit, 'method' | 'url'> { id: ResourceAlternateKey; resource: string; body: Partial; } export interface UpsertParams extends Omit< Params, 'id' | 'method' | 'url' > { id: { [key in StringKeyOf]?: Primitive }; resource: string; body: Partial; }