create amnet-shared for web/native shared files

This commit is contained in:
ppc
2024-08-22 09:01:59 +01:00
parent 839d45884a
commit 733fa96b19
6 changed files with 2181 additions and 7 deletions
+57
View File
@@ -0,0 +1,57 @@
/**
* The latest version of the AMNet API this library supports
*/
export const AMNET_API_VERSION = 1;
export interface AMCardInRequest {
cardId: string;
}
export interface AMServerInfoResponse {
serverAddress: string;
serverName: string;
apiVersion: number;
}
/**
* Performs the card-in request to the specified server
* @param serverAddress The origin address of the server to perform the request against
* @param request The card-in request to send
* @param signal The abort signal to use for the request
*/
export async function performCardIn(serverAddress: string, request: AMCardInRequest, signal: AbortSignal) {
try {
const response = await fetch(`${serverAddress}/card`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(request),
signal: signal
});
return response.ok;
} catch {
return false;
}
}
/**
* Attempts to connect to the specified server and fetch its info
* @param serverAddress The origin address of the server to connect to
* @param abort The abort signal to use for the request (for cancellation)
*/
export async function fetchServerInfo(serverAddress: string, abort: AbortSignal): Promise<AMServerInfoResponse | null> {
try {
const response = await fetch(serverAddress, {
signal: abort
});
return {
...await response.json(),
serverAddress: serverAddress
} satisfies AMServerInfoResponse;
} catch {
return null;
}
}
+29
View File
@@ -0,0 +1,29 @@
export const CARD_ID_REGEX = /^(?:[0-9]{4} ?){5}$/i;
export function generateCardNumber(): string {
let cardId = '';
while (true) {
// don't start with a 3
const firstDigit = Math.floor(Math.random() * 10);
if (firstDigit !== 3) {
cardId = firstDigit.toString();
break;
}
}
for (let i = 0; i < 19; i++) {
cardId += Math.floor(Math.random() * 10).toString();
}
return cardId;
}
/**
* Validates the provided card id by known parameters
* @param id The card id to validate
*/
export function validateCardId(id: string): boolean {
return id[0] !== '3' && CARD_ID_REGEX.test(id);
}