├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .travis.yml ├── LICENSE ├── README.md ├── file-upload-worker-android.js ├── kinvey-nativescript-sdk.android.js ├── kinvey-nativescript-sdk.android.js.map ├── kinvey-nativescript-sdk.ios.js ├── kinvey-nativescript-sdk.ios.js.map ├── kinvey.d.ts ├── lib ├── before-checkForChanges.js ├── before-preview-sync.js ├── postinstall.js └── preuninstall.js ├── package.json ├── platforms ├── android │ ├── AndroidManifest.default.xml │ ├── AndroidManifest.xml │ ├── AndroidManifest.xml.default │ ├── AndroidManifest.xml.mic │ └── include.gradle └── ios │ ├── Info.default.plist │ ├── Info.plist.mic │ ├── Podfile │ └── app.entitlements ├── push.android.js ├── push.android.js.map ├── push.d.ts ├── push.ios.js └── push.ios.js.map /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | #### Steps to Reproduce 2 | 3 | 4 | #### Expected Result 5 | 6 | 7 | #### Actual Result 8 | 9 | 10 | #### Sample Code that demonstrates the issue 11 | 12 | 13 | #### Version of Kinvey NativeScript SDK 14 | 15 | 16 | #### Kinvey AppKey 17 | 18 | 19 | #### NodeJS version 20 | 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | #### Description 2 | 3 | 4 | #### Changes 5 | 6 | 7 | #### Tests 8 | 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '9' 4 | script: echo "No tests to run" 5 | jobs: 6 | include: 7 | - name: deploy stable 8 | if: tag =~ ^((?!-\w).)*$ 9 | deploy: 10 | provider: npm 11 | email: thomas.conner@me.com 12 | api_key: 13 | secure: jR52EFbQNmCDcU6sn5tUMrGS5/7Zie1W8Oefu0np0BMtm8O6SvHwz8moA6FRlV7QthwfIrPs8bje0jL5KkvNwbuYiTSeLRUdlg+s/0f3+prmpv6SAQAhrj9Z5h/eIhFUIZCJ/V1y5U4yIGklm4YggZIEqPN7Ez/t0fV0/zrXGoYyvDLFWQYvbahqfFuvhUhxklUHW31+64SW1pitHx2Y+meL+OClDRQ0+HNCh+CNrCMCuHS9zT+1Oed4Grj1fvrqhbyD9nXwZQguvSjvrGR0hi2yMVLvtblARGy8bfcFscH+D6koDlPlSDK7LAGgB0euFxawN4ML0++8NpRpDqueNjy19ZaobCPskabXIzmQuTFW0T92z+EHauU8xBboTWpwApOCaJF5yJWU2OgOiu6Rb87g5ysYYkTMlc0HMyBvJ4/qLdYxAfZ3DiJOrPujJuSMeDsDHqojioLtDrZmvZAvsSt89oj/qOxqedVJA6fuCXmOwfN9LAkF9UitIskjdMR/Vi+HziGcWR+spmnZStBQKGklvk/tYEjyviVqFZd9M0jQdnxt11QvHyHePTHymnl0FERh4DmEMzChnHnqEEvK04qHRUkrKefDoW7WyScFyyVkPdIVzXeTG6vWyDXHUa19DA+IQ3BWtKSf6HG2pzKN9bvqIrRhgnj5hqIPIqUpP2g= 14 | on: 15 | branch: master 16 | tags: true 17 | - name: deploy beta 18 | if: tag =~ ^v?([0-9])*\.[0-9]*\.[0-9]*-\w+$ 19 | deploy: 20 | provider: npm 21 | tag: beta 22 | email: thomas.conner@me.com 23 | api_key: 24 | secure: jR52EFbQNmCDcU6sn5tUMrGS5/7Zie1W8Oefu0np0BMtm8O6SvHwz8moA6FRlV7QthwfIrPs8bje0jL5KkvNwbuYiTSeLRUdlg+s/0f3+prmpv6SAQAhrj9Z5h/eIhFUIZCJ/V1y5U4yIGklm4YggZIEqPN7Ez/t0fV0/zrXGoYyvDLFWQYvbahqfFuvhUhxklUHW31+64SW1pitHx2Y+meL+OClDRQ0+HNCh+CNrCMCuHS9zT+1Oed4Grj1fvrqhbyD9nXwZQguvSjvrGR0hi2yMVLvtblARGy8bfcFscH+D6koDlPlSDK7LAGgB0euFxawN4ML0++8NpRpDqueNjy19ZaobCPskabXIzmQuTFW0T92z+EHauU8xBboTWpwApOCaJF5yJWU2OgOiu6Rb87g5ysYYkTMlc0HMyBvJ4/qLdYxAfZ3DiJOrPujJuSMeDsDHqojioLtDrZmvZAvsSt89oj/qOxqedVJA6fuCXmOwfN9LAkF9UitIskjdMR/Vi+HziGcWR+spmnZStBQKGklvk/tYEjyviVqFZd9M0jQdnxt11QvHyHePTHymnl0FERh4DmEMzChnHnqEEvK04qHRUkrKefDoW7WyScFyyVkPdIVzXeTG6vWyDXHUa19DA+IQ3BWtKSf6HG2pzKN9bvqIrRhgnj5hqIPIqUpP2g= 25 | on: 26 | branch: master 27 | tags: true 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### **IMPORTANT: The Kinvey NativeScript SDK repository has now moved to: https://github.com/Kinvey/js-sdk/tree/master/packages/nativescript-sdk. Please go to this repository to submit issues and pull requests.** 2 | 3 | 4 | 5 | # Overview 6 | 7 | [Kinvey](http://www.kinvey.com) (pronounced Kin-vey, like convey) makes it ridiculously easy for developers to setup, use and operate a cloud backend for their mobile apps. They don't have to worry about connecting to various cloud services, setting up servers for their backend, or maintaining and scaling them. 8 | 9 | ## Getting Started 10 | 11 | Install and save the Kinvey NativeScript SDK: 12 | 13 | ```javascript 14 | npm install --save kinvey-nativescript-sdk 15 | ``` 16 | 17 | Import the Kinvey NativeScript SDK: 18 | 19 | ```javascript 20 | const Kinvey = require('kinvey-nativescript-sdk'); 21 | ``` 22 | 23 | ## Mobile OS Compatibility 24 | 25 | The Kinvey NativeScript SDK supports the following Mobile OS versions: 26 | 27 | - iOS: 10.0+ 28 | - Android: 2.3.3+ 29 | 30 | ## Documentation 31 | 32 | For more detailed documentation, see [Kinvey DevCenter](https://devcenter.kinvey.com/nativescript). 33 | 34 | ## License 35 | 36 | See [LICENSE](LICENSE) for details. 37 | -------------------------------------------------------------------------------- /file-upload-worker-android.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | require("globals"); // necessary to bootstrap tns modules on the new thread 4 | var file_system_1 = require("tns-core-modules/file-system"); 5 | global.onmessage = function (msg) { 6 | var response = upload(msg.data); 7 | global.postMessage({ 8 | statusCode: response.code(), 9 | headers: mapHeaders(response.headers()), 10 | data: response.body().string() 11 | }); 12 | }; 13 | function upload(workerOptions) { 14 | var url = workerOptions.url, filePath = workerOptions.filePath, metadata = workerOptions.metadata, options = workerOptions.options; 15 | var byteArray = file_system_1.File.fromPath(filePath).readSync(); 16 | var client = buildClient(options); 17 | var request = buildRequest(url, byteArray, metadata, options); 18 | return client.newCall(request).execute(); 19 | } 20 | function buildClient(options) { 21 | var client = new okhttp3.OkHttpClient.Builder(); 22 | if (options.timeout > 0) { 23 | client = client.connectTimeout(options.timeout, java.util.concurrent.TimeUnit.MILLISECONDS) 24 | .writeTimeout(options.timeout, java.util.concurrent.TimeUnit.MILLISECONDS); 25 | } 26 | return client.build(); 27 | } 28 | function buildRequest(url, byteArray, metadata, options) { 29 | var mediaType = okhttp3.MediaType.parse(metadata.mimeType); 30 | var byteCount = metadata.size - options.start; 31 | var reqBody = okhttp3.RequestBody.create(mediaType, byteArray, options.start, byteCount); 32 | var requestBuilder = new okhttp3.Request.Builder() 33 | .url(url) 34 | .put(reqBody); 35 | for (var headerName in options.headers) { 36 | requestBuilder = requestBuilder.header(headerName, options.headers[headerName]); 37 | } 38 | return requestBuilder.build(); 39 | } 40 | function mapHeaders(javaHeaders) { 41 | var headers = {}; 42 | for (var i = 0; i < javaHeaders.size(); i += 1) { 43 | headers[javaHeaders.name(i).toLowerCase()] = javaHeaders.value(i); 44 | } 45 | return headers; 46 | } 47 | -------------------------------------------------------------------------------- /kinvey.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for Kinvey JavaScript SDK 2 | // Definitions by: Kinvey 3 | 4 | import { 5 | Observable 6 | } from 'rxjs'; 7 | 8 | export namespace Kinvey { 9 | export let appVersion: string; 10 | export function initialize(config?: ClientConfig): Promise ; 11 | export function init(config?: ClientConfig): Client; 12 | 13 | interface PingResponse { 14 | version: string; 15 | kinvey: string; 16 | appName: string; 17 | environmentName: string; 18 | } 19 | 20 | export function ping(): Promise; 21 | 22 | // Request Options interface 23 | interface RequestOptions { 24 | properties?: Properties; 25 | timeout?: number; 26 | useDeltaSet?: boolean; 27 | version?: string; 28 | micId?: string; 29 | } 30 | 31 | // ClientConfig interface 32 | interface ClientConfig { 33 | instanceId?: string; 34 | apiHostname?: string; 35 | micHostname?: string; 36 | appKey: string; 37 | appSecret?: string; 38 | masterSecret?: string; 39 | encryptionKey?: string; 40 | defaultTimeout?: number; 41 | } 42 | 43 | export namespace LiveService { 44 | type StatusHandler = (status: StatusMessage) => void; 45 | type MessageHandler = (payload: any) => void; 46 | type ErrorHandler = (error: KinveyError) => void; 47 | 48 | interface StatusMessage { 49 | category: string; 50 | operation: string; 51 | affectedChannels: string[]; 52 | subscribedChannels: string[]; 53 | affectedChannelGroups: string[]; 54 | lastTimetoken: number; 55 | currentTimetoken: number; 56 | } 57 | 58 | interface PlainStreamACLObject { 59 | _id?: string; 60 | publish?: string[]; 61 | subscribe?: string[]; 62 | groups?: { 63 | publish?: string, 64 | subscribe?: string[] 65 | } 66 | } 67 | 68 | interface MessageReceiver { 69 | onMessage?: MessageHandler; 70 | onStatus?: StatusHandler; 71 | onError?: ErrorHandler; 72 | } 73 | 74 | namespace Stream { 75 | class StreamACL { 76 | publishers: string[]; 77 | subscribers: string[]; 78 | publisherGroups: string[]; 79 | subscriberGroups: string[]; 80 | 81 | static isValidACLObject: (obj: any) => boolean; 82 | 83 | constructor(obj: StreamACL | PlainStreamACLObject); 84 | 85 | addPublishers(publishers: User | User[] | string | string[]): this; 86 | addSubscribers(publishers: User | User[] | string | string[]): this; 87 | addPublisherGroups(groups: string | string[] | { 88 | _id: string 89 | } | { 90 | _id: string 91 | }[]): this; 92 | addSubscriberGroups(groups: string | string[] | { 93 | _id: string 94 | } | { 95 | _id: string 96 | }[]): this; 97 | isNotEmpty(): boolean; 98 | toPlainObject(): PlainStreamACLObject; 99 | } 100 | } 101 | 102 | class Stream { 103 | name: string; 104 | 105 | constructor(name: string); 106 | 107 | getSubstreams(): Promise<{ 108 | _id: string 109 | }>; 110 | getACL(userId: string): Promise; 111 | setACL(userId: string, acl: PlainStreamACLObject | Stream.StreamACL): Promise; 112 | 113 | follow(userId: string, receiver: MessageReceiver): Promise; 114 | unfollow(userId: string): Promise; 115 | post(message: any): Promise<{ 116 | timetoken: string 117 | }>; 118 | 119 | listen(receiver: MessageReceiver): Promise; 120 | stopListening(): Promise; 121 | send(userId: string, message: any): Promise<{ 122 | timetoken: string 123 | }>; 124 | } 125 | 126 | function onConnectionStatusUpdates(handler: StatusHandler): void; 127 | 128 | function offConnectionStatusUpdates(handler?: StatusHandler): void; 129 | 130 | function isInitialized(): boolean; 131 | } 132 | 133 | // Client class 134 | export class Client { 135 | constructor(config: ClientConfig); 136 | readonly activeUser: {}; 137 | apiProtocol: string; 138 | apiHost: string; 139 | readonly apiHostname: string; 140 | micProtocol: string; 141 | micHost: string; 142 | readonly micHostname: string; 143 | appVersion: string; 144 | defaultTimeout: number; 145 | toPlainObject(): {}; 146 | static initialize(config: ClientConfig): Client; 147 | static sharedInstance(): Client; 148 | } 149 | 150 | // Acl class 151 | export class Acl { 152 | constructor(entity: {}) 153 | readonly creator: string; 154 | readonly readers: string[]; 155 | readonly writers: string[]; 156 | readonly readerGroups: string[]; 157 | readonly writerGroups: string[]; 158 | globallyReadable: boolean; 159 | globallyWritable: boolean; 160 | addReader(user: string): this; 161 | addReaderGroup(group: string[]): this; 162 | addWriter(user: string): this; 163 | adddWriterGroup(group: string[]): this; 164 | isGloballyReadable(): boolean; 165 | isGloballyWritable(): boolean; 166 | removeReader(user: string): this; 167 | removeReaderGroup(group: string[]): this; 168 | removeWriter(user: string): this; 169 | removeWriterGroup(group: string[]): this; 170 | toPlainObject(): {}; 171 | } 172 | 173 | // Metadata class 174 | export class Metadata { 175 | constructor(entity: {}); 176 | isLocal(): boolean; 177 | toPlainObject(): {}; 178 | } 179 | 180 | // Aggregation class 181 | export class Aggregation { 182 | constructor(options?: { 183 | query?: Query 184 | initial?: {} 185 | key?: {} 186 | reduceFn?: () => any 187 | }) 188 | by(field: string): this; 189 | toJSON(): { 190 | query: {} 191 | initial: {} 192 | key: {} 193 | reduce: () => any 194 | reduceFn: () => any 195 | condition: {} 196 | }; 197 | static count(field: string): Aggregation; 198 | static sum(field: string): Aggregation; 199 | static min(field: string): Aggregation; 200 | static max(field: string): Aggregation; 201 | static average(field: string): Aggregation; 202 | } 203 | 204 | // Group class 205 | export class Group extends Aggregation { } 206 | 207 | // Custom Endpoint class 208 | export class CustomEndpoint { 209 | static execute(endpoint: string, args?: {}, options?: RequestOptions): Promise<{}>; 210 | } 211 | 212 | // Properties class 213 | export class Properties { 214 | constructor(properties?: {}); 215 | get(name: string): string | undefined; 216 | set(name: string, value: any): this; 217 | has(name: string): boolean; 218 | add(property: {}): this; 219 | addAll(properties: {}): this; 220 | remove(name: string): this; 221 | clear(): this; 222 | toPlainObject(): {}; 223 | toString(): string; 224 | } 225 | 226 | // DataStoreType enum 227 | export enum DataStoreType { 228 | Cache, 229 | Network, 230 | Sync 231 | } 232 | 233 | // SyncOperation enum 234 | export enum SyncOperation { 235 | Create, 236 | Update, 237 | Delete 238 | } 239 | 240 | // Push Result interface 241 | interface PushResult { 242 | _id: string; 243 | operation: SyncOperation; 244 | entity?: T; 245 | error?: BaseError; 246 | } 247 | 248 | // Entity interface 249 | export interface Entity { 250 | _id: string; 251 | _acl?: Acl; 252 | _kmd?: any; 253 | } 254 | 255 | // SyncEntity interface 256 | interface SyncEntity extends Entity { 257 | collection: string; 258 | state: { 259 | operation: SyncOperation 260 | }; 261 | entityId: string; 262 | } 263 | 264 | // DataStore class 265 | export abstract class DataStore { 266 | static collection(collection: string, type?: DataStoreType, options?: { 267 | client?: Client; 268 | ttl?: number; 269 | useDeltaSet?: boolean; 270 | }): CacheStore; 271 | static clearCache(options?: RequestOptions): Promise<{}>; 272 | } 273 | 274 | // NetworkStore class 275 | class NetworkStore { 276 | protected constructor(); 277 | client: Client; 278 | pathname: string; 279 | 280 | find(query?: Query, options?: RequestOptions): Observable; 281 | findById(id: string, options?: RequestOptions): Observable; 282 | group(aggregation: Aggregation, options?: RequestOptions): Observable<{}>; 283 | count(query?: Query, options?: RequestOptions): Observable; 284 | create(entities: {}, options?: RequestOptions): Promise; 285 | update(entities: {}, options?: RequestOptions): Promise; 286 | save(entity: {}, options?: RequestOptions): Promise; 287 | remove(query?: Query, options?: RequestOptions): Promise<{ 288 | count: number 289 | }>; 290 | removeById(id: string, options?: RequestOptions): Promise<{ 291 | count: number 292 | }>; 293 | 294 | subscribe(receiver: LiveService.MessageReceiver): Promise; 295 | unsubscribe(): Promise; 296 | } 297 | 298 | // CacheStore class 299 | class CacheStore extends NetworkStore { 300 | useDeltaSet: boolean; 301 | 302 | clear(query?: Query, options?: RequestOptions): Promise<{ 303 | count: number 304 | }>; 305 | pendingSyncCount(query?: Query, options?: RequestOptions): Promise; 306 | pendingSyncEntities(query?: Query, options?: RequestOptions): Promise; 307 | push(query?: Query, options?: RequestOptions): Promise[]>; 308 | pull(query?: Query, options?: PullRequestOptions): Promise; 309 | sync(query?: Query, options?: PullRequestOptions): Promise<{ 310 | push: PushResult[], 311 | pull: number 312 | }>; 313 | clearSync(query?: Query, options?: RequestOptions): Promise<{ 314 | count: number 315 | }>; 316 | } 317 | 318 | // SyncStore class 319 | class SyncStore extends CacheStore { } 320 | 321 | // File Metadata interface 322 | interface FileMetadata { 323 | _id?: string; 324 | filename?: string; 325 | mimeType?: string; 326 | public?: boolean; 327 | size?: number; 328 | } 329 | 330 | // File interface 331 | export interface File extends Entity { 332 | _filename: string; 333 | _downloadURL: string; 334 | _expiresAt: string; 335 | _public: boolean; 336 | size: number; 337 | mimeType: string; 338 | } 339 | 340 | // Files class 341 | export class Files { 342 | static find(query?: Query, options?: RequestOptions): Promise; 343 | static findById(id: string, options?: RequestOptions): Promise; 344 | static download(name: string, options?: RequestOptions): Promise; 345 | static downloadByUrl(url: string, options?: RequestOptions): Promise<{}>; 346 | static stream(name: string, options?: RequestOptions): Promise; 347 | static group(aggregation: Aggregation, options?: RequestOptions): Promise<{}>; 348 | static count(query?: Query, options?: RequestOptions): Promise; 349 | static upload(file: {}, metadata?: FileMetadata, options?: RequestOptions): Promise; 350 | static remove(query?: Query, options?: RequestOptions): Promise<{ 351 | count: number 352 | }>; 353 | static removeById(id: string, options?: RequestOptions): Promise<{ 354 | count: number 355 | }>; 356 | } 357 | 358 | // Query class 359 | export class Query { 360 | fields: any[]; 361 | filter: {}; 362 | sort: string; 363 | limit: number; 364 | skip: number; 365 | constructor(options?: { 366 | fields?: any[] 367 | filter?: {} 368 | sort?: string 369 | limit?: number 370 | skip?: number 371 | }); 372 | isSupportedOffline(): boolean; 373 | equalTo(field: string, value: any): this; 374 | contains(field: string, values: any[]): this; 375 | containsAll(field: string, values: any[]): this; 376 | greaterThan(field: string, value: number | string): this; 377 | greaterThanOrEqualTo(field: string, value: number | string): this; 378 | lessThan(field: string, value: number | string): this; 379 | lessThanOrEqualTo(field: string, value: number | string): this; 380 | notEqualTo(field: string, value: any): this; 381 | notContainedIn(field: string, values: any[]): this; 382 | and(queries?: {} | Query | {}[] | Query[]): this; 383 | nor(queries?: {} | Query | {}[] | Query[]): this; 384 | or(queries?: {} | Query | {}[] | Query[]): this; 385 | exists(field: string, flag: boolean): this; 386 | mod(field: string, divisor: number, remainder: number): this; 387 | matches(field: string, regExp: string | RegExp, options?: {}): this; 388 | near(field: string, coord: number[], maxDistance?: number): this; 389 | withinBox(field: string, bottomLeftCoord: number, upperRightCoord: number): this; 390 | withinPolygon(field: string, coords: number[]): this; 391 | size(field: string, size: number): this; 392 | ascending(field: string): this; 393 | descending(field: string): this; 394 | toPlainObject(): { 395 | fields: any[] 396 | filter?: {} 397 | sort?: string 398 | limit?: number 399 | skip?: number 400 | }; 401 | toQueryString(): {}; 402 | toString(): string; 403 | } 404 | 405 | // Authorization Grant enum 406 | export enum AuthorizationGrant { 407 | AuthorizationCodeLoginPage, 408 | AuthorizationCodeAPI 409 | } 410 | 411 | // User class 412 | export class User { 413 | constructor(data?: {}, options?: { 414 | client?: Client 415 | }) 416 | data: {}; 417 | _id: string | undefined; 418 | _acl: Acl; 419 | metadata: Metadata; 420 | _kmd: Metadata; 421 | _socialIdentity: {} | undefined; 422 | authtoken: string | undefined; 423 | username: string | undefined; 424 | email: string | undefined; 425 | pathname: string; 426 | isActive(): boolean; 427 | isEmailVerified(): boolean; 428 | login(username: string, password: string): Promise; 429 | static login(username: string, password: string): Promise; 430 | loginWithMIC(redirectUri?: string, authorizationGrant?: AuthorizationGrant, options?: RequestOptions): Promise; 431 | static loginWithMIC(redirectUri?: string, authorizationGrant?: AuthorizationGrant, options?: RequestOptions): Promise; 432 | logout(options?: RequestOptions): Promise; 433 | static logout(options?: RequestOptions): Promise; 434 | signup(data?: {}, options?: RequestOptions): Promise; 435 | static signup(data?: {}, options?: RequestOptions): Promise; 436 | update(data: {}, options?: RequestOptions): Promise; 437 | static update(data: {}, options?: RequestOptions): Promise; 438 | me(options?: RequestOptions): Promise; 439 | static me(options?: RequestOptions): Promise; 440 | static verifyEmail(username: string, options?: RequestOptions): Promise<{}>; 441 | static forgotUsername(email: string, options?: RequestOptions): Promise<{}>; 442 | static resetPassword(username: string, options?: RequestOptions): Promise<{}>; 443 | static lookup(query?: Query, options?: RequestOptions): Observable<{}>; 444 | static exists(username: string, options?: RequestOptions): Promise<{}>; 445 | static getActiveUser(client?: Client): User | null; 446 | static registerForLiveService(): Promise; 447 | static unregisterFromLiveService(): Promise; 448 | registerForLiveService(): Promise; 449 | unregisterFromLiveService(): Promise; 450 | } 451 | 452 | // Error classes 453 | export abstract class BaseError { 454 | name: string; 455 | message: string; 456 | debug: string; 457 | code: number; 458 | kinveyRequestId: string; 459 | stack: string; 460 | constructor(message: string, debug: string, code: number, kinveyRequestId: string); 461 | } 462 | export class ActiveUserError extends BaseError { } 463 | export class ApiVersionNotAvailableError extends BaseError { } 464 | export class ApiVersionNotImplemented extends BaseError { } 465 | export class AppPromblemError extends BaseError { } 466 | export class BadRequestError extends BaseError { } 467 | export class BusinessLogicError extends BaseError { } 468 | export class CORSDisabledError extends BaseError { } 469 | export class DuplicateEndUsersError extends BaseError { } 470 | export class FeatureUnavailableError extends BaseError { } 471 | export class IncompleteRequestBodyError extends BaseError { } 472 | export class IndirectCollectionAccessDisallowedError extends BaseError { } 473 | export class InsufficientCredentialsError extends BaseError { } 474 | export class InvalidCredentialsError extends BaseError { } 475 | export class InvalidIdentifierError extends BaseError { } 476 | export class InvalidQuerySyntaxError extends BaseError { } 477 | export class JSONParseError extends BaseError { } 478 | export class KinveyError extends BaseError { } 479 | export class KinveyInternalErrorRetry extends BaseError { } 480 | export class KinveyInternalErrorStop extends BaseError { } 481 | export class MissingQueryError extends BaseError { } 482 | export class MissingRequestHeaderError extends BaseError { } 483 | export class MobileIdentityConnectError extends BaseError { } 484 | export class NetworkConnectionError extends BaseError { } 485 | export class NoActiveUserError extends BaseError { } 486 | export class NoResponseError extends BaseError { } 487 | export class NotFoundError extends BaseError { } 488 | export class ParameterValueOutOfRangeError extends BaseError { } 489 | export class PopupError extends BaseError { } 490 | export class QueryError extends BaseError { } 491 | export class ServerError extends BaseError { } 492 | export class StaleRequestError extends BaseError { } 493 | export class SyncError extends BaseError { } 494 | export class TimeoutError extends BaseError { } 495 | export class UserAlreadyExistsError extends BaseError { } 496 | export class WritesToCollectionDisallowedError extends BaseError { } 497 | } 498 | 499 | export let appVersion: string; 500 | 501 | export function initialize(config?: ClientConfig): Promise; 502 | export function init(config?: ClientConfig): Client; 503 | 504 | interface PingResponse { 505 | version: string; 506 | kinvey: string; 507 | appName: string; 508 | environmentName: string; 509 | } 510 | 511 | export function ping(): Promise; 512 | 513 | // Request Options interface 514 | interface RequestOptions { 515 | properties?: Properties; 516 | timeout?: number; 517 | useDeltaSet?: boolean; 518 | version?: string; 519 | micId?: string; 520 | } 521 | 522 | // ClientConfig interface 523 | interface ClientConfig { 524 | instanceId?: string; 525 | apiHostname?: string; 526 | micHostname?: string; 527 | appKey: string; 528 | appSecret?: string; 529 | masterSecret?: string; 530 | encryptionKey?: string; 531 | defaultTimeout?: number; 532 | } 533 | 534 | export namespace LiveService { 535 | type StatusHandler = (status: StatusMessage) => void; 536 | type MessageHandler = (payload: any) => void; 537 | type ErrorHandler = (error: KinveyError) => void; 538 | 539 | interface StatusMessage { 540 | category: string; 541 | operation: string; 542 | affectedChannels: string[]; 543 | subscribedChannels: string[]; 544 | affectedChannelGroups: string[]; 545 | lastTimetoken: number; 546 | currentTimetoken: number; 547 | } 548 | 549 | interface PlainStreamACLObject { 550 | _id?: string; 551 | publish?: string[]; 552 | subscribe?: string[]; 553 | groups?: { 554 | publish?: string, 555 | subscribe?: string[] 556 | } 557 | } 558 | 559 | interface MessageReceiver { 560 | onMessage?: MessageHandler; 561 | onStatus?: StatusHandler; 562 | onError?: ErrorHandler; 563 | } 564 | 565 | namespace Stream { 566 | class StreamACL { 567 | publishers: string[]; 568 | subscribers: string[]; 569 | publisherGroups: string[]; 570 | subscriberGroups: string[]; 571 | 572 | static isValidACLObject: (obj: any) => boolean; 573 | 574 | constructor(obj?: StreamACL | PlainStreamACLObject); 575 | 576 | addPublishers(publishers: User | User[] | string | string[]): this; 577 | addSubscribers(publishers: User | User[] | string | string[]): this; 578 | addPublisherGroups(groups: string | string[] | { 579 | _id: string 580 | } | { 581 | _id: string 582 | }[]): this; 583 | addSubscriberGroups(groups: string | string[] | { 584 | _id: string 585 | } | { 586 | _id: string 587 | }[]): this; 588 | isNotEmpty(): boolean; 589 | toPlainObject(): PlainStreamACLObject; 590 | } 591 | } 592 | 593 | class Stream { 594 | name: string; 595 | 596 | constructor(name: string); 597 | 598 | getSubstreams(): Promise<{ _id: string }[]>; 599 | getACL(userId: string): Promise; 600 | setACL(userId: string, acl: PlainStreamACLObject | Stream.StreamACL): Promise; 601 | 602 | follow(userId: string, receiver: MessageReceiver): Promise; 603 | unfollow(userId: string): Promise; 604 | post(message: any): Promise<{ 605 | timetoken: string 606 | }>; 607 | 608 | listen(receiver: MessageReceiver): Promise; 609 | stopListening(): Promise; 610 | send(userId: string, message: any): Promise<{ 611 | timetoken: string 612 | }>; 613 | } 614 | 615 | function onConnectionStatusUpdates(handler: StatusHandler): void; 616 | 617 | function offConnectionStatusUpdates(handler?: StatusHandler): void; 618 | 619 | function isInitialized(): boolean; 620 | } 621 | 622 | // Client class 623 | export class Client { 624 | constructor(config: ClientConfig); 625 | readonly activeUser: {}; 626 | apiProtocol: string; 627 | apiHost: string; 628 | readonly apiHostname: string; 629 | micProtocol: string; 630 | micHost: string; 631 | readonly micHostname: string; 632 | appVersion: string; 633 | defaultTimeout: number; 634 | toPlainObject(): {}; 635 | static initialize(config: ClientConfig): Client; 636 | static sharedInstance(): Client; 637 | } 638 | 639 | // Acl class 640 | export class Acl { 641 | constructor(entity: {}) 642 | readonly creator: string; 643 | readonly readers: string[]; 644 | readonly writers: string[]; 645 | readonly readerGroups: string[]; 646 | readonly writerGroups: string[]; 647 | globallyReadable: boolean; 648 | globallyWritable: boolean; 649 | addReader(user: string): this; 650 | addReaderGroup(group: string[]): this; 651 | addWriter(user: string): this; 652 | adddWriterGroup(group: string[]): this; 653 | isGloballyReadable(): boolean; 654 | isGloballyWritable(): boolean; 655 | removeReader(user: string): this; 656 | removeReaderGroup(group: string[]): this; 657 | removeWriter(user: string): this; 658 | removeWriterGroup(group: string[]): this; 659 | toPlainObject(): {}; 660 | } 661 | 662 | // Metadata class 663 | export class Metadata { 664 | constructor(entity: {}); 665 | isLocal(): boolean; 666 | toPlainObject(): {}; 667 | } 668 | 669 | // Aggregation class 670 | export class Aggregation { 671 | constructor(options?: { 672 | query?: Query 673 | initial?: {} 674 | key?: {} 675 | reduceFn?: () => any 676 | }) 677 | by(field: string): this; 678 | toJSON(): { 679 | query: {} 680 | initial: {} 681 | key: {} 682 | reduce: () => any 683 | reduceFn: () => any 684 | condition: {} 685 | }; 686 | static count(field: string): Aggregation; 687 | static sum(field: string): Aggregation; 688 | static min(field: string): Aggregation; 689 | static max(field: string): Aggregation; 690 | static average(field: string): Aggregation; 691 | } 692 | 693 | // Group class 694 | export class Group extends Aggregation { } 695 | 696 | // Custom Endpoint class 697 | export class CustomEndpoint { 698 | static execute(endpoint: string, args?: {}, options?: RequestOptions): Promise<{}>; 699 | } 700 | 701 | // Properties class 702 | export class Properties { 703 | constructor(properties?: {}); 704 | get(name: string): string | undefined; 705 | set(name: string, value: any): this; 706 | has(name: string): boolean; 707 | add(property: {}): this; 708 | addAll(properties: {}): this; 709 | remove(name: string): this; 710 | clear(): this; 711 | toPlainObject(): {}; 712 | toString(): string; 713 | } 714 | 715 | // DataStoreType enum 716 | export enum DataStoreType { 717 | Cache, 718 | Network, 719 | Sync 720 | } 721 | 722 | // SyncOperation enum 723 | export enum SyncOperation { 724 | Create, 725 | Update, 726 | Delete 727 | } 728 | 729 | // Push Result interface 730 | interface PushResult { 731 | _id: string; 732 | operation: SyncOperation; 733 | entity?: T; 734 | error?: BaseError; 735 | } 736 | 737 | // Entity interface 738 | export interface Entity { 739 | _id: string; 740 | _acl?: Acl; 741 | _kmd?: any; 742 | } 743 | 744 | // SyncEntity interface 745 | interface SyncEntity extends Entity { 746 | collection: string; 747 | state: { 748 | operation: SyncOperation 749 | }; 750 | entityId: string; 751 | } 752 | 753 | interface PullRequestOptions { 754 | timeout?: number, 755 | useDeltaSet?: boolean, 756 | autoPagination?: boolean | { pageSize?: number } 757 | } 758 | 759 | // DataStore class 760 | export abstract class DataStore { 761 | static collection(collection: string, type?: DataStoreType, options?: { 762 | client?: Client; 763 | ttl?: number; 764 | useDeltaSet?: boolean; 765 | }): CacheStore; 766 | static clearCache(options?: RequestOptions): Promise<{}>; 767 | } 768 | 769 | // NetworkStore class 770 | declare class NetworkStore { 771 | protected constructor(); 772 | client: Client; 773 | pathname: string; 774 | 775 | find(query?: Query, options?: RequestOptions): Observable; 776 | findById(id: string, options?: RequestOptions): Observable; 777 | group(aggregation: Aggregation, options?: RequestOptions): Observable<{}>; 778 | count(query?: Query, options?: RequestOptions): Observable; 779 | create(entity: T, options?: RequestOptions): Promise; 780 | update(entity: T, options?: RequestOptions): Promise; 781 | save(entity: T, options?: RequestOptions): Promise; 782 | remove(query?: Query, options?: RequestOptions): Promise<{ count: number }>; 783 | removeById(id: string, options?: RequestOptions): Promise<{ count: number }>; 784 | 785 | subscribe(receiver: LiveService.MessageReceiver): Promise; 786 | unsubscribe(): Promise; 787 | } 788 | 789 | // CacheStore class 790 | declare class CacheStore extends NetworkStore { 791 | useDeltaSet: boolean; 792 | 793 | clear(query?: Query, options?: RequestOptions): Promise<{ 794 | count: number 795 | }>; 796 | pendingSyncCount(query?: Query, options?: RequestOptions): Promise<{ 797 | count: number 798 | }>; 799 | pendingSyncEntities(query?: Query, options?: RequestOptions): Promise; 800 | push(query?: Query, options?: RequestOptions): Promise[]>; 801 | pull(query?: Query, options?: PullRequestOptions): Promise; 802 | sync(query?: Query, options?: PullRequestOptions): Promise<{ 803 | push: PushResult[], 804 | pull: number 805 | }>; 806 | clearSync(query?: Query, options?: RequestOptions): Promise<{ 807 | count: number 808 | }>; 809 | } 810 | 811 | // SyncStore class 812 | declare class SyncStore extends CacheStore { } 813 | 814 | // File Metadata interface 815 | interface FileMetadata { 816 | _id?: string; 817 | filename?: string; 818 | mimeType?: string; 819 | public?: boolean; 820 | size?: number; 821 | } 822 | 823 | // File interface 824 | export interface File extends Entity { 825 | _filename: string; 826 | _downloadURL: string; 827 | _expiresAt: string; 828 | _public: boolean; 829 | size: number; 830 | mimeType: string; 831 | } 832 | 833 | // Files class 834 | export class Files { 835 | static find(query?: Query, options?: RequestOptions): Promise; 836 | static findById(id: string, options?: RequestOptions): Promise; 837 | static download(name: string, options?: RequestOptions): Promise; 838 | static downloadByUrl(url: string, options?: RequestOptions): Promise<{}>; 839 | static stream(name: string, options?: RequestOptions): Promise; 840 | static group(aggregation: Aggregation, options?: RequestOptions): Promise<{}>; 841 | static count(query?: Query, options?: RequestOptions): Promise; 842 | static upload(file: {}, metadata?: FileMetadata, options?: RequestOptions): Promise; 843 | static remove(query?: Query, options?: RequestOptions): Promise<{ 844 | count: number 845 | }>; 846 | static removeById(id: string, options?: RequestOptions): Promise<{ 847 | count: number 848 | }>; 849 | } 850 | 851 | // Query class 852 | export class Query { 853 | fields: any[]; 854 | filter: {}; 855 | sort: string; 856 | limit: number; 857 | skip: number; 858 | constructor(options?: { 859 | fields?: any[] 860 | filter?: {} 861 | sort?: string 862 | limit?: number 863 | skip?: number 864 | }); 865 | isSupportedOffline(): boolean; 866 | equalTo(field: string, value: any): this; 867 | contains(field: string, values: any[]): this; 868 | containsAll(field: string, values: any[]): this; 869 | greaterThan(field: string, value: number | string): this; 870 | greaterThanOrEqualTo(field: string, value: number | string): this; 871 | lessThan(field: string, value: number | string): this; 872 | lessThanOrEqualTo(field: string, value: number | string): this; 873 | notEqualTo(field: string, value: any): this; 874 | notContainedIn(field: string, values: any[]): this; 875 | and(queries?: {} | Query | {}[] | Query[]): this; 876 | nor(queries?: {} | Query | {}[] | Query[]): this; 877 | or(queries?: {} | Query | {}[] | Query[]): this; 878 | exists(field: string, flag: boolean): this; 879 | mod(field: string, divisor: number, remainder: number): this; 880 | matches(field: string, regExp: string | RegExp, options?: {}): this; 881 | near(field: string, coord: number[], maxDistance?: number): this; 882 | withinBox(field: string, bottomLeftCoord: number, upperRightCoord: number): this; 883 | withinPolygon(field: string, coords: number[]): this; 884 | size(field: string, size: number): this; 885 | ascending(field: string): this; 886 | descending(field: string): this; 887 | toPlainObject(): { 888 | fields: any[] 889 | filter?: {} 890 | sort?: string 891 | limit?: number 892 | skip?: number 893 | }; 894 | toQueryString(): {}; 895 | toString(): string; 896 | } 897 | 898 | // Authorization Grant enum 899 | export enum AuthorizationGrant { 900 | AuthorizationCodeLoginPage, 901 | AuthorizationCodeAPI 902 | } 903 | 904 | // User class 905 | export class User { 906 | constructor(data?: {}, options?: { client?: Client }) 907 | data: any; 908 | _id: string | undefined; 909 | _acl: Acl; 910 | metadata: Metadata; 911 | _kmd: Metadata; 912 | _socialIdentity: {} | undefined; 913 | authtoken: string | undefined; 914 | username: string | undefined; 915 | email: string | undefined; 916 | pathname: string; 917 | isActive(): boolean; 918 | isEmailVerified(): boolean; 919 | login(username: string, password: string): Promise; 920 | static login(username: string, password: string): Promise; 921 | loginWithMIC(redirectUri?: string, authorizationGrant?: AuthorizationGrant, options?: RequestOptions): Promise; 922 | static loginWithMIC(redirectUri?: string, authorizationGrant?: AuthorizationGrant, options?: RequestOptions): Promise; 923 | logout(options?: RequestOptions): Promise; 924 | static logout(options?: RequestOptions): Promise; 925 | signup(data?: {}, options?: RequestOptions): Promise; 926 | static signup(data?: {}, options?: RequestOptions): Promise; 927 | update(data: {}, options?: RequestOptions): Promise; 928 | static update(data: {}, options?: RequestOptions): Promise; 929 | me(options?: RequestOptions): Promise; 930 | static me(options?: RequestOptions): Promise; 931 | static verifyEmail(username: string, options?: RequestOptions): Promise<{}>; 932 | static forgotUsername(email: string, options?: RequestOptions): Promise<{}>; 933 | static resetPassword(username: string, options?: RequestOptions): Promise<{}>; 934 | static lookup(query?: Query, options?: RequestOptions): Observable<{}>; 935 | static exists(username: string, options?: RequestOptions): Promise<{}>; 936 | static getActiveUser(client?: Client): User | null; 937 | static registerForLiveService(): Promise; 938 | static unregisterFromLiveService(): Promise; 939 | registerForLiveService(): Promise; 940 | unregisterFromLiveService(): Promise; 941 | } 942 | 943 | // Error classes 944 | export abstract class BaseError { 945 | name: string; 946 | message: string; 947 | debug: string; 948 | code: number; 949 | kinveyRequestId: string; 950 | stack: string; 951 | constructor(message: string, debug: string, code: number, kinveyRequestId: string); 952 | } 953 | export class ActiveUserError extends BaseError { } 954 | export class ApiVersionNotAvailableError extends BaseError { } 955 | export class ApiVersionNotImplemented extends BaseError { } 956 | export class AppPromblemError extends BaseError { } 957 | export class BadRequestError extends BaseError { } 958 | export class BusinessLogicError extends BaseError { } 959 | export class CORSDisabledError extends BaseError { } 960 | export class DuplicateEndUsersError extends BaseError { } 961 | export class FeatureUnavailableError extends BaseError { } 962 | export class IncompleteRequestBodyError extends BaseError { } 963 | export class IndirectCollectionAccessDisallowedError extends BaseError { } 964 | export class InsufficientCredentialsError extends BaseError { } 965 | export class InvalidCredentialsError extends BaseError { } 966 | export class InvalidIdentifierError extends BaseError { } 967 | export class InvalidQuerySyntaxError extends BaseError { } 968 | export class JSONParseError extends BaseError { } 969 | export class KinveyError extends BaseError { } 970 | export class KinveyInternalErrorRetry extends BaseError { } 971 | export class KinveyInternalErrorStop extends BaseError { } 972 | export class MissingQueryError extends BaseError { } 973 | export class MissingRequestHeaderError extends BaseError { } 974 | export class MobileIdentityConnectError extends BaseError { } 975 | export class NetworkConnectionError extends BaseError { } 976 | export class NoActiveUserError extends BaseError { } 977 | export class NoResponseError extends BaseError { } 978 | export class NotFoundError extends BaseError { } 979 | export class ParameterValueOutOfRangeError extends BaseError { } 980 | export class PopupError extends BaseError { } 981 | export class QueryError extends BaseError { } 982 | export class ServerError extends BaseError { } 983 | export class StaleRequestError extends BaseError { } 984 | export class SyncError extends BaseError { } 985 | export class TimeoutError extends BaseError { } 986 | export class UserAlreadyExistsError extends BaseError { } 987 | export class WritesToCollectionDisallowedError extends BaseError { } 988 | -------------------------------------------------------------------------------- /lib/before-checkForChanges.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fs = require('fs'); 3 | const url = require('url'); 4 | const pkg = require('../package.json'); 5 | 6 | module.exports = function (hookArgs) { 7 | return new Promise((resolve, reject) => { 8 | const appDirectoryPath = hookArgs && hookArgs.checkForChangesOpts && hookArgs.checkForChangesOpts.projectData && hookArgs.checkForChangesOpts.projectData.appDirectoryPath; 9 | 10 | if (!appDirectoryPath) { 11 | reject(new Error('Unable to get path to app directory')); 12 | } else { 13 | const platform = (hookArgs && hookArgs.checkForChangesOpts && hookArgs.checkForChangesOpts.platform.toLowerCase()) || ''; 14 | const pathToPackageJson = path.join(appDirectoryPath, 'package.json'); 15 | const packageJsonContent = JSON.parse(fs.readFileSync(pathToPackageJson)); 16 | const kinveyData = packageJsonContent.pluginsData && packageJsonContent.pluginsData[pkg.name]; 17 | const redirectUri = kinveyData && kinveyData.config && kinveyData.config.redirectUri; 18 | const parsedRedirectUri = redirectUri ? url.parse(redirectUri) : {}; 19 | const redirectUriScheme = (parsedRedirectUri.protocol && parsedRedirectUri.protocol.substring(0, parsedRedirectUri.protocol.indexOf(':'))) || undefined; 20 | 21 | if (platform === 'android') { 22 | const destinationAndroidManifestFile = path.join(__dirname, '..', 'platforms', 'android', 'AndroidManifest.xml'); 23 | 24 | if (redirectUriScheme) { 25 | const micAndroidManifestFile = path.join(__dirname, '..', 'platforms', 'android', 'AndroidManifest.xml.mic'); 26 | const micAndroidManifestFileContent = fs.readFileSync(micAndroidManifestFile).toString().replace(/{redirectUriScheme}/i, redirectUriScheme); 27 | const currentContent = fs.existsSync(destinationAndroidManifestFile) && fs.readFileSync(destinationAndroidManifestFile).toString(); 28 | if (currentContent !== micAndroidManifestFileContent) { 29 | fs.writeFileSync(destinationAndroidManifestFile, micAndroidManifestFileContent); 30 | } 31 | } else { 32 | const defaultAndroidManifestFile = path.join(__dirname, '..', 'platforms', 'android', 'AndroidManifest.xml.default'); 33 | const defaultAndroidManifestFileContent = fs.readFileSync(defaultAndroidManifestFile).toString(); 34 | const currentContent = fs.existsSync(destinationAndroidManifestFile) && fs.readFileSync(destinationAndroidManifestFile).toString(); 35 | if (currentContent !== defaultAndroidManifestFileContent) { 36 | fs.writeFileSync(destinationAndroidManifestFile, defaultAndroidManifestFileContent); 37 | } 38 | } 39 | } else if (platform === 'ios') { 40 | const destinationInfoPlistFile = path.join(__dirname, '..', 'platforms', 'ios', 'Info.plist'); 41 | 42 | if (redirectUriScheme) { 43 | const micInfoPlistFile = path.join(__dirname, '..', 'platforms', 'ios', 'Info.plist.mic'); 44 | const micInfoPlistFileContent = fs.readFileSync(micInfoPlistFile).toString().replace(/{redirectUriScheme}/i, redirectUriScheme); 45 | const currentContent = fs.existsSync(destinationInfoPlistFile) && fs.readFileSync(destinationInfoPlistFile).toString(); 46 | if (currentContent !== micInfoPlistFileContent) { 47 | fs.writeFileSync(destinationInfoPlistFile, micInfoPlistFileContent); 48 | } 49 | } 50 | } 51 | 52 | resolve(); 53 | } 54 | }); 55 | }; 56 | -------------------------------------------------------------------------------- /lib/before-preview-sync.js: -------------------------------------------------------------------------------- 1 | module.exports = function ($logger, hookArgs) { 2 | const previewAppSchema = hookArgs && hookArgs.projectData && hookArgs.projectData.previewAppSchema; 3 | const previewResumeScheme = previewAppSchema === "kspreview" ? "kspreviewresume://" : "nsplayresume://"; 4 | 5 | $logger.warn(`If you are using loginWithMIC() ensure that you have added ${previewResumeScheme} as a Redirect URI to your Mobile Identity Connect configuration at https://console.kinvey.com in order for Mobile Identity Connect login to work in the Preview app.`); 6 | }; 7 | -------------------------------------------------------------------------------- /lib/postinstall.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | require('nativescript-hook')(path.join(__dirname, "..")).postinstall(); 3 | -------------------------------------------------------------------------------- /lib/preuninstall.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | require('nativescript-hook')(path.join(__dirname, "..")).preuninstall(); 3 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "3.12.6", 3 | "name": "kinvey-nativescript-sdk", 4 | "description": "Kinvey NativeScript SDK for developing NativeScript applications.", 5 | "author": "Kinvey, Inc.", 6 | "homepage": "http://www.kinvey.com", 7 | "license": "Apache-2.0", 8 | "main": "kinvey-nativescript-sdk.js", 9 | "typings": "kinvey.d.ts", 10 | "dependencies": { 11 | "nativescript-hook": "0.2.4", 12 | "nativescript-sqlite": "latest", 13 | "nativescript-urlhandler": "^1.2.2", 14 | "rxjs": "~6.2.2" 15 | }, 16 | "files": [ 17 | "file-upload-worker-android.js", 18 | "kinvey-nativescript-sdk.android.js", 19 | "kinvey-nativescript-sdk.android.js.map", 20 | "kinvey-nativescript-sdk.ios.js", 21 | "kinvey-nativescript-sdk.ios.js.map", 22 | "kinvey.d.ts", 23 | "push.android.js", 24 | "push.android.js.map", 25 | "push.d.ts", 26 | "push.ios.js", 27 | "push.ios.js.map", 28 | "lib/before-checkForChanges.js", 29 | "lib/before-preview-sync.js", 30 | "lib/postinstall.js", 31 | "lib/preuninstall.js", 32 | "platforms/android/AndroidManifest.xml.default", 33 | "platforms/android/AndroidManifest.xml.mic", 34 | "platforms/android/include.gradle", 35 | "platforms/ios/Podfile", 36 | "platforms/ios/Info.plist.mic", 37 | "platforms/ios/app.entitlements" 38 | ], 39 | "nativescript": { 40 | "hooks": [ 41 | { 42 | "type": "before-checkForChanges", 43 | "script": "lib/before-checkForChanges.js", 44 | "inject": true 45 | }, 46 | { 47 | "type": "before-preview-sync", 48 | "script": "lib/before-preview-sync.js", 49 | "inject": true 50 | } 51 | ], 52 | "platforms": { 53 | "ios": "4.0.0", 54 | "android": "4.0.0" 55 | } 56 | }, 57 | "scripts": { 58 | "postinstall": "node lib/postinstall.js", 59 | "preuninstall": "node lib/preuninstall.js" 60 | } 61 | } -------------------------------------------------------------------------------- /platforms/android/AndroidManifest.default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /platforms/android/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /platforms/android/AndroidManifest.xml.default: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /platforms/android/AndroidManifest.xml.mic: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /platforms/android/include.gradle: -------------------------------------------------------------------------------- 1 | repositories { 2 | mavenCentral() 3 | } 4 | 5 | dependencies { 6 | compile 'com.orhanobut:hawk:2.0.1' 7 | compile 'com.squareup.okhttp3:okhttp:3.8.1' 8 | compile 'com.android.support:appcompat-v7:27.0.2' 9 | compile 'com.android.support:customtabs:27.0.2' 10 | } 11 | -------------------------------------------------------------------------------- /platforms/ios/Info.default.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleURLTypes 6 | 7 | 8 | CFBundleTypeRole 9 | Editor 10 | CFBundleURLSchemes 11 | 12 | {redirectUriScheme} 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /platforms/ios/Info.plist.mic: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleURLTypes 6 | 7 | 8 | CFBundleTypeRole 9 | Editor 10 | CFBundleURLSchemes 11 | 12 | {redirectUriScheme} 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /platforms/ios/Podfile: -------------------------------------------------------------------------------- 1 | platform :ios, '9.0' 2 | pod 'SAMKeychain', '~> 1.5.2' 3 | -------------------------------------------------------------------------------- /platforms/ios/app.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | keychain-access-groups 6 | 7 | $(AppIdentifierPrefix)$(PRODUCT_BUNDLE_IDENTIFIER) 8 | 9 | 10 | -------------------------------------------------------------------------------- /push.android.js: -------------------------------------------------------------------------------- 1 | /** 2 | * kinvey-nativescript-sdk - Kinvey NativeScript SDK for developing NativeScript applications. 3 | * @version v3.12.6 4 | * @author Kinvey, Inc. 5 | * @link http://www.kinvey.com 6 | * @license Apache-2.0 7 | */ 8 | module.exports=function(e){var t={};function n(r){if(t[r]){return t[r].exports}var i=t[r]={i:r,l:false,exports:{}};e[r].call(i.exports,i,i.exports,n);i.l=true;return i.exports}n.m=e;n.c=t;n.d=function(e,t,r){if(!n.o(e,t)){Object.defineProperty(e,t,{configurable:false,enumerable:true,get:r})}};n.n=function(e){var t=e&&e.__esModule?function t(){return e["default"]}:function t(){return e};n.d(t,"a",t);return t};n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};n.p="kinvey-nativescript-sdk/";return n(n.s=586)}({0:function(e,t,n){(function(t,r){var i;(function(t,n){true?e.exports=n():typeof define==="function"&&define.amd?define(n):t.ES6Promise=n()})(this,function(){"use strict";function e(e){var t=typeof e;return e!==null&&(t==="object"||t==="function")}function o(e){return typeof e==="function"}var s=undefined;if(Array.isArray){s=Array.isArray}else{s=function(e){return Object.prototype.toString.call(e)==="[object Array]"}}var u=s;var f=0;var a=undefined;var c=undefined;var l=function e(t,n){k[f]=t;k[f+1]=n;f+=2;if(f===2){if(c){c(E)}else{x()}}};function h(e){c=e}function v(e){l=e}var p=typeof window!=="undefined"?window:undefined;var d=p||{};var y=d.MutationObserver||d.WebKitMutationObserver;var _=typeof self==="undefined"&&typeof t!=="undefined"&&{}.toString.call(t)==="[object process]";var m=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function g(){return function(){return t.nextTick(E)}}function w(){if(typeof a!=="undefined"){return function(){a(E)}}return T()}function b(){var e=0;var t=new y(E);var n=document.createTextNode("");t.observe(n,{characterData:true});return function(){n.data=e=++e%2}}function P(){var e=new MessageChannel;e.port1.onmessage=E;return function(){return e.port2.postMessage(0)}}function T(){var e=setTimeout;return function(){return e(E,1)}}var k=new Array(1e3);function E(){for(var e=0;e0&&this._events[e].length>i){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);if(typeof console.trace==="function"){console.trace()}}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){if(!r(t))throw TypeError("listener must be a function");var n=false;function i(){this.removeListener(e,i);if(!n){n=true;t.apply(this,arguments)}}i.listener=t;this.on(e,i);return this};n.prototype.removeListener=function(e,t){var n,i,s,u;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;n=this._events[e];s=n.length;i=-1;if(n===t||r(n.listener)&&n.listener===t){delete this._events[e];if(this._events.removeListener)this.emit("removeListener",e,t)}else if(o(n)){for(u=s;u-- >0;){if(n[u]===t||n[u].listener&&n[u].listener===t){i=u;break}}if(i<0)return this;if(n.length===1){n.length=0;delete this._events[e]}else{n.splice(i,1)}if(this._events.removeListener)this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(t in this._events){if(t==="removeListener")continue;this.removeAllListeners(t)}this.removeAllListeners("removeListener");this._events={};return this}n=this._events[e];if(r(n)){this.removeListener(e,n)}else if(n){while(n.length)this.removeListener(e,n[n.length-1])}delete this._events[e];return this};n.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(r(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;else if(t)return t.length}return 0};n.listenerCount=function(e,t){return e.listenerCount(t)};function r(e){return typeof e==="function"}function i(e){return typeof e==="number"}function o(e){return typeof e==="object"&&e!==null}function s(e){return e===void 0}},586:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:true});var r=n(0);var i=n(60);var o=n(234);var s=n(587);var u;try{u=n(588)}catch(e){}var f=function(e){__extends(t,e);function t(){var t=e.call(this)||this;var n=function(e){if(e.android&&typeof t.notificationCallback==="function"){var n=e.android;var r=n.getIntent();var i=r.getExtras();var o={foreground:false};if(i){var s=i.keySet().iterator();while(s.hasNext()){var u=s.next();if(u!=="from"&&u!=="collapse_key"&&!u.startsWith("google.")){o[u]=i.get(u)}}}t.notificationCallback(o)}};i.off(i.resumeEvent,n);i.on(i.resumeEvent,n);return t}t.prototype._registerWithPushPlugin=function(e){var t=this;if(e===void 0){e={}}var n=e.android||{};return new r.Promise(function(r,i){if(!u){return i(new o.KinveyError("NativeScript Push Plugin is not installed.","Please refer to http://devcenter.kinvey.com/nativescript/guides/push#ProjectSetUp for help with"+" setting up your project."))}t.notificationCallback=e.notificationCallback;var s=n.notificationCallbackAndroid;n.notificationCallbackAndroid=function(n,r){if(typeof s==="function"){s(n,r)}if(typeof e.notificationCallback==="function"){var i=JSON.parse(n);i.title=r.getTitle();i.body=r.getBody();e.notificationCallback(i)}t.emit("notification",JSON.parse(n))};u.register(n,r,i)})};t.prototype._unregisterWithPushPlugin=function(e){if(e===void 0){e={}}var t=e.android||{};return new r.Promise(function(e,n){if(!u){return n(new o.KinveyError("NativeScript Push Plugin is not installed.","Please refer to http://devcenter.kinvey.com/nativescript/guides/push#ProjectSetUp for help with"+" setting up your project."))}u.unregister(e,n,t)})};return t}(s.PushCommon);var a=new f;t.Push=a},587:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:true});var r=n(0);var i=n(55);var o=n(127);var s=n(234);var u="__device";var f=function(e){__extends(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}Object.defineProperty(t.prototype,"client",{get:function(){return s.client()},enumerable:true,configurable:true});t.prototype.onNotification=function(e){return this.on("notification",e)};t.prototype.onceNotification=function(e){return this.once("notification",e)};t.prototype.register=function(e){var t=this;if(e===void 0){e={}}return this._registerWithPushPlugin(e).then(function(n){if(!n){throw new s.KinveyError("Unable to retrieve the device token to register this device for push notifications.")}return t._registerWithKinvey(n,e)}).then(function(e){return t._saveTokenToCache(e)})};t.prototype.unregister=function(e){var t=this;if(e===void 0){e={}}return this._unregisterWithPushPlugin(e).then(function(){return t._getTokenFromCache()}).then(function(n){if(!n){throw new s.KinveyError("Unable to retrieve the device token to unregister this device for push notifications.")}return t._unregisterWithKinvey(n,e)}).then(function(){return t._deleteTokenFromCache()})};t.prototype._registerWithPushPlugin=function(e){if(e===void 0){e={}}return r.Promise.reject(new s.KinveyError("Unable to register for push notifications."))};t.prototype._unregisterWithPushPlugin=function(e){if(e===void 0){e={}}return r.Promise.reject(new s.KinveyError("Unable to unregister for push notifications."))};t.prototype._registerWithKinvey=function(e,t){if(t===void 0){t={}}var n=s.User.getActiveUser(this.client);if(!n){return r.Promise.reject(new s.KinveyError("Unable to register this device for push notifications.","You must login a user."))}var i=new s.KinveyRequest({method:s.RequestMethod.POST,url:this.client.apiHostname+"/push/"+this.client.appKey+"/register-device",authType:n?s.AuthType.Session:s.AuthType.Master,data:{platform:o.device.os.toLowerCase(),framework:"nativescript",deviceId:e},timeout:t.timeout,client:this.client});return i.execute().then(function(){return e})};t.prototype._unregisterWithKinvey=function(e,t){if(t===void 0){t={}}var n=s.User.getActiveUser(this.client);if(!n){return r.Promise.reject(new s.KinveyError("Unable to unregister this device for push notifications.","You must login a user."))}var i=new s.KinveyRequest({method:s.RequestMethod.POST,url:this.client.apiHostname+"/push/"+this.client.appKey+"/unregister-device",authType:n?s.AuthType.Session:s.AuthType.Master,data:{platform:o.device.os.toLowerCase(),framework:"nativescript",deviceId:e},timeout:t.timeout,client:this.client});return i.execute().then(function(e){return e.data})};t.prototype._getTokenFromCache=function(){var e=s.User.getActiveUser(this.client);if(!e){throw new s.KinveyError("Unable to retrieve device token.","You must login a user.")}return this._getOfflineRepo().then(function(t){return t.readById(u,e._id)}).catch(function(e){if(e instanceof s.NotFoundError){return{}}throw e}).then(function(e){if(e){return e.token}return null})};t.prototype._saveTokenToCache=function(e){var t=s.User.getActiveUser(this.client);if(!t){throw new s.KinveyError("Unable to save device token.","You must login a user.")}var n={_id:t._id,userId:t._id,token:e};return this._getOfflineRepo().then(function(e){return e.update(u,n)}).then(function(){return e})};t.prototype._deleteTokenFromCache=function(){var e=s.User.getActiveUser(this.client);if(!e){throw new s.KinveyError("Unable to delete device token.","You must login a user.")}return this._getOfflineRepo().then(function(t){return t.deleteById(u,e._id)}).then(function(){return null})};t.prototype._getOfflineRepo=function(){if(!this._offlineRepoPromise){this._offlineRepoPromise=s.DataAccess.repositoryProvider.getOfflineRepository()}return this._offlineRepoPromise};return t}(i.EventEmitter);t.PushCommon=f},588:function(e,t){e.exports=require("nativescript-push-notifications")},60:function(e,t){e.exports=require("application")},93:function(e,t){var n=e.exports={};var r;var i;function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){r=setTimeout}else{r=o}}catch(e){r=o}try{if(typeof clearTimeout==="function"){i=clearTimeout}else{i=s}}catch(e){i=s}})();function u(e){if(r===setTimeout){return setTimeout(e,0)}if((r===o||!r)&&setTimeout){r=setTimeout;return setTimeout(e,0)}try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function f(e){if(i===clearTimeout){return clearTimeout(e)}if((i===s||!i)&&clearTimeout){i=clearTimeout;return clearTimeout(e)}try{return i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}var a=[];var c=false;var l;var h=-1;function v(){if(!c||!l){return}c=false;if(l.length){a=l.concat(a)}else{h=-1}if(a.length){p()}}function p(){if(c){return}var e=u(v);c=true;var t=a.length;while(t){l=a;a=[];while(++h1){for(var n=1;n void 34 | }; 35 | ios?: { 36 | alert?: boolean, 37 | badge?: boolean, 38 | sound?: boolean, 39 | interactiveSettings: { 40 | actions: IosInteractiveNotificationAction[], 41 | categories: IosInteractiveNotificationCategory[] 42 | }, 43 | notificationCallbackIOS?: (message: any) => void 44 | }; 45 | notificationCallback?: (message: any) => void; 46 | } 47 | 48 | // Push class 49 | export class Push { 50 | private constructor(); 51 | static pathname: string; 52 | static isSupported(): boolean; 53 | static onNotification(listener: (notifaction: any) => void); 54 | static onceNotification(listener: (notifaction: any) => void); 55 | static register(options: PushOptions): Promise; 56 | static unregister(options: PushOptions): Promise; 57 | } 58 | -------------------------------------------------------------------------------- /push.ios.js: -------------------------------------------------------------------------------- 1 | /** 2 | * kinvey-nativescript-sdk - Kinvey NativeScript SDK for developing NativeScript applications. 3 | * @version v3.12.6 4 | * @author Kinvey, Inc. 5 | * @link http://www.kinvey.com 6 | * @license Apache-2.0 7 | */ 8 | module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=580)}({0:function(e,t,n){(function(t,r){var i;i=function(){"use strict";function e(e){return"function"==typeof e}var i=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=0,s=void 0,u=void 0,c=function(e,t){d[o]=e,d[o+1]=t,2===(o+=2)&&(u?u(_):b())};var a="undefined"!=typeof window?window:void 0,h=a||{},f=h.MutationObserver||h.WebKitMutationObserver,l="undefined"==typeof self&&void 0!==t&&"[object process]"==={}.toString.call(t),v="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function p(){var e=setTimeout;return function(){return e(_,1)}}var d=new Array(1e3);function _(){for(var e=0;e0&&this._events[e].length>s&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){if(!r(t))throw TypeError("listener must be a function");var n=!1;function i(){this.removeListener(e,i),n||(n=!0,t.apply(this,arguments))}return i.listener=t,this.on(e,i),this},n.prototype.removeListener=function(e,t){var n,o,s,u;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(s=(n=this._events[e]).length,o=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(u=s;u-- >0;)if(n[u]===t||n[u].listener&&n[u].listener===t){o=u;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},580:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,i=n(0),o=n(234),s=n(581);try{r=n(582)}catch(e){}var u=new(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype._registerWithPushPlugin=function(e){var t=this;void 0===e&&(e={});var n=e.ios||{};return new i.Promise(function(i,s){if(!r)return s(new o.KinveyError("NativeScript Push Plugin is not installed.","Please refer to http://devcenter.kinvey.com/nativescript/guides/push#ProjectSetUp for help with setting up your project."));var u=n.notificationCallbackIOS;n.notificationCallbackIOS=function(n){"function"==typeof u&&u(n),"function"==typeof e.notificationCallback&&(n.foreground="1"===n.foreground,e.notificationCallback(n)),t.emit("notification",n)},r.register(n,function(e){n.interactiveSettings?r.registerUserNotificationSettings(function(){i(e)},function(t){i(e)}):i(e)},s)})},t.prototype._unregisterWithPushPlugin=function(e){void 0===e&&(e={});var t=e.ios||{};return new i.Promise(function(e,n){if(!r)return n(new o.KinveyError("NativeScript Push Plugin is not installed.","Please refer to http://devcenter.kinvey.com/nativescript/guides/push#ProjectSetUp for help with setting up your project."));r.unregister(e,n,t)})},t}(s.PushCommon));t.Push=u},581:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(55),o=n(126),s=n(234),u=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),Object.defineProperty(t.prototype,"client",{get:function(){return s.client()},enumerable:!0,configurable:!0}),t.prototype.onNotification=function(e){return this.on("notification",e)},t.prototype.onceNotification=function(e){return this.once("notification",e)},t.prototype.register=function(e){var t=this;return void 0===e&&(e={}),this._registerWithPushPlugin(e).then(function(n){if(!n)throw new s.KinveyError("Unable to retrieve the device token to register this device for push notifications.");return t._registerWithKinvey(n,e)}).then(function(e){return t._saveTokenToCache(e)})},t.prototype.unregister=function(e){var t=this;return void 0===e&&(e={}),this._unregisterWithPushPlugin(e).then(function(){return t._getTokenFromCache()}).then(function(n){if(!n)throw new s.KinveyError("Unable to retrieve the device token to unregister this device for push notifications.");return t._unregisterWithKinvey(n,e)}).then(function(){return t._deleteTokenFromCache()})},t.prototype._registerWithPushPlugin=function(e){return void 0===e&&(e={}),r.Promise.reject(new s.KinveyError("Unable to register for push notifications."))},t.prototype._unregisterWithPushPlugin=function(e){return void 0===e&&(e={}),r.Promise.reject(new s.KinveyError("Unable to unregister for push notifications."))},t.prototype._registerWithKinvey=function(e,t){void 0===t&&(t={});var n=s.User.getActiveUser(this.client);return n?new s.KinveyRequest({method:s.RequestMethod.POST,url:this.client.apiHostname+"/push/"+this.client.appKey+"/register-device",authType:n?s.AuthType.Session:s.AuthType.Master,data:{platform:o.device.os.toLowerCase(),framework:"nativescript",deviceId:e},timeout:t.timeout,client:this.client}).execute().then(function(){return e}):r.Promise.reject(new s.KinveyError("Unable to register this device for push notifications.","You must login a user."))},t.prototype._unregisterWithKinvey=function(e,t){void 0===t&&(t={});var n=s.User.getActiveUser(this.client);return n?new s.KinveyRequest({method:s.RequestMethod.POST,url:this.client.apiHostname+"/push/"+this.client.appKey+"/unregister-device",authType:n?s.AuthType.Session:s.AuthType.Master,data:{platform:o.device.os.toLowerCase(),framework:"nativescript",deviceId:e},timeout:t.timeout,client:this.client}).execute().then(function(e){return e.data}):r.Promise.reject(new s.KinveyError("Unable to unregister this device for push notifications.","You must login a user."))},t.prototype._getTokenFromCache=function(){var e=s.User.getActiveUser(this.client);if(!e)throw new s.KinveyError("Unable to retrieve device token.","You must login a user.");return this._getOfflineRepo().then(function(t){return t.readById("__device",e._id)}).catch(function(e){if(e instanceof s.NotFoundError)return{};throw e}).then(function(e){return e?e.token:null})},t.prototype._saveTokenToCache=function(e){var t=s.User.getActiveUser(this.client);if(!t)throw new s.KinveyError("Unable to save device token.","You must login a user.");var n={_id:t._id,userId:t._id,token:e};return this._getOfflineRepo().then(function(e){return e.update("__device",n)}).then(function(){return e})},t.prototype._deleteTokenFromCache=function(){var e=s.User.getActiveUser(this.client);if(!e)throw new s.KinveyError("Unable to delete device token.","You must login a user.");return this._getOfflineRepo().then(function(t){return t.deleteById("__device",e._id)}).then(function(){return null})},t.prototype._getOfflineRepo=function(){return this._offlineRepoPromise||(this._offlineRepoPromise=s.DataAccess.repositoryProvider.getOfflineRepository()),this._offlineRepoPromise},t}(i.EventEmitter);t.PushCommon=u},582:function(e,t){e.exports=require("nativescript-push-notifications")},92:function(e,t){var n,r,i=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function u(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(e){r=s}}();var c,a=[],h=!1,f=-1;function l(){h&&c&&(h=!1,c.length?a=c.concat(a):f=-1,a.length&&v())}function v(){if(!h){var e=u(l);h=!0;for(var t=a.length;t;){for(c=a,a=[];++f1)for(var n=1;n postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {function} resolver\n Useful for tooling.\n @constructor\n*/\nfunction Promise$2(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise$2.all = all$1;\nPromise$2.race = race$1;\nPromise$2.resolve = resolve$1;\nPromise$2.reject = reject$1;\nPromise$2._setScheduler = setScheduler;\nPromise$2._setAsap = setAsap;\nPromise$2._asap = asap;\n\nPromise$2.prototype = {\n constructor: Promise$2,\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection) {\n return this.then(null, onRejection);\n }\n};\n\n/*global self*/\nfunction polyfill$1() {\n var local = undefined;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise$2;\n}\n\n// Strange compat..\nPromise$2.polyfill = polyfill$1;\nPromise$2.Promise = Promise$2;\n\nreturn Promise$2;\n\n})));\n\n//# sourceMappingURL=es6-promise.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// /home/travis/build/Kinvey/js-sdk/node_modules/es6-promise/dist/es6-promise.js\n// module id = 0\n// module chunks = 0 1","module.exports = require(\"platform\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"platform\"\n// module id = 126\n// module chunks = 0 1","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 23\n// module chunks = 0 1","module.exports = require(\"./kinvey-nativescript-sdk\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"./kinvey-nativescript-sdk\"\n// module id = 234\n// module chunks = 1","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// /home/travis/build/Kinvey/js-sdk/node_modules/events/events.js\n// module id = 55\n// module chunks = 0 1","import { Promise } from 'es6-promise';\nimport { KinveyError } from './kinvey-nativescript-sdk';\nimport { PushCommon } from './common';\nimport { PushConfig, IOSPushConfig } from './';\n// tslint:disable-next-line:variable-name\nlet PushPlugin;\n\ntry {\n PushPlugin = require('nativescript-push-notifications');\n} catch (e) {\n // Just catch the error\n}\n\nclass IOSPush extends PushCommon {\n protected _registerWithPushPlugin(options = {}): Promise {\n const config = options.ios || {};\n\n return new Promise((resolve, reject) => {\n if (!PushPlugin) {\n return reject(new KinveyError('NativeScript Push Plugin is not installed.',\n 'Please refer to http://devcenter.kinvey.com/nativescript/guides/push#ProjectSetUp for help with'\n + ' setting up your project.'));\n }\n\n const usersNotificationCallback = config.notificationCallbackIOS;\n config.notificationCallbackIOS = (message: any) => {\n if (typeof usersNotificationCallback === 'function') {\n usersNotificationCallback(message);\n }\n\n if (typeof options.notificationCallback === 'function') {\n // let's transform the \"foreground\" (\"0\" / \"1\") into a proper boolean value\n message.foreground = message.foreground === \"1\";\n options.notificationCallback(message);\n }\n\n (this as any).emit('notification', message);\n };\n\n PushPlugin.register(config, (token) => {\n if (config.interactiveSettings) {\n PushPlugin.registerUserNotificationSettings(() => {\n resolve(token);\n }, (error) => {\n // do something with error\n resolve(token);\n });\n } else {\n resolve(token);\n }\n }, reject);\n });\n }\n\n protected _unregisterWithPushPlugin(options = {}): Promise {\n const config = options.ios || {};\n\n return new Promise((resolve, reject) => {\n if (!PushPlugin) {\n return reject(new KinveyError('NativeScript Push Plugin is not installed.',\n 'Please refer to http://devcenter.kinvey.com/nativescript/guides/push#ProjectSetUp for help with'\n + ' setting up your project.'));\n }\n\n PushPlugin.unregister(resolve, reject, config);\n });\n }\n}\n\n// tslint:disable-next-line:variable-name\nconst Push = new IOSPush();\nexport { Push };\n\n\n\n// WEBPACK FOOTER //\n// ./src/push/push.ios.ts","import { Promise } from 'es6-promise';\nimport { EventEmitter } from 'events';\n\nimport { device as Device } from 'tns-core-modules/platform';\nimport {\n client,\n KinveyError,\n NotFoundError,\n User,\n AuthType,\n KinveyRequest,\n RequestMethod,\n DataAccess\n} from './kinvey-nativescript-sdk';\nimport { PushConfig } from './';\n\nconst deviceCollectionName = '__device';\n\nexport class PushCommon extends EventEmitter {\n private _offlineRepoPromise: Promise;\n\n get client() {\n return client();\n }\n\n onNotification(listener: (data: any) => void) {\n return (this as any).on('notification', listener);\n }\n\n onceNotification(listener: (data: any) => void) {\n return (this as any).once('notification', listener);\n }\n\n register(options = {}) {\n return this._registerWithPushPlugin(options)\n .then((token) => {\n if (!token) {\n throw new KinveyError('Unable to retrieve the device token to register this device for push notifications.');\n }\n\n return this._registerWithKinvey(token, options);\n })\n .then((token) => {\n return this._saveTokenToCache(token);\n });\n }\n\n unregister(options = {}) {\n return this._unregisterWithPushPlugin(options)\n .then(() => {\n return this._getTokenFromCache();\n })\n .then((token) => {\n if (!token) {\n throw new KinveyError('Unable to retrieve the device token to unregister this device for push notifications.');\n }\n\n return this._unregisterWithKinvey(token, options);\n })\n .then(() => {\n return this._deleteTokenFromCache();\n });\n }\n\n protected _registerWithPushPlugin(options = {}): Promise {\n return Promise.reject(new KinveyError('Unable to register for push notifications.'));\n }\n\n protected _unregisterWithPushPlugin(options = {}): Promise {\n return Promise.reject(new KinveyError('Unable to unregister for push notifications.'));\n }\n\n private _registerWithKinvey(token: string, options = {}): Promise {\n const activeUser = User.getActiveUser(this.client);\n\n if (!activeUser) {\n return Promise.reject(new KinveyError('Unable to register this device for push notifications.',\n 'You must login a user.'));\n }\n\n const request = new KinveyRequest({\n method: RequestMethod.POST,\n url: `${this.client.apiHostname}/push/${this.client.appKey}/register-device`,\n authType: activeUser ? AuthType.Session : AuthType.Master,\n data: {\n platform: Device.os.toLowerCase(),\n framework: 'nativescript',\n deviceId: token\n },\n timeout: options.timeout,\n client: this.client\n });\n return request.execute().then(() => token);\n }\n\n private _unregisterWithKinvey(token: string, options = {}): Promise {\n const activeUser = User.getActiveUser(this.client);\n\n if (!activeUser) {\n return Promise.reject(new KinveyError('Unable to unregister this device for push notifications.',\n 'You must login a user.'));\n }\n\n const request = new KinveyRequest({\n method: RequestMethod.POST,\n url: `${this.client.apiHostname}/push/${this.client.appKey}/unregister-device`,\n authType: activeUser ? AuthType.Session : AuthType.Master,\n data: {\n platform: Device.os.toLowerCase(),\n framework: 'nativescript',\n deviceId: token\n },\n timeout: options.timeout,\n client: this.client\n });\n return request.execute().then(response => response.data);\n }\n\n private _getTokenFromCache(): Promise {\n const activeUser = User.getActiveUser(this.client);\n\n if (!activeUser) {\n throw new KinveyError('Unable to retrieve device token.',\n 'You must login a user.');\n }\n\n return this._getOfflineRepo()\n .then(repo => repo.readById(deviceCollectionName, activeUser._id))\n .catch((error) => {\n if (error instanceof NotFoundError) {\n return {} as any;\n }\n\n throw error;\n })\n .then((device) => {\n if (device) {\n return device.token;\n }\n\n return null;\n });\n }\n\n private _saveTokenToCache(token: any): Promise {\n const activeUser = User.getActiveUser(this.client);\n\n if (!activeUser) {\n throw new KinveyError('Unable to save device token.',\n 'You must login a user.');\n }\n\n const device = {\n _id: activeUser._id,\n userId: activeUser._id,\n token: token\n };\n\n return this._getOfflineRepo()\n .then(repo => repo.update(deviceCollectionName, device))\n .then(() => token);\n }\n\n private _deleteTokenFromCache(): Promise {\n const activeUser = User.getActiveUser(this.client);\n\n if (!activeUser) {\n throw new KinveyError('Unable to delete device token.',\n 'You must login a user.');\n }\n\n return this._getOfflineRepo()\n .then((repo) => repo.deleteById(deviceCollectionName, activeUser._id))\n .then(() => null);\n }\n\n private _getOfflineRepo() {\n if (!this._offlineRepoPromise) {\n this._offlineRepoPromise = DataAccess.repositoryProvider.getOfflineRepository();\n }\n return this._offlineRepoPromise;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/push/common.ts","module.exports = require(\"nativescript-push-notifications\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"nativescript-push-notifications\"\n// module id = 582\n// module chunks = 1","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// /home/travis/build/Kinvey/js-sdk/node_modules/node-libs-browser/node_modules/process/browser.js\n// module id = 92\n// module chunks = 0 1"],"sourceRoot":""} --------------------------------------------------------------------------------