npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@beaconsmind/ionic-sdk

v0.3.0

Published

Beaconsmind SDK for Ionic

Downloads

7

Readme

@beaconsmind/ionic-sdk

Beaconsmind SDK for Ionic.

Prerequisites

As a Beaconsmind client, a contained environment is provided for Beaconsmind services being hosted and maintained by Beaconsmind.

The hostname of the provided environment is required to properly access Beaconsmind API and to use Beaconsmind SDK

example: https://adidas.bms.beaconsmind.com

Please contact Beaconsmind support for the required information about acquiring a valid environment and hostname.

1. Installing

npm install @beaconsmind/ionic-sdk
npx cap sync

Make sure your iOS Deployment Target is 11.0 or above.

Make sure your Android minSdkVersion is 23 or above.

2. Permissions

Beaconsmind SDK requires bluetooth and location permission (whenInUse or always) to detect nearby beacon devices and notification permission to send offers. Consider using a package of choice to request those permissions. Make sure to follow the setup required for native iOS & Android.

3. Initialize the SDK

This will initialize the SDK and try to retrieve the logged-in user. Call this method as soon as your app starts, so the sdk can track all touchpoints and beacon events correctly.

import { Beaconsmind } from '@beaconsmind/ionic-sdk';

const initializeResponse = await Beaconsmind.initialize({
  hostname: 'https://test-develop-suite.azurewebsites.net/',
  appVersion: '0.0.1',
  platformOptions: {
    android: {
      usePassiveScanning: true,
      notification: {
        androidNotificationBadgeName: 'ic_beacons',
        androidNotificationChannelName: 'beaconsmind',
        androidNotificationTitle: 'Beaconsmind sdk demo',
        androidNotificationText: 'Listening to beacons',
      },
    },
  },
});

console.log(initializeResponse);

See:

4. Authentication

When using Beaconsmind authentication

This approach implies that the customer data is kept in Beaconsmind backend. Use UserManager.login method to perform customer authentication.

To login existing user.

const loginResponse = await Beaconsmind.login({
  username: usernameValue,
  password: passwordValue,
});

console.log(loginResponse);

See:

To register a new user.

const signUpResponse = await Beaconsmind.instance.signup({
    username: usernameValue,
    firstName: firstNameValue,
    lastName: lastnameValue,
    password: passwordValue,
    confirmPassword: confirmPasswordValue,
  });

console.log(signUpResponse);

See:

When using own authentication mechanism

This approach implies that the customer data is kept in clients backend. The authentication is done by the client app before the Beaconsmind API is used. Whenever customer is authenticated, use Beaconsmind.importAccount method to send basic customer data to Beaconsmind. The customer data is updated only the first time the method is called. The client app can track if the customer was imported before and omit personal data from following importAccount calls.

const importAccountResponse = await Beaconsmind.importAccount({
  id: '3287e422-961a-4d47-8eaa-a58e0bd536a1',
  email: '[email protected]',
  firstName: 'John',
  lastName: 'Doe',
  language: 'en',
  gender: 'male',
  // UNIX timestamp represented in seconds.
  birthDateSeconds: 831589200, 
});

console.log(importAccountResponse);

See:

Log out

In order to log out the current account and stop listening for beacons, call the Beaconsmind.logout() method.

See:

6. Notifications

The SDK uses APNS for iOS, and Firebase for Android. You can use the @capacitor/push-notifications package in order to configure it.

Setting device token

import { Beaconsmind } from '@beaconsmind/ionic-sdk';
import { PushNotifications } from '@capacitor/push-notifications';

PushNotifications.addListener('registration', async token => {
  alert('Registration token: ' + token.value);

  const registerDeviceTokenResponse = await Beaconsmind.registerDeviceToken({
    deviceToken: token.value,
  });

  console.log(registerDeviceTokenResponse);
});

See:

Supporting multiple push notification providers

Issue

On Android, if there is more than one package used to receive push notifications, for example: capacitor-moengage-core & @capacitor/push-notifications, then only one package will be notified about a push notification.

Explanation

Each package used to receive push notifications has it’s on AndroidManifest.xml file (manifest) where it declares a service that should receive and handle the FCM messages — here is an example from the @capacitor/push-notifications package.

