Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

2.6 KB
Raw Blame
/**
 * Backend source-of-truth read layer for Policies: fetch the stored policies
 * (grouped by catalog category) and decode them onto the frontend's per-category
 * state for the editor's enforcement path.
 *
 * The frontend is keyed by policy (one policy per catalog entry); the backend is a
 * flat list with assigned ids. The bridge is `output.options.categoryId`, which
 * `policyPipeline` decodes on read.
 */

import * as policyApi from "@editor/services/policyApi";
import {
  fromBackendPolicy,
  type DecodedPolicy,
} from "@editor/services/policyPipeline";
import type { PolicyState } from "@editor/types/policies";

/**
 * Fetch every stored policy and decode it, keyed by its catalog category. If two
 * stored policies share a category (shouldn't happen — one per category), the
 * last one wins; policies with no recognised key are skipped.
 */
export async function fetchPoliciesByCategory(): Promise<
  Map<string, DecodedPolicy>
> {
  // The backend returns policies in the team's run order; the list index IS the
  // order (server-side, shared team-wide), which we carry onto the decoded state.
  const stored = await policyApi.listPolicies();
  const byCategory = new Map<string, DecodedPolicy>();
  stored.forEach((policy, index) => {
    const decoded = fromBackendPolicy(policy);
    // A pipeline built on the Pipelines page has no category tile, so it keys by its own id
    // rather than being dropped - one set to run on the editor still has to reach the auto-run.
    const key = decoded.policyKey || decoded.id;
    if (key) byCategory.set(key, { ...decoded, order: index });
  });
  return byCategory;
}

/** Project backend policy settings onto the editor's cached enforcement state. */
export function decodedToState(decoded: DecodedPolicy): PolicyState {
  return {
    configured: true,
    enabled: decoded.enabled,
    name: decoded.name,
    owner: decoded.owner,
    sources: decoded.sources,
    runsOnEditor: decoded.runsOnEditor,
    externalOutput: decoded.externalOutput,
    required: decoded.required,
    scopeTypes: decoded.scopeTypes,
    reviewerEmail: decoded.reviewerEmail,
    fieldValues: decoded.fieldValues,
    outputMode: decoded.folder.outputMode,
    outputName: decoded.folder.outputName,
    outputNamePosition: decoded.folder.outputNamePosition,
    runOn: decoded.folder.runOn,
    backendId: decoded.id,
    firstOperation: decoded.firstOperation,
    // Server-side run-order position (team-wide); drives the settings reorder list.
    order: decoded.order,
    // Catalog-category policies are built-in defaults (not deletable); a builder pipeline is not.
    isDefault: Boolean(decoded.policyKey),
  };
}