1
0
Fork 0
mirror of synced 2024-06-29 03:30:34 +12:00

feat(sdk): release web 4.0.1

This commit is contained in:
Torsten Dittmann 2021-09-20 18:37:24 +02:00
parent f4bdc60df4
commit 1a760ffb95
6 changed files with 194 additions and 146 deletions

View file

@ -15,7 +15,7 @@ return [
[ [
'key' => 'web', 'key' => 'web',
'name' => 'Web', 'name' => 'Web',
'version' => '4.0.1', 'version' => '4.0.2',
'url' => 'https://github.com/appwrite/sdk-for-web', 'url' => 'https://github.com/appwrite/sdk-for-web',
'package' => 'https://www.npmjs.com/package/appwrite', 'package' => 'https://www.npmjs.com/package/appwrite',
'enabled' => true, 'enabled' => true,

View file

@ -64,7 +64,7 @@
"slickdeals/statsd": "3.1.0" "slickdeals/statsd": "3.1.0"
}, },
"require-dev": { "require-dev": {
"appwrite/sdk-generator": "0.14.4", "appwrite/sdk-generator": "0.14.5",
"phpunit/phpunit": "9.5.6", "phpunit/phpunit": "9.5.6",
"swoole/ide-helper": "4.6.7", "swoole/ide-helper": "4.6.7",
"textalk/websocket": "1.5.2", "textalk/websocket": "1.5.2",

100
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "82b47392837605b4fb552e5c9374c4cc", "content-hash": "3acb593da6b69af88e3b527b81929ed4",
"packages": [ "packages": [
{ {
"name": "adhocore/jwt", "name": "adhocore/jwt",
@ -2516,16 +2516,16 @@
}, },
{ {
"name": "appwrite/sdk-generator", "name": "appwrite/sdk-generator",
"version": "0.14.4", "version": "0.14.5",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/appwrite/sdk-generator.git", "url": "https://github.com/appwrite/sdk-generator.git",
"reference": "b89a51170f99e6977df72c46522c7d931257bc28" "reference": "6dfed83fb3aa85304ba86aeb2f1f282b9d8f80e5"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/appwrite/sdk-generator/zipball/b89a51170f99e6977df72c46522c7d931257bc28", "url": "https://api.github.com/repos/appwrite/sdk-generator/zipball/6dfed83fb3aa85304ba86aeb2f1f282b9d8f80e5",
"reference": "b89a51170f99e6977df72c46522c7d931257bc28", "reference": "6dfed83fb3aa85304ba86aeb2f1f282b9d8f80e5",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2559,22 +2559,22 @@
"description": "Appwrite PHP library for generating API SDKs for multiple programming languages and platforms", "description": "Appwrite PHP library for generating API SDKs for multiple programming languages and platforms",
"support": { "support": {
"issues": "https://github.com/appwrite/sdk-generator/issues", "issues": "https://github.com/appwrite/sdk-generator/issues",
"source": "https://github.com/appwrite/sdk-generator/tree/0.14.4" "source": "https://github.com/appwrite/sdk-generator/tree/0.14.5"
}, },
"time": "2021-09-07T13:23:19+00:00" "time": "2021-09-20T16:32:51+00:00"
}, },
{ {
"name": "composer/package-versions-deprecated", "name": "composer/package-versions-deprecated",
"version": "1.11.99.3", "version": "1.11.99.4",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/composer/package-versions-deprecated.git", "url": "https://github.com/composer/package-versions-deprecated.git",
"reference": "fff576ac850c045158a250e7e27666e146e78d18" "reference": "b174585d1fe49ceed21928a945138948cb394600"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/composer/package-versions-deprecated/zipball/fff576ac850c045158a250e7e27666e146e78d18", "url": "https://api.github.com/repos/composer/package-versions-deprecated/zipball/b174585d1fe49ceed21928a945138948cb394600",
"reference": "fff576ac850c045158a250e7e27666e146e78d18", "reference": "b174585d1fe49ceed21928a945138948cb394600",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2618,7 +2618,7 @@
"description": "Composer plugin that provides efficient querying for installed package versions (no runtime IO)", "description": "Composer plugin that provides efficient querying for installed package versions (no runtime IO)",
"support": { "support": {
"issues": "https://github.com/composer/package-versions-deprecated/issues", "issues": "https://github.com/composer/package-versions-deprecated/issues",
"source": "https://github.com/composer/package-versions-deprecated/tree/1.11.99.3" "source": "https://github.com/composer/package-versions-deprecated/tree/1.11.99.4"
}, },
"funding": [ "funding": [
{ {
@ -2634,7 +2634,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2021-08-17T13:49:14+00:00" "time": "2021-09-13T08:41:34+00:00"
}, },
{ {
"name": "composer/semver", "name": "composer/semver",
@ -3230,16 +3230,16 @@
}, },
{ {
"name": "nikic/php-parser", "name": "nikic/php-parser",
"version": "v4.12.0", "version": "v4.13.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/nikic/PHP-Parser.git", "url": "https://github.com/nikic/PHP-Parser.git",
"reference": "6608f01670c3cc5079e18c1dab1104e002579143" "reference": "50953a2691a922aa1769461637869a0a2faa3f53"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/6608f01670c3cc5079e18c1dab1104e002579143", "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/50953a2691a922aa1769461637869a0a2faa3f53",
"reference": "6608f01670c3cc5079e18c1dab1104e002579143", "reference": "50953a2691a922aa1769461637869a0a2faa3f53",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3280,9 +3280,9 @@
], ],
"support": { "support": {
"issues": "https://github.com/nikic/PHP-Parser/issues", "issues": "https://github.com/nikic/PHP-Parser/issues",
"source": "https://github.com/nikic/PHP-Parser/tree/v4.12.0" "source": "https://github.com/nikic/PHP-Parser/tree/v4.13.0"
}, },
"time": "2021-07-21T10:44:31+00:00" "time": "2021-09-20T12:20:58+00:00"
}, },
{ {
"name": "openlss/lib-array2xml", "name": "openlss/lib-array2xml",
@ -3559,16 +3559,16 @@
}, },
{ {
"name": "phpdocumentor/type-resolver", "name": "phpdocumentor/type-resolver",
"version": "1.4.0", "version": "1.5.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpDocumentor/TypeResolver.git", "url": "https://github.com/phpDocumentor/TypeResolver.git",
"reference": "6a467b8989322d92aa1c8bf2bebcc6e5c2ba55c0" "reference": "30f38bffc6f24293dadd1823936372dfa9e86e2f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/6a467b8989322d92aa1c8bf2bebcc6e5c2ba55c0", "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/30f38bffc6f24293dadd1823936372dfa9e86e2f",
"reference": "6a467b8989322d92aa1c8bf2bebcc6e5c2ba55c0", "reference": "30f38bffc6f24293dadd1823936372dfa9e86e2f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3576,7 +3576,8 @@
"phpdocumentor/reflection-common": "^2.0" "phpdocumentor/reflection-common": "^2.0"
}, },
"require-dev": { "require-dev": {
"ext-tokenizer": "*" "ext-tokenizer": "*",
"psalm/phar": "^4.8"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
@ -3602,39 +3603,39 @@
"description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
"support": { "support": {
"issues": "https://github.com/phpDocumentor/TypeResolver/issues", "issues": "https://github.com/phpDocumentor/TypeResolver/issues",
"source": "https://github.com/phpDocumentor/TypeResolver/tree/1.4.0" "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.5.0"
}, },
"time": "2020-09-17T18:55:26+00:00" "time": "2021-09-17T15:28:14+00:00"
}, },
{ {
"name": "phpspec/prophecy", "name": "phpspec/prophecy",
"version": "1.13.0", "version": "1.14.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpspec/prophecy.git", "url": "https://github.com/phpspec/prophecy.git",
"reference": "be1996ed8adc35c3fd795488a653f4b518be70ea" "reference": "d86dfc2e2a3cd366cee475e52c6bb3bbc371aa0e"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/be1996ed8adc35c3fd795488a653f4b518be70ea", "url": "https://api.github.com/repos/phpspec/prophecy/zipball/d86dfc2e2a3cd366cee475e52c6bb3bbc371aa0e",
"reference": "be1996ed8adc35c3fd795488a653f4b518be70ea", "reference": "d86dfc2e2a3cd366cee475e52c6bb3bbc371aa0e",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"doctrine/instantiator": "^1.2", "doctrine/instantiator": "^1.2",
"php": "^7.2 || ~8.0, <8.1", "php": "^7.2 || ~8.0, <8.2",
"phpdocumentor/reflection-docblock": "^5.2", "phpdocumentor/reflection-docblock": "^5.2",
"sebastian/comparator": "^3.0 || ^4.0", "sebastian/comparator": "^3.0 || ^4.0",
"sebastian/recursion-context": "^3.0 || ^4.0" "sebastian/recursion-context": "^3.0 || ^4.0"
}, },
"require-dev": { "require-dev": {
"phpspec/phpspec": "^6.0", "phpspec/phpspec": "^6.0 || ^7.0",
"phpunit/phpunit": "^8.0 || ^9.0" "phpunit/phpunit": "^8.0 || ^9.0"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "1.11.x-dev" "dev-master": "1.x-dev"
} }
}, },
"autoload": { "autoload": {
@ -3669,29 +3670,29 @@
], ],
"support": { "support": {
"issues": "https://github.com/phpspec/prophecy/issues", "issues": "https://github.com/phpspec/prophecy/issues",
"source": "https://github.com/phpspec/prophecy/tree/1.13.0" "source": "https://github.com/phpspec/prophecy/tree/1.14.0"
}, },
"time": "2021-03-17T13:42:18+00:00" "time": "2021-09-10T09:02:12+00:00"
}, },
{ {
"name": "phpunit/php-code-coverage", "name": "phpunit/php-code-coverage",
"version": "9.2.6", "version": "9.2.7",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "f6293e1b30a2354e8428e004689671b83871edde" "reference": "d4c798ed8d51506800b441f7a13ecb0f76f12218"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/f6293e1b30a2354e8428e004689671b83871edde", "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/d4c798ed8d51506800b441f7a13ecb0f76f12218",
"reference": "f6293e1b30a2354e8428e004689671b83871edde", "reference": "d4c798ed8d51506800b441f7a13ecb0f76f12218",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"ext-dom": "*", "ext-dom": "*",
"ext-libxml": "*", "ext-libxml": "*",
"ext-xmlwriter": "*", "ext-xmlwriter": "*",
"nikic/php-parser": "^4.10.2", "nikic/php-parser": "^4.12.0",
"php": ">=7.3", "php": ">=7.3",
"phpunit/php-file-iterator": "^3.0.3", "phpunit/php-file-iterator": "^3.0.3",
"phpunit/php-text-template": "^2.0.2", "phpunit/php-text-template": "^2.0.2",
@ -3740,7 +3741,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.6" "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.7"
}, },
"funding": [ "funding": [
{ {
@ -3748,7 +3749,7 @@
"type": "github" "type": "github"
} }
], ],
"time": "2021-03-28T07:26:59+00:00" "time": "2021-09-17T05:39:03+00:00"
}, },
{ {
"name": "phpunit/php-file-iterator", "name": "phpunit/php-file-iterator",
@ -4995,7 +4996,6 @@
"type": "github" "type": "github"
} }
], ],
"abandoned": true,
"time": "2020-09-28T06:45:17+00:00" "time": "2020-09-28T06:45:17+00:00"
}, },
{ {
@ -5995,16 +5995,16 @@
}, },
{ {
"name": "twig/twig", "name": "twig/twig",
"version": "v2.14.6", "version": "v2.14.7",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/twigphp/Twig.git", "url": "https://github.com/twigphp/Twig.git",
"reference": "27e5cf2b05e3744accf39d4c68a3235d9966d260" "reference": "8e202327ee1ed863629de9b18a5ec70ac614d88f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/twigphp/Twig/zipball/27e5cf2b05e3744accf39d4c68a3235d9966d260", "url": "https://api.github.com/repos/twigphp/Twig/zipball/8e202327ee1ed863629de9b18a5ec70ac614d88f",
"reference": "27e5cf2b05e3744accf39d4c68a3235d9966d260", "reference": "8e202327ee1ed863629de9b18a5ec70ac614d88f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -6014,7 +6014,7 @@
}, },
"require-dev": { "require-dev": {
"psr/container": "^1.0", "psr/container": "^1.0",
"symfony/phpunit-bridge": "^4.4.9|^5.0.9" "symfony/phpunit-bridge": "^4.4.9|^5.0.9|^6.0"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
@ -6058,7 +6058,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/twigphp/Twig/issues", "issues": "https://github.com/twigphp/Twig/issues",
"source": "https://github.com/twigphp/Twig/tree/v2.14.6" "source": "https://github.com/twigphp/Twig/tree/v2.14.7"
}, },
"funding": [ "funding": [
{ {
@ -6070,7 +6070,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2021-05-16T12:12:47+00:00" "time": "2021-09-17T08:39:54+00:00"
}, },
{ {
"name": "vimeo/psalm", "name": "vimeo/psalm",

View file

@ -5,13 +5,14 @@ function rejected(value){try{step(generator["throw"](value));}catch(e){reject(e)
function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);} function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);}
step((generator=generator.apply(thisArg,_arguments||[])).next());});} step((generator=generator.apply(thisArg,_arguments||[])).next());});}
class AppwriteException extends Error{constructor(message,code=0,response=''){super(message);this.name='AppwriteException';this.message=message;this.code=code;this.response=response;}} class AppwriteException extends Error{constructor(message,code=0,response=''){super(message);this.name='AppwriteException';this.message=message;this.code=code;this.response=response;}}
class Appwrite{constructor(){this.config={endpoint:'https://appwrite.io/v1',endpointRealtime:'',project:'',key:'',jwt:'',locale:'',mode:'',};this.headers={'x-sdk-version':'appwrite:web:4.0.1','X-Appwrite-Response-Format':'0.10.0',};this.realtime={socket:undefined,timeout:undefined,channels:{},lastMessage:undefined,createSocket:()=>{var _a,_b;const channels=new URLSearchParams();channels.set('project',this.config.project);for(const property in this.realtime.channels){channels.append('channels[]',property);} class Appwrite{constructor(){this.config={endpoint:'https://appwrite.io/v1',endpointRealtime:'',project:'',key:'',jwt:'',locale:'',mode:'',};this.headers={'x-sdk-version':'appwrite:web:4.0.1','X-Appwrite-Response-Format':'0.10.0',};this.realtime={socket:undefined,timeout:undefined,url:'',channels:new Set(),subscriptions:new Map(),subscriptionsCounter:0,reconnect:true,reconnectAttempts:0,lastMessage:undefined,connect:()=>{clearTimeout(this.realtime.timeout);this.realtime.timeout=window===null||window===void 0?void 0:window.setTimeout(()=>{this.realtime.createSocket();},50);},getTimeout:()=>{switch(true){case this.realtime.reconnectAttempts<5:return 1000;case this.realtime.reconnectAttempts<15:return 5000;case this.realtime.reconnectAttempts<100:return 10000;default:return 60000;}},createSocket:()=>{var _a,_b;if(this.realtime.channels.size<1)
if(((_a=this.realtime.socket)===null||_a===void 0?void 0:_a.readyState)===WebSocket.OPEN){this.realtime.socket.close();} return;const channels=new URLSearchParams();channels.set('project',this.config.project);this.realtime.channels.forEach(channel=>{channels.append('channels[]',channel);});const url=this.config.endpointRealtime+'/realtime?'+channels.toString();if(url!==this.realtime.url||!this.realtime.socket||((_a=this.realtime.socket)===null||_a===void 0?void 0:_a.readyState)>WebSocket.OPEN){if(this.realtime.socket&&((_b=this.realtime.socket)===null||_b===void 0?void 0:_b.readyState)<WebSocket.CLOSING){this.realtime.reconnect=false;this.realtime.socket.close();}
this.realtime.socket=new WebSocket(this.config.endpointRealtime+'/realtime?'+channels.toString());(_b=this.realtime.socket)===null||_b===void 0?void 0:_b.addEventListener('message',this.realtime.authenticate);for(const channel in this.realtime.channels){this.realtime.channels[channel].forEach(callback=>{var _a;(_a=this.realtime.socket)===null||_a===void 0?void 0:_a.addEventListener('message',callback);});} this.realtime.url=url;this.realtime.socket=new WebSocket(url);this.realtime.socket.addEventListener('message',this.realtime.onMessage);this.realtime.socket.addEventListener('open',_event=>{this.realtime.reconnectAttempts=0;});this.realtime.socket.addEventListener('close',event=>{var _a,_b,_c;if(!this.realtime.reconnect||(((_b=(_a=this.realtime)===null||_a===void 0?void 0:_a.lastMessage)===null||_b===void 0?void 0:_b.type)==='error'&&((_c=this.realtime)===null||_c===void 0?void 0:_c.lastMessage.data).code===1008)){this.realtime.reconnect=true;return;}
this.realtime.socket.addEventListener('close',event=>{var _a,_b,_c;if(((_b=(_a=this.realtime)===null||_a===void 0?void 0:_a.lastMessage)===null||_b===void 0?void 0:_b.type)==='error'&&((_c=this.realtime)===null||_c===void 0?void 0:_c.lastMessage.data).code===1008){return;} const timeout=this.realtime.getTimeout();console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`,event.reason);setTimeout(()=>{this.realtime.reconnectAttempts++;this.realtime.createSocket();},timeout);});}},onMessage:(event)=>{var _a,_b;try{const message=JSON.parse(event.data);this.realtime.lastMessage=message;switch(message.type){case'connected':const cookie=JSON.parse((_a=window.localStorage.getItem('cookieFallback'))!==null&&_a!==void 0?_a:'{}');const session=cookie===null||cookie===void 0?void 0:cookie[`a_session_${this.config.project}`];const messageData=message.data;if(session&&!messageData.user){(_b=this.realtime.socket)===null||_b===void 0?void 0:_b.send(JSON.stringify({type:'authentication',data:{session}}));}
console.error('Realtime got disconnected. Reconnect will be attempted in 1 second.',event.reason);setTimeout(()=>{this.realtime.createSocket();},1000);});},authenticate:(event)=>{var _a,_b,_c;const message=JSON.parse(event.data);if(message.type==='connected'&&((_a=this.realtime.socket)===null||_a===void 0?void 0:_a.readyState)===WebSocket.OPEN){const cookie=JSON.parse((_b=window.localStorage.getItem('cookieFallback'))!==null&&_b!==void 0?_b:"{}");const session=cookie===null||cookie===void 0?void 0:cookie[`a_session_${this.config.project}`];const data=message.data;if(session&&!data.user){(_c=this.realtime.socket)===null||_c===void 0?void 0:_c.send(JSON.stringify({type:"authentication",data:{session}}));}}},onMessage:(channel,callback)=>(event)=>{try{const message=JSON.parse(event.data);this.realtime.lastMessage=message;if(message.type==='event'){let data=message.data;if(data.channels&&data.channels.includes(channel)){callback(data);}} break;case'event':let data=message.data;if(data===null||data===void 0?void 0:data.channels){const isSubscribed=data.channels.some(channel=>this.realtime.channels.has(channel));if(!isSubscribed)
else if(message.type==='error'){throw message.data;}} return;this.realtime.subscriptions.forEach(subscription=>{if(data.channels.some(channel=>subscription.channels.includes(channel))){setTimeout(()=>subscription.callback(data));}});}
catch(e){console.error(e);}}};this.account={get:()=>__awaiter(this,void 0,void 0,function*(){let path='/account';let payload={};const uri=new URL(this.config.endpoint+path);return yield this.call('get',uri,{'content-type':'application/json',},payload);}),create:(email,password,name)=>__awaiter(this,void 0,void 0,function*(){if(typeof email==='undefined'){throw new AppwriteException('Missing required parameter: "email"');} break;case'error':throw message.data;default:break;}}
catch(e){console.error(e);}},cleanUp:channels=>{this.realtime.channels.forEach(channel=>{if(channels.includes(channel)){let found=Array.from(this.realtime.subscriptions).some(([_key,subscription])=>{return subscription.channels.includes(channel);});if(!found){this.realtime.channels.delete(channel);}}});}};this.account={get:()=>__awaiter(this,void 0,void 0,function*(){let path='/account';let payload={};const uri=new URL(this.config.endpoint+path);return yield this.call('get',uri,{'content-type':'application/json',},payload);}),create:(email,password,name)=>__awaiter(this,void 0,void 0,function*(){if(typeof email==='undefined'){throw new AppwriteException('Missing required parameter: "email"');}
if(typeof password==='undefined'){throw new AppwriteException('Missing required parameter: "password"');} if(typeof password==='undefined'){throw new AppwriteException('Missing required parameter: "password"');}
let path='/account';let payload={};if(typeof email!=='undefined'){payload['email']=email;} let path='/account';let payload={};if(typeof email!=='undefined'){payload['email']=email;}
if(typeof password!=='undefined'){payload['password']=password;} if(typeof password!=='undefined'){payload['password']=password;}
@ -462,21 +463,20 @@ const uri=new URL(this.config.endpoint+path);return yield this.call('patch',uri,
if(typeof emailVerification==='undefined'){throw new AppwriteException('Missing required parameter: "emailVerification"');} if(typeof emailVerification==='undefined'){throw new AppwriteException('Missing required parameter: "emailVerification"');}
let path='/users/{userId}/verification'.replace('{userId}',userId);let payload={};if(typeof emailVerification!=='undefined'){payload['emailVerification']=emailVerification;} let path='/users/{userId}/verification'.replace('{userId}',userId);let payload={};if(typeof emailVerification!=='undefined'){payload['emailVerification']=emailVerification;}
const uri=new URL(this.config.endpoint+path);return yield this.call('patch',uri,{'content-type':'application/json',},payload);})};} const uri=new URL(this.config.endpoint+path);return yield this.call('patch',uri,{'content-type':'application/json',},payload);})};}
setEndpoint(endpoint){this.config.endpoint=endpoint;this.config.endpointRealtime=this.config.endpointRealtime||this.config.endpoint.replace("https://","wss://").replace("http://","ws://");return this;} setEndpoint(endpoint){this.config.endpoint=endpoint;this.config.endpointRealtime=this.config.endpointRealtime||this.config.endpoint.replace('https://','wss://').replace('http://','ws://');return this;}
setEndpointRealtime(endpointRealtime){this.config.endpointRealtime=endpointRealtime;return this;} setEndpointRealtime(endpointRealtime){this.config.endpointRealtime=endpointRealtime;return this;}
setProject(value){this.headers['X-Appwrite-Project']=value;this.config.project=value;return this;} setProject(value){this.headers['X-Appwrite-Project']=value;this.config.project=value;return this;}
setKey(value){this.headers['X-Appwrite-Key']=value;this.config.key=value;return this;} setKey(value){this.headers['X-Appwrite-Key']=value;this.config.key=value;return this;}
setJWT(value){this.headers['X-Appwrite-JWT']=value;this.config.jwt=value;return this;} setJWT(value){this.headers['X-Appwrite-JWT']=value;this.config.jwt=value;return this;}
setLocale(value){this.headers['X-Appwrite-Locale']=value;this.config.locale=value;return this;} setLocale(value){this.headers['X-Appwrite-Locale']=value;this.config.locale=value;return this;}
setMode(value){this.headers['X-Appwrite-Mode']=value;this.config.mode=value;return this;} setMode(value){this.headers['X-Appwrite-Mode']=value;this.config.mode=value;return this;}
subscribe(channels,callback){let channelArray=typeof channels==='string'?[channels]:channels;let savedChannels=[];channelArray.forEach((channel,index)=>{if(!(channel in this.realtime.channels)){this.realtime.channels[channel]=[];} subscribe(channels,callback){let channelArray=typeof channels==='string'?[channels]:channels;channelArray.forEach(channel=>this.realtime.channels.add(channel));const counter=this.realtime.subscriptionsCounter++;this.realtime.subscriptions.set(counter,{channels:channelArray,callback});this.realtime.connect();return()=>{this.realtime.subscriptions.delete(counter);this.realtime.cleanUp(channelArray);this.realtime.connect();};}
savedChannels[index]={name:channel,index:(this.realtime.channels[channel].push(this.realtime.onMessage(channel,callback))-1)};clearTimeout(this.realtime.timeout);this.realtime.timeout=window===null||window===void 0?void 0:window.setTimeout(()=>{this.realtime.createSocket();},1);});return()=>{savedChannels.forEach(channel=>{var _a;(_a=this.realtime.socket)===null||_a===void 0?void 0:_a.removeEventListener('message',this.realtime.channels[channel.name][channel.index]);this.realtime.channels[channel.name].splice(channel.index,1);});};} call(method,url,headers={},params={}){var _a,_b;return __awaiter(this,void 0,void 0,function*(){method=method.toUpperCase();headers=Object.assign(Object.assign({},headers),this.headers);let options={method,headers,credentials:'include'};if(typeof window!=='undefined'&&window.localStorage){headers['X-Fallback-Cookies']=(_a=window.localStorage.getItem('cookieFallback'))!==null&&_a!==void 0?_a:'';}
call(method,url,headers={},params={}){var _a,_b;return __awaiter(this,void 0,void 0,function*(){method=method.toUpperCase();headers=Object.assign(Object.assign({},headers),this.headers);let options={method,headers,credentials:'include'};if(typeof window!=='undefined'&&window.localStorage){headers['X-Fallback-Cookies']=(_a=window.localStorage.getItem('cookieFallback'))!==null&&_a!==void 0?_a:"";}
if(method==='GET'){for(const[key,value]of Object.entries(this.flatten(params))){url.searchParams.append(key,value);}} if(method==='GET'){for(const[key,value]of Object.entries(this.flatten(params))){url.searchParams.append(key,value);}}
else{switch(headers['content-type']){case'application/json':options.body=JSON.stringify(params);break;case'multipart/form-data':let formData=new FormData();for(const key in params){if(Array.isArray(params[key])){formData.append(key+'[]',params[key].join(','));} else{switch(headers['content-type']){case'application/json':options.body=JSON.stringify(params);break;case'multipart/form-data':let formData=new FormData();for(const key in params){if(Array.isArray(params[key])){formData.append(key+'[]',params[key].join(','));}
else{formData.append(key,params[key]);}} else{formData.append(key,params[key]);}}
options.body=formData;delete headers['content-type'];break;}} options.body=formData;delete headers['content-type'];break;}}
try{let data=null;const response=yield crossFetch.fetch(url.toString(),options);if((_b=response.headers.get("content-type"))===null||_b===void 0?void 0:_b.includes("application/json")){data=yield response.json();} try{let data=null;const response=yield crossFetch.fetch(url.toString(),options);if((_b=response.headers.get('content-type'))===null||_b===void 0?void 0:_b.includes('application/json')){data=yield response.json();}
else{data={message:yield response.text()};} else{data={message:yield response.text()};}
if(400<=response.status){throw new AppwriteException(data===null||data===void 0?void 0:data.message,response.status,data);} if(400<=response.status){throw new AppwriteException(data===null||data===void 0?void 0:data.message,response.status,data);}
const cookieFallback=response.headers.get('X-Fallback-Cookies');if(typeof window!=='undefined'&&window.localStorage&&cookieFallback){window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.');window.localStorage.setItem('cookieFallback',cookieFallback);} const cookieFallback=response.headers.get('X-Fallback-Cookies');if(typeof window!=='undefined'&&window.localStorage&&cookieFallback){window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.');window.localStorage.setItem('cookieFallback',cookieFallback);}

View file

@ -5,13 +5,14 @@ function rejected(value){try{step(generator["throw"](value));}catch(e){reject(e)
function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);} function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);}
step((generator=generator.apply(thisArg,_arguments||[])).next());});} step((generator=generator.apply(thisArg,_arguments||[])).next());});}
class AppwriteException extends Error{constructor(message,code=0,response=''){super(message);this.name='AppwriteException';this.message=message;this.code=code;this.response=response;}} class AppwriteException extends Error{constructor(message,code=0,response=''){super(message);this.name='AppwriteException';this.message=message;this.code=code;this.response=response;}}
class Appwrite{constructor(){this.config={endpoint:'https://appwrite.io/v1',endpointRealtime:'',project:'',key:'',jwt:'',locale:'',mode:'',};this.headers={'x-sdk-version':'appwrite:web:4.0.1','X-Appwrite-Response-Format':'0.10.0',};this.realtime={socket:undefined,timeout:undefined,channels:{},lastMessage:undefined,createSocket:()=>{var _a,_b;const channels=new URLSearchParams();channels.set('project',this.config.project);for(const property in this.realtime.channels){channels.append('channels[]',property);} class Appwrite{constructor(){this.config={endpoint:'https://appwrite.io/v1',endpointRealtime:'',project:'',key:'',jwt:'',locale:'',mode:'',};this.headers={'x-sdk-version':'appwrite:web:4.0.1','X-Appwrite-Response-Format':'0.10.0',};this.realtime={socket:undefined,timeout:undefined,url:'',channels:new Set(),subscriptions:new Map(),subscriptionsCounter:0,reconnect:true,reconnectAttempts:0,lastMessage:undefined,connect:()=>{clearTimeout(this.realtime.timeout);this.realtime.timeout=window===null||window===void 0?void 0:window.setTimeout(()=>{this.realtime.createSocket();},50);},getTimeout:()=>{switch(true){case this.realtime.reconnectAttempts<5:return 1000;case this.realtime.reconnectAttempts<15:return 5000;case this.realtime.reconnectAttempts<100:return 10000;default:return 60000;}},createSocket:()=>{var _a,_b;if(this.realtime.channels.size<1)
if(((_a=this.realtime.socket)===null||_a===void 0?void 0:_a.readyState)===WebSocket.OPEN){this.realtime.socket.close();} return;const channels=new URLSearchParams();channels.set('project',this.config.project);this.realtime.channels.forEach(channel=>{channels.append('channels[]',channel);});const url=this.config.endpointRealtime+'/realtime?'+channels.toString();if(url!==this.realtime.url||!this.realtime.socket||((_a=this.realtime.socket)===null||_a===void 0?void 0:_a.readyState)>WebSocket.OPEN){if(this.realtime.socket&&((_b=this.realtime.socket)===null||_b===void 0?void 0:_b.readyState)<WebSocket.CLOSING){this.realtime.reconnect=false;this.realtime.socket.close();}
this.realtime.socket=new WebSocket(this.config.endpointRealtime+'/realtime?'+channels.toString());(_b=this.realtime.socket)===null||_b===void 0?void 0:_b.addEventListener('message',this.realtime.authenticate);for(const channel in this.realtime.channels){this.realtime.channels[channel].forEach(callback=>{var _a;(_a=this.realtime.socket)===null||_a===void 0?void 0:_a.addEventListener('message',callback);});} this.realtime.url=url;this.realtime.socket=new WebSocket(url);this.realtime.socket.addEventListener('message',this.realtime.onMessage);this.realtime.socket.addEventListener('open',_event=>{this.realtime.reconnectAttempts=0;});this.realtime.socket.addEventListener('close',event=>{var _a,_b,_c;if(!this.realtime.reconnect||(((_b=(_a=this.realtime)===null||_a===void 0?void 0:_a.lastMessage)===null||_b===void 0?void 0:_b.type)==='error'&&((_c=this.realtime)===null||_c===void 0?void 0:_c.lastMessage.data).code===1008)){this.realtime.reconnect=true;return;}
this.realtime.socket.addEventListener('close',event=>{var _a,_b,_c;if(((_b=(_a=this.realtime)===null||_a===void 0?void 0:_a.lastMessage)===null||_b===void 0?void 0:_b.type)==='error'&&((_c=this.realtime)===null||_c===void 0?void 0:_c.lastMessage.data).code===1008){return;} const timeout=this.realtime.getTimeout();console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`,event.reason);setTimeout(()=>{this.realtime.reconnectAttempts++;this.realtime.createSocket();},timeout);});}},onMessage:(event)=>{var _a,_b;try{const message=JSON.parse(event.data);this.realtime.lastMessage=message;switch(message.type){case'connected':const cookie=JSON.parse((_a=window.localStorage.getItem('cookieFallback'))!==null&&_a!==void 0?_a:'{}');const session=cookie===null||cookie===void 0?void 0:cookie[`a_session_${this.config.project}`];const messageData=message.data;if(session&&!messageData.user){(_b=this.realtime.socket)===null||_b===void 0?void 0:_b.send(JSON.stringify({type:'authentication',data:{session}}));}
console.error('Realtime got disconnected. Reconnect will be attempted in 1 second.',event.reason);setTimeout(()=>{this.realtime.createSocket();},1000);});},authenticate:(event)=>{var _a,_b,_c;const message=JSON.parse(event.data);if(message.type==='connected'&&((_a=this.realtime.socket)===null||_a===void 0?void 0:_a.readyState)===WebSocket.OPEN){const cookie=JSON.parse((_b=window.localStorage.getItem('cookieFallback'))!==null&&_b!==void 0?_b:"{}");const session=cookie===null||cookie===void 0?void 0:cookie[`a_session_${this.config.project}`];const data=message.data;if(session&&!data.user){(_c=this.realtime.socket)===null||_c===void 0?void 0:_c.send(JSON.stringify({type:"authentication",data:{session}}));}}},onMessage:(channel,callback)=>(event)=>{try{const message=JSON.parse(event.data);this.realtime.lastMessage=message;if(message.type==='event'){let data=message.data;if(data.channels&&data.channels.includes(channel)){callback(data);}} break;case'event':let data=message.data;if(data===null||data===void 0?void 0:data.channels){const isSubscribed=data.channels.some(channel=>this.realtime.channels.has(channel));if(!isSubscribed)
else if(message.type==='error'){throw message.data;}} return;this.realtime.subscriptions.forEach(subscription=>{if(data.channels.some(channel=>subscription.channels.includes(channel))){setTimeout(()=>subscription.callback(data));}});}
catch(e){console.error(e);}}};this.account={get:()=>__awaiter(this,void 0,void 0,function*(){let path='/account';let payload={};const uri=new URL(this.config.endpoint+path);return yield this.call('get',uri,{'content-type':'application/json',},payload);}),create:(email,password,name)=>__awaiter(this,void 0,void 0,function*(){if(typeof email==='undefined'){throw new AppwriteException('Missing required parameter: "email"');} break;case'error':throw message.data;default:break;}}
catch(e){console.error(e);}},cleanUp:channels=>{this.realtime.channels.forEach(channel=>{if(channels.includes(channel)){let found=Array.from(this.realtime.subscriptions).some(([_key,subscription])=>{return subscription.channels.includes(channel);});if(!found){this.realtime.channels.delete(channel);}}});}};this.account={get:()=>__awaiter(this,void 0,void 0,function*(){let path='/account';let payload={};const uri=new URL(this.config.endpoint+path);return yield this.call('get',uri,{'content-type':'application/json',},payload);}),create:(email,password,name)=>__awaiter(this,void 0,void 0,function*(){if(typeof email==='undefined'){throw new AppwriteException('Missing required parameter: "email"');}
if(typeof password==='undefined'){throw new AppwriteException('Missing required parameter: "password"');} if(typeof password==='undefined'){throw new AppwriteException('Missing required parameter: "password"');}
let path='/account';let payload={};if(typeof email!=='undefined'){payload['email']=email;} let path='/account';let payload={};if(typeof email!=='undefined'){payload['email']=email;}
if(typeof password!=='undefined'){payload['password']=password;} if(typeof password!=='undefined'){payload['password']=password;}
@ -462,21 +463,20 @@ const uri=new URL(this.config.endpoint+path);return yield this.call('patch',uri,
if(typeof emailVerification==='undefined'){throw new AppwriteException('Missing required parameter: "emailVerification"');} if(typeof emailVerification==='undefined'){throw new AppwriteException('Missing required parameter: "emailVerification"');}
let path='/users/{userId}/verification'.replace('{userId}',userId);let payload={};if(typeof emailVerification!=='undefined'){payload['emailVerification']=emailVerification;} let path='/users/{userId}/verification'.replace('{userId}',userId);let payload={};if(typeof emailVerification!=='undefined'){payload['emailVerification']=emailVerification;}
const uri=new URL(this.config.endpoint+path);return yield this.call('patch',uri,{'content-type':'application/json',},payload);})};} const uri=new URL(this.config.endpoint+path);return yield this.call('patch',uri,{'content-type':'application/json',},payload);})};}
setEndpoint(endpoint){this.config.endpoint=endpoint;this.config.endpointRealtime=this.config.endpointRealtime||this.config.endpoint.replace("https://","wss://").replace("http://","ws://");return this;} setEndpoint(endpoint){this.config.endpoint=endpoint;this.config.endpointRealtime=this.config.endpointRealtime||this.config.endpoint.replace('https://','wss://').replace('http://','ws://');return this;}
setEndpointRealtime(endpointRealtime){this.config.endpointRealtime=endpointRealtime;return this;} setEndpointRealtime(endpointRealtime){this.config.endpointRealtime=endpointRealtime;return this;}
setProject(value){this.headers['X-Appwrite-Project']=value;this.config.project=value;return this;} setProject(value){this.headers['X-Appwrite-Project']=value;this.config.project=value;return this;}
setKey(value){this.headers['X-Appwrite-Key']=value;this.config.key=value;return this;} setKey(value){this.headers['X-Appwrite-Key']=value;this.config.key=value;return this;}
setJWT(value){this.headers['X-Appwrite-JWT']=value;this.config.jwt=value;return this;} setJWT(value){this.headers['X-Appwrite-JWT']=value;this.config.jwt=value;return this;}
setLocale(value){this.headers['X-Appwrite-Locale']=value;this.config.locale=value;return this;} setLocale(value){this.headers['X-Appwrite-Locale']=value;this.config.locale=value;return this;}
setMode(value){this.headers['X-Appwrite-Mode']=value;this.config.mode=value;return this;} setMode(value){this.headers['X-Appwrite-Mode']=value;this.config.mode=value;return this;}
subscribe(channels,callback){let channelArray=typeof channels==='string'?[channels]:channels;let savedChannels=[];channelArray.forEach((channel,index)=>{if(!(channel in this.realtime.channels)){this.realtime.channels[channel]=[];} subscribe(channels,callback){let channelArray=typeof channels==='string'?[channels]:channels;channelArray.forEach(channel=>this.realtime.channels.add(channel));const counter=this.realtime.subscriptionsCounter++;this.realtime.subscriptions.set(counter,{channels:channelArray,callback});this.realtime.connect();return()=>{this.realtime.subscriptions.delete(counter);this.realtime.cleanUp(channelArray);this.realtime.connect();};}
savedChannels[index]={name:channel,index:(this.realtime.channels[channel].push(this.realtime.onMessage(channel,callback))-1)};clearTimeout(this.realtime.timeout);this.realtime.timeout=window===null||window===void 0?void 0:window.setTimeout(()=>{this.realtime.createSocket();},1);});return()=>{savedChannels.forEach(channel=>{var _a;(_a=this.realtime.socket)===null||_a===void 0?void 0:_a.removeEventListener('message',this.realtime.channels[channel.name][channel.index]);this.realtime.channels[channel.name].splice(channel.index,1);});};} call(method,url,headers={},params={}){var _a,_b;return __awaiter(this,void 0,void 0,function*(){method=method.toUpperCase();headers=Object.assign(Object.assign({},headers),this.headers);let options={method,headers,credentials:'include'};if(typeof window!=='undefined'&&window.localStorage){headers['X-Fallback-Cookies']=(_a=window.localStorage.getItem('cookieFallback'))!==null&&_a!==void 0?_a:'';}
call(method,url,headers={},params={}){var _a,_b;return __awaiter(this,void 0,void 0,function*(){method=method.toUpperCase();headers=Object.assign(Object.assign({},headers),this.headers);let options={method,headers,credentials:'include'};if(typeof window!=='undefined'&&window.localStorage){headers['X-Fallback-Cookies']=(_a=window.localStorage.getItem('cookieFallback'))!==null&&_a!==void 0?_a:"";}
if(method==='GET'){for(const[key,value]of Object.entries(this.flatten(params))){url.searchParams.append(key,value);}} if(method==='GET'){for(const[key,value]of Object.entries(this.flatten(params))){url.searchParams.append(key,value);}}
else{switch(headers['content-type']){case'application/json':options.body=JSON.stringify(params);break;case'multipart/form-data':let formData=new FormData();for(const key in params){if(Array.isArray(params[key])){formData.append(key+'[]',params[key].join(','));} else{switch(headers['content-type']){case'application/json':options.body=JSON.stringify(params);break;case'multipart/form-data':let formData=new FormData();for(const key in params){if(Array.isArray(params[key])){formData.append(key+'[]',params[key].join(','));}
else{formData.append(key,params[key]);}} else{formData.append(key,params[key]);}}
options.body=formData;delete headers['content-type'];break;}} options.body=formData;delete headers['content-type'];break;}}
try{let data=null;const response=yield crossFetch.fetch(url.toString(),options);if((_b=response.headers.get("content-type"))===null||_b===void 0?void 0:_b.includes("application/json")){data=yield response.json();} try{let data=null;const response=yield crossFetch.fetch(url.toString(),options);if((_b=response.headers.get('content-type'))===null||_b===void 0?void 0:_b.includes('application/json')){data=yield response.json();}
else{data={message:yield response.text()};} else{data={message:yield response.text()};}
if(400<=response.status){throw new AppwriteException(data===null||data===void 0?void 0:data.message,response.status,data);} if(400<=response.status){throw new AppwriteException(data===null||data===void 0?void 0:data.message,response.status,data);}
const cookieFallback=response.headers.get('X-Fallback-Cookies');if(typeof window!=='undefined'&&window.localStorage&&cookieFallback){window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.');window.localStorage.setItem('cookieFallback',cookieFallback);} const cookieFallback=response.headers.get('X-Fallback-Cookies');if(typeof window!=='undefined'&&window.localStorage&&cookieFallback){window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.');window.localStorage.setItem('cookieFallback',cookieFallback);}

View file

@ -53,71 +53,128 @@
this.realtime = { this.realtime = {
socket: undefined, socket: undefined,
timeout: undefined, timeout: undefined,
channels: {}, url: '',
channels: new Set(),
subscriptions: new Map(),
subscriptionsCounter: 0,
reconnect: true,
reconnectAttempts: 0,
lastMessage: undefined, lastMessage: undefined,
connect: () => {
clearTimeout(this.realtime.timeout);
this.realtime.timeout = window === null || window === void 0 ? void 0 : window.setTimeout(() => {
this.realtime.createSocket();
}, 50);
},
getTimeout: () => {
switch (true) {
case this.realtime.reconnectAttempts < 5:
return 1000;
case this.realtime.reconnectAttempts < 15:
return 5000;
case this.realtime.reconnectAttempts < 100:
return 10000;
default:
return 60000;
}
},
createSocket: () => { createSocket: () => {
var _a, _b; var _a, _b;
if (this.realtime.channels.size < 1)
return;
const channels = new URLSearchParams(); const channels = new URLSearchParams();
channels.set('project', this.config.project); channels.set('project', this.config.project);
for (const property in this.realtime.channels) { this.realtime.channels.forEach(channel => {
channels.append('channels[]', property); channels.append('channels[]', channel);
} });
if (((_a = this.realtime.socket) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) { const url = this.config.endpointRealtime + '/realtime?' + channels.toString();
this.realtime.socket.close(); if (url !== this.realtime.url || // Check if URL is present
} !this.realtime.socket || // Check if WebSocket has not been created
this.realtime.socket = new WebSocket(this.config.endpointRealtime + '/realtime?' + channels.toString()); ((_a = this.realtime.socket) === null || _a === void 0 ? void 0 : _a.readyState) > WebSocket.OPEN // Check if WebSocket is CLOSING (3) or CLOSED (4)
(_b = this.realtime.socket) === null || _b === void 0 ? void 0 : _b.addEventListener('message', this.realtime.authenticate); ) {
for (const channel in this.realtime.channels) { if (this.realtime.socket &&
this.realtime.channels[channel].forEach(callback => { ((_b = this.realtime.socket) === null || _b === void 0 ? void 0 : _b.readyState) < WebSocket.CLOSING // Close WebSocket if it is CONNECTING (0) or OPEN (1)
var _a; ) {
(_a = this.realtime.socket) === null || _a === void 0 ? void 0 : _a.addEventListener('message', callback); this.realtime.reconnect = false;
this.realtime.socket.close();
}
this.realtime.url = url;
this.realtime.socket = new WebSocket(url);
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
this.realtime.socket.addEventListener('open', _event => {
this.realtime.reconnectAttempts = 0;
});
this.realtime.socket.addEventListener('close', event => {
var _a, _b, _c;
if (!this.realtime.reconnect ||
(((_b = (_a = this.realtime) === null || _a === void 0 ? void 0 : _a.lastMessage) === null || _b === void 0 ? void 0 : _b.type) === 'error' && // Check if last message was of type error
((_c = this.realtime) === null || _c === void 0 ? void 0 : _c.lastMessage.data).code === 1008 // Check for policy violation 1008
)) {
this.realtime.reconnect = true;
return;
}
const timeout = this.realtime.getTimeout();
console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`, event.reason);
setTimeout(() => {
this.realtime.reconnectAttempts++;
this.realtime.createSocket();
}, timeout);
}); });
} }
this.realtime.socket.addEventListener('close', event => {
var _a, _b, _c;
if (((_b = (_a = this.realtime) === null || _a === void 0 ? void 0 : _a.lastMessage) === null || _b === void 0 ? void 0 : _b.type) === 'error' && ((_c = this.realtime) === null || _c === void 0 ? void 0 : _c.lastMessage.data).code === 1008) {
return;
}
console.error('Realtime got disconnected. Reconnect will be attempted in 1 second.', event.reason);
setTimeout(() => {
this.realtime.createSocket();
}, 1000);
});
}, },
authenticate: (event) => { onMessage: (event) => {
var _a, _b, _c; var _a, _b;
const message = JSON.parse(event.data);
if (message.type === 'connected' && ((_a = this.realtime.socket) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
const cookie = JSON.parse((_b = window.localStorage.getItem('cookieFallback')) !== null && _b !== void 0 ? _b : "{}");
const session = cookie === null || cookie === void 0 ? void 0 : cookie[`a_session_${this.config.project}`];
const data = message.data;
if (session && !data.user) {
(_c = this.realtime.socket) === null || _c === void 0 ? void 0 : _c.send(JSON.stringify({
type: "authentication",
data: {
session
}
}));
}
}
},
onMessage: (channel, callback) => (event) => {
try { try {
const message = JSON.parse(event.data); const message = JSON.parse(event.data);
this.realtime.lastMessage = message; this.realtime.lastMessage = message;
if (message.type === 'event') { switch (message.type) {
let data = message.data; case 'connected':
if (data.channels && data.channels.includes(channel)) { const cookie = JSON.parse((_a = window.localStorage.getItem('cookieFallback')) !== null && _a !== void 0 ? _a : '{}');
callback(data); const session = cookie === null || cookie === void 0 ? void 0 : cookie[`a_session_${this.config.project}`];
} const messageData = message.data;
} if (session && !messageData.user) {
else if (message.type === 'error') { (_b = this.realtime.socket) === null || _b === void 0 ? void 0 : _b.send(JSON.stringify({
throw message.data; type: 'authentication',
data: {
session
}
}));
}
break;
case 'event':
let data = message.data;
if (data === null || data === void 0 ? void 0 : data.channels) {
const isSubscribed = data.channels.some(channel => this.realtime.channels.has(channel));
if (!isSubscribed)
return;
this.realtime.subscriptions.forEach(subscription => {
if (data.channels.some(channel => subscription.channels.includes(channel))) {
setTimeout(() => subscription.callback(data));
}
});
}
break;
case 'error':
throw message.data;
default:
break;
} }
} }
catch (e) { catch (e) {
console.error(e); console.error(e);
} }
},
cleanUp: channels => {
this.realtime.channels.forEach(channel => {
if (channels.includes(channel)) {
let found = Array.from(this.realtime.subscriptions).some(([_key, subscription]) => {
return subscription.channels.includes(channel);
});
if (!found) {
this.realtime.channels.delete(channel);
}
}
});
} }
}; };
this.account = { this.account = {
@ -4264,7 +4321,7 @@
*/ */
setEndpoint(endpoint) { setEndpoint(endpoint) {
this.config.endpoint = endpoint; this.config.endpoint = endpoint;
this.config.endpointRealtime = this.config.endpointRealtime || this.config.endpoint.replace("https://", "wss://").replace("http://", "ws://"); this.config.endpointRealtime = this.config.endpointRealtime || this.config.endpoint.replace('https://', 'wss://').replace('http://', 'ws://');
return this; return this;
} }
/** /**
@ -4371,26 +4428,17 @@
*/ */
subscribe(channels, callback) { subscribe(channels, callback) {
let channelArray = typeof channels === 'string' ? [channels] : channels; let channelArray = typeof channels === 'string' ? [channels] : channels;
let savedChannels = []; channelArray.forEach(channel => this.realtime.channels.add(channel));
channelArray.forEach((channel, index) => { const counter = this.realtime.subscriptionsCounter++;
if (!(channel in this.realtime.channels)) { this.realtime.subscriptions.set(counter, {
this.realtime.channels[channel] = []; channels: channelArray,
} callback
savedChannels[index] = {
name: channel,
index: (this.realtime.channels[channel].push(this.realtime.onMessage(channel, callback)) - 1)
};
clearTimeout(this.realtime.timeout);
this.realtime.timeout = window === null || window === void 0 ? void 0 : window.setTimeout(() => {
this.realtime.createSocket();
}, 1);
}); });
this.realtime.connect();
return () => { return () => {
savedChannels.forEach(channel => { this.realtime.subscriptions.delete(counter);
var _a; this.realtime.cleanUp(channelArray);
(_a = this.realtime.socket) === null || _a === void 0 ? void 0 : _a.removeEventListener('message', this.realtime.channels[channel.name][channel.index]); this.realtime.connect();
this.realtime.channels[channel.name].splice(channel.index, 1);
});
}; };
} }
call(method, url, headers = {}, params = {}) { call(method, url, headers = {}, params = {}) {
@ -4404,7 +4452,7 @@
credentials: 'include' credentials: 'include'
}; };
if (typeof window !== 'undefined' && window.localStorage) { if (typeof window !== 'undefined' && window.localStorage) {
headers['X-Fallback-Cookies'] = (_a = window.localStorage.getItem('cookieFallback')) !== null && _a !== void 0 ? _a : ""; headers['X-Fallback-Cookies'] = (_a = window.localStorage.getItem('cookieFallback')) !== null && _a !== void 0 ? _a : '';
} }
if (method === 'GET') { if (method === 'GET') {
for (const [key, value] of Object.entries(this.flatten(params))) { for (const [key, value] of Object.entries(this.flatten(params))) {
@ -4434,7 +4482,7 @@
try { try {
let data = null; let data = null;
const response = yield crossFetch.fetch(url.toString(), options); const response = yield crossFetch.fetch(url.toString(), options);
if ((_b = response.headers.get("content-type")) === null || _b === void 0 ? void 0 : _b.includes("application/json")) { if ((_b = response.headers.get('content-type')) === null || _b === void 0 ? void 0 : _b.includes('application/json')) {
data = yield response.json(); data = yield response.json();
} }
else { else {