Skip to content

Commit

Permalink
[bindgen] Refactor namespaces (#5376)
Browse files Browse the repository at this point in the history
* WIP on improving the type-tests

* Removed a stray comment start

* Fixed missing @ts-expect-error in bundle.d.ts

* Propagate local app name and version

* Renamed AuthClients to Auth

This is to avoid breaking the API just yet.

* Refactored namespaces

* Fixed namespaced Types export

* Fixed InsertionModel types

* Fixed a type-o

* Ensuring named exports are correct

* Updated unit tests to import from ../index

* Fixed some exported types

* Merged Dictionary interface and class

* Reverting removal of `Realm.Credentials`

* Reordered and exporting MutableSubscriptionSet

* Updated AppConfiguration#baseUrl docs

* Adding links to ClientResetError deprecation

* Exporting types pr review

* Adding "CanonicalObjectSchema" to Realm namespace

* Export CanonicalPropertySchema

And added a link to it on the CanonicalObjectSchemaProperty.
  • Loading branch information
kraenhansen committed Mar 1, 2023
1 parent b8fcca5 commit bb2c968
Show file tree
Hide file tree
Showing 36 changed files with 781 additions and 244 deletions.
2 changes: 1 addition & 1 deletion install-tests/react-native/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ yargs(hideBin(process.argv))
const env = getEnv({ newArchitecture, engine });

console.log(`Initializing react-native@${reactNativeVersion} template into '${appPath}'`);
console.log("New achitecture is", newArchitecture ? "enabled" : "disabled");
console.log("New architecture is", newArchitecture ? "enabled" : "disabled");

if (fs.existsSync(appPath) && force) {
console.log("Deleting existing app directory! (because --force)");
Expand Down
1 change: 0 additions & 1 deletion packages/realm/src/Collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import { CallbackAdder, IllegalConstructorError, Listeners, assert, binding } fr
* objects which matched the query when the enumeration is begun, even if some of them are
* deleted or modified to be excluded by the filter during the enumeration.
*
* @memberof Realm
* @since 0.11.0
*/
export abstract class Collection<
Expand Down
28 changes: 15 additions & 13 deletions packages/realm/src/Configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,12 @@ import {
validateSyncConfiguration,
} from "./internal";

// export type Configuration = ConfigurationWithSync | ConfigurationWithoutSync;
export type Configuration = BaseConfiguration;
/**
* A function which can be called to migrate a Realm from one version of the schema to another.
*/
export type MigrationCallback = (oldRealm: Realm, newRealm: Realm) => void;

type BaseConfiguration = {
export type BaseConfiguration = {
path?: string;
schema?: (RealmObjectConstructor<any> | ObjectSchema)[];
schemaVersion?: number;
Expand All @@ -50,13 +48,15 @@ type BaseConfiguration = {
onMigration?: MigrationCallback;
};

// type ConfigurationWithSync = BaseConfiguration & {
// sync: Record<string, unknown>;
// };
export type ConfigurationWithSync = BaseConfiguration & {
sync: SyncConfiguration;
};

// type ConfigurationWithoutSync = BaseConfiguration & {
// sync?: never;
// };
export type ConfigurationWithoutSync = BaseConfiguration & {
sync?: never;
};

export type Configuration = ConfigurationWithSync | ConfigurationWithoutSync;

// export type PartitionValue = string | number | null | ObjectId | UUID;

Expand Down Expand Up @@ -123,7 +123,7 @@ type BaseConfiguration = {
// *
// * Example:
// * ```
// * const config: Realm.Configuration = {
// * const config: Configuration = {
// * sync: {
// * user,
// * flexible: true,
Expand All @@ -146,9 +146,9 @@ type BaseConfiguration = {
// /**
// * Callback called with the {@link Realm} instance to allow you to setup the
// * initial set of subscriptions by calling `realm.subscriptions.update`.
// * See {@link Realm.App.Sync.SubscriptionSet.update} for more information.
// * See {@link SubscriptionSet.update} for more information.
// */
// update: (subs: Realm.App.Sync.MutableSubscriptionSet, realm: Realm) => void;
// update: (subs: MutableSubscriptionSet, realm: Realm) => void;
// /**
// * If `true`, the {@link update} callback will be rerun every time the Realm is
// * opened (e.g. every time a user opens your app), otherwise (by default) it
Expand Down Expand Up @@ -264,7 +264,9 @@ export function validateConfiguration(config: unknown): asserts config is Config
if (encryptionKey !== undefined) {
assert(
encryptionKey instanceof ArrayBuffer || ArrayBuffer.isView(encryptionKey) || encryptionKey instanceof Int8Array,
`Expected 'encryptionKey' on realm configuration to be an ArrayBuffer, ArrayBufferView (Uint8Array), or Int8Array, got ${TypeAssertionError.deriveType(encryptionKey)}.`,
`Expected 'encryptionKey' on realm configuration to be an ArrayBuffer, ArrayBufferView (Uint8Array), or Int8Array, got ${TypeAssertionError.deriveType(
encryptionKey,
)}.`,
);
}
}
25 changes: 10 additions & 15 deletions packages/realm/src/Dictionary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ const REALM = Symbol("Dictionary#realm");
const INTERNAL = Symbol("Dictionary#internal");
const HELPERS = Symbol("Dictionary#helpers");

type DictionaryChangeSet = {
export type DictionaryChangeSet = {
deletions: string[];
modifications: string[];
insertions: string[];
};
type DictionaryChangeCallback = (dictionary: Dictionary, changes: DictionaryChangeSet) => void;
export type DictionaryChangeCallback = (dictionary: Dictionary, changes: DictionaryChangeSet) => void;

const DEFAULT_PROPERTY_DESCRIPTOR: PropertyDescriptor = { configurable: true, enumerable: true };
const PROXY_HANDLER: ProxyHandler<Dictionary> = {
Expand Down Expand Up @@ -101,8 +101,6 @@ const PROXY_HANDLER: ProxyHandler<Dictionary> = {
*
* Dictionaries behave mostly like a JavaScript object i.e., as a key/value pair
* where the key is a string.
*
* @memberof Realm
*/
export class Dictionary<T = unknown> extends Collection<string, T, [string, T], [string, T], DictionaryChangeCallback> {
/**
Expand Down Expand Up @@ -184,14 +182,14 @@ export class Dictionary<T = unknown> extends Collection<string, T, [string, T],
*/
private [HELPERS]!: TypeHelpers;

// @ts-expect-error We're exposing methods in the end-users namespace of keys
/** @ts-expect-error We're exposing methods in the end-users namespace of keys */
[key: string]: T;

*[Symbol.iterator]() {
yield* this.entries();
}

// @ts-expect-error We're exposing methods in the end-users namespace of keys
/** @ts-expect-error We're exposing methods in the end-users namespace of keys */
*keys() {
const snapshot = this[INTERNAL].keys.snapshot();
const size = snapshot.size();
Expand All @@ -202,7 +200,7 @@ export class Dictionary<T = unknown> extends Collection<string, T, [string, T],
}
}

// @ts-expect-error We're exposing methods in the end-users namespace of keys
/** @ts-expect-error We're exposing methods in the end-users namespace of keys */
*values() {
const { fromBinding } = this[HELPERS];
const snapshot = this[INTERNAL].values.snapshot();
Expand All @@ -213,7 +211,7 @@ export class Dictionary<T = unknown> extends Collection<string, T, [string, T],
}
}

// @ts-expect-error We're exposing methods in the end-users namespace of keys
/** @ts-expect-error We're exposing methods in the end-users namespace of keys */
*entries() {
const { fromBinding } = this[HELPERS];
const keys = this[INTERNAL].keys.snapshot();
Expand All @@ -227,7 +225,7 @@ export class Dictionary<T = unknown> extends Collection<string, T, [string, T],
}
}

// @ts-expect-error We're exposing methods in the end-users namespace of keys
/** @ts-expect-error We're exposing methods in the end-users namespace of keys */
isValid() {
return this[INTERNAL].isValid;
}
Expand All @@ -238,8 +236,7 @@ export class Dictionary<T = unknown> extends Collection<string, T, [string, T],
* @throws {@link AssertionError} If not inside a write transaction or if value violates type constraints
* @returns The dictionary
* @since 10.6.0
*/
// @ts-expect-error We're exposing methods in the end-users namespace of keys
* @ts-expect-error We're exposing methods in the end-users namespace of keys */
set(elements: { [key: string]: T }): this;
/**
* Adds an element with the specified key and value to the dictionary or updates value if key exists.
Expand Down Expand Up @@ -276,8 +273,7 @@ export class Dictionary<T = unknown> extends Collection<string, T, [string, T],
* @throws {@link AssertionError} If not inside a write transaction.
* @returns The dictionary
* @since 10.6.0
*/
// @ts-expect-error We're exposing methods in the end-users namespace of keys
* @ts-expect-error We're exposing methods in the end-users namespace of keys */
remove(key: string | string[]): this {
assert.inTransaction(this[REALM]);
const internal = this[INTERNAL];
Expand All @@ -293,8 +289,7 @@ export class Dictionary<T = unknown> extends Collection<string, T, [string, T],
* Use circular JSON serialization libraries such as [@ungap/structured-clone](https://www.npmjs.com/package/@ungap/structured-clone)
* and [flatted](https://www.npmjs.com/package/flatted) to stringify Realm entities that have circular structures.
* @returns A plain object.
**/
// @ts-expect-error We're exposing methods in the users value namespace
* @ts-expect-error We're exposing methods in the end-users namespace of keys */
toJSON(_?: string, cache?: unknown): DefaultObject;
/** @internal */
toJSON(_?: string, cache = new JSONCacheMap()): DefaultObject {
Expand Down
19 changes: 12 additions & 7 deletions packages/realm/src/InsertionModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@

import { Collection, Dictionary, List, RealmObject } from "./internal";

type AnyCollection = Collection<any, any, any, any, any>;
type AnyDictionary = Dictionary<any>;
type AnyList = List<any>;
type AnyRealmObject = RealmObject<any>;

type ExtractPropertyNamesOfType<T, PropType> = {
[K in keyof T]: T[K] extends PropType ? K : never;
}[keyof T];
Expand All @@ -26,7 +31,7 @@ type ExtractPropertyNamesOfType<T, PropType> = {
* Exchanges properties defined as {@link List<T>} with an optional {@link Array<T | RealmInsertionModel<T>>}.
*/
type RealmListsRemappedModelPart<T> = {
[K in ExtractPropertyNamesOfType<T, List>]?: T[K] extends List<infer GT>
[K in ExtractPropertyNamesOfType<T, AnyList>]?: T[K] extends List<infer GT>
? Array<GT | RealmInsertionModel<GT>>
: never;
};
Expand All @@ -35,26 +40,26 @@ type RealmListsRemappedModelPart<T> = {
* Exchanges properties defined as {@link Dictionary<T>} with an optional key to mixed value object.
*/
type RealmDictionaryRemappedModelPart<T> = {
[K in ExtractPropertyNamesOfType<T, Dictionary>]?: T[K] extends Dictionary<infer ValueType>
[K in ExtractPropertyNamesOfType<T, AnyDictionary>]?: T[K] extends Dictionary<infer ValueType>
? { [key: string]: ValueType }
: never;
};

/** Omits all properties of a model which are not defined by the schema */
type OmittedRealmTypes<T> = Omit<
T,
| keyof RealmObject
| keyof AnyRealmObject
/* eslint-disable-next-line @typescript-eslint/ban-types */
| ExtractPropertyNamesOfType<T, Function> // TODO: Figure out the use-case for this
| ExtractPropertyNamesOfType<T, Collection>
| ExtractPropertyNamesOfType<T, Dictionary>
| ExtractPropertyNamesOfType<T, AnyCollection>
| ExtractPropertyNamesOfType<T, AnyDictionary>
>;

/** Remaps realm types to "simpler" types (arrays and objects) */
type RemappedRealmTypes<T> = RealmListsRemappedModelPart<T> & RealmDictionaryRemappedModelPart<T>;

/**
* Joins T stripped of all keys which value extends Realm.Collection and all inherited from Realm.Object,
* with only the keys which value extends Realm.List, remapped as Arrays.
* Joins T stripped of all keys which value extends {@link Collection} and all inherited from {@link RealmObject},
* with only the keys which value extends {@link List}, remapped as Arrays.
*/
export type RealmInsertionModel<T> = OmittedRealmTypes<T> & RemappedRealmTypes<T>;
6 changes: 2 additions & 4 deletions packages/realm/src/List.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import {
IllegalConstructorError,
ObjectSchema,
OrderedCollection,
OrderedCollectionHelpers,
Realm,
Expand All @@ -33,9 +34,6 @@ type PartiallyWriteableArray<T> = Pick<Array<T>, "pop" | "push" | "shift" | "uns
* Lists mostly behave like normal Javascript Arrays, except for that they can
* only store values of a single type (indicated by the `type` and `optional`
* properties of the List), and can only be modified inside a {@link Realm.write | write} transaction.
*
* @extends Realm.Collection
* @memberof Realm
*/
export class List<T = unknown> extends OrderedCollection<T> implements PartiallyWriteableArray<T> {
/**
Expand Down Expand Up @@ -125,7 +123,7 @@ export class List<T = unknown> extends OrderedCollection<T> implements Partially
*
* @param items Values to add to the list.
* @throws {TypeError} If a `value` is not of a type which can be stored in
* the list, or if an object being added to the list does not match the {@link Realm.ObjectSchema} for the list.
* the list, or if an object being added to the list does not match the {@link ObjectSchema} for the list.
*
* @throws {@link AssertionError} If not inside a write transaction.
* @returns A number equal to the new length of
Expand Down
12 changes: 5 additions & 7 deletions packages/realm/src/Object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@ import {
ClassHelpers,
Constructor,
DefaultObject,
Dictionary,
JSONCacheMap,
ObjectChangeCallback,
ObjectListeners,
OrderedCollection,
Realm,
RealmInsertionModel,
RealmObjectConstructor,
Results,
TypeAssertionError,
assert,
binding,
flags,
Expand Down Expand Up @@ -294,11 +295,7 @@ export class RealmObject<T = DefaultObject> {
if (typeof value == "function") {
continue;
}
if (
value instanceof Realm.Object ||
value instanceof Realm.OrderedCollection ||
value instanceof Realm.Dictionary
) {
if (value instanceof RealmObject || value instanceof OrderedCollection || value instanceof Dictionary) {
// recursively trigger `toJSON` for Realm instances with the same cache.
result[key] = value.toJSON(key, cache);
} else {
Expand Down Expand Up @@ -352,7 +349,7 @@ export class RealmObject<T = DefaultObject> {
assert(collectionHelpers, "collection helpers");
const tableView = this[INTERNAL].getBacklinkView(tableRef, columnKey);
const results = binding.Results.fromTableView(this[REALM].internal, tableView);
return new Realm.Results(this[REALM], results, collectionHelpers);
return new Results(this[REALM], results, collectionHelpers);
}

/**
Expand Down Expand Up @@ -480,4 +477,5 @@ export class RealmObject<T = DefaultObject> {
}

// We like to refer to this as "Realm.Object"
// TODO: Determine if we want to revisit this if we're going away from a namespaced API
Object.defineProperty(RealmObject, "name", { value: "Realm.Object" });
Loading

0 comments on commit bb2c968

Please sign in to comment.