When app is built, the app’s manifest is merged with each manifest from packages that it depends on. As a result, the final manifest will contain multiple services declared to receive FCM messages, but the system will deliver push notification only to one of them, the one that is declared earlier.

If there is a service declaration at the app’s manifest, then it will take a precedence over service declarations from packages’ manifest.

Solution

In order to deliver push notifications to services declared by each package, a proxy service declared at the app’s manifest needs to be introduced. It will be responsible for intercepting push notifications and forwarding them to other services coming from used packages.

Implementation

  1. Add FirebaseMessagingServiceProxy.kt file to your Android app project.
  2. In the FirebaseMessagingServiceProxy file, update messagingServices list with push notification services that you want to notify. Make sure to add necessary imports at the top of the file in order to access them.
  3. Register the FirebaseMessgingServiceProxy in the app’s manifest.

7. Offers

Beacons ranging is used to pick up offers. In respect to offers, when users receive pushes about a new offer, read an offer and consume an offer, API calls need to be sent to recognize user activity.

Getting offers

Interacting with offers

8. Beacons

Interacting with beacons

Beacons feature uses BLE transmitters which can be picked up by devices. In Beaconsmind, BLE transmitters are used to present offers based on a physical location of a device.

Every beacon is defined by it's UUID and major and minor numbers. A list of beacons is persisted and maintained on Beaconsmind environment for each client.

In order to start monitoring nearby beacon devices, call Beaconsmind.startListeningBeacons(). Make sure that the bluetooth & location permissions have been granted. To stop the monitoring process, call Beaconsmind.stopListeningBeacons(). In order to obtain a list of beacon devices that are within range, call Beaconsmind.getBeaconContactsSummary().

See:

Read more about beacons

Deployment

Log in into the npm package registry by running

npm login

In the root directory, run:

npx release-it

For the wizard questions, answer in the following way:

  • Publish @beaconsmind/ionic-sdk to npm? Yes
  • Commit? Yes
  • Tag (x.y.z)? Yes
  • Push? Yes

API

setMinLogLevel(...)

setMinLogLevel({ minLogLevel }: { minLogLevel: LogLevel; }) => Promise<Response>

Sets the minimum log level.

| Param | Type | | --------- | --------------------------------------------------------------- | | __0 | { minLogLevel: LogLevel; } |

Returns: Promise<Response>


initialize(...)

initialize(options: InitializeOptions) => Promise<Response>

Initializes the SDK.

Call this method as soon as your app starts, so the sdk can track all touchpoints and beacon events correctly.

| Param | Type | | ------------- | --------------------------------------------------------------- | | options | InitializeOptions |

Returns: Promise<Response>


initializeDevelop(...)

initializeDevelop(options: InitializeOptions) => Promise<Response>

For development purposes only. Alternative initialization method.

Kickstart sdk testing and integration by a single method call. Invokes [initialize] and sets the sdk in development mode.

When initialized with this method the sdk requests permissions on it own by.

  • Your app must use activity which implements [ActivityResultCaller].

| Param | Type | | ------------- | --------------------------------------------------------------- | | options | InitializeOptions |

Returns: Promise<Response>


login(...)

login({ username, password }: { username: string; password: string; }) => Promise<Response>

Performs login and immediately starts listening for beacons

| Param | Type | | --------- | ---------------------------------------------------- | | __0 | { username: string; password: string; } |

Returns: Promise<Response>


signUp(...)

signUp(options: SignUpOptions) => Promise<UserIdResponse>

Creates a new account login and immediately starts listening for beacons.

| Param | Type | | ------------- | ------------------------------------------------------- | | options | SignUpOptions |

Returns: Promise<UserIdResponse>


importAccount(...)

importAccount(options: ImportAccountOptions) => Promise<UserIdResponse>

When the customer is using 3rd party authentication and not relying on Beaconsmind to keep the customer's private data, this endpoint is used to import the customer into Beaconsmind and to obtain a token with which the app can send tracking data to us. The token does NOT provide access to any personal customer info. If personal data is present in the request, it will only be updated the first time the endpoint is invoked for that customer. Once the authentication is done by the app, the username is sent to Beaconsmind using /api/accounts/import to receive a JWT for access to Beaconsmind backend. In this case, Beaconsmind will not allow any personal data to be accessed and it’s the apps responsibility to only send personal data the first time /api/accounts/import is used. When using import, editing profile is disabled.

