Suite of AT Protocol TypeScript libraries built on web standards
1/**
2 * Validates a record key (rkey)
3 * @param rkey - Record key to validate
4 * @throws {InvalidRecordKeyError} if the record key is invalid
5 */
6export const ensureValidRecordKey = (rkey: string): void => {
7 if (rkey.length > 512 || rkey.length < 1) {
8 throw new InvalidRecordKeyError("record key must be 1 to 512 characters");
9 }
10 // simple regex to enforce most constraints via just regex and length.
11 if (!/^[a-zA-Z0-9_~.:-]{1,512}$/.test(rkey)) {
12 throw new InvalidRecordKeyError("record key syntax not valid (regex)");
13 }
14 if (rkey === "." || rkey === "..") {
15 throw new InvalidRecordKeyError("record key can not be '.' or '..'");
16 }
17};
18
19/**
20 * Validates a record key (rkey) to a boolean
21 * @param rkey - Record key to validate
22 * @returns true if the record key is valid, false otherwise
23 */
24export const isValidRecordKey = (rkey: string): boolean => {
25 try {
26 ensureValidRecordKey(rkey);
27 } catch (err) {
28 if (err instanceof InvalidRecordKeyError) {
29 return false;
30 }
31 throw err;
32 }
33
34 return true;
35};
36
37export class InvalidRecordKeyError extends Error {}