@xata.io/client 0.12.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -6,6 +6,9 @@ declare type FetchImpl = (url: string, init?: {
6
6
  ok: boolean;
7
7
  status: number;
8
8
  json(): Promise<any>;
9
+ headers?: {
10
+ get(name: string): string | null;
11
+ };
9
12
  }>;
10
13
  declare type WorkspaceApiUrlBuilder = (path: string, pathParams: Record<string, string>) => string;
11
14
  declare type FetcherExtraProps = {
@@ -2798,7 +2801,7 @@ declare class DatabaseApi {
2798
2801
  getGitBranchesMapping(workspace: WorkspaceID, dbName: DBName): Promise<ListGitBranchesResponse>;
2799
2802
  addGitBranchesEntry(workspace: WorkspaceID, dbName: DBName, body: AddGitBranchesEntryRequestBody): Promise<AddGitBranchesEntryResponse>;
2800
2803
  removeGitBranchesEntry(workspace: WorkspaceID, dbName: DBName, gitBranch: string): Promise<void>;
2801
- resolveBranch(workspace: WorkspaceID, dbName: DBName, gitBranch: string): Promise<ResolveBranchResponse>;
2804
+ resolveBranch(workspace: WorkspaceID, dbName: DBName, gitBranch?: string, fallbackBranch?: string): Promise<ResolveBranchResponse>;
2802
2805
  }
2803
2806
  declare class BranchApi {
2804
2807
  private extraProps;
@@ -2867,25 +2870,24 @@ declare type SelectableColumn<O, RecursivePath extends any[] = []> = '*' | 'id'
2867
2870
  declare type SelectedPick<O extends XataRecord, Key extends SelectableColumn<O>[]> = XataRecord & UnionToIntersection<Values<{
2868
2871
  [K in Key[number]]: NestedValueAtColumn<O, K> & XataRecord;
2869
2872
  }>>;
2870
- declare type ValueAtColumn<O, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<RemoveNullable<O[K]> extends Record<string, any> ? V extends SelectableColumn<RemoveNullable<O[K]>> ? {
2871
- V: ValueAtColumn<RemoveNullable<O[K]>, V>;
2872
- } : never : O[K]> : never : never;
2873
+ declare type ValueAtColumn<O, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<NonNullable<O[K]> extends infer Item ? Item extends Record<string, any> ? V extends SelectableColumn<Item> ? {
2874
+ V: ValueAtColumn<Item, V>;
2875
+ } : never : O[K] : never> : never : never;
2873
2876
  declare type MAX_RECURSION = 5;
2874
2877
  declare type NestedColumns<O, RecursivePath extends any[]> = RecursivePath['length'] extends MAX_RECURSION ? never : If<IsObject<O>, Values<{
2875
- [K in DataProps<O>]: If<IsArray<RemoveNullable<O[K]>>, K, // If the property is an array, we stop recursion. We don't support object arrays yet
2876
- If<IsObject<RemoveNullable<O[K]>>, RemoveNullable<O[K]> extends XataRecord ? SelectableColumn<RemoveNullable<O[K]>, [...RecursivePath, O[K]]> extends infer Column ? Column extends string ? K | `${K}.${Column}` : never : never : `${K}.${StringKeys<RemoveNullable<O[K]>> | '*'}`, // This allows usage of objects that are not links
2877
- K>>;
2878
+ [K in DataProps<O>]: NonNullable<O[K]> extends infer Item ? If<IsArray<Item>, K, // If the property is an array, we stop recursion. We don't support object arrays yet
2879
+ If<IsObject<Item>, Item extends XataRecord ? SelectableColumn<Item, [...RecursivePath, Item]> extends infer Column ? Column extends string ? K | `${K}.${Column}` : never : never : Item extends Date ? K : `${K}.${StringKeys<Item> | '*'}`, // This allows usage of objects that are not links
2880
+ K>> : never;
2878
2881
  }>, never>;
2879
2882
  declare type DataProps<O> = Exclude<StringKeys<O>, StringKeys<XataRecord>>;
2880
2883
  declare type NestedValueAtColumn<O, Key extends SelectableColumn<O>> = Key extends `${infer N}.${infer M}` ? N extends DataProps<O> ? {
2881
- [K in N]: M extends SelectableColumn<RemoveNullable<O[K]>> ? RemoveNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], NestedValueAtColumn<RemoveNullable<O[K]>, M> & XataRecord> : ForwardNullable<O[K], NestedValueAtColumn<RemoveNullable<O[K]>, M>> : unknown;
2884
+ [K in N]: M extends SelectableColumn<NonNullable<O[K]>> ? NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M> & XataRecord> : ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M>> : unknown;
2882
2885
  } : unknown : Key extends DataProps<O> ? {
2883
- [K in Key]: RemoveNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], SelectedPick<RemoveNullable<O[K]>, ['*']>> : O[K];
2886
+ [K in Key]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], SelectedPick<NonNullable<O[K]>, ['*']>> : O[K];
2884
2887
  } : Key extends '*' ? {
2885
- [K in StringKeys<O>]: RemoveNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], Link<RemoveNullable<O[K]>>> : O[K];
2888
+ [K in StringKeys<O>]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], Link<NonNullable<O[K]>>> : O[K];
2886
2889
  } : unknown;