| Param | Type | | ------------- | --------------------------------------------------------------------- | | options | ImportAccountOptions |

Returns: Promise<UserIdResponse>


logout()

logout() => Promise<Response>

Logs out the current account and stops listening for beacons.

Returns: Promise<Response>


getOAuthContext()

getOAuthContext() => Promise<UserIdResponse>

Returns the currently logged in user id.

Returns: Promise<UserIdResponse>


getProfile()

getProfile() => Promise<ProfileResponse>

Returns the currently logged in user profile data.

Returns: Promise<ProfileResponse>


updateProfile(...)

updateProfile(options: any) => Promise<ProfileResponse>

Updates the currently logged in user profile data.

| Param | Type | | ------------- | ---------------- | | options | any |

Returns: Promise<ProfileResponse>


registerDeviceToken(...)

registerDeviceToken({ deviceToken }: { deviceToken: string; }) => Promise<Response>

Register the device token in Beaconsmind servers in order receive offers push notifications.

| Param | Type | | --------- | ------------------------------------- | | __0 | { deviceToken: string; } |

Returns: Promise<Response>


loadOffers()

loadOffers() => Promise<OffersResponse>

Loads the list of offers for the current user.

Returns: Promise<OffersResponse>


loadOffer(...)

loadOffer({ offerId }: { offerId: number; }) => Promise<Offer>

Loads the offer details for the given offer id.

| Param | Type | | --------- | --------------------------------- | | __0 | { offerId: number; } |

Returns: Promise<Offer>


markOfferAsReceived(...)

markOfferAsReceived({ offerId }: { offerId: number; }) => Promise<Response>

Marks the offer as received.

Call this when an offer is received via push notification.

| Param | Type | | --------- | --------------------------------- | | __0 | { offerId: number; } |

Returns: Promise<Response>


markOfferAsRead(...)

markOfferAsRead({ offerId }: { offerId: number; }) => Promise<Response>

Marks the offer as read.

Call this when the user opens the offer.

| Param | Type | | --------- | --------------------------------- | | __0 | { offerId: number; } |

Returns: Promise<Response>


markOfferAsRedeemed(...)

markOfferAsRedeemed({ offerId }: { offerId: number; }) => Promise<Response>

Marks the offer as redeemed.

Call this when the user redeems the offer.

| Param | Type | | --------- | --------------------------------- | | __0 | { offerId: number; } |

Returns: Promise<Response>


startListeningBeacons()

startListeningBeacons() => Promise<Response>

Starts listening for beacons devices. It requires the following permissions to work:

  • location (whenInUse/always)
  • bluetooth

Returns: Promise<Response>


stopListeningBeacons()

stopListeningBeacons() => Promise<Response>

Stops listening for beacons devices.

Returns: Promise<Response>


updateHostname(...)

updateHostname({ hostname }: { hostname: string; }) => Promise<Response>

Updates the hostname that the SDK will use to connect to the Beaconsmind servers.

| Param | Type | | --------- | ---------------------------------- | | __0 | { hostname: string; } |

Returns: Promise<Response>


getBeaconContactsSummary()

getBeaconContactsSummary() => Promise<BeaconContactSummaryResponse>

Get a list of all the beacons that are currently in range.

Returns: Promise<BeaconContactSummaryResponse>


Interfaces

InitializeOptions

| Prop | Type | | --------------------- | ------------------------------------------------------------------------------- | | appVersion | string | | hostname | string | | platformOptions | InitializePlatformOptions |

InitializePlatformOptions

| Prop | Type | | ------------- | ----------------------------------------------------------------------------- | | android | InitializeAndroidOptions |

InitializeAndroidOptions

| Prop | Type | Description | | ------------------------ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | notification | AndroidNotificationOptions | null | Options that describe the content of the native Android notification that is displayed to user when a foreground service responsible for scanning. The notification is displayed when [usePassiveScanning] is set to false. | | usePassiveScanning | boolean | The SDK supports two types of BLE scanning: - active scanning, - passive scanning. When scanning actively, the Beaconsmind SDK will start a foreground service and show a pinned notification described by [notificationOptions]. By default, the SDK uses passive scanning, i.e. [usePassiveScanning] is set to true. |

