@scriptables/manifest
Version:
Utilities to generate, parse, and update manifest headers in Scriptable scripts.
81 lines (66 loc) • 2.28 kB
text/typescript
/* eslint-disable @typescript-eslint/naming-convention */
import {ScriptableManifest} from './types';
/**
* Boolean converter
*/
const BooleanConverter = (value: any): boolean | any => {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number' && (value === 0 || value === 1)) {
return value === 1;
}
if (typeof value === 'string') {
const lower = value.toLowerCase();
return lower === 'true' || lower === '1';
}
return value;
};
/**
* String to lowercase converter
*/
const ToLowerCaseConverter = (value: any): string | any => {
if (typeof value === 'string') {
return value.toLowerCase();
}
return value;
};
/**
* Convert the input to a string array and convert all elements to lowercase
*/
const ShareSheetInputsConverter = (value: string | string[]): string[] => {
// If the input is a string, convert it to a single element array
const array = Array.isArray(value) ? value : [value];
// Convert all elements to lowercase
return array.map(item => String(item).toLowerCase());
};
/**
* Transform the mapping table and select the corresponding conversion function based on the key name
*/
const converters: Partial<Record<keyof ScriptableManifest, (value: any) => any>> = {
alwaysRunInApp: BooleanConverter,
shareSheetInputs: ShareSheetInputsConverter,
iconColor: ToLowerCaseConverter,
iconGlyph: ToLowerCaseConverter,
};
/**
* The type definition of the Manifest object
*/
type Manifest = {
[key: string]: any;
};
/**
* The normalized manifest key is camelCase, and the value is converted according to a predefined converter
*/
export function normalizeManifest(manifest: Manifest): ScriptableManifest {
const normalized: Record<string, any> = {};
for (const [key, value] of Object.entries(manifest ?? {})) {
// Convert kebab/snake case to camel case
const normalizedKey = key.replace(/[-_](.)/g, (_, c) => c.toUpperCase());
// Select the corresponding converter and keep the original value if it is not defined
const converter = converters[normalizedKey as keyof typeof converters] || ((val: any) => val);
const normalizedValue = converter(value);
normalized[normalizedKey] = normalizedValue;
}
return normalized as ScriptableManifest;
}