2887
- declare type RemoveNullable<T> = T extends null | undefined ? never : T;
2888
- declare type ForwardNullable<T, R> = T extends RemoveNullable<T> ? R : R | null;
2890
+ declare type ForwardNullable<T, R> = T extends NonNullable<T> ? R : R | null;
2889
2891
 
2890
2892
  /**
2891
2893
  * Represents an identifiable record from the database.
@@ -2950,9 +2952,9 @@ declare function isXataRecord(x: any): x is XataRecord & Record<string, unknown>
2950
2952
  declare type EditableData<O extends BaseData> = {
2951
2953
  [K in keyof O]: O[K] extends XataRecord ? {
2952
2954
  id: string;
2953
- } : NonNullable<O[K]> extends XataRecord ? {
2955
+ } | string : NonNullable<O[K]> extends XataRecord ? {
2954
2956
  id: string;
2955
- } | null | undefined : O[K];
2957
+ } | string | null | undefined : O[K];
2956
2958
  };
2957
2959
 
2958
2960
  /**
@@ -3083,7 +3085,7 @@ declare type QueryOptions<T extends XataRecord> = BaseOptions<T> & (CursorQueryO
3083
3085
  declare class Query<Record extends XataRecord, Result extends XataRecord = Record> implements Paginable<Record, Result> {
3084
3086
  #private;
3085
3087
  readonly meta: PaginationQueryMeta;
3086
- readonly records: Result[];
3088
+ readonly records: RecordArray<Result>;
3087
3089
  constructor(repository: Repository<Record> | null, table: string, data: Partial<QueryOptions<Record>>, rawParent?: Partial<QueryOptions<Record>>);
3088
3090
  getQueryOptions(): QueryOptions<Record>;
3089
3091
  key(): string;
@@ -3206,19 +3208,19 @@ declare class Query<Record extends XataRecord, Result extends XataRecord = Recor
3206
3208
  * Performs the query in the database and returns a set of results.
3207
3209
  * @returns An array of records from the database.
3208
3210
  */
3209
- getMany(): Promise<Result[]>;
3211
+ getMany(): Promise<RecordArray<Result>>;
3210
3212
  /**
3211
3213
  * Performs the query in the database and returns a set of results.
3212
3214
  * @param options Additional options to be used when performing the query.
3213
3215
  * @returns An array of records from the database.
3214
3216
  */
3215
- getMany(options: OmitBy<QueryOptions<Record>, 'columns'>): Promise<Result[]>;
3217
+ getMany(options: OmitBy<QueryOptions<Record>, 'columns'>): Promise<RecordArray<Result>>;
3216
3218
  /**
3217
3219
  * Performs the query in the database and returns a set of results.
3218
3220
  * @param options Additional options to be used when performing the query.
3219
3221
  * @returns An array of records from the database.
3220
3222
  */
3221
- getMany<Options extends RequiredBy<QueryOptions<Record>, 'columns'>>(options: Options): Promise<SelectedPick<Record, typeof options['columns']>[]>;
3223
+ getMany<Options extends RequiredBy<QueryOptions<Record>, 'columns'>>(options: Options): Promise<RecordArray<SelectedPick<Record, typeof options['columns']>>>;
3222
3224
  /**
3223
3225
  * Performs the query in the database and returns all the results.
3224
3226
  * Warning: If there are a large number of results, this method can have performance implications.
@@ -3304,7 +3306,7 @@ declare type PaginationQueryMeta = {
3304
3306
  };
3305
3307
  interface Paginable<Record extends XataRecord, Result extends XataRecord = Record> {
3306
3308
  meta: PaginationQueryMeta;
3307
- records: Result[];
3309
+ records: RecordArray<Result>;
3308
3310
  nextPage(size?: number, offset?: number): Promise<Page<Record, Result>>;
3309
3311
  previousPage(size?: number, offset?: number): Promise<Page<Record, Result>>;
3310
3312
  firstPage(size?: number, offset?: number): Promise<Page<Record, Result>>;
@@ -3324,7 +3326,7 @@ declare class Page<Record extends XataRecord, Result extends XataRecord = Record
3324
3326
  /**
3325
3327
  * The set of results for this page.
3326
3328
  */