AndroidNotificationOptions

| Prop | Type | Description | | ------------------------------------ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | androidNotificationBadgeName | string | Name of the native icon resource. Default value: "ic_beacons". Reference: https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setSmallIcon(int) | | androidNotificationTitle | string | Title of the notification (first row). Default value: "Beaconsmind". Reference: https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setContentTitle(java.lang.CharSequence) | | androidNotificationText | string | Body of the notification (second row). Default value: "Listening for Beacons". Reference: https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setContentText(java.lang.CharSequence) | | androidNotificationChannelName | string | The user visible name of the channel. Default value: "beaconsmind". Reference: https://developer.android.com/reference/android/app/NotificationChannel#NotificationChannel(java.lang.String,%20java.lang.CharSequence,%20int) |

SignUpOptions

| Prop | Type | | ---------------------- | ------------------- | | username | string | | firstName | string | | lastName | string | | password | string | | confirmPassword | string | | language | string | | gender | string | | favoriteStoreID | number | | birthDateSeconds | number | | countryCode | string |

ImportAccountOptions

| Prop | Type | | ---------------------- | ------------------- | | id | string | | email | string | | firstName | string | | lastName | string | | language | string | | gender | string | | birthDateSeconds | number |

ProfileResponse

| Prop | Type | | ------------------------------ | --------------------------------------------- | | id | string | | userName | string | | claims | string[] | | roles | string[] | | gender | string | null | | firstName | string | | lastName | string | | fullName | string | | street | string | null | | houseNumber | string | null | | zipCode | string | null | | city | string | null | | country | string | null | | landlinePhone | string | null | | phoneNumber | string | null | | url | string | null | | disablePushNotifications | boolean | | newsLetterSubscription | boolean | | joinDate | Date | | birthDate | Date | null | | clubId | string | null | | favoriteStore | string | null | | favoriteStoreId | number | null |

Date

Enables basic storage and retrieval of dates and times.

| Method | Signature | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | | toString | () => string | Returns a string representation of a date. The format of the string depends on the locale. | | toDateString | () => string | Returns a date as a string value. | | toTimeString | () => string | Returns a time as a string value. | | toLocaleString | () => string | Returns a value as a string value appropriate to the host environment's current locale. | | toLocaleDateString | () => string | Returns a date as a string value appropriate to the host environment's current locale. | | toLocaleTimeString | () => string | Returns a time as a string value appropriate to the host environment's current locale. | | valueOf | () => number | Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. | | getTime | () => number | Gets the time value in milliseconds. | | getFullYear | () => number | Gets the year, using local time. | | getUTCFullYear | () => number | Gets the year using Universal Coordinated Time (UTC). | | getMonth | () => number | Gets the month, using local time. | | getUTCMonth | () => number | Gets the month of a Date object using Universal Coordinated Time (UTC). | | getDate | () => number | Gets the day-of-the-month, using local time. | | getUTCDate | () => number | Gets the day-of-the-month, using Universal Coordinated Time (UTC). | | getDay | () => number | Gets the day of the week, using local time. | | getUTCDay | () => number | Gets the day of the week using Universal Coordinated Time (UTC). | | getHours | () => number | Gets the hours in a date, using local time. | | getUTCHours | () => number | Gets the hours value in a Date object using Universal Coordinated Time (UTC). | | getMinutes | () => number | Gets the minutes of a Date object, using local time. | | getUTCMinutes | () => number | Gets the minutes of a Date object using Universal Coordinated Time (UTC). | | getSeconds | () => number | Gets the seconds of a Date object, using local time. | | getUTCSeconds | () => number | Gets the seconds of a Date object using Universal Coordinated Time (UTC). | | getMilliseconds | () => number | Gets the milliseconds of a Date, using local time. | | getUTCMilliseconds | () => number | Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). | | getTimezoneOffset | () => number | Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). | | setTime | (time: number) => number | Sets the date and time value in the Date object. | | setMilliseconds | (ms: number) => number | Sets the milliseconds value in the Date object using local time. | | setUTCMilliseconds | (ms: number) => number | Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). | | setSeconds | (sec: number, ms?: number | undefined) => number | Sets the seconds value in the Date object using local time. | | setUTCSeconds | (sec: number, ms?: number | undefined) => number | Sets the seconds value in the Date object using Universal Coordinated Time (UTC). | | setMinutes | (min: number, sec?: number | undefined, ms?: number | undefined) => number | Sets the minutes value in the Date object using local time. | | setUTCMinutes | (min: number, sec?: number | undefined, ms?: number | undefined) => number | Sets the minutes value in the Date object using Universal Coordinated Time (UTC). | | setHours | (hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => number | Sets the hour value in the Date object using local time. | | setUTCHours | (hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => number | Sets the hours value in the Date object using Universal Coordinated Time (UTC). | | setDate | (date: number) => number | Sets the numeric day-of-the-month value of the Date object using local time. | | setUTCDate | (date: number) => number | Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). | | setMonth | (month: number, date?: number | undefined) => number | Sets the month value in the Date object using local time. | | setUTCMonth | (month: number, date?: number | undefined) => number | Sets the month value in the Date object using Universal Coordinated Time (UTC). | | setFullYear | (year: number, month?: number | undefined, date?: number | undefined) => number | Sets the year of the Date object using local time. | | setUTCFullYear | (year: number, month?: number | undefined, date?: number | undefined) => number | Sets the year value in the Date object using Universal Coordinated Time (UTC). | | toUTCString | () => string | Returns a date converted to a string using Universal Coordinated Time (UTC). | | toISOString | () => string | Returns a date as a string value in ISO format. | | toJSON | (key?: any) => string | Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. |

