{"version":3,"file":"version-manifest.cjs","names":["join","existsSync","BuildEntryReportSchema","readFileSync","composeVersionManifest","bundleUrlToStagedPath","resolveContained","path","readdirSync","statSync","WorkspaceVersionManifestSchema","MF_MANIFEST_FILENAME","mark","manifestDocumentUrl","verifyDocument","asDigest","reasonOf"],"sources":["../../../src/services/deploy/version-manifest.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport path, { join } from \"node:path\";\nimport {\n  type BuildEntryReport,\n  BuildEntryReportSchema,\n  MF_MANIFEST_FILENAME,\n} from \"every-plugin/build/artifact-names\";\nimport {\n  composeVersionManifest,\n  type SourceRef,\n  type WorkspaceVersionManifest,\n  WorkspaceVersionManifestSchema,\n} from \"every-plugin/version-manifest\";\nimport { bundleUrlToStagedPath, resolveContained } from \"../resolution/resolver\";\nimport {\n  asDigest,\n  clearVerifiedCache,\n  mark,\n  type Verified,\n  verifyDocument,\n} from \"../verify/engine\";\nimport { manifestDocumentUrl, reasonOf } from \"./manifest-verify\";\n\n/** Read a workspace dist's build-report.json (ticket 01's entry-name report). */\nexport function readBuildReport(distRoot: string): BuildEntryReport | null {\n  const reportPath = join(distRoot, \"build-report.json\");\n  if (!existsSync(reportPath)) return null;\n  try {\n    return BuildEntryReportSchema.parse(JSON.parse(readFileSync(reportPath, \"utf8\")));\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Compose the workspace's version manifest from the dist build reports and\n * the **server-computed** SRI map of the upload response (MAP decision 6 —\n * SRI is authoritative from the storage boundary, never computed\n * client-side). Returns null when the dist predates hashed entry names\n * (no report, or the SRI map lacks the entry) — the deploy leg then aborts:\n * uploaded workspaces must pin.\n */\nexport function composeWorkspaceVersionManifest(input: {\n  report: BuildEntryReport;\n  ssrReport?: BuildEntryReport | null;\n  integrityMap: Record<string, string>;\n  /** full per-file SRI map of the dist — recorded for the next deploy's diff */\n  files?: Record<string, string>;\n  /** slot-relative immutable version directory (`versions/<dirId>`, #826) —\n   * artifact coordinates resolve against it instead of the slot root */\n  dir?: string;\n  /** source archive reference (publish.sourcePublish) — server-computed SRI */\n  source?: SourceRef;\n  /** the repo HEAD the build was produced from — best-effort, may be absent */\n  gitSha?: string;\n}): WorkspaceVersionManifest | null {\n  const { report, ssrReport, integrityMap, files, dir, source, gitSha } = input;\n\n  const entryIntegrity = integrityMap[report.entry];\n  if (!entryIntegrity) return null;\n\n  const ssrEntry = ssrReport?.entry;\n  const ssrIntegrity = ssrEntry ? integrityMap[`ssr/${ssrEntry}`] : undefined;\n\n  return composeVersionManifest({\n    ...(dir ? { dir } : {}),\n    entry: report.entry,\n    entryIntegrity,\n    ...(ssrEntry && ssrIntegrity\n      ? { ssr: { entry: `ssr/${ssrEntry}`, integrity: ssrIntegrity } }\n      : {}),\n    ...(report.browserManifest && integrityMap[report.browserManifest]\n      ? {\n          browserManifest: {\n            file: report.browserManifest,\n            integrity: integrityMap[report.browserManifest]!,\n          },\n        }\n      : {}),\n    ...(report.css && integrityMap[report.css]\n      ? { assets: { css: integrityMap[report.css]! } }\n      : {}),\n    // Shared-singleton semantics (#546): the web report's record is primary —\n    // the node env resolves the same workspace's node_modules, so the two\n    // agree; an ssr-only report still carries the record.\n    ...((report.shared ?? ssrReport?.shared)\n      ? { shared: (report.shared ?? ssrReport?.shared)! }\n      : {}),\n    ...(files ? { files } : {}),\n    ...(source ? { source } : {}),\n    ...(gitSha ? { gitSha } : {}),\n  });\n}\n\n/**\n * Version-manifest resolution (atomic-deploys 04): a config remote's\n * `pin` ({ manifest, integrity }) resolves to the derived entry-level fields\n * every consumer needs. Verification and the process-lifetime\n * last-known-good cache live in the verify engine; a fetch or SRI failure\n * with nothing cached propagates (a boot-time resolution failure fails the\n * deploy, which is the platform's rollback).\n */\n\nexport interface ResolvedRemoteVersion {\n  /** The remote's production base (slot root — unprefixed by the version dir). */\n  base: string;\n  /** Absolute URL of the content-hashed container entry. */\n  entryUrl: string;\n  entryIntegrity: string;\n  /** Absolute URL of the hashed browser manifest (mf-manifest), when present. */\n  browserManifestUrl?: string;\n  /** Absolute URL of the content-hashed SSR entry, when present. */\n  ssrEntryUrl?: string;\n  ssrIntegrity?: string;\n  /** Shared-singleton `name → version` the pinned build embedded (#546) —\n   * stamped onto UI remotes so the host's composition guard can detect a\n   * platform skew before loading. */\n  sharedVersions?: Record<string, string>;\n  /** Slot-relative immutable version directory the artifact coordinates\n   * resolve against (`versions/<dirId>`, #826) — undefined on legacy\n   * manifests, which resolve against the slot root. */\n  dir?: string;\n  /** Full per-file digest map of the dist (object path → SRI), when the\n   * pinned manifest carries one — the diff base for skip-unchanged uploads. */\n  files?: Record<string, string>;\n  /** Source archive reference from the pinned manifest (publish.sourcePublish). */\n  source?: SourceRef;\n}\n\nexport interface RemoteDigest {\n  /** versioned manifest filename, relative to the remote's production base */\n  manifest: string;\n  /** the manifest document's own SRI */\n  integrity: string;\n}\n\nexport function clearRemoteVersionCache(): void {\n  clearVerifiedCache();\n}\n\nfunction remoteVersionFromManifest(\n  base: string,\n  manifest: WorkspaceVersionManifest,\n  options?: { ignoreDir?: boolean },\n): ResolvedRemoteVersion {\n  const trimmedBase = base.replace(/\\/$/, \"\");\n  const fileBase =\n    manifest.dir && !options?.ignoreDir ? `${trimmedBase}/${manifest.dir}` : trimmedBase;\n  return {\n    base: trimmedBase,\n    entryUrl: `${fileBase}/${manifest.entry}`,\n    entryIntegrity: manifest.entryIntegrity,\n    ...(manifest.dir ? { dir: manifest.dir } : {}),\n    ...(manifest.browserManifest\n      ? { browserManifestUrl: `${fileBase}/${manifest.browserManifest.file}` }\n      : {}),\n    ...(manifest.ssr\n      ? {\n          ssrEntryUrl: `${fileBase}/${manifest.ssr.entry}`,\n          ssrIntegrity: manifest.ssr.integrity,\n        }\n      : {}),\n    ...(manifest.shared ? { sharedVersions: manifest.shared } : {}),\n    ...(manifest.files ? { files: manifest.files } : {}),\n    ...(manifest.source ? { source: manifest.source } : {}),\n  };\n}\n\n/** Every artifact URL the resolved pin attests, keyed by the URL the runtime\n * actually fetches (the resolved hashed entry, the ssr entry, and each file\n * in the pin's files map) → its SRI. Integrity-in-pipeline keying: register\n * these and the loader verifies bytes at fetch time (#642's fork class —\n * fixed-name keying beside hashed fetches — cannot reconstruct this map). */\nexport function resolvedIntegrityMap(r: ResolvedRemoteVersion): Record<string, string> {\n  const map: Record<string, string> = {\n    [r.entryUrl]: r.entryIntegrity,\n  };\n  if (r.ssrEntryUrl && r.ssrIntegrity) {\n    map[r.ssrEntryUrl] = r.ssrIntegrity;\n  }\n  const fileBase = r.dir ? `${r.base.replace(/\\/$/, \"\")}/${r.dir}` : r.base.replace(/\\/$/, \"\");\n  for (const [file, integrity] of Object.entries(r.files ?? {})) {\n    map[`${fileBase}/${file.replace(/^\\//, \"\")}`] = integrity;\n  }\n  return map;\n}\n\n/**\n * Staged-remote preference (ADR 0020/0021 self-contained tier): when a runtime\n * stages its own namespace under `BOS_BUNDLE_DIR`, a remote resolves from the\n * staged dist's own version manifest instead of the config's pin — pinned\n * manifest bytes that predate the image (deploy lag after a release bump)\n * cannot exist in the staged namespace, so their hashed files would 404 the\n * disk and fall through to the network, where the stale immutable bytes\n * still answer 200 and boot a foreign build. The staged manifest is trusted\n * (staged by the image build itself) and skipped entirely when the remote is\n * absent from the staged namespace or the pinned manifest is present (the\n * normal healthy case, which keeps the pin's SRI check).\n */\nfunction readStagedRemoteVersion(base: string, digest: RemoteDigest): ResolvedRemoteVersion | null {\n  const bundleDir = process.env.BOS_BUNDLE_DIR;\n  if (!bundleDir) return null;\n\n  const slotDir = bundleUrlToStagedPath(base, bundleDir);\n  if (!slotDir || !existsSync(slotDir)) return null;\n\n  const pinnedManifestPath = resolveContained(slotDir, digest.manifest);\n  if (!pinnedManifestPath || existsSync(pinnedManifestPath)) return null;\n\n  const versionsDir = path.join(slotDir, \"versions\");\n  if (!existsSync(versionsDir)) return null;\n  const manifests = readdirSync(versionsDir)\n    .filter((name) => name.endsWith(\".json\"))\n    .map((name) => path.join(versionsDir, name))\n    .filter((file) => statSync(file).isFile())\n    .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs || (a < b ? -1 : 1));\n  if (manifests.length === 0) return null;\n  const manifestPath = manifests[0];\n  if (!manifestPath) return null;\n\n  try {\n    const manifest = WorkspaceVersionManifestSchema.parse(\n      JSON.parse(readFileSync(manifestPath, \"utf8\")),\n    );\n    // Staged dists materialize flat at the slot dir — `versions/<dirId>/` is\n    // a CDN-layout concept the disk does not carry, so the manifest's dir\n    // must not prefix the staged coordinates.\n    return remoteVersionFromManifest(base, manifest, { ignoreDir: true });\n  } catch {\n    return null;\n  }\n}\n\n/**\n * The container manifest document a pinned boot registers (#874): the pin's\n * hashed browser manifest copy when the build emitted one — immutable in both\n * the CDN layout and the staged flat layout — else the fixed name under the\n * pin's immutable version directory (#826; CDN only — staged dists are flat\n * on disk), else the fixed name at the slot root. The last tier is the\n * legacy/dev shape, and the tier the #874 incident rode: reading the fixed\n * name at the mutable slot root lets a later root publish move bytes the\n * child's pin never named.\n */\nexport function pinnedManifestDocumentUrl(\n  fallbackUrl: string,\n  resolved: Pick<ResolvedRemoteVersion, \"base\" | \"dir\" | \"browserManifestUrl\">,\n): string {\n  if (resolved.browserManifestUrl) return resolved.browserManifestUrl;\n  if (resolved.dir && !process.env.BOS_BUNDLE_DIR) {\n    return `${resolved.base.replace(/\\/$/, \"\")}/${resolved.dir}/${MF_MANIFEST_FILENAME}`;\n  }\n  return fallbackUrl;\n}\n\nexport async function resolveRemoteVersion(input: {\n  base: string;\n  digest: RemoteDigest;\n  fetchImpl?: typeof fetch;\n}): Promise<Verified<ResolvedRemoteVersion>> {\n  const staged = readStagedRemoteVersion(input.base, input.digest);\n  if (staged) return mark(staged);\n\n  const manifestUrl = manifestDocumentUrl(input.base, input.digest.manifest);\n  try {\n    const manifest = await verifyDocument({\n      url: manifestUrl,\n      expected: asDigest(input.digest.integrity),\n      schema: WorkspaceVersionManifestSchema,\n      fetchImpl: input.fetchImpl,\n    });\n    return mark(remoteVersionFromManifest(input.base, manifest));\n  } catch (error) {\n    throw new Error(\n      `[SRI] version manifest verification failed for ${manifestUrl}: ${reasonOf(error)}`,\n    );\n  }\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAgB,gBAAgB,UAA2C;CACzE,MAAM,iBAAaA,gBAAK,UAAU,mBAAmB;CACrD,IAAI,KAACC,oBAAW,UAAU,GAAG,OAAO;CACpC,IAAI;EACF,OAAOC,yDAAuB,MAAM,KAAK,UAAMC,sBAAa,YAAY,MAAM,CAAC,CAAC;CAClF,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;AAUA,SAAgB,gCAAgC,OAaZ;CAClC,MAAM,EAAE,QAAQ,WAAW,cAAc,OAAO,KAAK,QAAQ,WAAW;CAExE,MAAM,iBAAiB,aAAa,OAAO;CAC3C,IAAI,CAAC,gBAAgB,OAAO;CAE5B,MAAM,WAAW,WAAW;CAC5B,MAAM,eAAe,WAAW,aAAa,OAAO,cAAc;CAElE,WAAOC,sDAAuB;EAC5B,GAAI,MAAM,EAAE,IAAI,IAAI,CAAC;EACrB,OAAO,OAAO;EACd;EACA,GAAI,YAAY,eACZ,EAAE,KAAK;GAAE,OAAO,OAAO;GAAY,WAAW;EAAa,EAAE,IAC7D,CAAC;EACL,GAAI,OAAO,mBAAmB,aAAa,OAAO,mBAC9C,EACE,iBAAiB;GACf,MAAM,OAAO;GACb,WAAW,aAAa,OAAO;EACjC,EACF,IACA,CAAC;EACL,GAAI,OAAO,OAAO,aAAa,OAAO,OAClC,EAAE,QAAQ,EAAE,KAAK,aAAa,OAAO,KAAM,EAAE,IAC7C,CAAC;EAIL,GAAK,OAAO,UAAU,WAAW,SAC7B,EAAE,QAAS,OAAO,UAAU,WAAW,OAAS,IAChD,CAAC;EACL,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAC3B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAC7B,CAAC;AACH;AA4CA,SAAg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