3327
- readonly records: Result[];
3329
+ readonly records: RecordArray<Result>;
3328
3330
  constructor(query: Query<Record, Result>, meta: PaginationQueryMeta, records?: Result[]);
3329
3331
  /**
3330
3332
  * Retrieves the next page of results.
@@ -3373,10 +3375,42 @@ declare type OffsetNavigationOptions = {
3373
3375
  offset?: number;
3374
3376
  };
3375
3377
  declare const PAGINATION_MAX_SIZE = 200;
3376
- declare const PAGINATION_DEFAULT_SIZE = 200;
3378
+ declare const PAGINATION_DEFAULT_SIZE = 20;
3377
3379
  declare const PAGINATION_MAX_OFFSET = 800;
3378
3380
  declare const PAGINATION_DEFAULT_OFFSET = 0;
3379
3381
  declare function isCursorPaginationOptions(options: Record<string, unknown> | undefined | null): options is CursorNavigationOptions;
3382
+ declare class RecordArray<Result extends XataRecord> extends Array<Result> {
3383
+ #private;
3384
+ constructor(page: Paginable<any, Result>, overrideRecords?: Result[]);
3385
+ /**
3386
+ * Retrieve next page of records
3387
+ *
3388
+ * @returns A new array of objects
3389
+ */
3390
+ nextPage(size?: number, offset?: number): Promise<RecordArray<Result>>;
3391
+ /**
3392
+ * Retrieve previous page of records
3393
+ *
3394
+ * @returns A new array of objects
3395
+ */
3396
+ previousPage(size?: number, offset?: number): Promise<RecordArray<Result>>;
3397
+ /**
3398
+ * Retrieve first page of records
3399
+ *
3400
+ * @returns A new array of objects
3401
+ */
3402
+ firstPage(size?: number, offset?: number): Promise<RecordArray<Result>>;
3403
+ /**
3404
+ * Retrieve last page of records
3405
+ *
3406
+ * @returns A new array of objects
3407
+ */
3408
+ lastPage(size?: number, offset?: number): Promise<RecordArray<Result>>;
3409
+ /**
3410
+ * @returns Boolean indicating if there is a next page
3411
+ */
3412
+ hasNextPage(): boolean;
3413
+ }
3380
3414
 
3381
3415
  /**
3382
3416
  * Common interface for performing operations on a table.
@@ -3408,6 +3442,18 @@ declare abstract class Repository<Data extends BaseData, Record extends XataReco
3408
3442
  * @returns The persisted records for the given ids (if a record could not be found it is not returned).
3409
3443
  */
3410
3444
  abstract read(ids: string[]): Promise<Array<Readonly<SelectedPick<Record, ['*']>>>>;
