├── .gitignore ├── README.md ├── dist ├── main │ ├── index.d.ts │ ├── index.d.ts.map │ ├── index.js │ └── index.js.map ├── module │ ├── index.d.ts │ ├── index.d.ts.map │ ├── index.js │ └── index.js.map └── umd │ └── supascriptconsole.js ├── docs ├── sample_chome_console_details.png └── sample_chrome_console_output.png ├── package-lock.json ├── package.json ├── src └── index.ts ├── tsconfig.json ├── tsconfig.module.json └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SupaScriptConsole 2 | Javascript/Typescript library for local (client-side) console logging of Supabase rpc calls (PostgreSQL functions) 3 | 4 | ## Purpose 5 | This library allows you see the console log output from your Supabase / PostgreSQL server functions written in [SupaScript](https://github.com/burggraf/SupaScript). (SupaScript is a JavaScript-based, NodeJS-like, Deno-inspired set of extensions for Supabase & PostgreSQL server functions.) 6 | 7 | ## Example 8 | Here's a screen shot of the Google Chrome Console showing console logging for a function running in a Supabase PostgreSQL instance: 9 | 10 | ![Chrome Debugger](./docs/sample_chrome_console_output.png) 11 | 12 | And you can drill down on the "details" object to get complete details on the log item: 13 | 14 | ![Details Drill-down](./docs/sample_chome_console_details.png) 15 | 16 | ## Install 17 | ``` 18 | npm install supascriptconsole --save 19 | ``` 20 | 21 | ## Usage 22 | To use it, just call the `startLogging()` function and pass it an object. The object can either contain a reference to a `Supabase object` you've already opened with the `supabase.js` library, or it can contain `url` and (anon) `key` strings. (See both examples below) 23 | 24 | Import the library at the top of your module: 25 | ```js 26 | import { startLogging } from 'supascriptconsole'; 27 | ``` 28 | Now just call it in your code (usually in a constructor or other startup code): 29 | 30 | ### Option 1: call it with your Supabase url and public (anonymous) key: 31 | ```js 32 | startLogging({url: 'https://xxxxxxxxxxxxxxxxxxxx.supabase.co', key:'yyyyyyyyyyyyyyyyyyyyyyyyyyy'}); 33 | ``` 34 | ### Option 2: call it with your Supabase object: 35 | ```js 36 | import { createClient, SupabaseClient } from '@supabase/supabase-js'; 37 | // then 38 | supabase = createClient(myUrl, myKey); 39 | // start logging using the supabase object (which you'll probably use later to call your .rpc functions! 40 | startLogging({supabase: this.supabase}); 41 | // Let's call a server function so we can see some pretty console output in our browser console! 42 | const { data, error } = await this.supabase.rpc('test_console'); 43 | ``` 44 | 45 | To stop logging, just assign the output to a variable then call `unsubscribe()` on that variable later. 46 | ```js 47 | this.subscription = startLogging({supabase: this.supabase}); 48 | // later 49 | this.subscription.unsubscribe(); 50 | ``` 51 | ## How to add logging to your SupaScript functions 52 | See the [SupaScript Console Docs](https://github.com/burggraf/SupaScript/blob/main/docs/console.md) 53 | 54 | ## Logging types supported 55 | In your SupaScript functions, you can use: 56 | ```js 57 | console.log(); 58 | console.info(); 59 | console.warn(); 60 | console.error(); 61 | console.assert(); 62 | console.time(); 63 | console.timeEnd() 64 | ``` 65 | 66 | ## SupaScript (server side) complete example 67 | ```js 68 | create or replace function test_console() returns text as $$ 69 | console.time('test-my-function'); 70 | console.log('logged to the console at:', new Date()); 71 | for (let x = 0; x < 100000; x++) { 72 | const busyWork = 'this is loop #' + x.toString(); 73 | } 74 | console.log('strings', 12345, {'object': {'with': 'nested', 'items': [1, 2, 3, 'Go!']}}); 75 | console.info('shows up in green'); 76 | console.warn('shows up in yellow'); 77 | console.error('shows up in red'); 78 | console.assert(false, 'only logs if the first parameter evaluates to false'); 79 | 80 | console.timeEnd('test-my-function'); // profiling FTW! 81 | return 'ok'; 82 | $$ language plv8; 83 | ``` 84 | 85 | ## Call the server function in your client code 86 | ```js 87 | const { data, error } = await this.supabase 88 | .rpc('test_console'); 89 | ``` 90 | Now you can call the function from your client code and view the console debug messages right in your browser while testing your app! 91 | -------------------------------------------------------------------------------- /dist/main/index.d.ts: -------------------------------------------------------------------------------- 1 | import { RealtimeSubscription } from '@supabase/supabase-js'; 2 | declare function startLogging(obj: any): RealtimeSubscription | null; 3 | export { startLogging }; 4 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /dist/main/index.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAGxF,iBAAS,YAAY,CAAE,GAAG,EAAE,GAAG,GAAG,oBAAoB,GAAG,IAAI,CAwC3D;AAIL,OAAO,EAAE,YAAY,EAAE,CAAC"} -------------------------------------------------------------------------------- /dist/main/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.startLogging = void 0; 4 | const supabase_js_1 = require("@supabase/supabase-js"); 5 | function startLogging(obj) { 6 | const style = { 7 | 'INFO': 'color: white; background: darkgreen; border:1px solid darkgreen;', 8 | 'ASSERT': 'color: white; background: darkred; border:1px solid darkred;', 9 | 'ERROR': 'color: white; background: darkred; border:1px solid darkred;', 10 | 'LOG': 'color: black; background: white; border:1px solid;', 11 | 'TIMER': 'color: black; background: white; border:1px solid;', 12 | 'WARN': 'color: black; background: yellow; border:1px solid;', 13 | }; 14 | const icon = { 15 | 'INFO': String.fromCodePoint(0x1f7e2), 16 | 'ASSERT': String.fromCodePoint(0x274e), 17 | 'ERROR': String.fromCodePoint(0x1f534), 18 | 'LOG': String.fromCodePoint(0x26aa), 19 | 'TIMER': String.fromCodePoint(0x231b), 20 | 'WARN': String.fromCodePoint(0x1f7e1), 21 | }; 22 | let supabase; 23 | if (obj.supabase) { 24 | supabase = obj.supabase; 25 | } 26 | else if (obj.url && obj.key) { 27 | supabase = supabase_js_1.createClient(obj.url, obj.key); 28 | } 29 | else { 30 | console.error('%c %s ', style.ERROR, '\Error connecting to PostgreSQL ... you must either pass an object with a Supabase Client { supabase: mySupabaseClientObject } or an object with url and key { url: "https://xxx.supabase.co", key: "anon-key"} \n'); 31 | return null; 32 | } 33 | console.log('%c %s ', style.INFO, '\nConnected to PostgreSQL ... listening for console messages from SupaScript functions...\n'); 34 | let subscription; 35 | subscription = supabase 36 | .from('supascript_log') 37 | .on('INSERT', (payload) => { 38 | const type = payload.new.log_type; 39 | payload.new.content.unshift(icon[type]); 40 | console.log('%c pgFunc %o', style[type], ...payload.new.content, { details: payload.new }); 41 | }) 42 | .subscribe(); 43 | return subscription; 44 | } 45 | exports.startLogging = startLogging; 46 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /dist/main/index.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,uDAA2F;AAGxF,SAAS,YAAY,CAAE,GAAQ;IAC9B,MAAM,KAAK,GAAQ;QACf,MAAM,EAAE,kEAAkE;QAC1E,QAAQ,EAAE,8DAA8D;QACxE,OAAO,EAAE,8DAA8D;QACvE,KAAK,EAAE,oDAAoD;QAC3D,OAAO,EAAE,oDAAoD;QAC7D,MAAM,EAAE,qDAAqD;KAC9D,CAAC;IACF,MAAM,IAAI,GAAQ;QAChB,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC;QACrC,QAAQ,EAAE,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QACtC,OAAO,EAAE,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC;QACtC,KAAK,EAAE,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QACnC,OAAO,EAAE,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QACrC,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC;KACtC,CAAC;IACF,IAAI,QAAwB,CAAC;IAC7B,IAAI,GAAG,CAAC,QAAQ,EAAE;QAChB,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;KACzB;SAAM,IAAI,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE;QAC7B,QAAQ,GAAG,0BAAY,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;KAC3C;SAAM;QACL,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAK,EACnC,oNAAoN,CAAC,CAAC;QACtN,OAAO,IAAI,CAAC;KACb;IACD,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,EAChC,6FAA6F,CAAC,CAAC;IAE/F,IAAI,YAAkC,CAAC;IACvC,YAAY,GAAG,QAAQ;SACtB,IAAI,CAAC,gBAAgB,CAAC;SACtB,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAY,EAAE,EAAE;QAC7B,MAAM,IAAI,GAAW,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC1C,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACxC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,EAAC,OAAO,EAAC,OAAO,CAAC,GAAG,EAAC,CAAC,CAAC;IAC1F,CAAC,CAAC;SACD,SAAS,EAAE,CAAC;IACb,OAAO,YAAY,CAAC;AACtB,CAAC;AAII,oCAAY"} -------------------------------------------------------------------------------- /dist/module/index.d.ts: -------------------------------------------------------------------------------- 1 | import { RealtimeSubscription } from '@supabase/supabase-js'; 2 | declare function startLogging(obj: any): RealtimeSubscription | null; 3 | export { startLogging }; 4 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /dist/module/index.d.ts.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAGxF,iBAAS,YAAY,CAAE,GAAG,EAAE,GAAG,GAAG,oBAAoB,GAAG,IAAI,CAwC3D;AAIL,OAAO,EAAE,YAAY,EAAE,CAAC"} -------------------------------------------------------------------------------- /dist/module/index.js: -------------------------------------------------------------------------------- 1 | import { createClient } from '@supabase/supabase-js'; 2 | function startLogging(obj) { 3 | const style = { 4 | 'INFO': 'color: white; background: darkgreen; border:1px solid darkgreen;', 5 | 'ASSERT': 'color: white; background: darkred; border:1px solid darkred;', 6 | 'ERROR': 'color: white; background: darkred; border:1px solid darkred;', 7 | 'LOG': 'color: black; background: white; border:1px solid;', 8 | 'TIMER': 'color: black; background: white; border:1px solid;', 9 | 'WARN': 'color: black; background: yellow; border:1px solid;', 10 | }; 11 | const icon = { 12 | 'INFO': String.fromCodePoint(0x1f7e2), 13 | 'ASSERT': String.fromCodePoint(0x274e), 14 | 'ERROR': String.fromCodePoint(0x1f534), 15 | 'LOG': String.fromCodePoint(0x26aa), 16 | 'TIMER': String.fromCodePoint(0x231b), 17 | 'WARN': String.fromCodePoint(0x1f7e1), 18 | }; 19 | let supabase; 20 | if (obj.supabase) { 21 | supabase = obj.supabase; 22 | } 23 | else if (obj.url && obj.key) { 24 | supabase = createClient(obj.url, obj.key); 25 | } 26 | else { 27 | console.error('%c %s ', style.ERROR, '\Error connecting to PostgreSQL ... you must either pass an object with a Supabase Client { supabase: mySupabaseClientObject } or an object with url and key { url: "https://xxx.supabase.co", key: "anon-key"} \n'); 28 | return null; 29 | } 30 | console.log('%c %s ', style.INFO, '\nConnected to PostgreSQL ... listening for console messages from SupaScript functions...\n'); 31 | let subscription; 32 | subscription = supabase 33 | .from('supascript_log') 34 | .on('INSERT', (payload) => { 35 | const type = payload.new.log_type; 36 | payload.new.content.unshift(icon[type]); 37 | console.log('%c pgFunc %o', style[type], ...payload.new.content, { details: payload.new }); 38 | }) 39 | .subscribe(); 40 | return subscription; 41 | } 42 | export { startLogging }; 43 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /dist/module/index.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAwC,MAAM,uBAAuB,CAAC;AAGxF,SAAS,YAAY,CAAE,GAAQ;IAC9B,MAAM,KAAK,GAAQ;QACf,MAAM,EAAE,kEAAkE;QAC1E,QAAQ,EAAE,8DAA8D;QACxE,OAAO,EAAE,8DAA8D;QACvE,KAAK,EAAE,oDAAoD;QAC3D,OAAO,EAAE,oDAAoD;QAC7D,MAAM,EAAE,qDAAqD;KAC9D,CAAC;IACF,MAAM,IAAI,GAAQ;QAChB,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC;QACrC,QAAQ,EAAE,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QACtC,OAAO,EAAE,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC;QACtC,KAAK,EAAE,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QACnC,OAAO,EAAE,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;QACrC,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC;KACtC,CAAC;IACF,IAAI,QAAwB,CAAC;IAC7B,IAAI,GAAG,CAAC,QAAQ,EAAE;QAChB,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;KACzB;SAAM,IAAI,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE;QAC7B,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;KAC3C;SAAM;QACL,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAK,EACnC,oNAAoN,CAAC,CAAC;QACtN,OAAO,IAAI,CAAC;KACb;IACD,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,EAChC,6FAA6F,CAAC,CAAC;IAE/F,IAAI,YAAkC,CAAC;IACvC,YAAY,GAAG,QAAQ;SACtB,IAAI,CAAC,gBAAgB,CAAC;SACtB,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAY,EAAE,EAAE;QAC7B,MAAM,IAAI,GAAW,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC1C,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACxC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,EAAC,OAAO,EAAC,OAAO,CAAC,GAAG,EAAC,CAAC,CAAC;IAC1F,CAAC,CAAC;SACD,SAAS,EAAE,CAAC;IACb,OAAO,YAAY,CAAC;AACtB,CAAC;AAIL,OAAO,EAAE,YAAY,EAAE,CAAC"} -------------------------------------------------------------------------------- /dist/umd/supascriptconsole.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.supascriptconsole=t():e.supascriptconsole=t()}(self,(function(){return(()=>{var e={489:(e,t,r)=>{"use strict";r.r(t),r.d(t,{GoTrueApi:()=>b,GoTrueClient:()=>S,RealtimeClient:()=>Z,RealtimeSubscription:()=>Y,SupabaseClient:()=>ye,Transformers:()=>s,createClient:()=>ve});var s={};r.r(s),r.d(s,{PostgresTypes:()=>E,convertCell:()=>A,convertChangeData:()=>R,convertColumn:()=>C,toArray:()=>F,toBoolean:()=>U,toDate:()=>N,toDateRange:()=>D,toFloat:()=>B,toInt:()=>M,toIntRange:()=>L,toJson:()=>H,toTimestampString:()=>G});var n=r(98),i=r.n(n),o=function(e,t,r,s){return new(r||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}))};const a=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e);function h(e,t,r,s){return o(this,void 0,void 0,(function*(){return new Promise(((n,o)=>{i()(t,((e,t,r)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e||(s.headers=Object.assign({"Content-Type":"text/plain;charset=UTF-8"},null==t?void 0:t.headers),s.body=JSON.stringify(r)),s})(e,r,s)).then((e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?n:e.json()})).then((e=>n(e))).catch((e=>((e,t)=>{if("function"!=typeof e.json)return t(e);e.json().then((r=>t({message:a(r),status:(null==e?void 0:e.status)||500})))})(e,o)))}))}))}function c(e,t,r){return o(this,void 0,void 0,(function*(){return h("POST",e,r,t)}))}const l="supabase.auth.token",u={name:"sb:token",lifetime:28800,domain:"",path:"/",sameSite:"lax"};function d(e,t,r){const s=r.map((t=>{return r=t,s=function(e){if(!e||!e.headers||!e.headers.host)throw new Error('The "host" request header is not available');const t=e.headers.host.indexOf(":")>-1&&e.headers.host.split(":")[0]||e.headers.host;return!(["localhost","127.0.0.1"].indexOf(t)>-1)}(e),function(e,t,r){const s=r||{},n=encodeURIComponent,i=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;if("function"!=typeof n)throw new TypeError("option encode is invalid");if(!i.test(e))throw new TypeError("argument name is invalid");const o=n(t);if(o&&!i.test(o))throw new TypeError("argument val is invalid");let a=e+"="+o;if(null!=s.maxAge){const e=s.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(s.domain){if(!i.test(s.domain))throw new TypeError("option domain is invalid");a+="; Domain="+s.domain}if(s.path){if(!i.test(s.path))throw new TypeError("option path is invalid");a+="; Path="+s.path}if(s.expires){if("function"!=typeof s.expires.toUTCString)throw new TypeError("option expires is invalid");a+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(a+="; HttpOnly"),s.secure&&(a+="; Secure"),s.sameSite)switch("string"==typeof s.sameSite?s.sameSite.toLowerCase():s.sameSite){case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}(r.name,r.value,{maxAge:r.maxAge,expires:new Date(Date.now()+1e3*r.maxAge),httpOnly:!0,secure:s,path:null!==(n=r.path)&&void 0!==n?n:"/",domain:null!==(i=r.domain)&&void 0!==i?i:"",sameSite:null!==(o=r.sameSite)&&void 0!==o?o:"lax"});var r,s,n,i,o})),n=t.getHeader("Set-Cookie");n&&(n instanceof Array?Array.prototype.push.apply(s,n):"string"==typeof n&&s.push(n)),t.setHeader("Set-Cookie",s)}function p(e,t,r){d(e,t,[r])}function f(e){return Math.round(Date.now()/1e3)+e}const m=()=>"undefined"!=typeof window;function g(e,t){t||(t=window.location.href),e=e.replace(/[\[\]]/g,"\\$&");var r=new RegExp("[?&#]"+e+"(=([^&#]*)|&|#|$)").exec(t);return r?r[2]?decodeURIComponent(r[2].replace(/\+/g," ")):"":null}class y{constructor(e){this.localStorage=e||globalThis.localStorage}clear(){return this.localStorage.clear()}key(e){return this.localStorage.key(e)}setItem(e,t){return this.localStorage.setItem(e,t)}getItem(e){return this.localStorage.getItem(e)}removeItem(e){return this.localStorage.removeItem(e)}}var v=function(e,t,r,s){return new(r||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}))};class b{constructor({url:e="",headers:t={},cookieOptions:r}){this.url=e,this.headers=t,this.cookieOptions=Object.assign(Object.assign({},u),r)}signUpWithEmail(e,t,r={}){return v(this,void 0,void 0,(function*(){try{let s=Object.assign({},this.headers);r.redirectTo&&(s.referer=r.redirectTo);const n=yield c(`${this.url}/signup`,{email:e,password:t},{headers:s});let i=Object.assign({},n);return i.expires_in&&(i.expires_at=f(n.expires_in)),{data:i,error:null}}catch(e){return{data:null,error:e}}}))}signInWithEmail(e,t,r={}){return v(this,void 0,void 0,(function*(){try{let s=Object.assign({},this.headers);r.redirectTo&&(s.referer=r.redirectTo);const n=yield c(`${this.url}/token?grant_type=password`,{email:e,password:t},{headers:s});let i=Object.assign({},n);return i.expires_in&&(i.expires_at=f(n.expires_in)),{data:i,error:null}}catch(e){return{data:null,error:e}}}))}sendMagicLinkEmail(e,t={}){return v(this,void 0,void 0,(function*(){try{let r=Object.assign({},this.headers);return t.redirectTo&&(r.referer=t.redirectTo),{data:yield c(`${this.url}/magiclink`,{email:e},{headers:r}),error:null}}catch(e){return{data:null,error:e}}}))}inviteUserByEmail(e,t={}){return v(this,void 0,void 0,(function*(){try{let r=Object.assign({},this.headers);return t.redirectTo&&(r.referer=t.redirectTo),{data:yield c(`${this.url}/invite`,{email:e},{headers:r}),error:null}}catch(e){return{data:null,error:e}}}))}resetPasswordForEmail(e,t={}){return v(this,void 0,void 0,(function*(){try{let r=Object.assign({},this.headers);return t.redirectTo&&(r.referer=t.redirectTo),{data:yield c(`${this.url}/recover`,{email:e},{headers:r}),error:null}}catch(e){return{data:null,error:e}}}))}_createRequestHeaders(e){const t=Object.assign({},this.headers);return t.Authorization=`Bearer ${e}`,t}signOut(e){return v(this,void 0,void 0,(function*(){try{return yield c(`${this.url}/logout`,{},{headers:this._createRequestHeaders(e),noResolveJson:!0}),{error:null}}catch(e){return{error:e}}}))}getUrlForProvider(e,t){let r=[`provider=${e}`];return(null==t?void 0:t.redirectTo)&&r.push(`redirect_to=${t.redirectTo}`),(null==t?void 0:t.scopes)&&r.push(`scopes=${t.scopes}`),`${this.url}/authorize?${r.join("&")}`}getUser(e){return v(this,void 0,void 0,(function*(){try{const t=yield function(e,t){return o(this,void 0,void 0,(function*(){return h("GET",e,t)}))}(`${this.url}/user`,{headers:this._createRequestHeaders(e)});return{user:t,data:t,error:null}}catch(e){return{user:null,data:null,error:e}}}))}updateUser(e,t){return v(this,void 0,void 0,(function*(){try{const r=yield function(e,t,r){return o(this,void 0,void 0,(function*(){return h("PUT",e,r,t)}))}(`${this.url}/user`,t,{headers:this._createRequestHeaders(e)});return{user:r,data:r,error:null}}catch(e){return{user:null,data:null,error:e}}}))}refreshAccessToken(e){return v(this,void 0,void 0,(function*(){try{const t=yield c(`${this.url}/token?grant_type=refresh_token`,{refresh_token:e},{headers:this.headers});let r=Object.assign({},t);return r.expires_in&&(r.expires_at=f(t.expires_in)),{data:r,error:null}}catch(e){return{data:null,error:e}}}))}setAuthCookie(e,t){"POST"!==e.method&&(t.setHeader("Allow","POST"),t.status(405).end("Method Not Allowed"));const{event:r,session:s}=e.body;if(!r)throw new Error("Auth event missing!");if("SIGNED_IN"===r){if(!s)throw new Error("Auth session missing!");p(e,t,{name:this.cookieOptions.name,value:s.access_token,domain:this.cookieOptions.domain,maxAge:this.cookieOptions.lifetime,path:this.cookieOptions.path,sameSite:this.cookieOptions.sameSite})}"SIGNED_OUT"===r&&function(e,t,r){p(e,t,{name:r,value:"",maxAge:-1})}(e,t,this.cookieOptions.name),t.status(200).json({})}getUserByCookie(e){return v(this,void 0,void 0,(function*(){try{if(!e.cookies)throw new Error("Not able to parse cookies! When using Express make sure the cookie-parser middleware is in use!");if(!e.cookies[this.cookieOptions.name])throw new Error("No cookie found!");const t=e.cookies[this.cookieOptions.name],{user:r,error:s}=yield this.getUser(t);if(s)throw s;return{user:r,data:r,error:null}}catch(e){return{user:null,data:null,error:e}}}))}}var w=function(e,t,r,s){return new(r||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}))};"object"!=typeof globalThis&&(Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__);const _={url:"http://localhost:9999",autoRefreshToken:!0,persistSession:!0,localStorage:globalThis.localStorage,detectSessionInUrl:!0,headers:{}};class S{constructor(e){this.stateChangeEmitters=new Map;const t=Object.assign(Object.assign({},_),e);this.currentUser=null,this.currentSession=null,this.autoRefreshToken=t.autoRefreshToken,this.persistSession=t.persistSession,this.localStorage=new y(t.localStorage),this.api=new b({url:t.url,headers:t.headers,cookieOptions:t.cookieOptions}),this._recoverSession(),this._recoverAndRefresh();try{t.detectSessionInUrl&&m()&&g("access_token")&&this.getSessionFromUrl({storeSession:!0})}catch(e){console.log("Error getting session from URL.")}}signUp({email:e,password:t},r={}){return w(this,void 0,void 0,(function*(){try{this._removeSession();const{data:s,error:n}=yield this.api.signUpWithEmail(e,t,{redirectTo:r.redirectTo});if(n)throw n;if(!s)throw"An error occurred on sign up.";let i=null,o=null;return s.access_token&&(i=s,o=i.user,this._saveSession(i),this._notifyAllSubscribers("SIGNED_IN")),s.id&&(o=s),{data:s,user:o,session:i,error:null}}catch(e){return{data:null,user:null,session:null,error:e}}}))}signIn({email:e,password:t,provider:r},s={}){return w(this,void 0,void 0,(function*(){try{if(this._removeSession(),e&&!t){const{error:t}=yield this.api.sendMagicLinkEmail(e,{redirectTo:s.redirectTo});return{data:null,user:null,session:null,error:t}}if(e&&t)return this._handleEmailSignIn(e,t,{redirectTo:s.redirectTo});if(r)return this._handleProviderSignIn(r,{redirectTo:s.redirectTo,scopes:s.scopes});throw new Error("You must provide either an email or a third-party provider.")}catch(e){return{data:null,user:null,session:null,error:e}}}))}user(){return this.currentUser}session(){return this.currentSession}refreshSession(){var e;return w(this,void 0,void 0,(function*(){try{if(!(null===(e=this.currentSession)||void 0===e?void 0:e.access_token))throw new Error("Not logged in.");const{error:t}=yield this._callRefreshToken();if(t)throw t;return{data:this.currentSession,user:this.currentUser,error:null}}catch(e){return{data:null,user:null,error:e}}}))}update(e){var t;return w(this,void 0,void 0,(function*(){try{if(!(null===(t=this.currentSession)||void 0===t?void 0:t.access_token))throw new Error("Not logged in.");const{user:r,error:s}=yield this.api.updateUser(this.currentSession.access_token,e);if(s)throw s;if(!r)throw Error("Invalid user data.");const n=Object.assign(Object.assign({},this.currentSession),{user:r});return this._saveSession(n),this._notifyAllSubscribers("USER_UPDATED"),{data:r,user:r,error:null}}catch(e){return{data:null,user:null,error:e}}}))}getSessionFromUrl(e){return w(this,void 0,void 0,(function*(){try{if(!m())throw new Error("No browser detected.");const t=g("error_description");if(t)throw new Error(t);const r=g("provider_token"),s=g("access_token");if(!s)throw new Error("No access_token detected.");const n=g("expires_in");if(!n)throw new Error("No expires_in detected.");const i=g("refresh_token");if(!i)throw new Error("No refresh_token detected.");const o=g("token_type");if(!o)throw new Error("No token_type detected.");const a=Math.round(Date.now()/1e3)+parseInt(n),{user:h,error:c}=yield this.api.getUser(s);if(c)throw c;const l={provider_token:r,access_token:s,expires_in:parseInt(n),expires_at:a,refresh_token:i,token_type:o,user:h};return(null==e?void 0:e.storeSession)&&(this._saveSession(l),this._notifyAllSubscribers("SIGNED_IN"),"recovery"===g("type")&&this._notifyAllSubscribers("PASSWORD_RECOVERY")),window.location.hash="",{data:l,error:null}}catch(e){return{data:null,error:e}}}))}signOut(){var e;return w(this,void 0,void 0,(function*(){const t=null===(e=this.currentSession)||void 0===e?void 0:e.access_token;if(this._removeSession(),this._notifyAllSubscribers("SIGNED_OUT"),t){const{error:e}=yield this.api.signOut(t);if(e)return{error:e}}return{error:null}}))}onAuthStateChange(e){try{const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),r=this,s={id:t,callback:e,unsubscribe:()=>{r.stateChangeEmitters.delete(t)}};return this.stateChangeEmitters.set(t,s),{data:s,error:null}}catch(e){return{data:null,error:e}}}_handleEmailSignIn(e,t,r={}){var s;return w(this,void 0,void 0,(function*(){try{const{data:n,error:i}=yield this.api.signInWithEmail(e,t,{redirectTo:r.redirectTo});return i||!n?{data:null,user:null,session:null,error:i}:((null===(s=null==n?void 0:n.user)||void 0===s?void 0:s.confirmed_at)&&(this._saveSession(n),this._notifyAllSubscribers("SIGNED_IN")),{data:n,user:n.user,session:n,error:null})}catch(e){return{data:null,user:null,session:null,error:e}}}))}_handleProviderSignIn(e,t={}){const r=this.api.getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes});try{return m()&&(window.location.href=r),{provider:e,url:r,data:null,session:null,user:null,error:null}}catch(t){return r?{provider:e,url:r,data:null,session:null,user:null,error:null}:{data:null,user:null,session:null,error:t}}}_recoverSession(){var e;try{const t=m()&&(null===(e=this.localStorage)||void 0===e?void 0:e.getItem(l));if(!t)return null;const r=JSON.parse(t),{currentSession:s,expiresAt:n}=r;n>=Math.round(Date.now()/1e3)&&(null==s?void 0:s.user)&&(this._saveSession(s),this._notifyAllSubscribers("SIGNED_IN"))}catch(e){console.log("error",e)}}_recoverAndRefresh(){return w(this,void 0,void 0,(function*(){try{const e=m()&&(yield this.localStorage.getItem(l));if(!e)return null;const t=JSON.parse(e),{currentSession:r,expiresAt:s}=t;if(st.callback(e,this.currentSession)))}_saveSession(e){this.currentSession=e,this.currentUser=e.user;const t=e.expires_at,r=Math.round(Date.now()/1e3);t&&this._startAutoRefreshToken(1e3*(t-r-60)),this.persistSession&&e.expires_at&&this._persistSession(this.currentSession)}_persistSession(e){const t={currentSession:e,expiresAt:e.expires_at};m()&&this.localStorage.setItem(l,JSON.stringify(t))}_removeSession(){return w(this,void 0,void 0,(function*(){this.currentSession=null,this.currentUser=null,this.refreshTokenTimer&&clearTimeout(this.refreshTokenTimer),m()&&(yield this.localStorage.removeItem(l))}))}_startAutoRefreshToken(e){this.refreshTokenTimer&&clearTimeout(this.refreshTokenTimer),e&&this.autoRefreshToken&&(this.refreshTokenTimer=setTimeout((()=>this._callRefreshToken()),e))}}class T extends S{constructor(e){super(e)}}var E;class k{constructor(e){Object.assign(this,e)}then(e,t){return void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),"GET"!==this.method&&"HEAD"!==this.method&&(this.headers["Content-Type"]="application/json"),i()(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body)}).then((e=>{return t=this,r=void 0,n=function*(){var t,r,s;let n=null,i=null,o=null;if(e.ok){const n=null===(t=this.headers.Prefer)||void 0===t?void 0:t.split(",").includes("return=minimal");if("HEAD"!==this.method&&!n){const t=yield e.text();t&&""!==t&&(i=JSON.parse(t))}const a=null===(r=this.headers.Prefer)||void 0===r?void 0:r.match(/count=(exact|planned|estimated)/),h=null===(s=e.headers.get("content-range"))||void 0===s?void 0:s.split("/");a&&h&&h.length>1&&(o=parseInt(h[1]))}else n=yield e.json();return{error:n,data:i,count:o,status:e.status,statusText:e.statusText,body:i}},new((s=void 0)||(s=Promise))((function(e,i){function o(e){try{h(n.next(e))}catch(e){i(e)}}function a(e){try{h(n.throw(e))}catch(e){i(e)}}function h(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s((function(e){e(r)}))).then(o,a)}h((n=n.apply(t,r||[])).next())}));var t,r,s,n})).then(e,t)}}class $ extends k{select(e="*"){let t=!1;const r=e.split("").map((e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e))).join("");return this.url.searchParams.set("select",r),this}order(e,{ascending:t=!0,nullsFirst:r=!1,foreignTable:s}={}){const n=void 0===s?"order":`${s}.order`,i=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${i?`${i},`:""}${e}.${t?"asc":"desc"}.${r?"nullsfirst":"nullslast"}`),this}limit(e,{foreignTable:t}={}){const r=void 0===t?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:r}={}){const s=void 0===r?"offset":`${r}.offset`,n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(n,""+(t-e+1)),this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}}class x extends ${constructor(){super(...arguments),this.cs=this.contains,this.cd=this.containedBy,this.sl=this.rangeLt,this.sr=this.rangeGt,this.nxl=this.rangeGte,this.nxr=this.rangeLte,this.adj=this.rangeAdjacent,this.ov=this.overlaps}not(e,t,r){return this.url.searchParams.append(`${e}`,`not.${t}.${r}`),this}or(e,{foreignTable:t}={}){const r=void 0===t?"or":`${t}.or`;return this.url.searchParams.append(r,`(${e})`),this}eq(e,t){return this.url.searchParams.append(`${e}`,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(`${e}`,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(`${e}`,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(`${e}`,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(`${e}`,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(`${e}`,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(`${e}`,`like.${t}`),this}ilike(e,t){return this.url.searchParams.append(`${e}`,`ilike.${t}`),this}is(e,t){return this.url.searchParams.append(`${e}`,`is.${t}`),this}in(e,t){const r=t.map((e=>"string"==typeof e&&new RegExp("[,()]").test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(`${e}`,`in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(`${e}`,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(`${e}`,`cs.{${t.join(",")}}`):this.url.searchParams.append(`${e}`,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(`${e}`,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(`${e}`,`cd.{${t.join(",")}}`):this.url.searchParams.append(`${e}`,`cd.${JSON.stringify(t)}`),this}rangeLt(e,t){return this.url.searchParams.append(`${e}`,`sl.${t}`),this}rangeGt(e,t){return this.url.searchParams.append(`${e}`,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(`${e}`,`nxl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(`${e}`,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(`${e}`,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(`${e}`,`ov.${t}`):this.url.searchParams.append(`${e}`,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s=null}={}){let n="";"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(`${e}`,`${n}fts${i}.${t}`),this}fts(e,t,{config:r}={}){const s=void 0===r?"":`(${r})`;return this.url.searchParams.append(`${e}`,`fts${s}.${t}`),this}plfts(e,t,{config:r}={}){const s=void 0===r?"":`(${r})`;return this.url.searchParams.append(`${e}`,`plfts${s}.${t}`),this}phfts(e,t,{config:r}={}){const s=void 0===r?"":`(${r})`;return this.url.searchParams.append(`${e}`,`phfts${s}.${t}`),this}wfts(e,t,{config:r}={}){const s=void 0===r?"":`(${r})`;return this.url.searchParams.append(`${e}`,`wfts${s}.${t}`),this}filter(e,t,r){return this.url.searchParams.append(`${e}`,`${t}.${r}`),this}match(e){return Object.keys(e).forEach((t=>{this.url.searchParams.append(`${t}`,`eq.${e[t]}`)})),this}}class j extends k{constructor(e,{headers:t={},schema:r}={}){super({}),this.url=new URL(e),this.headers=Object.assign({},t),this.schema=r}select(e="*",{head:t=!1,count:r=null}={}){this.method="GET";let s=!1;const n=e.split("").map((e=>/\s/.test(e)&&!s?"":('"'===e&&(s=!s),e))).join("");return this.url.searchParams.set("select",n),r&&(this.headers.Prefer=`count=${r}`),t&&(this.method="HEAD"),new x(this)}insert(e,{upsert:t=!1,onConflict:r,returning:s="representation",count:n=null}={}){this.method="POST";const i=[`return=${s}`];return t&&i.push("resolution=merge-duplicates"),t&&void 0!==r&&this.url.searchParams.set("on_conflict",r),this.body=e,n&&i.push(`count=${n}`),this.headers.Prefer=i.join(","),new x(this)}upsert(e,{onConflict:t,returning:r="representation",count:s=null}={}){this.method="POST";const n=["resolution=merge-duplicates",`return=${r}`];return void 0!==t&&this.url.searchParams.set("on_conflict",t),this.body=e,s&&n.push(`count=${s}`),this.headers.Prefer=n.join(","),new x(this)}update(e,{returning:t="representation",count:r=null}={}){this.method="PATCH";const s=[`return=${t}`];return this.body=e,r&&s.push(`count=${r}`),this.headers.Prefer=s.join(","),new x(this)}delete({returning:e="representation",count:t=null}={}){this.method="DELETE";const r=[`return=${e}`];return t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new x(this)}}class P extends k{constructor(e,{headers:t={},schema:r}={}){super({}),this.url=new URL(e),this.headers=Object.assign({},t),this.schema=r}rpc(e,{count:t=null}={}){return this.method="POST",this.body=e,t&&(void 0!==this.headers.Prefer?this.headers.Prefer+=`,count=${t}`:this.headers.Prefer=`count=${t}`),new $(this)}}class O{constructor(e,{headers:t={},schema:r}={}){this.url=e,this.headers=t,this.schema=r}auth(e){return this.headers.Authorization=`Bearer ${e}`,this}from(e){const t=`${this.url}/${e}`;return new j(t,{headers:this.headers,schema:this.schema})}rpc(e,t,{count:r=null}={}){const s=`${this.url}/rpc/${e}`;return new P(s,{headers:this.headers,schema:this.schema}).rpc(t,{count:r})}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(E||(E={}));const R=(e,t,r={})=>{let s={},n=void 0!==r.skipTypes?r.skipTypes:[];return Object.entries(t).map((([r,i])=>{s[r]=C(r,e,t,n)})),s},C=(e,t,r,s)=>{let n=t.find((t=>t.name==e));return!n||s.includes(n.type)?I(r[e]):A(n.type,r[e])},A=(e,t)=>{try{if(null===t)return null;if("_"===e.charAt(0)){let r=e.slice(1,e.length);return F(t,r)}switch(e){case E.abstime:return I(t);case E.bool:return U(t);case E.date:return I(t);case E.daterange:return D(t);case E.float4:case E.float8:return B(t);case E.int2:case E.int4:return M(t);case E.int4range:return L(t);case E.int8:return M(t);case E.int8range:return L(t);case E.json:case E.jsonb:return H(t);case E.money:case E.numeric:return B(t);case E.oid:return M(t);case E.reltime:case E.time:return I(t);case E.timestamp:return G(t);case E.timestamptz:case E.timetz:return I(t);case E.tsrange:case E.tstzrange:return D(t);default:return I(t)}}catch(r){return console.log(`Could not convert cell of type ${e} and value ${t}`),console.log(`This is the error: ${r}`),t}},I=e=>e,U=e=>{switch(e){case"t":return!0;case"f":return!1;default:return null}},N=e=>new Date(e),D=e=>{let t=JSON.parse(e);return[new Date(t[0]),new Date(t[1])]},B=e=>parseFloat(e),M=e=>parseInt(e),L=e=>{let t=JSON.parse(e);return[parseInt(t[0]),parseInt(t[1])]},H=e=>JSON.parse(e),F=(e,t)=>{let r=e.slice(1,e.length-1);return(r.length>0?r.split(","):[]).map((e=>A(t,e)))},G=e=>e.replace(" ","T");var J,q,z,K;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(J||(J={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(q||(q={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave"}(z||(z={})),function(e){e.websocket="websocket"}(K||(K={}));class W{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout((()=>{this.tries=this.tries+1,this.callback()}),this.timerCalc(this.tries+1))}}class V{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref}))}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||(this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)})),this.timeoutTimer=setTimeout((()=>{this.trigger("timeout",{})}),this.timeout))}trigger(e,t){this.refEvent&&this.channel.trigger(this.refEvent,{status:e,response:t})}_cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter((t=>t.status===e)).forEach((e=>e.callback(t)))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}class Y{constructor(e,t={},r){this.topic=e,this.params=t,this.socket=r,this.bindings=[],this.state=q.closed,this.joinedOnce=!1,this.pushBuffer=[],this.timeout=this.socket.timeout,this.joinPush=new V(this,z.join,this.params,this.timeout),this.rejoinTimer=new W((()=>this.rejoinUntilConnected()),this.socket.reconnectAfterMs),this.joinPush.receive("ok",(()=>{this.state=q.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((e=>e.send())),this.pushBuffer=[]})),this.onClose((()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=q.closed,this.socket.remove(this)})),this.onError((e=>{this.isLeaving()||this.isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=q.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("timeout",(()=>{this.isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=q.errored,this.rejoinTimer.scheduleTimeout())})),this.on(z.reply,((e,t)=>{this.trigger(this.replyEventName(t),e)}))}rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this.rejoin()}subscribe(e=this.timeout){if(this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";return this.joinedOnce=!0,this.rejoin(e),this.joinPush}onClose(e){this.on(z.close,e)}onError(e){this.on(z.error,(t=>e(t)))}on(e,t){this.bindings.push({event:e,callback:t})}off(e){this.bindings=this.bindings.filter((t=>t.event!==e))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new V(this,e,t,r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}unsubscribe(e=this.timeout){this.state=q.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this.trigger(z.close,"leave",this.joinRef())},r=new V(this,z.leave,{},e);return r.receive("ok",(()=>t())).receive("timeout",(()=>t())),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,t,r){return t}isMember(e){return this.topic===e}joinRef(){return this.joinPush.ref}sendJoin(e){this.state=q.joining,this.joinPush.resend(e)}rejoin(e=this.timeout){this.isLeaving()||this.sendJoin(e)}trigger(e,t,r){let{close:s,error:n,leave:i,join:o}=z;if(r&&[s,n,i,o].indexOf(e)>=0&&r!==this.joinRef())return;let a=this.onMessage(e,t,r);if(t&&!a)throw"channel onMessage callbacks must return the payload, modified or unmodified";this.bindings.filter((r=>"*"===r.event?e===(null==t?void 0:t.type):r.event===e)).map((e=>e.callback(a,r)))}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===q.closed}isErrored(){return this.state===q.errored}isJoined(){return this.state===q.joined}isJoining(){return this.state===q.joining}isLeaving(){return this.state===q.leaving}}var Q=r(840);const X=()=>{};class Z{constructor(e,t){this.channels=[],this.endPoint="",this.headers={},this.params={},this.timeout=1e4,this.transport=Q.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.longpollerTimeout=2e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=X,this.conn=null,this.sendBuffer=[],this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.endPoint=`${e}/${K.websocket}`,(null==t?void 0:t.params)&&(this.params=t.params),(null==t?void 0:t.headers)&&(this.headers=t.headers),(null==t?void 0:t.timeout)&&(this.timeout=t.timeout),(null==t?void 0:t.logger)&&(this.logger=t.logger),(null==t?void 0:t.transport)&&(this.transport=t.transport),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs),(null==t?void 0:t.longpollerTimeout)&&(this.longpollerTimeout=t.longpollerTimeout),this.reconnectAfterMs=(null==t?void 0:t.reconnectAfterMs)?t.reconnectAfterMs:e=>[1e3,2e3,5e3,1e4][e-1]||1e4,this.encode=(null==t?void 0:t.encode)?t.encode:(e,t)=>t(JSON.stringify(e)),this.decode=(null==t?void 0:t.decode)?t.decode:(e,t)=>t(JSON.parse(e)),this.reconnectTimer=new W((()=>{return e=this,t=void 0,s=function*(){yield this.disconnect(),this.connect()},new((r=void 0)||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}));var e,t,r,s}),this.reconnectAfterMs)}connect(){this.conn||(this.conn=new this.transport(this.endPointURL(),[],null,this.headers),this.conn&&(this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e)))}disconnect(e,t){return new Promise(((r,s)=>{try{this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t||""):this.conn.close(),this.conn=null),r({error:null,data:!0})}catch(e){r({error:e,data:!1})}}))}log(e,t,r){this.logger(e,t,r)}onOpen(e){this.stateChangeCallbacks.open.push(e)}onClose(e){this.stateChangeCallbacks.close.push(e)}onError(e){this.stateChangeCallbacks.error.push(e)}onMessage(e){this.stateChangeCallbacks.message.push(e)}connectionState(){switch(this.conn&&this.conn.readyState){case J.connecting:return"connecting";case J.open:return"open";case J.closing:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.channels=this.channels.filter((t=>t.joinRef()!==e.joinRef()))}channel(e,t={}){let r=new Y(e,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:s,ref:n}=e,i=()=>{this.encode(e,(e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)}))};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?i():this.sendBuffer.push(i)}onConnMessage(e){this.decode(e.data,(e=>{let{topic:t,event:r,payload:s,ref:n}=e;n&&n===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${t} ${r} ${n&&"("+n+")"||""}`,s),this.channels.filter((e=>e.isMember(t))).forEach((e=>e.trigger(r,s,n))),this.stateChangeCallbacks.message.forEach((t=>t(e)))}))}endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_onConnOpen(){this.log("transport",`connected to ${this.endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>this._sendHeartbeat()),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach((e=>e()))}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((t=>t(e)))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach((t=>t(e)))}_triggerChanError(){this.channels.forEach((e=>e.trigger(z.error)))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef)return this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),void(null===(e=this.conn)||void 0===e||e.close(1e3,"hearbeat timeout"));this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef})}}}class ee{constructor(e,t,r){const s="*"===r?`realtime:${t}`:`realtime:${t}:${r}`;this.subscription=e.channel(s)}getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=R(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=R(e.columns,e.old_record)),t}on(e,t){return this.subscription.on(e,(e=>{let r={schema:e.schema,table:e.table,commit_timestamp:e.commit_timestamp,eventType:e.type,new:{},old:{}};r=Object.assign(Object.assign({},r),this.getPayloadRecords(e)),t(r)})),this}subscribe(e=(()=>{})){return this.subscription.onError((t=>e("SUBSCRIPTION_ERROR",t))),this.subscription.onClose((()=>e("CLOSED"))),this.subscription.subscribe().receive("ok",(()=>e("SUBSCRIBED"))).receive("error",(t=>e("SUBSCRIPTION_ERROR",t))).receive("timeout",(()=>e("RETRYING_AFTER_TIMEOUT"))),this.subscription}}class te extends j{constructor(e,{headers:t={},schema:r,realtime:s,table:n}){super(e,{headers:t,schema:r}),this._subscription=new ee(s,r,n),this._realtime=s}on(e,t){return this._realtime.isConnected()||this._realtime.connect(),this._subscription.on(e,t)}}var re=function(e,t,r,s){return new(r||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}))};const se=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e);function ne(e,t,r,s,n){return re(this,void 0,void 0,(function*(){return new Promise(((o,a)=>{i()(t,((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))})(e,r,s,n)).then((e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?o(e):e.json()})).then((e=>o(e))).catch((e=>((e,t)=>{if("function"!=typeof e.json)return t(e);e.json().then((r=>t({message:se(r),status:(null==e?void 0:e.status)||500})))})(e,a)))}))}))}function ie(e,t,r){return re(this,void 0,void 0,(function*(){return ne("GET",e,t,r)}))}function oe(e,t,r,s){return re(this,void 0,void 0,(function*(){return ne("POST",e,r,s,t)}))}function ae(e,t,r,s){return re(this,void 0,void 0,(function*(){return ne("DELETE",e,r,s,t)}))}var he=function(e,t,r,s){return new(r||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}))};const ce=()=>"undefined"!=typeof window;var le=function(e,t,r,s){return new(r||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}))};const ue={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},de={cacheControl:"3600"};class pe{constructor(e,t={},r){this.url=e,this.headers=t,this.bucketId=r}upload(e,t,r){return le(this,void 0,void 0,(function*(){try{if(!ce())throw new Error("No browser detected.");const s=new FormData;s.append("",t,t.name);const n=Object.assign(Object.assign({},de),r);s.append("cacheControl",n.cacheControl);const i=this._getFinalPath(e),o=yield fetch(`${this.url}/object/${i}`,{method:"POST",body:s,headers:Object.assign({},this.headers)});return o.ok?{data:{Key:i},error:null}:{data:null,error:yield o.json()}}catch(e){return{data:null,error:e}}}))}update(e,t,r){return le(this,void 0,void 0,(function*(){try{if(!ce())throw new Error("No browser detected.");const s=new FormData;s.append("",t,t.name);const n=Object.assign(Object.assign({},de),r);s.append("cacheControl",n.cacheControl);const i=this._getFinalPath(e),o=yield fetch(`${this.url}/object/${i}`,{method:"PUT",body:s,headers:Object.assign({},this.headers)});return o.ok?{data:{Key:i},error:null}:{data:null,error:yield o.json()}}catch(e){return{data:null,error:e}}}))}move(e,t){return le(this,void 0,void 0,(function*(){try{return{data:yield oe(`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(e){return{data:null,error:e}}}))}createSignedUrl(e,t){return le(this,void 0,void 0,(function*(){try{const r=this._getFinalPath(e);let s=yield oe(`${this.url}/object/sign/${r}`,{expiresIn:t},{headers:this.headers});const n=`${this.url}${s.signedURL}`;return s={signedURL:n},{data:s,error:null,signedURL:n}}catch(e){return{data:null,error:e,signedURL:null}}}))}download(e){return le(this,void 0,void 0,(function*(){try{const t=this._getFinalPath(e),r=yield ie(`${this.url}/object/${t}`,{headers:this.headers,noResolveJson:!0});return{data:yield r.blob(),error:null}}catch(e){return{data:null,error:e}}}))}remove(e){return le(this,void 0,void 0,(function*(){try{return{data:yield ae(`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){return{data:null,error:e}}}))}list(e,t,r){return le(this,void 0,void 0,(function*(){try{const s=Object.assign(Object.assign(Object.assign({},ue),t),{prefix:e||""});return{data:yield oe(`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(e){return{data:null,error:e}}}))}_getFinalPath(e){return`${this.bucketId}/${e}`}}class fe extends class{constructor(e,t={}){this.url=e,this.headers=t}listBuckets(){return he(this,void 0,void 0,(function*(){try{return{data:yield ie(`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){return{data:null,error:e}}}))}getBucket(e){return he(this,void 0,void 0,(function*(){try{return{data:yield ie(`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){return{data:null,error:e}}}))}createBucket(e){return he(this,void 0,void 0,(function*(){try{return{data:yield oe(`${this.url}/bucket`,{id:e,name:e},{headers:this.headers}),error:null}}catch(e){return{data:null,error:e}}}))}emptyBucket(e){return he(this,void 0,void 0,(function*(){try{return{data:yield oe(`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){return{data:null,error:e}}}))}deleteBucket(e){return he(this,void 0,void 0,(function*(){try{return{data:yield ae(`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){return{data:null,error:e}}}))}}{constructor(e,t={}){super(e,t)}from(e){return new pe(this.url,this.headers,e)}}var me=function(e,t,r,s){return new(r||(r=Promise))((function(n,i){function o(e){try{h(s.next(e))}catch(e){i(e)}}function a(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((s=s.apply(e,t||[])).next())}))};const ge={schema:"public",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,localStorage:globalThis.localStorage,headers:{}};class ye{constructor(e,t,r){if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const s=Object.assign(Object.assign({},ge),r);this.restUrl=`${e}/rest/v1`,this.realtimeUrl=`${e}/realtime/v1`.replace("http","ws"),this.authUrl=`${e}/auth/v1`,this.storageUrl=`${e}/storage/v1`,this.schema=s.schema,this.auth=this._initSupabaseAuthClient(s),this.realtime=this._initRealtimeClient()}get storage(){return new fe(this.storageUrl,this._getAuthHeaders())}from(e){const t=`${this.restUrl}/${e}`;return new te(t,{headers:this._getAuthHeaders(),schema:this.schema,realtime:this.realtime,table:e})}rpc(e,t){return this._initPostgRESTClient().rpc(e,t)}removeSubscription(e){return new Promise((t=>me(this,void 0,void 0,(function*(){try{yield this._closeSubscription(e);const r=this.getSubscriptions().length;if(!r){const{error:e}=yield this.realtime.disconnect();if(e)return t({error:e})}return t({error:null,data:{openSubscriptions:r}})}catch(e){return t({error:e})}}))))}_closeSubscription(e){return me(this,void 0,void 0,(function*(){e.isClosed()||(yield this._closeChannel(e))}))}getSubscriptions(){return this.realtime.channels}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,localStorage:s}){return new T({url:this.authUrl,headers:{Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`},autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,localStorage:s})}_initRealtimeClient(){return new Z(this.realtimeUrl,{params:{apikey:this.supabaseKey}})}_initPostgRESTClient(){return new O(this.restUrl,{headers:this._getAuthHeaders(),schema:this.schema})}_getAuthHeaders(){var e,t;const r={},s=null!==(t=null===(e=this.auth.session())||void 0===e?void 0:e.access_token)&&void 0!==t?t:this.supabaseKey;return r.apikey=this.supabaseKey,r.Authorization=`Bearer ${s}`,r}_closeChannel(e){return new Promise(((t,r)=>{e.unsubscribe().receive("ok",(()=>(this.realtime.remove(e),t(!0)))).receive("error",(e=>r(e)))}))}}const ve=(e,t,r)=>new ye(e,t,r)},98:function(e,t){var r="undefined"!=typeof self?self:this,s=function(){function e(){this.fetch=!1,this.DOMException=r.DOMException}return e.prototype=r,new e}();!function(e){!function(t){var r="URLSearchParams"in e,s="Symbol"in e&&"iterator"in Symbol,n="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),i="FormData"in e,o="ArrayBuffer"in e;if(o)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function c(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function u(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return s&&(t[Symbol.iterator]=function(){return t}),t}function d(e){this.map={},e instanceof d?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function p(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function f(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function m(e){var t=new FileReader,r=f(t);return t.readAsArrayBuffer(e),r}function g(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function y(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:n&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:i&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o&&n&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=g(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o&&(ArrayBuffer.prototype.isPrototypeOf(e)||h(e))?this._bodyArrayBuffer=g(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},n&&(this.blob=function(){var e=p(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(m)}),this.text=function(){var e,t,r,s=p(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,r=f(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),s=0;s-1?s:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n)}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),s=r.shift().replace(/\+/g," "),n=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(s),decodeURIComponent(n))}})),t}function _(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new d(t.headers),this.url=t.url||"",this._initBody(e)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},y.call(b.prototype),y.call(_.prototype),_.prototype.clone=function(){return new _(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},_.error=function(){var e=new _(null,{status:0,statusText:""});return e.type="error",e};var S=[301,302,303,307,308];_.redirect=function(e,t){if(-1===S.indexOf(t))throw new RangeError("Invalid status code");return new _(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function T(e,r){return new Promise((function(s,i){var o=new b(e,r);if(o.signal&&o.signal.aborted)return i(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function h(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new d,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),s=r.shift().trim();if(s){var n=r.join(":").trim();t.append(s,n)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var n="response"in a?a.response:a.responseText;s(new _(n,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new t.DOMException("Aborted","AbortError"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&n&&(a.responseType="blob"),o.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),o.signal&&(o.signal.addEventListener("abort",h),a.onreadystatechange=function(){4===a.readyState&&o.signal.removeEventListener("abort",h)}),a.send(void 0===o._bodyInit?null:o._bodyInit)}))}T.polyfill=!0,e.fetch||(e.fetch=T,e.Headers=d,e.Request=b,e.Response=_),t.Headers=d,t.Request=b,t.Response=_,t.fetch=T,Object.defineProperty(t,"__esModule",{value:!0})}({})}(s),s.fetch.ponyfill=!0,delete s.fetch.polyfill;var n=s;(t=n.fetch).default=n.fetch,t.fetch=n.fetch,t.Headers=n.Headers,t.Request=n.Request,t.Response=n.Response,e.exports=t},284:e=>{var t=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};e.exports=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(e){return t()}try{return __global__||t()}finally{delete Object.prototype.__global__}}()},840:(e,t,r)=>{var s;if("object"==typeof globalThis)s=globalThis;else try{s=r(284)}catch(e){}finally{if(s||"undefined"==typeof window||(s=window),!s)throw new Error("Could not determine global this")}var n=s.WebSocket||s.MozWebSocket,i=r(387);function o(e,t){return t?new n(e,t):new n(e)}n&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(o,e,{get:function(){return n[e]}})})),e.exports={w3cwebsocket:n?o:null,version:i}},387:(e,t,r)=>{e.exports=r(847).version},847:e=>{"use strict";e.exports={version:"1.0.34"}}},t={};function r(s){var n=t[s];if(void 0!==n)return n.exports;var i=t[s]={exports:{}};return e[s].call(i.exports,i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{"use strict";var e=s;Object.defineProperty(e,"__esModule",{value:!0}),e.startLogging=void 0;const t=r(489);e.startLogging=function(e){const r={INFO:"color: white; background: darkgreen; border:1px solid darkgreen;",ASSERT:"color: white; background: darkred; border:1px solid darkred;",ERROR:"color: white; background: darkred; border:1px solid darkred;",LOG:"color: black; background: white; border:1px solid;",TIMER:"color: black; background: white; border:1px solid;",WARN:"color: black; background: yellow; border:1px solid;"},s={INFO:String.fromCodePoint(128994),ASSERT:String.fromCodePoint(10062),ERROR:String.fromCodePoint(128308),LOG:String.fromCodePoint(9898),TIMER:String.fromCodePoint(8987),WARN:String.fromCodePoint(128993)};let n,i;if(e.supabase)n=e.supabase;else{if(!e.url||!e.key)return console.error("%c %s ",r.ERROR,'Error connecting to PostgreSQL ... you must either pass an object with a Supabase Client { supabase: mySupabaseClientObject } or an object with url and key { url: "https://xxx.supabase.co", key: "anon-key"} \n'),null;n=t.createClient(e.url,e.key)}return console.log("%c %s ",r.INFO,"\nConnected to PostgreSQL ... listening for console messages from SupaScript functions...\n"),i=n.from("supascript_log").on("INSERT",(e=>{const t=e.new.log_type;e.new.content.unshift(s[t]),console.log("%c pgFunc %o",r[t],...e.new.content,{details:e.new})})).subscribe(),i}})(),s})()})); -------------------------------------------------------------------------------- /docs/sample_chome_console_details.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burggraf/SupaScriptConsole/3aa86aa8ad7a5e4dba8c871e3d27fc5ccc114003/docs/sample_chome_console_details.png -------------------------------------------------------------------------------- /docs/sample_chrome_console_output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burggraf/SupaScriptConsole/3aa86aa8ad7a5e4dba8c871e3d27fc5ccc114003/docs/sample_chrome_console_output.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "supascriptconsole", 3 | "version": "1.0.0", 4 | "description": "Javascript library for local console logging of Supabase rpc calls (PostgreSQL functions)", 5 | "main": "./dist/main/index.js", 6 | "module": "./dist/module/index.js", 7 | "types": "./dist/main/index.d.ts", 8 | "files": [ 9 | "dist" 10 | ], 11 | "scripts": { 12 | "test": "echo \"Error: no test specified\" && exit 1", 13 | "build": "run-s build:*", 14 | "build:main": "tsc -p tsconfig.json", 15 | "build:module": "tsc -p tsconfig.module.json", 16 | "build:umd": "webpack", 17 | "publish-lib": "npm run build && npm publish", 18 | "publish-beta": "npm run build && npm publish --tag beta", 19 | "publish-dryrun": "npm run build && npm publish --dry-run" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/burggraf/SupaScriptConsole.git" 24 | }, 25 | "keywords": [ 26 | "supabase", 27 | "postgresql", 28 | "javascript" 29 | ], 30 | "author": "Mark Burggraf", 31 | "license": "ISC", 32 | "bugs": { 33 | "url": "https://github.com/burggraf/SupaScriptConsole/issues" 34 | }, 35 | "homepage": "https://github.com/burggraf/SupaScriptConsole#readme", 36 | "dependencies": { 37 | "@supabase/supabase-js": "^1.11.7" 38 | }, 39 | "devDependencies": { 40 | "npm-run-all": "^4.1.5", 41 | "run-s": "*", 42 | "ts-loader": "^9.0.2", 43 | "typescript": "^3.9.9", 44 | "webpack": "^5.35.0", 45 | "webpack-cli": "^4.6.0" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { createClient, SupabaseClient, RealtimeSubscription } from '@supabase/supabase-js'; 2 | 3 | 4 | function startLogging (obj: any): RealtimeSubscription | null { 5 | const style: any = { 6 | 'INFO': 'color: white; background: darkgreen; border:1px solid darkgreen;', 7 | 'ASSERT': 'color: white; background: darkred; border:1px solid darkred;', 8 | 'ERROR': 'color: white; background: darkred; border:1px solid darkred;', 9 | 'LOG': 'color: black; background: white; border:1px solid;', 10 | 'TIMER': 'color: black; background: white; border:1px solid;', 11 | 'WARN': 'color: black; background: yellow; border:1px solid;', 12 | }; 13 | const icon: any = { 14 | 'INFO': String.fromCodePoint(0x1f7e2), 15 | 'ASSERT': String.fromCodePoint(0x274e), 16 | 'ERROR': String.fromCodePoint(0x1f534), 17 | 'LOG': String.fromCodePoint(0x26aa), 18 | 'TIMER': String.fromCodePoint(0x231b), 19 | 'WARN': String.fromCodePoint(0x1f7e1), 20 | }; 21 | let supabase: SupabaseClient; 22 | if (obj.supabase) { 23 | supabase = obj.supabase; 24 | } else if (obj.url && obj.key) { 25 | supabase = createClient(obj.url, obj.key); 26 | } else { 27 | console.error('%c %s ', style.ERROR, 28 | '\Error connecting to PostgreSQL ... you must either pass an object with a Supabase Client { supabase: mySupabaseClientObject } or an object with url and key { url: "https://xxx.supabase.co", key: "anon-key"} \n'); 29 | return null; 30 | } 31 | console.log('%c %s ', style.INFO, 32 | '\nConnected to PostgreSQL ... listening for console messages from SupaScript functions...\n'); 33 | 34 | let subscription: RealtimeSubscription; 35 | subscription = supabase 36 | .from('supascript_log') 37 | .on('INSERT', (payload: any) => { 38 | const type: string = payload.new.log_type; 39 | payload.new.content.unshift(icon[type]); 40 | console.log('%c pgFunc %o', style[type], ...payload.new.content, {details:payload.new}); 41 | }) 42 | .subscribe(); 43 | return subscription; 44 | } 45 | 46 | 47 | 48 | export { startLogging }; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "src" 4 | ], 5 | "exclude": ["node_modules/**/*.ts"], 6 | "compilerOptions": { 7 | "module": "CommonJS", 8 | "target": "ES2015", 9 | "declaration": true, 10 | "declarationMap": true, 11 | "outDir": "dist/main", 12 | "rootDir": "src", 13 | "sourceMap": true, 14 | 15 | "strict": true, 16 | 17 | "esModuleInterop": true, 18 | "moduleResolution": "Node", 19 | 20 | "forceConsistentCasingInFileNames": true, 21 | "stripInternal": true, 22 | "allowSyntheticDefaultImports": true 23 | } 24 | } -------------------------------------------------------------------------------- /tsconfig.module.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig", 3 | "compilerOptions": { 4 | "module": "ES2015", 5 | "outDir": "dist/module" 6 | } 7 | } 8 | 9 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack') 2 | const path = require('path') 3 | 4 | module.exports = { 5 | entry: './src/index.ts', 6 | output: { 7 | path: path.resolve(__dirname, 'dist/umd'), 8 | filename: 'supascriptconsole.js', 9 | library: { 10 | type: 'umd', 11 | name: 'supascriptconsole', 12 | }, 13 | }, 14 | mode: "production", 15 | module: { 16 | rules: [ 17 | { 18 | test: /\.ts$/, 19 | loader: 'ts-loader', 20 | options: { 21 | transpileOnly: true, 22 | }, 23 | }, 24 | ], 25 | }, 26 | resolve: { 27 | extensions: ['.ts', '.js', '.json'], 28 | }, 29 | plugins: [ 30 | new webpack.DefinePlugin({ 31 | process: 'process/browser', 32 | }), 33 | ], 34 | } 35 | 36 | --------------------------------------------------------------------------------