internetarchive-sdk-js
Version:
NodeJS / Typescript SDK for Internet Archive APIs
50 lines (49 loc) • 1.54 kB
JavaScript
import { readPackageJSON } from 'pkg-types';
import { randomBytes } from 'crypto';
import slugify from 'slugify';
import { z } from 'zod';
export async function getPackageInfo() {
try {
return await readPackageJSON('./node_modules/internetarchive-sdk-js/package.json');
}
catch {
return null;
}
}
export function generateItemIdFromMetadata(metadata) {
const uuid = randomBytes(8).toString('hex').toLowerCase();
const title = metadata?.title && metadata?.subject
? `${metadata?.subject}-${metadata?.title}-${uuid}`
: metadata?.collection
? `${metadata?.collection}-${uuid}`
: uuid;
return slugify(title, {
replacement: '-',
lower: true,
strict: true,
trim: true,
});
}
export function isASCII(str) {
// eslint-disable-next-line no-control-regex
return /^[\x00-\x7F]+$/.test(str);
}
export function parseZodErrorToString(err) {
return err.issues.map((issue, _idx) => {
const path = issue.path?.[0] ? `${issue.path?.[0]} - ` : '';
return path + `${issue.message}`;
}).join(', ');
}
/* https://github.com/colinhacks/zod/issues/61 */
export function oneOf(key1, key2) {
return (arg, ctx) => {
if ((arg[key1] === undefined) === (arg[key2] === undefined)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Either <${key1}> or <${key2}> must be set.`,
});
return false;
}
return true;
};
}