3445
+ /**
3446
+ * Queries a single record from the table by the id in the object.
3447
+ * @param object Object containing the id of the record.
3448
+ * @returns The persisted record for the given id or null if the record could not be found.
3449
+ */
3450
+ abstract read(object: Identifiable): Promise<Readonly<SelectedPick<Record, ['*']> | null>>;
3451
+ /**
3452
+ * Queries multiple records from the table by the ids in the objects.
3453
+ * @param objects Array of objects containing the ids of the records.
3454
+ * @returns The persisted records for the given ids (if a record could not be found it is not returned).
3455
+ */
3456
+ abstract read(objects: Identifiable[]): Promise<Array<Readonly<SelectedPick<Record, ['*']>>>>;
3411
3457
  /**
3412
3458
  * Partially update a single record.
3413
3459
  * @param object An object with its id and the columns to be updated.
@@ -3499,6 +3545,8 @@ declare class RestRepository<Data extends BaseData, Record extends XataRecord =
3499
3545
  create(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
3500
3546
  read(recordId: string): Promise<SelectedPick<Record, ['*']> | null>;
3501
3547
  read(recordIds: string[]): Promise<Array<Readonly<SelectedPick<Record, ['*']>>>>;
3548
+ read(object: Identifiable): Promise<SelectedPick<Record, ['*']> | null>;
3549
+ read(objects: Identifiable[]): Promise<Array<Readonly<SelectedPick<Record, ['*']>>>>;
3502
3550
  update(object: Partial<EditableData<Data>> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
3503
3551
  update(recordId: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
3504
3552
  update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
@@ -3684,4 +3732,4 @@ declare class XataError extends Error {
3684
3732
  constructor(message: string, status: number);
3685
3733
  }
3686
3734
 
3687
- export { AcceptWorkspaceMemberInviteError, AcceptWorkspaceMemberInvitePathParams, AcceptWorkspaceMemberInviteVariables, AddGitBranchesEntryError, AddGitBranchesEntryPathParams, AddGitBranchesEntryRequestBody, AddGitBranchesEntryResponse, AddGitBranchesEntryVariables, AddTableColumnError, AddTableColumnPathParams, AddTableColumnVariables, BaseClient, BaseClientOptions, BaseData, BulkInsertTableRecordsError, BulkInsertTableRecordsPathParams, BulkInsertTableRecordsRequestBody, BulkInsertTableRecordsResponse, BulkInsertTableRecordsVariables, CacheImpl, CancelWorkspaceMemberInviteError, CancelWorkspaceMemberInvitePathParams, CancelWorkspaceMemberInviteVariables, ClientConstructor, CreateBranchError, CreateBranchPathParams, CreateBranchQueryParams, CreateBranchRequestBody, CreateBranchVariables, CreateDatabaseError, CreateDatabasePathParams, CreateDatabaseRequestBody, CreateDatabaseResponse, CreateDatabaseVariables, CreateTableError, CreateTablePathParams, CreateTableVariables, CreateUserAPIKeyError, CreateUserAPIKeyPathParams, CreateUserAPIKeyResponse, CreateUserAPIKeyVariables, CreateWorkspaceError, CreateWorkspaceVariables, CursorNavigationOptions, DeleteBranchError, DeleteBranchPathParams, DeleteBranchVariables, DeleteColumnError, DeleteColumnPathParams, DeleteColumnVariables, DeleteDatabaseError, DeleteDatabasePathParams, DeleteDatabaseVariables, DeleteRecordError, DeleteRecordPathParams, DeleteRecordVariables, DeleteTableError, DeleteTablePathParams, DeleteTableVariables, DeleteUserAPIKeyError, DeleteUserAPIKeyPathParams, DeleteUserAPIKeyVariables, DeleteUserError, DeleteUserVariables, DeleteWorkspaceError, DeleteWorkspacePathParams, DeleteWorkspaceVariables, EditableData, ExecuteBranchMigrationPlanError, ExecuteBranchMigrationPlanPathParams, ExecuteBranchMigrationPlanRequestBody, ExecuteBranchMigrationPlanVariables, FetchImpl, FetcherExtraProps, GetBranchDetailsError, GetBranchDetailsPathParams, GetBranchDetailsVariables, GetBranchListError, GetBranchListPathParams, GetBranchListVariables, GetBranchMetadataError, GetBranchMetadataPathParams, GetBranchMetadataVariables, GetBranchMigrationHistoryError, GetBranchMigrationHistoryPathParams, GetBranchMigrationHistoryRequestBody, GetBranchMigrationHistoryResponse, GetBranchMigrationHistoryVariables, GetBranchMigrationPlanError, GetBranchMigrationPlanPathParams, GetBranchMigrationPlanVariables, GetBranchStatsError, GetBranchStatsPathParams, GetBranchStatsResponse, GetBranchStatsVariables, GetColumnError, GetColumnPathParams, GetColumnVariables, GetDatabaseListError, GetDatabaseListPathParams, GetDatabaseListVariables, GetGitBranchesMappingError, GetGitBranchesMappingPathParams, GetGitBranchesMappingVariables, GetRecordError, GetRecordPathParams, GetRecordRequestBody, GetRecordVariables, GetTableColumnsError, GetTableColumnsPathParams, GetTableColumnsResponse, GetTableColumnsVariables, GetTableSchemaError, GetTableSchemaPathParams, GetTableSchemaResponse, GetTableSchemaVariables, GetUserAPIKeysError, GetUserAPIKeysResponse, GetUserAPIKeysVariables, GetUserError, GetUserVariables, GetWorkspaceError, GetWorkspaceMembersListError, GetWorkspaceMembersListPathParams, GetWorkspaceMembersListVariables, GetWorkspacePathParams, GetWorkspaceVariables, GetWorkspacesListError, GetWorkspacesListResponse, GetWorkspacesListVariables, Identifiable, InsertRecordError, InsertRecordPathParams, InsertRecordResponse, InsertRecordVariables, InsertRecordWithIDError, InsertRecordWithIDPathParams, InsertRecordWithIDQueryParams, InsertRecordWithIDVariables, InviteWorkspaceMemberError, InviteWorkspaceMemberPathParams, InviteWorkspaceMemberRequestBody, InviteWorkspaceMemberVariables, OffsetNavigationOptions, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Paginable, PaginationQueryMeta, Query, QueryTableError, QueryTablePathParams, QueryTableRequestBody, QueryTableVariables, RemoveGitBranchesEntryError, RemoveGitBranchesEntryPathParams, RemoveGitBranchesEntryQueryParams, RemoveGitBranchesEntryVariables, RemoveWorkspaceMemberError, RemoveWorkspaceMemberPathParams, RemoveWorkspaceMemberVariables, Repository, ResendWorkspaceMemberInviteError, ResendWorkspaceMemberInvitePathParams, ResendWorkspaceMemberInviteVariables, ResolveBranchError, ResolveBranchPathParams, ResolveBranchQueryParams, ResolveBranchResponse, ResolveBranchVariables, responses as Responses, RestRepository, SchemaDefinition, SchemaPlugin, SchemaPluginResult, schemas as Schemas, SearchBranchError, SearchBranchPathParams, SearchBranchRequestBody, SearchBranchVariables, SearchOptions, SearchPlugin, SearchPluginResult, SearchTableError, SearchTablePathParams, SearchTableRequestBody, SearchTableVariables, SelectableColumn, SelectedPick, SetTableSchemaError, SetTableSchemaPathParams, SetTableSchemaRequestBody, SetTableSchemaVariables, SimpleCache, SimpleCacheOptions, UpdateBranchMetadataError, UpdateBranchMetadataPathParams, UpdateBranchMetadataVariables, UpdateColumnError, UpdateColumnPathParams, UpdateColumnRequestBody, UpdateColumnVariables, UpdateRecordWithIDError, UpdateRecordWithIDPathParams, UpdateRecordWithIDQueryParams, UpdateRecordWithIDVariables, UpdateTableError, UpdateTablePathParams, UpdateTableRequestBody, UpdateTableVariables, UpdateUserError, UpdateUserVariables, UpdateWorkspaceError, UpdateWorkspaceMemberRoleError, UpdateWorkspaceMemberRolePathParams, UpdateWorkspaceMemberRoleRequestBody, UpdateWorkspaceMemberRoleVariables, UpdateWorkspacePathParams, UpdateWorkspaceVariables, UpsertRecordWithIDError, UpsertRecordWithIDPathParams, UpsertRecordWithIDQueryParams, UpsertRecordWithIDVariables, ValueAtColumn, XataApiClient, XataApiClientOptions, XataApiPlugin, XataError, XataPlugin, XataPluginOptions, XataRecord, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
3735
+ export { AcceptWorkspaceMemberInviteError, AcceptWorkspaceMemberInvitePathParams, AcceptWorkspaceMemberInviteVariables, AddGitBranchesEntryError, AddGitBranchesEntryPathParams, AddGitBranchesEntryRequestBody, AddGitBranchesEntryResponse, AddGitBranchesEntryVariables, AddTableColumnError, AddTableColumnPathParams, AddTableColumnVariables, BaseClient, BaseClientOptions, BaseData, BulkInsertTableRecordsError, BulkInsertTableRecordsPathParams, BulkInsertTableRecordsRequestBody, BulkInsertTableRecordsResponse, BulkInsertTableRecordsVariables, CacheImpl, CancelWorkspaceMemberInviteError, CancelWorkspaceMemberInvitePathParams, CancelWorkspaceMemberInviteVariables, ClientConstructor, CreateBranchError, CreateBranchPathParams, CreateBranchQueryParams, CreateBranchRequestBody, CreateBranchVariables, CreateDatabaseError, CreateDatabasePathParams, CreateDatabaseRequestBody, CreateDatabaseResponse, CreateDatabaseVariables, CreateTableError, CreateTablePathParams, CreateTableVariables, CreateUserAPIKeyError, CreateUserAPIKeyPathParams, CreateUserAPIKeyResponse, CreateUserAPIKeyVariables, CreateWorkspaceError, CreateWorkspaceVariables, CursorNavigationOptions, DeleteBranchError, DeleteBranchPathParams, DeleteBranchVariables, DeleteColumnError, DeleteColumnPathParams, DeleteColumnVariables, DeleteDatabaseError, DeleteDatabasePathParams, DeleteDatabaseVariables, DeleteRecordError, DeleteRecordPathParams, DeleteRecordVariables, DeleteTableError, DeleteTablePathParams, DeleteTableVariables, DeleteUserAPIKeyError, DeleteUserAPIKeyPathParams, DeleteUserAPIKeyVariables, DeleteUserError, DeleteUserVariables, DeleteWorkspaceError, DeleteWorkspacePathParams, DeleteWorkspaceVariables, EditableData, ExecuteBranchMigrationPlanError, ExecuteBranchMigrationPlanPathParams, ExecuteBranchMigrationPlanRequestBody, ExecuteBranchMigrationPlanVariables, FetchImpl, FetcherExtraProps, GetBranchDetailsError, GetBranchDetailsPathParams, GetBranchDetailsVariables, GetBranchListError, GetBranchListPathParams, GetBranchListVariables, GetBranchMetadataError, GetBranchMetadataPathParams, GetBranchMetadataVariables, GetBranchMigrationHistoryError, GetBranchMigrationHistoryPathParams, GetBranchMigrationHistoryRequestBody, GetBranchMigrationHistoryResponse, GetBranchMigrationHistoryVariables, GetBranchMigrationPlanError, GetBranchMigrationPlanPathParams, GetBranchMigrationPlanVariables, GetBranchStatsError, GetBranchStatsPathParams, GetBranchStatsResponse, GetBranchStatsVariables, GetColumnError, GetColumnPathParams, GetColumnVariables, GetDatabaseListError, GetDatabaseListPathParams, GetDatabaseListVariables, GetGitBranchesMappingError, GetGitBranchesMappingPathParams, GetGitBranchesMappingVariables, GetRecordError, GetRecordPathParams, GetRecordRequestBody, GetRecordVariables, GetTableColumnsError, GetTableColumnsPathParams, GetTableColumnsResponse, GetTableColumnsVariables, GetTableSchemaError, GetTableSchemaPathParams, GetTableSchemaResponse, GetTableSchemaVariables, GetUserAPIKeysError, GetUserAPIKeysResponse, GetUserAPIKeysVariables, GetUserError, GetUserVariables, GetWorkspaceError, GetWorkspaceMembersListError, GetWorkspaceMembersListPathParams, GetWorkspaceMembersListVariables, GetWorkspacePathParams, GetWorkspaceVariables, GetWorkspacesListError, GetWorkspacesListResponse, GetWorkspacesListVariables, Identifiable, InsertRecordError, InsertRecordPathParams, InsertRecordResponse, InsertRecordVariables, InsertRecordWithIDError, InsertRecordWithIDPathParams, InsertRecordWithIDQueryParams, InsertRecordWithIDVariables, InviteWorkspaceMemberError, InviteWorkspaceMemberPathParams, InviteWorkspaceMemberRequestBody, InviteWorkspaceMemberVariables, OffsetNavigationOptions, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Paginable, PaginationQueryMeta, Query, QueryTableError, QueryTablePathParams, QueryTableRequestBody, QueryTableVariables, RecordArray, RemoveGitBranchesEntryError, RemoveGitBranchesEntryPathParams, RemoveGitBranchesEntryQueryParams, RemoveGitBranchesEntryVariables, RemoveWorkspaceMemberError, RemoveWorkspaceMemberPathParams, RemoveWorkspaceMemberVariables, Repository, ResendWorkspaceMemberInviteError, ResendWorkspaceMemberInvitePathParams, ResendWorkspaceMemberInviteVariables, ResolveBranchError, ResolveBranchPathParams, ResolveBranchQueryParams, ResolveBranchResponse, ResolveBranchVariables, responses as Responses, RestRepository, SchemaDefinition, SchemaPlugin, SchemaPluginResult, schemas as Schemas, SearchBranchError, SearchBranchPathParams, SearchBranchRequestBody, SearchBranchVariables, SearchOptions, SearchPlugin, SearchPluginResult, SearchTableError, SearchTablePathParams, SearchTableRequestBody, SearchTableVariables, SelectableColumn, SelectedPick, SetTableSchemaError, SetTableSchemaPathParams, SetTableSchemaRequestBody, SetTableSchemaVariables, SimpleCache, SimpleCacheOptions, UpdateBranchMetadataError, UpdateBranchMetadataPathParams, UpdateBranchMetadataVariables, UpdateColumnError, UpdateColumnPathParams, UpdateColumnRequestBody, UpdateColumnVariables, UpdateRecordWithIDError, UpdateRecordWithIDPathParams, UpdateRecordWithIDQueryParams, UpdateRecordWithIDVariables, UpdateTableError, UpdateTablePathParams, UpdateTableRequestBody, UpdateTableVariables, UpdateUserError, UpdateUserVariables, UpdateWorkspaceError, UpdateWorkspaceMemberRoleError, UpdateWorkspaceMemberRolePathParams, UpdateWorkspaceMemberRoleRequestBody, UpdateWorkspaceMemberRoleVariables, UpdateWorkspacePathParams, UpdateWorkspaceVariables, UpsertRecordWithIDError, UpsertRecordWithIDPathParams, UpsertRecordWithIDQueryParams, UpsertRecordWithIDVariables, ValueAtColumn, XataApiClient, XataApiClientOptions, XataApiPlugin, XataError, XataPlugin, XataPluginOptions, XataRecord, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
package/dist/index.mjs CHANGED
@@ -17,7 +17,8 @@ function toBase64(value) {
17
17
  try {
18
18
  return btoa(value);
19
19
  } catch (err) {
20
- return Buffer.from(value).toString("base64");
20
+ const buf = Buffer;
21
+ return buf.from(value).toString("base64");
21
22
  }
22
23
  }
23
24
 
@@ -73,21 +74,28 @@ function getFetchImplementation(userFetch) {
73
74
  return fetchImpl;
74
75
  }
75
76
 
77
+ const VERSION = "0.13.2";
78
+
76
79
  class ErrorWithCause extends Error {
77
80
  constructor(message, options) {
78
81
  super(message, options);
79
82
  }
80
83
  }
81
84
  class FetcherError extends ErrorWithCause {
82
- constructor(status, data) {
85
+ constructor(status, data, requestId) {
83
86
  super(getMessage(data));
84
87
  this.status = status;
85
88
  this.errors = isBulkError(data) ? data.errors : void 0;
89
+ this.requestId = requestId;
86
90
  if (data instanceof Error) {
87
91
  this.stack = data.stack;
88
92
  this.cause = data.cause;
89
93
  }
90
94
  }
95
+ toString() {
96
+ const error = super.toString();
97
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
98
+ }
91
99
  }
92
100
  function isBulkError(error) {
93
101
  return isObject(error) && Array.isArray(error.errors);
@@ -110,7 +118,12 @@ function getMessage(data) {
110
118
  }
111
119
 
112
120
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
113
- const query = new URLSearchParams(queryParams).toString();
121
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
122
+ if (value === void 0 || value === null)
123
+ return acc;
124
+ return { ...acc, [key]: value };
125
+ }, {});
126
+ const query = new URLSearchParams(cleanQueryParams).toString();
114
127
  const queryString = query.length > 0 ? `?${query}` : "";
115
128
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
116
129
  };
@@ -150,6 +163,7 @@ async function fetch$1({
150
163
  body: body ? JSON.stringify(body) : void 0,
151
164
  headers: {
152
165
  "Content-Type": "application/json",
166
+ "User-Agent": `Xata client-ts/${VERSION}`,
153
167
  ...headers,
154
168
  ...hostHeader(fullUrl),
155
169
  Authorization: `Bearer ${apiKey}`
@@ -158,14 +172,15 @@ async function fetch$1({
158
172
  if (response.status === 204) {
159
173
  return {};
160
174
  }
175
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
161
176
  try {
162
177
  const jsonResponse = await response.json();
163
178
  if (response.ok) {
164
179
  return jsonResponse;
165
180
  }
166
- throw new FetcherError(response.status, jsonResponse);
181
+ throw new FetcherError(response.status, jsonResponse, requestId);
167
182
  } catch (error) {
168
- throw new FetcherError(response.status, error);
183
+ throw new FetcherError(response.status, error, requestId);
169
184
  }
170
185
  }
171
186
 
@@ -689,10 +704,10 @@ class DatabaseApi {
689
704
  ...this.extraProps
690
705
  });
691
706
  }
692
- resolveBranch(workspace, dbName, gitBranch) {
707
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
693
708
  return operationsByTag.database.resolveBranch({
694
709
  pathParams: { workspace, dbName },
695
- queryParams: { gitBranch },
710
+ queryParams: { gitBranch, fallbackBranch },
696
711
  ...this.extraProps
697
712
  });
698
713
  }
@@ -942,13 +957,13 @@ var __privateSet$5 = (obj, member, value, setter) => {
942
957
  setter ? setter.call(obj, value) : member.set(obj, value);
943
958
  return value;
944
959
  };
945
- var _query;
960
+ var _query, _page;
946
961
  class Page {
947
962
  constructor(query, meta, records = []) {
948
963
  __privateAdd$6(this, _query, void 0);
949
964
  __privateSet$5(this, _query, query);
950
965
  this.meta = meta;
951
- this.records = records;
966
+ this.records = new RecordArray(this, records);
952
967
  }
953
968
  async nextPage(size, offset) {
954
969
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -968,12 +983,40 @@ class Page {
968
983
  }
969
984
  _query = new WeakMap();
970
985
  const PAGINATION_MAX_SIZE = 200;
971
- const PAGINATION_DEFAULT_SIZE = 200;
986
+ const PAGINATION_DEFAULT_SIZE = 20;
972
987
  const PAGINATION_MAX_OFFSET = 800;
973
988
  const PAGINATION_DEFAULT_OFFSET = 0;
974
989
  function isCursorPaginationOptions(options) {
975
990
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
976
991
  }
992
+ const _RecordArray = class extends Array {
993
+ constructor(page, overrideRecords) {
994
+ super(...overrideRecords ?? page.records);
995
+ __privateAdd$6(this, _page, void 0);
996
+ __privateSet$5(this, _page, page);
997
+ }
998
+ async nextPage(size, offset) {
999
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1000
+ return new _RecordArray(newPage);
1001
+ }
1002
+ async previousPage(size, offset) {
1003
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1004
+ return new _RecordArray(newPage);
1005
+ }
1006
+ async firstPage(size, offset) {
1007
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1008
+ return new _RecordArray(newPage);
1009
+ }
1010
+ async lastPage(size, offset) {
1011
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1012
+ return new _RecordArray(newPage);
1013
+ }
1014
+ hasNextPage() {
1015
+ return __privateGet$6(this, _page).meta.page.more;
1016
+ }
1017
+ };
1018
+ let RecordArray = _RecordArray;
1019
+ _page = new WeakMap();
977
1020
 
978
1021
  var __accessCheck$5 = (obj, member, msg) => {
979
1022
  if (!member.has(obj))
@@ -1000,7 +1043,7 @@ const _Query = class {
1000
1043
  __privateAdd$5(this, _repository, void 0);
1001
1044
  __privateAdd$5(this, _data, { filter: {} });
1002
1045
  this.meta = { page: { cursor: "start", more: true } };
1003
- this.records = [];
1046
+ this.records = new RecordArray(this, []);
1004
1047
  __privateSet$4(this, _table$1, table);
1005
1048
  if (repository) {
1006
1049
  __privateSet$4(this, _repository, repository);
@@ -1089,8 +1132,11 @@ const _Query = class {
1089
1132
  }
1090
1133
  }
1091
1134
  async getMany(options = {}) {
1092
- const { records } = await this.getPaginated(options);
1093
- return records;
1135
+ const page = await this.getPaginated(options);
1136
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1137
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1138
+ }
1139
+ return page.records;
1094
1140
  }
1095
1141
  async getAll(options = {}) {
1096
1142
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1219,9 +1265,29 @@ class RestRepository extends Query {
1219
1265
  if (Array.isArray(a)) {
1220
1266
  if (a.length === 0)
1221
1267
  return [];
1222
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1223
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1224
- return records;
1268
+ const [itemsWithoutIds, itemsWithIds, order] = a.reduce(([accWithoutIds, accWithIds, accOrder], item) => {
1269
+ const condition = isString(item.id);
1270
+ accOrder.push(condition);
1271
+ if (condition) {
1272
+ accWithIds.push(item);
1273
+ } else {
1274
+ accWithoutIds.push(item);
1275
+ }
1276
+ return [accWithoutIds, accWithIds, accOrder];
1277
+ }, [[], [], []]);
1278
+ const recordsWithoutId = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, itemsWithoutIds);
1279
+ await Promise.all(recordsWithoutId.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1280
+ if (itemsWithIds.length > 100) {
1281
+ console.warn("Bulk create operation with id is not optimized in the Xata API yet, this request might be slow");
1282
+ }
1283
+ const recordsWithId = await Promise.all(itemsWithIds.map((object) => this.create(object)));
1284
+ return order.map((condition) => {
1285
+ if (condition) {
1286
+ return recordsWithId.shift();
1287
+ } else {
1288
+ return recordsWithoutId.shift();
1289
+ }
1290
+ }).filter((record) => !!record);
1225
1291
  }
1226
1292
  if (isString(a) && isObject(b)) {
1227
1293
  if (a === "")
@@ -1248,16 +1314,18 @@ class RestRepository extends Query {
1248
1314
  if (Array.isArray(a)) {
1249
1315
  if (a.length === 0)
1250
1316
  return [];
1251
- return this.getAll({ filter: { id: { $any: a } } });
1317
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1318
+ return this.getAll({ filter: { id: { $any: ids } } });
1252
1319
  }
1253
- if (isString(a)) {
1254
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, a);
1320
+ const id = isString(a) ? a : a.id;
1321
+ if (isString(id)) {
1322
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1255
1323
  if (cacheRecord)
1256
1324
  return cacheRecord;
1257
1325
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1258
1326
  try {
1259
1327
  const response = await getRecord({
1260
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: a },
1328
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1261
1329
  ...fetchProps
1262
1330
  });
1263
1331
  const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
@@ -1429,7 +1497,7 @@ bulkInsertTableRecords_fn = async function(objects) {
1429
1497
  body: { records },
1430
1498
  ...fetchProps
1431
1499
  });
1432
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1500
+ const finalObjects = await this.read(response.recordIDs);
1433
1501
  if (finalObjects.length !== objects.length) {
1434
1502
  throw new Error("The server failed to save some records");
1435
1503
  }
@@ -1833,10 +1901,7 @@ async function getDatabaseBranch(branch, options) {
1833
1901
  apiUrl: databaseURL,
1834
1902
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1835
1903
  workspacesApiUrl: `${protocol}//${host}`,
1836
- pathParams: {
1837
- dbBranchName,
1838
- workspace
1839
- }
1904
+ pathParams: { dbBranchName, workspace }
1840
1905
  });
1841
1906
  } catch (err) {
1842
1907
  if (isObject(err) && err.status === 404)
@@ -1973,5 +2038,5 @@ class XataError extends Error {
1973
2038
  }
1974
2039
  }
1975
2040
 
1976
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2041
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
1977
2042
  //# sourceMappingURL=index.mjs.map