Skip to content

Commit

Permalink
use dynamic variable export to manage token
Browse files Browse the repository at this point in the history
  • Loading branch information
martypdx committed Nov 3, 2023
1 parent 4a6a1df commit 971b0d9
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 75 deletions.
5 changes: 5 additions & 0 deletions www/src/services/auth.js
@@ -1,5 +1,10 @@
import { client } from './supabase.js';

export let token = null;
watchAuth((_event, session) => {
token = session?.access_token ?? null;
});

export function watchAuth(callback) {
client.auth.onAuthStateChange(callback);
}
Expand Down
101 changes: 49 additions & 52 deletions www/src/services/spirit-wave.js
@@ -1,22 +1,26 @@
import { watchAuth } from './auth.js';

// Tests for this regex: https://regex101.com/r/5zXb2v/2
const ExtractPreContentRegex = /<pre>(.+?)<\/pre>/gims;

let token = null;

watchAuth((event, session) => {
token = session.access_token;
});
import { token } from './auth.js';

const SUPABASE_PROJECT_URL = window.SUPABASE_PROJECT_URL || '';
const API_URL = `${SUPABASE_PROJECT_URL}/functions/v1/play`;

// const API_KEY = window.SUPABASE_API_KEY;
// const API_KEY_QUERY = API_KEY ? `?apikey=${encodeURIComponent(API_KEY)}` : '';
export async function getStream(sessionId) {
const res = await getResponse(API_URL, sessionId);

// const getUrl = path => `${API_URL}${path}${API_KEY_QUERY}`;
try {
await handleNotOk(res);
return res.body.pipeThrough(new TextDecoderStream());
}
catch (err) {
//TODO: handle more failures:
// - no body
// - piping issues thru textdecoder?

// eslint-disable-next-line no-console
console.log (err);
if (err instanceof ConnectivityError) throw err;
throw new FetchError(err);
}
}

function getResponse(url, sessionId) {
try {
Expand All @@ -33,45 +37,6 @@ function getResponse(url, sessionId) {
}
}

export const getStream = async (sessionId) => {
const res = await getResponse(API_URL, sessionId);
try {
if (!res.ok) {
let error = null;
error = await res.text();
if (error.startsWith('<!DOCTYPE html>')) {
const matches = error.matchAll(ExtractPreContentRegex);
let message = `${res.status}: ${res.statusText}`;
for (const [, group] of matches) {
message += '\n' + (group ?? '');
}

throw message;
}
else {
try {
error = JSON.parse(error);
}
finally {
// eslint-disable-next-line no-unsafe-finally
throw error;
}
}
}

return res.body.pipeThrough(new TextDecoderStream());
}
catch (err) {
//TODO: handle different failures:
// - res.json issues (might go in code block with .json()?)
// - no body
// - piping issues thru textdecoder?

// eslint-disable-next-line no-console
console.log (err);
throw new FetchError(err);
}
};

class FetchError extends Error {
constructor(statusCode, statusText, err) {
Expand All @@ -90,3 +55,35 @@ class ConnectivityError extends Error {
}
}

async function handleNotOk(res) {
if (res.ok) return;

let error = null;
error = await res.text();
handleHtmlError(error, res);

try {
error = JSON.parse(error);
}
catch (_) { /* no-op */ }

throw error;
}


// Tests for this regex: https://regex101.com/r/5zXb2v/2
const ExtractPreContentRegex = /<pre>(.+?)<\/pre>/gims;

function handleHtmlError(error, res) {
// usually proxy dev server
if (!error.startsWith('<!DOCTYPE html>')) return;

const matches = error.matchAll(ExtractPreContentRegex);
let message = `${res.status}: ${res.statusText}`;
for (const [, group] of matches) {
message += '\n' + (group ?? '');
}

throw message;
}

41 changes: 18 additions & 23 deletions www/src/session.js
Expand Up @@ -11,20 +11,31 @@ export async function startSession() {
return;
}

const { id:sessionId } = data;

const streamAI = () => getStream(sessionId);

console.log('session id', sessionId);

await tryStream(streamAI);
const { id: sessionId } = data;
const stream = await getStream(sessionId);
await tryStream(stream);
await injectContinue();

const done = document.createElement('p');
done.textContent = 'all done';
output.append(done); // *** output
}

async function tryStream(stream) {
const domStream = htmlToDomStream(output); // *** output
try {
await stream.pipeTo(domStream);
}
catch (err) {
// TODO: better handling of failures. maybe a service at some point
let message = err?.message;
if (typeof message === 'object') {
message = JSON.stringify(message, true, 2);
}
alert(err?.constructor?.name + ' - ' + message);
}
}

async function injectContinue() {
const p = document.createElement('p');
const button = document.createElement('button');
Expand All @@ -43,19 +54,3 @@ async function injectContinue() {
});
});
}

async function tryStream(getStream) {
const domStream = htmlToDomStream(output); // *** output
try {
const stream = await getStream();
await stream.pipeTo(domStream);
}
catch (err) {
// TODO: better handling of failures. maybe a service at some point
let message = err?.message;
if (typeof message === 'object') {
message = JSON.stringify(message, true, 2);
}
alert(err?.constructor?.name + ' - ' + message);
}
}

0 comments on commit 971b0d9

Please sign in to comment.