OffersResponse

| Prop | Type | | ------------ | -------------------- | | offers | Offer[] |

Offer

| Prop | Type | | ------------------ | ----------------------------------------------------- | | offerId | number | | title | string | | text | string | | imageUrl | string | | thumbnailUrl | string | | validity | string | | isRedeemed | boolean | | isRedeemable | boolean | | isVoucher | boolean | | tileAmount | number | | callToAction | { title: string; link: string; } | null |

BeaconContactSummaryResponse

| Prop | Type | | ------------- | ----------------------------------- | | beacons | BeaconContactSummary[] |

BeaconContactSummary

A class that holds information about the beacon device.

It consists of the beacon unique identifier ([uuid], [minor], [major]), the beacon's name ([name]) and the name of the [store] that it is located in.

Additionally, it contains data related to its signal strength and the number of times it was contacted.

| Prop | Type | Description | | ------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | uuid | string | Beacon's uuid. | | major | string | Beacon's major. | | minor | string | Beacon's minor. | | name | string | Beacon's name. | | store | string | The name of the store that the beacon is located in. | | currentRSSI | number | null | Beacon's current signal strength in dB. Null if the beacon has not been contacted yet. RSSI is an abbreviation from Received Signal Strength Indicator. See: https://en.wikipedia.org/wiki/Received_signal_strength_indication | | averageRSSI | number | null | Beacon's average signal strength in dB (based on the last contacts). Null if the beacon has not been contacted yet. | | lastContactTimestamp | number | null | Last beacon contact timestamp represented as unix timestamp in milliseconds. Null when the beacon has not been contacted yet. | | contactFrequencyPerMinute | number | Contacts frequency per minute. | | contactsCount | number | Indicates how many times the beacon was contacted. | | isInRange | boolean | Returns if the beacon is within range. |

Type Aliases

Response

{ result: boolean }

UserIdResponse

{ userId: string } | null

Enums

LogLevel

| Members | Value | Description | | ------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------- | | debug | 'debug' | Any developer-level debug info, repeating events, e.g.: - monitoring/location callbacks, - networking success results. | | info | 'info' | Bigger events/steps in the SDK lifecycle, e.g.: - starting/stopping services, - initializing SDK, - one-time events. | | warning | 'warning' | Allowed, but not-optimal, inconsistent state, e.g.: - trying to start monitoring without permissions. | | error | 'error' | Not allowed state (any error). | | silent | 'silent' | No logging at all. |