Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[All packages] Internal API changes & Cleanups #149

Merged
merged 5 commits into from
Nov 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ aliases: [
# CircleCI workspace.
&dependency-paths [
"node_modules",
"packages/commons/node_modules",
"packages/provider/node_modules",
"packages/react-native/node_modules",
"packages/types/node_modules",
Expand All @@ -16,6 +17,7 @@ aliases: [
# List of build output paths that should be persisted to the
# CircleCI workspace.
&build-output-paths [
"packages/commons/dist",
"packages/provider/dist",
"packages/react-native/dist",
"packages/types/dist",
Expand Down
63 changes: 39 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,9 @@

See the [developer documentation](https://docs.magic.link) to learn how you can master the Magic SDK in a matter of minutes.

## 📦 Package Ecosystem

| Package directory | Package Name | Changelog | Description |
| ----------------- | ------------ | ------- | ----------- |
| [`/web`](./packages/web) | [`magic-sdk`](https://www.npmjs.com/package/magic-sdk) | [CHANGELOG](./packages/web/CHANGELOG.md) | Web/browser entry-point for Magic SDK. |
| [`/react-native`](./packages/react-native) | [`@magic-sdk/react-native`](https://www.npmjs.com/package/@magic-sdk/react-native) | [CHANGELOG](./packages/react-native/CHANGELOG.md) | React Native entry-point for Magic SDK. |
| [`/types`](./packages/types) | [`@magic-sdk/types`](https://www.npmjs.com/package/@magic-sdk/types) | [CHANGELOG](./packages/types/CHANGELOG.md) | Core typings shared between JavaScript entry-points of Magic SDK. |
| [`/provider`](./packages/provider) | [`@magic-sdk/provider`](https://www.npmjs.com/package/@magic-sdk/provider) | [CHANGELOG](./packages/provider/CHANGELOG.md) | Core business logic shared between JavaScript entry-points of Magic SDK. |
## ⚡️ Quick Start

## 🔗 Installation
### Installation

Integrating your app with Magic will require our client-side NPM package:

Expand All @@ -42,7 +35,43 @@ Alternatively, you can load via CDN with by adding a script tag to your app’s
<script src="https://cdn.jsdelivr.net/npm/magic-sdk/dist/magic.js"></script>
```

## 🔗 Testing
### Usage

Sign up or log in to the [developer dashboard](https://dashboard.magic.link) to receive API keys that will allow your application to interact with Magic's authentication APIs.

Then, you can start authenticating users with _just one method!_ Magic works across all modern desktop, mobile Chrome, Safari and Firefox browsers.

```ts
import { Magic } from 'magic-sdk';

const magic = new Magic('YOUR_API_KEY');

await magic.auth.loginWithMagicLink({ email: 'your.email@example.com' });
```

## 📦 Package Ecosystem

### Entry points

These are packages _you_ can install to enable Magic JS SDK functionality for your client-side application.

| Package directory | Package Name | Changelog | Description |
| ----------------- | ------------ | --------- | ----------- |
| [`/web`](./packages/web) | [`magic-sdk`](https://www.npmjs.com/package/magic-sdk) | [CHANGELOG](./packages/web/CHANGELOG.md) | Web/browser entry-point for Magic SDK. |
| [`/react-native`](./packages/react-native) | [`@magic-sdk/react-native`](https://www.npmjs.com/package/@magic-sdk/react-native) | [CHANGELOG](./packages/react-native/CHANGELOG.md) | React Native entry-point for Magic SDK. |

### Internals

These are packages Magic JS SDK uses internally to work seamlessly across platforms.

| Package directory | Package Name | Changelog | Description |
| ----------------- | ------------ | --------- | ----------- |
| [`/types`](./packages/types) | [`@magic-sdk/types`](https://www.npmjs.com/package/@magic-sdk/types) | [CHANGELOG](./packages/types/CHANGELOG.md) | Core typings shared between JavaScript entry-points of Magic SDK. |
| [`/provider`](./packages/provider) | [`@magic-sdk/provider`](https://www.npmjs.com/package/@magic-sdk/provider) | [CHANGELOG](./packages/provider/CHANGELOG.md) | Core business logic shared between JavaScript entry-points of Magic SDK. |
| [`/commons`](./packages/commons) | [`@magic-sdk/commons`](https://www.npmjs.com/package/@magic-sdk/commons) | [CHANGELOG](./packages/commons/CHANGELOG.md) | Exposes a listing of common public APIs from `@magic-sdk/provider` and `@magic-sdk/typings` to the platform-specific entry points. |

## 🚦 Testing

Run tests for all packages
```bash
yarn test
Expand All @@ -58,17 +87,3 @@ Test specific files
```bash
yarn test /test/**/constructor.spec.ts
```

## ⚡️ Quick Start

Sign up or log in to the [developer dashboard](https://dashboard.magic.link) to receive API keys that will allow your application to interact with Magic's authentication APIs.

Then, you can start authenticating users with _just one method!_ Magic works across all modern desktop, mobile Chrome, Safari and Firefox browsers.

```ts
import { Magic } from 'magic-sdk';

const magic = new Magic('YOUR_API_KEY');

await magic.auth.loginWithMagicLink({ email: 'your.email@example.com' });
```
2 changes: 2 additions & 0 deletions packages/commons/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/node_modules
/dist
7 changes: 7 additions & 0 deletions packages/commons/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
extends: ['../../.eslintrc'],
parserOptions: {
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname,
},
}
2 changes: 2 additions & 0 deletions packages/commons/.lintstagedrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
'*.{ts,tsx}':
- eslint --fix
1 change: 1 addition & 0 deletions packages/commons/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../../.prettierrc.js');
Empty file added packages/commons/CHANGELOG.md
Empty file.
21 changes: 21 additions & 0 deletions packages/commons/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Magic Labs, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions packages/commons/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# ✨ Magic JavaScript SDK Commons

[![<MagicLabs>](https://circleci.com/gh/magiclabs/magic-js.svg?style=shield)](https://circleci.com/gh/magiclabs/magic-js)

> Exposes a listing of common public APIs from `@magic-sdk/provider` and `@magic-sdk/typings` to the platform-specific entry points (`magic-sdk` and `@magic-sdk/react-native`)

<p align="center">
<a href="https://github.com/magiclabs/magic-js/blob/master/packages/public/LICENSE">License</a> ·
<a href="https://github.com/magiclabs/magic-js/blob/master/CONTRIBUTING.md">Contributing Guide</a>
</p>

## 📖 Documentation

See the [developer documentation](https://docs.magic.link) to learn how you can master the Magic SDK in a matter of minutes.

## Looking to Get Started With Magic?

This package is an internal dependency of the Magic JavaScript SDK ecosystem. If you're looking to get started with Magic's passwordless authentication for web or React native, check out one of these:

- Web: [`magic-sdk`](https://github.com/magiclabs/magic-js/tree/master/packages/web)
- React Native: [`@magic-sdk/react-native`](https://github.com/magiclabs/magic-js/tree/master/packages/react-native)
24 changes: 24 additions & 0 deletions packages/commons/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "@magic-sdk/commons",
"version": "0.1.0",
"description": "Exposes a listing of common public APIs from the Magic JS SDK ecosystem.",
"author": "Magic Labs <team@magic.link> (https://magic.link/)",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/magiclabs/magic-js"
},
"homepage": "https://magic.link",
"files": [
"dist/*"
],
"target": "web",
"main": "dist/commonjs/index.js",
"module": "dist/module/index.js",
"types": "dist/commonjs/index.d.ts",
"peerDependencies": {
"@magic-sdk/provider": "^3.0.1",
"@magic-sdk/types": "^2.0.1"
},
"gitHead": "1ef062ea699d48d5e9a9375a93b7c147632b05ca"
}
16 changes: 16 additions & 0 deletions packages/commons/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Only re-export modules & types that are intended
// for the public API from this file.

export {
Extension,
MagicSDKError as SDKError,
MagicExtensionError as ExtensionError,
MagicExtensionWarning as ExtensionWarning,
MagicRPCError as RPCError,
MagicSDKWarning as SDKWarning,
MagicSDKAdditionalConfiguration,
PromiEvent,
isPromiEvent,
} from '@magic-sdk/provider';

export * from '@magic-sdk/types';
17 changes: 17 additions & 0 deletions packages/commons/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.settings.json",

"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist/commonjs"
},

"include": [
"./src/**/*.ts",
],

"references": [
{ "path": "../types/tsconfig.json" },
{ "path": "../provider/tsconfig.json" },
]
}
18 changes: 18 additions & 0 deletions packages/commons/tsconfig.module.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": "../../tsconfig.settings.json",

"compilerOptions": {
"module": "es6",
"rootDir": "./src",
"outDir": "./dist/module"
},

"include": [
"./src/**/*.ts",
],

"references": [
{ "path": "../types/tsconfig.module.json" },
{ "path": "../provider/tsconfig.module.json" },
]
}
1 change: 1 addition & 0 deletions packages/provider/src/core/json-rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function standardizeJsonRpcRequestPayload(payload: Partial<JsonRpcRequest
markPayloadAsPreprocessed(payload);
}

/* eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion */
return payload as JsonRpcRequestPayload;
}

Expand Down
10 changes: 4 additions & 6 deletions packages/provider/src/core/payload-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,11 @@ export abstract class PayloadTransport {
/**
* Create an instance of `PayloadTransport`
*
* @param overlay - The `IframeController` context to which the event will be
* posted.
* @param endpoint - The URL for the relevant iframe context.
* @param encodedQueryParams - The unique, encoded query parameters for the
* @param parameters - The unique, encoded query parameters for the
* relevant iframe context.
*/
constructor(protected readonly endpoint: string, protected readonly encodedQueryParams: string) {
constructor(protected readonly endpoint: string, protected readonly parameters: string) {
this.init();
}

Expand Down Expand Up @@ -100,7 +98,7 @@ export abstract class PayloadTransport {
const batchData: JsonRpcResponse[] = [];
const batchIds = Array.isArray(payload) ? payload.map((p) => p.id) : [];

await overlay.postMessage({ msgType: `${msgType}-${this.encodedQueryParams}`, payload });
await overlay.postMessage({ msgType: `${msgType}-${this.parameters}`, payload });

/** Collect successful RPC responses and resolve. */
const acknowledgeResponse = (removeEventListener: RemoveEventListenerFunction) => (event: MagicMessageEvent) => {
Expand Down Expand Up @@ -146,7 +144,7 @@ export abstract class PayloadTransport {
// `initMessageListener`.
/* istanbul ignore next */
const listener = (event: MagicMessageEvent) => {
if (event.data.msgType === `${msgType}-${this.encodedQueryParams}`) boundHandler(event);
if (event.data.msgType === `${msgType}-${this.parameters}`) boundHandler(event);
};

this.messageHandlers.add(listener);
Expand Down
29 changes: 13 additions & 16 deletions packages/provider/src/core/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ export class SDKBase {
private static readonly __transports__: Map<string, PayloadTransport> = new Map();
private static readonly __overlays__: Map<string, ViewController> = new Map();

public readonly endpoint: string;
public readonly encodedQueryParams: string;
protected readonly endpoint: string;
protected readonly parameters: string;

/**
* Contains methods for starting a Magic SDK authentication flow.
Expand Down Expand Up @@ -137,16 +137,16 @@ export class SDKBase {
const { defaultEndpoint, version } = SDKEnvironment;
this.endpoint = createURL(options?.endpoint ?? defaultEndpoint).origin;

// Assign API Modules
// Prepare built-in modules
this.auth = new AuthModule(this);
this.user = new UserModule(this);
this.rpcProvider = new RPCProviderModule(this);

// Prepare Extensions
// Prepare extensions
const extConfig: any = prepareExtensions.call(this, options);

// Build query params for the current `ViewController`
this.encodedQueryParams = encodeJSON<QueryParameters>({
// Encode parameters as base64-JSON
this.parameters = encodeJSON<QueryParameters>({
API_KEY: this.apiKey,
DOMAIN_ORIGIN: window.location ? window.location.origin : '',
ETH_NETWORK: options?.network,
Expand All @@ -163,26 +163,23 @@ export class SDKBase {
* `MagicSDK` instance.
*/
protected get transport(): PayloadTransport {
if (!SDKBase.__transports__.has(this.encodedQueryParams)) {
SDKBase.__transports__.set(
this.encodedQueryParams,
new SDKEnvironment.PayloadTransport(this.endpoint, this.encodedQueryParams),
);
if (!SDKBase.__transports__.has(this.parameters)) {
SDKBase.__transports__.set(this.parameters, new SDKEnvironment.PayloadTransport(this.endpoint, this.parameters));
}

return SDKBase.__transports__.get(this.encodedQueryParams)!;
return SDKBase.__transports__.get(this.parameters)!;
}

/**
* Represents the view controller associated with this `MagicSDK` instance.
*/
protected get overlay(): ViewController {
if (!SDKBase.__overlays__.has(this.encodedQueryParams)) {
const controller = new SDKEnvironment.ViewController(this.transport, this.endpoint, this.encodedQueryParams);
SDKBase.__overlays__.set(this.encodedQueryParams, controller);
if (!SDKBase.__overlays__.has(this.parameters)) {
const controller = new SDKEnvironment.ViewController(this.transport);
SDKBase.__overlays__.set(this.parameters, controller);
}

return SDKBase.__overlays__.get(this.encodedQueryParams)!;
return SDKBase.__overlays__.get(this.parameters)!;
}

/**
Expand Down
17 changes: 12 additions & 5 deletions packages/provider/src/core/view-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,21 @@ import { PayloadTransport } from './payload-transport';

export abstract class ViewController<Transport extends PayloadTransport = PayloadTransport> {
public ready: Promise<void>;
protected readonly endpoint: string;
protected readonly parameters: string;

constructor(
protected readonly transport: Transport,
protected readonly endpoint: string,
protected readonly encodedQueryParams: string,
) {
constructor(protected readonly transport: Transport) {
// Get the `endpoint` and `parameters` value
// from the underlying `transport` instance.
this.endpoint = (transport as any).endpoint;
this.parameters = (transport as any).parameters;

// Create a promise that resolves when
// the view is ready for messages.
this.ready = this.waitForReady();

if (this.init) this.init();

this.listen();
}

Expand Down
3 changes: 0 additions & 3 deletions packages/provider/src/util/base64-json.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { QueryParameters } from '@magic-sdk/types';
import { createDeprecationWarning } from '../core/sdk-exceptions';

/**
* Given a JSON-serializable object, encode as a Base64 string.
*/
Expand Down
14 changes: 7 additions & 7 deletions packages/provider/test/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ export const MAGIC_RELAYER_FULL_URL = 'https://auth.magic.link';
export const TEST_API_KEY = 'pk_test_123';
export const LIVE_API_KEY = 'pk_live_123';
export const ENCODED_QUERY_PARAMS = 'testqueryparams';
export const MSG_TYPES = (encodedQueryParams = ENCODED_QUERY_PARAMS) => ({
MAGIC_HANDLE_RESPONSE: `MAGIC_HANDLE_RESPONSE-${encodedQueryParams}`,
MAGIC_OVERLAY_READY: `MAGIC_OVERLAY_READY-${encodedQueryParams}`,
MAGIC_SHOW_OVERLAY: `MAGIC_SHOW_OVERLAY-${encodedQueryParams}`,
MAGIC_HIDE_OVERLAY: `MAGIC_HIDE_OVERLAY-${encodedQueryParams}`,
MAGIC_HANDLE_REQUEST: `MAGIC_HANDLE_REQUEST-${encodedQueryParams}`,
MAGIC_HANDLE_EVENT: `MAGIC_HANDLE_EVENT-${encodedQueryParams}`,
export const MSG_TYPES = (parameters = ENCODED_QUERY_PARAMS) => ({
MAGIC_HANDLE_RESPONSE: `MAGIC_HANDLE_RESPONSE-${parameters}`,
MAGIC_OVERLAY_READY: `MAGIC_OVERLAY_READY-${parameters}`,
MAGIC_SHOW_OVERLAY: `MAGIC_SHOW_OVERLAY-${parameters}`,
MAGIC_HIDE_OVERLAY: `MAGIC_HIDE_OVERLAY-${parameters}`,
MAGIC_HANDLE_REQUEST: `MAGIC_HANDLE_REQUEST-${parameters}`,
MAGIC_HANDLE_EVENT: `MAGIC_HANDLE_EVENT-${parameters}`,
});
Loading