All files / metadata/src/safeFunctions compile.ts

17.5% Statements 14/80
18.57% Branches 13/70
20.83% Functions 5/24
17.94% Lines 14/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353                                                                                                                                                      137x                             137x           137x                             2329x                                 3151x                               3973x 3973x                                   2055x     2055x       2055x 3151x 3151x     3151x           2055x                                                                                                                                                                                                                                                                                                                                                      
/**
 * The **safe function compiler**: turns the JSON vocabulary in `types.ts` into
 * executable predicates and value readers, with no `eval` and no
 * `new Function`.
 *
 * The compiler is strict, and reads its rules from `schema.ts`. It does not
 * know the names of the subject: the `readName` of the site gives the reader
 * of each name, and can reject a name. The default reads an own property of
 * the subject, never `Object.prototype`. See
 * `packages/docs/docs/concepts/safe-functions.md`.
 *
 * @module safeFunctions/compile
 */
 
import { compileExpression } from './expression';
import { compileMatchTest } from './matchTests';
import {
  at,
  conditionShape,
  INSTANCE_EXPRESSION_SCOPE,
  invalidAt,
  isUnsafeKey,
  matchForm,
  readOwn,
  safeFunctionSchema,
  unrecognized,
  valueShape,
} from './schema';
import type {
  ExpressionScope,
  NameReader,
  NameReaderFunction,
  Schema,
  SchemaSite,
  ShapeCompiler,
} from './schema';
import type {
  CompiledPredicate,
  CompiledValue,
  RawCondition,
  RawValue,
  SafeFunctionSubject,
} from './types';
import { hasNoValue } from './values';
 
export {
  compareFinite,
  hasNoValue,
  isAbsent,
  isEmpty,
  isTrue,
  looseEquals,
} from './values';
 
/**
 * Where a condition or a value is compiled. Every field is optional; the
 * defaults compile a stand-alone definition called `(instance, context)`.
 */
export type CompileOptions = {
  /** Path of the definition, for messages, e.g. `rule 'r'.matches`. */
  path?: string;
  /** What is being compiled, for messages. Defaults to `safe function definition`. */
  definition?: string;
  /**
   * The expression variables of the place. Defaults to
   * {@link INSTANCE_EXPRESSION_SCOPE}: called `(instance, context)`, bare
   * identifiers read the attributes of `instance`.
   */
  expression?: ExpressionScope;
  /** The call signature of the place, for messages. */
  call?: string;
  /** The reader of a name. Defaults to an own-property read of the subject. */
  readName?: NameReader;
};
 
const DEFAULT_DEFINITION = 'safe function definition';
 
/**
 * Throws with the offending fragment inlined - a definition is usually authored
 * by hand or shipped as config, so a mistake in it must name itself.
 */
export function invalid(message: string, fragment: unknown): never {
  return invalidAt(
    { path: '', definition: DEFAULT_DEFINITION },
    message,
    fragment
  );
}
 
/** Reads `subject[name]`, and then `[field]` of that, as own properties. */
export const readOwnName: NameReader = (name, _site, field) =>
  field === undefined
    ? (subject) => readOwn(subject, name)
    : (subject) => readOwn(readOwn(subject, name), field);
 
/** The compilers of the generic shapes, keyed by shape name. */
export const safeFunctionCompilers: Record<string, ShapeCompiler> = {
  condition: (fragment, site) => compileConditionAt(fragment, site),
  matchTest: (fragment, site) => compileMatchTest(fragment, site),
  value: (fragment, site) => compileValueAt(fragment, site),
};
 
/**
 * Builds the site of a stand-alone compile, for {@link compileCondition} and
 * {@link compileValue}.
 */
export function createSite(
  options: CompileOptions = {},
  schema: Schema = safeFunctionSchema,
  compilers: Record<string, ShapeCompiler> = safeFunctionCompilers
): SchemaSite {
  return {
    path: options.path ?? '',
    definition: options.definition ?? DEFAULT_DEFINITION,
    schema,
    compilers,
    readName: options.readName ?? readOwnName,
    expression: options.expression ?? INSTANCE_EXPRESSION_SCOPE,
    call: options.call,
  };
}
 
/** The reader of a name at a site. */
export function readNameAt(
  name: string,
  site: SchemaSite,
  field?: string
): NameReaderFunction {
  return (site.readName ?? readOwnName)(name, site, field);
}
 
/**
 * Compiles an expression with the variables of its place. A syntax error, or
 * a bare identifier where the place has no implicit scope, throws with the
 * path of the place.
 */
export function compileExpressionAt(
  source: string,
  site: SchemaSite,
  scope: ExpressionScope & {
    receivers?: Readonly<Record<string, string>>;
    unavailableReceivers?: Readonly<Record<string, string>>;
  } = site.expression ?? INSTANCE_EXPRESSION_SCOPE
) {
  try {
    return compileExpression(source, {
      params: scope.params,
      implicitScope: scope.implicitScope,
      receivers: scope.receivers,
      unavailableReceivers: scope.unavailableReceivers,
    });
  } catch (error) {
    return invalidAt(site, (error as Error).message);
  }
}
 
/**
 * Compiles a condition at a site. See {@link compileCondition}.
 */
