1import Debug from 'debug';
2
3import { InfoPlist } from './IosConfig.types';
4import { ConfigPlugin } from '../Plugin.types';
5import { withInfoPlist } from '../plugins/ios-plugins';
6
7const debug = Debug('expo:config-plugins:ios:permissions');
8
9export function applyPermissions<Defaults extends Record<string, string> = Record<string, string>>(
10  defaults: Defaults,
11  permissions: Partial<Record<keyof Defaults, string | false>>,
12  infoPlist: InfoPlist
13): InfoPlist {
14  const entries = Object.entries(defaults);
15  if (entries.length === 0) {
16    debug(`No defaults provided: ${JSON.stringify(permissions)}`);
17  }
18  for (const [permission, description] of entries) {
19    if (permissions[permission] === false) {
20      debug(`Deleting "${permission}"`);
21      delete infoPlist[permission];
22    } else {
23      infoPlist[permission] = permissions[permission] || infoPlist[permission] || description;
24      debug(`Setting "${permission}" to "${infoPlist[permission]}"`);
25    }
26  }
27  return infoPlist;
28}
29
30/**
31 * Helper method for creating mods to apply default permissions.
32 *
33 * @param action
34 */
35export function createPermissionsPlugin<
36  Defaults extends Record<string, string> = Record<string, string>,
37>(defaults: Defaults, name?: string) {
38  const withIosPermissions: ConfigPlugin<Record<keyof Defaults, string | undefined | false>> = (
39    config,
40    permissions
41  ) =>
42    withInfoPlist(config, async (config) => {
43      config.modResults = applyPermissions(defaults, permissions, config.modResults);
44      return config;
45    });
46  if (name) {
47    Object.defineProperty(withIosPermissions, 'name', {
48      value: name,
49    });
50  }
51  return withIosPermissions;
52}
53