export function compileConditionAt<Subject extends SafeFunctionSubject>(
  condition: unknown,
  site: SchemaSite
): CompiledPredicate<Subject> {
  Iif (typeof condition === 'function') {
    return condition as CompiledPredicate<Subject>;
  }
  Iif (!condition || typeof condition !== 'object' || Array.isArray(condition)) {
    return unrecognized(conditionShape, condition, site);
  }
 
  const entries = Object.entries(condition).map(([name, test]) => {
    const entrySite = at(site, name);
    Iif (isUnsafeKey(name)) {
      invalidAt(entrySite, `the name "${name}" is not allowed`, condition);
    }
    return {
      read: readNameAt(name, entrySite),
      test: compileMatchTest(test, entrySite),
    };
  });
 
  return (subject, context) =>
    entries.every(({ read, test }) =>
      test(read(subject, context), subject, context)
    );
}
 
/**
 * Compiles a {@link RawCondition} into a safe predicate: a map of name to
 * test, where every entry must hold (see `matchTests.ts` for the tests).
 *
 * An actual function passes through as is.
 *
 * @param condition - the condition as data.
 * @param options - where the condition sits, and the reader of a name.
 * @throws when the condition is not a form the schema accepts.
 */
export function compileCondition<Subject extends SafeFunctionSubject>(
  condition: RawCondition,
  options: CompileOptions = {}
): CompiledPredicate<Subject> {
  return compileConditionAt<Subject>(condition, createSite(options));
}
 
/** One segment of a parsed template: literal text, or a name and its field. */
export type TemplateSegment =
  | { literal: string }
  | { name: string; field?: string };
 
/**
 * Parses a `{ template: 'text {Name} {group.field} more' }` text into its
 * literal and placeholder segments. `\{` and `\}` escape a brace. A
 * placeholder is a name, or a name and one field.
 */
export function parseTemplate(
  template: string,
  site: Pick<SchemaSite, 'path' | 'definition'> = {
    path: '',
    definition: DEFAULT_DEFINITION,
  }
): TemplateSegment[] {
  if (typeof template !== 'string') {
    invalidAt(site, 'template must be a string', template);
  }
 
  const segments: TemplateSegment[] = [];
  let literal = '';
 
  for (let i = 0; i < template.length; i++) {
    const char = template[i];
 
    if (char === '\\' && (template[i + 1] === '{' || template[i + 1] === '}')) {
      literal += template[i + 1];
      i++;
      continue;
    }
 
    if (char !== '{') {
      literal += char;
      continue;
    }
 
    const end = template.indexOf('}', i + 1);
    if (end === -1) {
      invalidAt(site, 'template has an unclosed "{"', template);
    }
    const placeholder = template.slice(i + 1, end).trim();
    if (!placeholder) {
      invalidAt(site, 'template has an empty "{}" placeholder', template);
    }
    const [name, field, ...rest] = placeholder.split('.');
    if (!name || field === '' || rest.length) {
      invalidAt(
        site,
        `template placeholder "{${placeholder}}" must be a name, or a name and one field`,
        template
      );
    }
    if (literal) {
      segments.push({ literal });
      literal = '';
    }
    segments.push(field === undefined ? { name } : { name, field });
    i = end;
  }
 
  if (literal) {
    segments.push({ literal });
  }
  return segments;
}
 
/**
 * Compiles a `{ template: 'text {Name} more' }` value into a reader that
 * substitutes each placeholder with the value of its name. The `readName` of
 * the site gives the reader of each name.
 *
 * Substitution is all it does - there is no arithmetic or expression syntax -
 * so a template is never a route to evaluated code. A name with no value
 * substitutes an empty string.
 */
export function compileTemplate<Subject extends SafeFunctionSubject>(
  template: string,
  site: SchemaSite = createSite()
): CompiledValue<Subject> {
  const parts = parseTemplate(template, site).map((segment) =>
    'literal' in segment
      ? () => segment.literal
      : readNameAt(segment.name, site, segment.field)
  );
  return (subject, context) =>
    parts
      .map((part) => {
        const value = part(subject, context);
        return hasNoValue(value) ? '' : String(value);
      })
      .join('');
}
 
/**
 * Compiles a value at a site. See {@link compileValue}.
 */
export function compileValueAt<Subject extends SafeFunctionSubject>(
  value: unknown,
  site: SchemaSite
): CompiledValue<Subject> {
  if (typeof value === 'function') {
    return value as CompiledValue<Subject>;
  }
 
  if (typeof value === 'string') {
    return readNameAt(value, site) as CompiledValue<Subject>;
  }
 
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    return unrecognized(valueShape, value, site);
  }
 
  const [form] = matchForm(valueShape, value, site);
  const fields = value as Record<string, unknown>;
 
  if (form === 'template') {
    return compileTemplate<Subject>(
      fields.template as string,
      at(site, 'template')
    );
  }
 
  // Not coerced: in value position the expression's own result is the point.
  const evaluate = compileExpressionAt(
    fields.expression as string,
    at(site, 'expression')
  );
  return (subject, context) => evaluate(subject, context);
}
 
/**
 * Compiles a {@link RawValue} into a safe value reader: a name, a template or
 * an expression.
 *
 * An actual function passes through as is.
 *
 * @param value - the value as data.
 * @param options - where the value sits, and the reader of a name.
 * @throws when the value is not a form the schema accepts.
 */
export function compileValue<Subject extends SafeFunctionSubject>(
  value: RawValue,
  options: CompileOptions = {}
): CompiledValue<Subject> {
  return compileValueAt<Subject>(value, createSite(options));
}