@aglyn/tenant-data-admin 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/scope-sharing-sweep.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * KEEPING \"ALL SITES EXCEPT…\" TRUE AS SITES COME AND GO (AGL-4047).\n *\n * A document shared this way names its included sites in `visibleTo`, the one\n * field readers enforce. A new site therefore has to be added to it, and a\n * site that left has to come off it. {@link sweepScopeSharingAfterSiteChange}\n * does that after every change to `orgs/{orgId}.hosts`: a site created, moved\n * in or out, or erased.\n *\n * ## What it costs when nothing is marked\n *\n * One query per declared collection, each answering nothing, and not one\n * write. Every workspace pays that on a site change and nothing more, which\n * is why a sweep document is only written once a marked document turns up.\n *\n * ## Each document in its own transaction, reading the org document\n *\n * The transaction reads `orgs/{orgId}` as well as the document, so what it\n * writes is computed from the sites that are true at commit. A site claimed\n * while the sweep runs either serializes before it (and the sweep sees the\n * site) or after it (and the sweep that claim starts sees the document).\n *\n * ## Inline for a few seconds, then the job\n *\n * The caller is a person creating or deleting a site, so a trigger works for\n * {@link INLINE_BUDGET_MS} and leaves the rest to the job, from a cursor in\n * `orgs/{orgId}/scopeSweeps/{sweepId}`. That document exists only while work\n * is left, so the job's query answers nothing on a quiet beat. No rule opens\n * the path: only this server code reads or writes it.\n *\n * Every step is idempotent. A second sweep, or a resumed one going over a\n * document again, reads `current` and writes nothing.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n reconcileAllExcept,\n SCOPE_MODE_ALL_EXCEPT,\n type ScopeSharingFields,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { runPluginDeclarationsRepair } from '@aglyn/aglyn/plugin-manager/plugin-declarations-repair'\nimport {\n listScopeSharingCollections,\n type ResolvedScopeSharingCollection,\n scopeSharingPatchFor,\n} from '@aglyn/aglyn/plugin-manager/plugin-scope-sharing'\nimport {\n type CollectionReference,\n type DocumentReference,\n FieldPath,\n FieldValue,\n type Firestore,\n type QueryDocumentSnapshot,\n type QuerySnapshot,\n} from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\n/** Where a sweep with work left records its cursor. */\nexport const SCOPE_SWEEPS_COLLECTION = 'scopeSweeps'\n/** Marked documents read at a time in one collection. */\nconst PAGE_SIZE = 100\n/** Transactions running at once. */\nconst CONCURRENCY = 8\n/** How long a person's site change waits for the sweep. */\nexport const INLINE_BUDGET_MS = 3_000\n/** How long one job beat spends, across every sweep it takes. */\nexport const JOB_BUDGET_MS = 20_000\n/** Sweeps one beat reads. */\nconst SWEEPS_PER_BEAT = 10\n/** Beats a failing sweep gets. The weekly drift report still counts its documents. */\nexport const MAX_SWEEP_ATTEMPTS = 5\n\nexport type ScopeSweepReason = 'site-added' | 'site-removed' | 'drift-repair'\n\nexport interface ScopeSweepCounts {\n /** Marked documents read. */\n marked: number\n /** Written because they had fallen behind. */\n changed: number\n /** Past their collection's limit, and so no longer widening. */\n capped: number\n /** A marker the helper cannot act on: left alone, and reported. */\n invalid: number\n /** A transaction or patch that threw. */\n failed: number\n}\n\nexport interface ScopeSweepResult extends ScopeSweepCounts {\n /** Every declared collection was walked to its end. */\n complete: boolean\n /** Where to carry on from, when `complete` is false. */\n cursor: ScopeSweepCursor | null\n}\n\n/** A position in {@link listScopeSharingCollections}. */\nexport interface ScopeSweepCursor {\n collection: string\n afterId: string | null\n}\n\nconst emptyCounts = (): ScopeSweepCounts => ({\n marked: 0,\n changed: 0,\n capped: 0,\n invalid: 0,\n failed: 0,\n})\n\nconst platformFirestore = () => firebaseAdmin.app().firestore() as unknown as Firestore\n\n/** The sites `orgs/{orgId}.hosts` names. */\nexport function orgHostIdsFromDoc(org: Readonly<Record<string, unknown>> | undefined): string[] {\n const hosts = org?.['hosts']\n if (!hosts || typeof hosts !== 'object' || Array.isArray(hosts)) return []\n return Object.entries(hosts as Record<string, unknown>)\n .filter(([, on]) => Boolean(on))\n .map(([hostId]) => hostId)\n}\n\n/** The sites a document keeps whatever it excludes, per its declaration. */\nfunction keptHostIds(\n declared: ResolvedScopeSharingCollection,\n doc: Readonly<Record<string, unknown>>,\n): string[] {\n const kept: string[] = []\n for (const field of declared.keepSiteFields ?? []) {\n const value = doc[field]\n if (typeof value === 'string' && value) kept.push(value)\n if (Array.isArray(value)) {\n for (const id of value) if (typeof id === 'string' && id) kept.push(id)\n }\n }\n return kept\n}\n\n/** The marked documents of one collection, in the order a cursor can resume. */\nfunction markedPage(collectionRef: CollectionReference, afterId: string | null): Promise<QuerySnapshot> {\n const ordered = collectionRef\n .where('scopeMode', '==', SCOPE_MODE_ALL_EXCEPT)\n .orderBy(FieldPath.documentId())\n return (afterId ? ordered.startAfter(afterId) : ordered).limit(PAGE_SIZE).get()\n}\n\n/** Runs `work` over `items`, at most {@link CONCURRENCY} at a time. */\nasync function eachConcurrently<T>(\n items: readonly T[],\n work: (item: T) => Promise<void>,\n): Promise<void> {\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => {\n while (next < items.length) {\n const item = items[next]\n next += 1\n await work(item)\n }\n }),\n )\n}\n\n/** A write's data: a `null` marker field is deleted, never stored. */\nexport function fieldsToWrite(fields: ScopeSharingFields): Record<string, unknown> {\n return {\n visibleTo: fields.visibleTo,\n scopeMode: fields.scopeMode ?? FieldValue.delete(),\n scopeExcept: fields.scopeExcept ?? FieldValue.delete(),\n }\n}\n\n/** The document as it will read after the write, for a patch to work from. */\nfunction asStored(\n data: Readonly<Record<string, unknown>>,\n fields: ScopeSharingFields,\n): Record<string, unknown> {\n const next: Record<string, unknown> = { ...data, visibleTo: fields.visibleTo }\n if (fields.scopeMode) {\n next['scopeMode'] = fields.scopeMode\n next['scopeExcept'] = fields.scopeExcept\n } else {\n delete next['scopeMode']\n delete next['scopeExcept']\n }\n return next\n}\n\n/** Brings one marked document level, in its own transaction. */\nasync function reconcileDocument(\n db: Firestore,\n orgRef: DocumentReference,\n declared: ResolvedScopeSharingCollection,\n docRef: DocumentReference,\n counts: ScopeSweepCounts,\n): Promise<void> {\n const status = await db.runTransaction(async (tx) => {\n const [org, doc] = await tx.getAll(orgRef, docRef)\n // The workspace went while this ran, and the document with it.\n if (!org.exists || !doc.exists) return 'current'\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, orgHostIdsFromDoc(org.data()), {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n if (answer.fields) {\n const patch = declared.patch\n ? await requiredPatch(declared.name)(declared.name, asStored(data, answer.fields))\n : {}\n // Not an edit, so `updatedAt` stays: a list ordered by it must not\n // reshuffle because a site was added somewhere in the workspace.\n tx.update(docRef, { ...fieldsToWrite(answer.fields), ...patch })\n }\n return answer.status\n })\n if (status === 'changed') counts.changed += 1\n if (status === 'capped') counts.capped += 1\n if (status === 'invalid') counts.invalid += 1\n}\n\nfunction requiredPatch(collection: string) {\n const patch = scopeSharingPatchFor(collection)\n if (!patch) throw new Error(`no scope-sharing patch is registered for ${collection}`)\n return patch\n}\n\n/**\n * A declared patch is missing where the boot step has not run. Runs it once,\n * and only when a marked document needs one, so a sweep that finds nothing\n * never pays for it.\n */\nasync function ensurePatches(\n collections: readonly ResolvedScopeSharingCollection[],\n): Promise<void> {\n if (collections.every((row) => !row.patch || scopeSharingPatchFor(row.name))) return\n await runPluginDeclarationsRepair().catch((error: unknown) => {\n console.error('[scope-sweep] the declarations repair failed', error)\n })\n}\n\nexport interface RunScopeSharingSweepInput {\n orgId: string\n /** Stops starting new work past this; omit to walk to the end. */\n budgetMs?: number\n /** Resume from here. */\n from?: ScopeSweepCursor | null\n /**\n * Called the first time a marked document turns up, so a sweep that finds\n * nothing writes nothing. A trigger records its sweep document here.\n */\n onFirstMarked?: () => Promise<void>\n firestore?: Firestore\n}\n\n/**\n * Walks every declared collection's marked documents and brings each level.\n * Throws only on a failed query; one document failing is counted and the walk\n * goes on, and an incomplete walk answers where it stopped.\n */\nexport async function runScopeSharingSweep(\n input: RunScopeSharingSweepInput,\n): Promise<ScopeSweepResult> {\n const db = input.firestore ?? platformFirestore()\n const orgRef = db.collection('orgs').doc(input.orgId)\n const collections = listScopeSharingCollections()\n const startAt = input.from\n ? Math.max(0, collections.findIndex((row) => row.name === input.from?.collection))\n : 0\n const remaining = collections.slice(startAt)\n const deadline = input.budgetMs == null ? null : Date.now() + input.budgetMs\n const counts = emptyCounts()\n\n // Every collection's first page at once, so the common answer of nothing\n // costs one round of queries rather than one after another.\n const pages = new Map<string, QueryDocumentSnapshot[]>()\n const firstAfter = (name: string) =>\n input.from && input.from.collection === name ? input.from.afterId : null\n await eachConcurrently(remaining, async (declared) => {\n const snapshot = await markedPage(orgRef.collection(declared.name), firstAfter(declared.name))\n pages.set(declared.name, snapshot.docs)\n })\n if ([...pages.values()].every((docs) => !docs.length)) {\n return { ...counts, complete: true, cursor: null }\n }\n await input.onFirstMarked?.()\n await ensurePatches(remaining)\n\n for (const declared of remaining) {\n let docs = pages.get(declared.name) ?? []\n let afterId = firstAfter(declared.name)\n while (docs.length) {\n if (deadline != null && Date.now() >= deadline) {\n return { ...counts, complete: false, cursor: { collection: declared.name, afterId } }\n }\n counts.marked += docs.length\n await eachConcurrently(docs, async (doc) => {\n try {\n await reconcileDocument(db, orgRef, declared, doc.ref, counts)\n } catch (error) {\n counts.failed += 1\n console.error(`[scope-sweep] ${declared.name}/${doc.id} in ${input.orgId} was not brought level`, error)\n }\n })\n afterId = docs[docs.length - 1].id\n if (docs.length < PAGE_SIZE) break\n docs = (await markedPage(orgRef.collection(declared.name), afterId)).docs\n }\n }\n return { ...counts, complete: true, cursor: null }\n}\n\n/**\n * What a change to a workspace's sites runs, once the change has committed.\n *\n * NEVER THROWS, because the site change is done and is what the person asked\n * for. Work it could not finish is left in a sweep document for the job, and\n * if even that write fails the weekly drift report finds what is behind.\n */\nexport async function sweepScopeSharingAfterSiteChange(input: {\n orgId: string\n reason: ScopeSweepReason\n hostId?: string\n firestore?: Firestore\n}): Promise<void> {\n const { orgId, reason, hostId } = input\n let sweepRef: DocumentReference | null = null\n const leaveForTheJob = async (cursor: ScopeSweepCursor | null, attempts: number) => {\n const db = input.firestore ?? platformFirestore()\n sweepRef ??= db.collection('orgs').doc(orgId).collection(SCOPE_SWEEPS_COLLECTION).doc(createResourceUid())\n await sweepRef.set({\n reason,\n ...(hostId ? { hostId } : {}),\n cursor,\n attempts,\n createdAtMs: Date.now(),\n })\n }\n try {\n const result = await runScopeSharingSweep({\n orgId,\n budgetMs: INLINE_BUDGET_MS,\n ...(input.firestore ? { firestore: input.firestore } : {}),\n onFirstMarked: () => leaveForTheJob(null, 0),\n })\n if (!result.complete) {\n await leaveForTheJob(result.cursor, 0)\n return\n }\n if (result.failed) {\n await leaveForTheJob(null, 1)\n return\n }\n await sweepRef?.delete()\n } catch (error) {\n console.error(`[scope-sweep] the sweep of ${orgId} after ${reason} did not finish`, error)\n await leaveForTheJob(null, 1).catch((writeError: unknown) => {\n console.error(`[scope-sweep] could not leave ${orgId}'s sweep for the job`, writeError)\n })\n }\n}\n\n/**\n * Carries on every unfinished sweep: the job's handler. A sweep document exists\n * only while work is left, so the unfiltered query needs no index and answers\n * nothing on a quiet beat, for one read.\n */\nexport async function resumeScopeSweeps(\n options: { budgetMs?: number; firestore?: Firestore } = {},\n): Promise<{ resumed: number; finished: number; droppedAfterFailing: number }> {\n const db = options.firestore ?? platformFirestore()\n const pending = await db.collectionGroup(SCOPE_SWEEPS_COLLECTION).limit(SWEEPS_PER_BEAT).get()\n const tally = { resumed: 0, finished: 0, droppedAfterFailing: 0 }\n const deadline = Date.now() + (options.budgetMs ?? JOB_BUDGET_MS)\n for (const sweep of pending.docs) {\n const budgetMs = deadline - Date.now()\n if (budgetMs <= 0) break\n tally.resumed += 1\n const orgRef = sweep.ref.parent.parent\n const attempts = Number(sweep.get('attempts') ?? 0)\n try {\n const org = orgRef ? await orgRef.get() : null\n // The workspace was erased after this was left. Nothing to bring level.\n if (!org?.exists) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n const result = await runScopeSharingSweep({\n orgId: org.id,\n budgetMs,\n from: (sweep.get('cursor') as ScopeSweepCursor | null | undefined) ?? null,\n firestore: db,\n })\n if (!result.complete) {\n await sweep.ref.update({ cursor: result.cursor })\n continue\n }\n if (!result.failed) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n throw new Error(`${result.failed} document(s) failed`)\n } catch (error) {\n console.error(`[scope-sweep] ${sweep.ref.path} failed on attempt ${attempts + 1}`, error)\n if (attempts + 1 >= MAX_SWEEP_ATTEMPTS) {\n // Stops holding a place in the beat. What it left behind is what the\n // weekly drift report counts, and that report goes to staff.\n await sweep.ref.delete().catch(() => undefined)\n tally.droppedAfterFailing += 1\n } else {\n await sweep.ref.update({ attempts: attempts + 1, cursor: null }).catch(() => undefined)\n }\n }\n }\n return tally\n}\n\n/** What the weekly report asks of one workspace. Reads only. */\nexport interface ScopeSharingDrift {\n /** Marked documents read. */\n marked: number\n /** Should read differently from how they read: what a sweep would write. */\n stale: number\n /** Past their collection's limit. A known state, reported and not alarmed. */\n capped: number\n /** A marker that cannot be acted on. */\n invalid: number\n}\n\nexport function emptyScopeSharingDrift(): ScopeSharingDrift {\n return { marked: 0, stale: 0, capped: 0, invalid: 0 }\n}\n\n/**\n * How far one workspace's marked documents are from what a sweep would write,\n * with the same helper the sweep uses. One query per declared collection when\n * nothing is marked.\n */\nexport async function scopeSharingDriftForOrg(\n orgRef: DocumentReference,\n orgData: Readonly<Record<string, unknown>> | undefined,\n): Promise<ScopeSharingDrift> {\n const drift = emptyScopeSharingDrift()\n const hostIds = orgHostIdsFromDoc(orgData)\n await eachConcurrently(listScopeSharingCollections(), async (declared) => {\n let afterId: string | null = null\n for (;;) {\n const page: QuerySnapshot = await markedPage(orgRef.collection(declared.name), afterId)\n for (const doc of page.docs) {\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, hostIds, {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n drift.marked += 1\n if (answer.status === 'invalid') drift.invalid += 1\n if (answer.status === 'capped') drift.capped += 1\n if (answer.fields) drift.stale += 1\n }\n if (page.docs.length < PAGE_SIZE) return\n afterId = page.docs[page.docs.length - 1].id\n }\n })\n return drift\n}\n"],"names":["createResourceUid","reconcileAllExcept","SCOPE_MODE_ALL_EXCEPT","runPluginDeclarationsRepair","listScopeSharingCollections","scopeSharingPatchFor","FieldPath","FieldValue","firebaseAdmin","SCOPE_SWEEPS_COLLECTION","PAGE_SIZE","CONCURRENCY","INLINE_BUDGET_MS","JOB_BUDGET_MS","SWEEPS_PER_BEAT","MAX_SWEEP_ATTEMPTS","emptyCounts","marked","changed","capped","invalid","failed","platformFirestore","app","firestore","orgHostIdsFromDoc","org","hosts","Array","isArray","Object","entries","filter","on","Boolean","map","hostId","keptHostIds","declared","doc","kept","field","keepSiteFields","value","push","id","markedPage","collectionRef","afterId","ordered","where","orderBy","documentId","startAfter","limit","get","eachConcurrently","items","work","next","Promise","all","from","length","Math","min","item","fieldsToWrite","fields","visibleTo","scopeMode","delete","scopeExcept","asStored","data","reconcileDocument","db","orgRef","docRef","counts","status","runTransaction","tx","getAll","exists","answer","maxIncluded","keepHostIds","patch","requiredPatch","name","update","collection","Error","ensurePatches","collections","every","row","catch","error","console","runScopeSharingSweep","input","orgId","startAt","max","findIndex","remaining","slice","deadline","budgetMs","Date","now","pages","Map","firstAfter","snapshot","set","docs","values","complete","cursor","onFirstMarked","ref","sweepScopeSharingAfterSiteChange","reason","sweepRef","leaveForTheJob","attempts","createdAtMs","result","writeError","resumeScopeSweeps","options","pending","collectionGroup","tally","resumed","finished","droppedAfterFailing","sweep","parent","Number","path","undefined","emptyScopeSharingDrift","stale","scopeSharingDriftForOrg","orgData","drift","hostIds","page"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,kBAAkB,EAClBC,qBAAqB,QAEhB,sCAAqC;AAC5C,SAASC,2BAA2B,QAAQ,yDAAwD;AACpG,SACEC,2BAA2B,EAE3BC,oBAAoB,QACf,mDAAkD;AACzD,SAGEC,SAAS,EACTC,UAAU,QAIL,2BAA0B;AACjC,OAAOC,mBAAmB,sBAAkB;AAE5C,qDAAqD,GACrD,OAAO,MAAMC,0BAA0B,cAAa;AACpD,uDAAuD,GACvD,MAAMC,YAAY;AAClB,kCAAkC,GAClC,MAAMC,cAAc;AACpB,yDAAyD,GACzD,OAAO,MAAMC,mBAAmB,KAAK;AACrC,+DAA+D,GAC/D,OAAO,MAAMC,gBAAgB,MAAM;AACnC,2BAA2B,GAC3B,MAAMC,kBAAkB;AACxB,oFAAoF,GACpF,OAAO,MAAMC,qBAAqB,EAAC;AA8BnC,MAAMC,cAAc,IAAyB,CAAA;QAC3CC,QAAQ;QACRC,SAAS;QACTC,QAAQ;QACRC,SAAS;QACTC,QAAQ;IACV,CAAA;AAEA,MAAMC,oBAAoB,IAAMd,cAAce,GAAG,GAAGC,SAAS;AAE7D,0CAA0C,GAC1C,OAAO,SAASC,kBAAkBC,GAAkD;IAClF,MAAMC,QAAQD,uBAAAA,GAAK,CAAC,QAAQ;IAC5B,IAAI,CAACC,SAAS,OAAOA,UAAU,YAAYC,MAAMC,OAAO,CAACF,QAAQ,OAAO,EAAE;IAC1E,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kB2H;IAClC,MAAM5F,iBAAiBpD,+BAA+B,OAAOkC;QAC3D,IAAIU,UAAyB;QAC7B,OAAS;YACP,MAAMuG,OAAsB,MAAMzG,WAAW+B,OAAOe,UAAU,CAACtD,SAASoD,IAAI,GAAG1C;YAC/E,KAAK,MAAMT,OAAOgH,KAAKjC,IAAI,CAAE;oBAGZhF;gBAFf,MAAMoC,OAAOnC,IAAImC,IAAI;gBACrB,MAAMW,SAASpF,mBAAmByE,MAAM4E,SAAS;oBAC/ChE,WAAW,GAAEhD,wBAAAA,SAASgD,WAAW,YAApBhD,wBAAwB;oBACrCiD,aAAalD,YAAYC,UAAUoC;gBACrC;gBACA2E,MAAMpI,MAAM,IAAI;gBAChB,IAAIoE,OAAOL,MAAM,KAAK,WAAWqE,MAAMjI,OAAO,IAAI;gBAClD,IAAIiE,OAAOL,MAAM,KAAK,UAAUqE,MAAMlI,MAAM,IAAI;gBAChD,IAAIkE,OAAOjB,MAAM,EAAEiF,MAAMH,KAAK,IAAI;YACpC;YACA,IAAIK,KAAKjC,IAAI,CAACvD,MAAM,GAAGrD,WAAW;YAClCsC,UAAUuG,KAAKjC,IAAI,CAACiC,KAAKjC,IAAI,CAACvD,MAAM,GAAG,EAAE,CAAClB,EAAE;QAC9C;IACF;IACA,OAAOwG;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/scope-sharing-sweep.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * KEEPING \"ALL SITES EXCEPT…\" TRUE AS SITES COME AND GO (AGL-4047).\n *\n * A document shared this way names its included sites in `visibleTo`, the one\n * field readers enforce. A new site therefore has to be added to it, and a\n * site that left has to come off it. {@link sweepScopeSharingAfterSiteChange}\n * does that after every change to `orgs/{orgId}.hosts`: a site created, moved\n * in or out, or erased.\n *\n * ## What it costs when nothing is marked\n *\n * One query per declared collection, each answering nothing, and not one\n * write. Every workspace pays that on a site change and nothing more, which\n * is why a sweep document is only written once a marked document turns up.\n *\n * ## Each document in its own transaction, reading the org document\n *\n * The transaction reads `orgs/{orgId}` as well as the document, so what it\n * writes is computed from the sites that are true at commit. A site claimed\n * while the sweep runs either serializes before it (and the sweep sees the\n * site) or after it (and the sweep that claim starts sees the document).\n *\n * ## Inline for a few seconds, then the job\n *\n * The caller is a person creating or deleting a site, so a trigger works for\n * {@link INLINE_BUDGET_MS} and leaves the rest to the job, from a cursor in\n * `orgs/{orgId}/scopeSweeps/{sweepId}`. That document exists only while work\n * is left, so the job's query answers nothing on a quiet beat. No rule opens\n * the path: only this server code reads or writes it.\n *\n * Every step is idempotent. A second sweep, or a resumed one going over a\n * document again, reads `current` and writes nothing.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n reconcileAllExcept,\n SCOPE_MODE_ALL_EXCEPT,\n type ScopeSharingFields,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { runPluginDeclarationsRepair } from '@aglyn/aglyn/plugin-manager/plugin-declarations-repair'\nimport {\n listScopeSharingCollections,\n listScopeSharingSiteChangeHooks,\n type ResolvedScopeSharingCollection,\n scopeSharingPatchFor,\n} from '@aglyn/aglyn/plugin-manager/plugin-scope-sharing'\nimport {\n type CollectionReference,\n type DocumentReference,\n FieldPath,\n FieldValue,\n type Firestore,\n type QueryDocumentSnapshot,\n type QuerySnapshot,\n} from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\n/** Where a sweep with work left records its cursor. */\nexport const SCOPE_SWEEPS_COLLECTION = 'scopeSweeps'\n/** Marked documents read at a time in one collection. */\nconst PAGE_SIZE = 100\n/** Transactions running at once. */\nconst CONCURRENCY = 8\n/** How long a person's site change waits for the sweep. */\nexport const INLINE_BUDGET_MS = 3_000\n/** How long one job beat spends, across every sweep it takes. */\nexport const JOB_BUDGET_MS = 20_000\n/** Sweeps one beat reads. */\nconst SWEEPS_PER_BEAT = 10\n/** Beats a failing sweep gets. The weekly drift report still counts its documents. */\nexport const MAX_SWEEP_ATTEMPTS = 5\n\nexport type ScopeSweepReason = 'site-added' | 'site-removed' | 'drift-repair'\n\nexport interface ScopeSweepCounts {\n /** Marked documents read. */\n marked: number\n /** Written because they had fallen behind. */\n changed: number\n /** Past their collection's limit, and so no longer widening. */\n capped: number\n /** A marker the helper cannot act on: left alone, and reported. */\n invalid: number\n /** A transaction or patch that threw. */\n failed: number\n}\n\nexport interface ScopeSweepResult extends ScopeSweepCounts {\n /** Every declared collection was walked to its end. */\n complete: boolean\n /** Where to carry on from, when `complete` is false. */\n cursor: ScopeSweepCursor | null\n}\n\n/** A position in {@link listScopeSharingCollections}. */\nexport interface ScopeSweepCursor {\n collection: string\n afterId: string | null\n}\n\nconst emptyCounts = (): ScopeSweepCounts => ({\n marked: 0,\n changed: 0,\n capped: 0,\n invalid: 0,\n failed: 0,\n})\n\nconst platformFirestore = () => firebaseAdmin.app().firestore() as unknown as Firestore\n\n/** The sites `orgs/{orgId}.hosts` names. */\nexport function orgHostIdsFromDoc(org: Readonly<Record<string, unknown>> | undefined): string[] {\n const hosts = org?.['hosts']\n if (!hosts || typeof hosts !== 'object' || Array.isArray(hosts)) return []\n return Object.entries(hosts as Record<string, unknown>)\n .filter(([, on]) => Boolean(on))\n .map(([hostId]) => hostId)\n}\n\n/** The sites a document keeps whatever it excludes, per its declaration. */\nfunction keptHostIds(\n declared: ResolvedScopeSharingCollection,\n doc: Readonly<Record<string, unknown>>,\n): string[] {\n const kept: string[] = []\n for (const field of declared.keepSiteFields ?? []) {\n const value = doc[field]\n if (typeof value === 'string' && value) kept.push(value)\n if (Array.isArray(value)) {\n for (const id of value) if (typeof id === 'string' && id) kept.push(id)\n }\n }\n return kept\n}\n\n/** The marked documents of one collection, in the order a cursor can resume. */\nfunction markedPage(collectionRef: CollectionReference, afterId: string | null): Promise<QuerySnapshot> {\n const ordered = collectionRef\n .where('scopeMode', '==', SCOPE_MODE_ALL_EXCEPT)\n .orderBy(FieldPath.documentId())\n return (afterId ? ordered.startAfter(afterId) : ordered).limit(PAGE_SIZE).get()\n}\n\n/** Runs `work` over `items`, at most {@link CONCURRENCY} at a time. */\nasync function eachConcurrently<T>(\n items: readonly T[],\n work: (item: T) => Promise<void>,\n): Promise<void> {\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => {\n while (next < items.length) {\n const item = items[next]\n next += 1\n await work(item)\n }\n }),\n )\n}\n\n/** A write's data: a `null` marker field is deleted, never stored. */\nexport function fieldsToWrite(fields: ScopeSharingFields): Record<string, unknown> {\n return {\n visibleTo: fields.visibleTo,\n scopeMode: fields.scopeMode ?? FieldValue.delete(),\n scopeExcept: fields.scopeExcept ?? FieldValue.delete(),\n }\n}\n\n/** The document as it will read after the write, for a patch to work from. */\nfunction asStored(\n data: Readonly<Record<string, unknown>>,\n fields: ScopeSharingFields,\n): Record<string, unknown> {\n const next: Record<string, unknown> = { ...data, visibleTo: fields.visibleTo }\n if (fields.scopeMode) {\n next['scopeMode'] = fields.scopeMode\n next['scopeExcept'] = fields.scopeExcept\n } else {\n delete next['scopeMode']\n delete next['scopeExcept']\n }\n return next\n}\n\n/** Brings one marked document level, in its own transaction. */\nasync function reconcileDocument(\n db: Firestore,\n orgRef: DocumentReference,\n declared: ResolvedScopeSharingCollection,\n docRef: DocumentReference,\n counts: ScopeSweepCounts,\n): Promise<void> {\n const status = await db.runTransaction(async (tx) => {\n const [org, doc] = await tx.getAll(orgRef, docRef)\n // The workspace went while this ran, and the document with it.\n if (!org.exists || !doc.exists) return 'current'\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, orgHostIdsFromDoc(org.data()), {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n if (answer.fields) {\n const patch = declared.patch\n ? await requiredPatch(declared.name)(declared.name, asStored(data, answer.fields))\n : {}\n // Not an edit, so `updatedAt` stays: a list ordered by it must not\n // reshuffle because a site was added somewhere in the workspace.\n tx.update(docRef, { ...fieldsToWrite(answer.fields), ...patch })\n }\n return answer.status\n })\n if (status === 'changed') counts.changed += 1\n if (status === 'capped') counts.capped += 1\n if (status === 'invalid') counts.invalid += 1\n}\n\nfunction requiredPatch(collection: string) {\n const patch = scopeSharingPatchFor(collection)\n if (!patch) throw new Error(`no scope-sharing patch is registered for ${collection}`)\n return patch\n}\n\n/**\n * A declared patch is missing where the boot step has not run. Runs it once,\n * and only when a marked document needs one, so a sweep that finds nothing\n * never pays for it.\n */\nasync function ensurePatches(\n collections: readonly ResolvedScopeSharingCollection[],\n): Promise<void> {\n if (collections.every((row) => !row.patch || scopeSharingPatchFor(row.name))) return\n await runPluginDeclarationsRepair().catch((error: unknown) => {\n console.error('[scope-sweep] the declarations repair failed', error)\n })\n}\n\nexport interface RunScopeSharingSweepInput {\n orgId: string\n /** Stops starting new work past this; omit to walk to the end. */\n budgetMs?: number\n /** Resume from here. */\n from?: ScopeSweepCursor | null\n /**\n * Called the first time a marked document turns up, so a sweep that finds\n * nothing writes nothing. A trigger records its sweep document here.\n */\n onFirstMarked?: () => Promise<void>\n firestore?: Firestore\n}\n\n/**\n * Walks every declared collection's marked documents and brings each level.\n * Throws only on a failed query; one document failing is counted and the walk\n * goes on, and an incomplete walk answers where it stopped.\n */\nexport async function runScopeSharingSweep(\n input: RunScopeSharingSweepInput,\n): Promise<ScopeSweepResult> {\n const db = input.firestore ?? platformFirestore()\n const orgRef = db.collection('orgs').doc(input.orgId)\n const collections = listScopeSharingCollections()\n const startAt = input.from\n ? Math.max(0, collections.findIndex((row) => row.name === input.from?.collection))\n : 0\n const remaining = collections.slice(startAt)\n const deadline = input.budgetMs == null ? null : Date.now() + input.budgetMs\n const counts = emptyCounts()\n\n // Every collection's first page at once, so the common answer of nothing\n // costs one round of queries rather than one after another.\n const pages = new Map<string, QueryDocumentSnapshot[]>()\n const firstAfter = (name: string) =>\n input.from && input.from.collection === name ? input.from.afterId : null\n await eachConcurrently(remaining, async (declared) => {\n const snapshot = await markedPage(orgRef.collection(declared.name), firstAfter(declared.name))\n pages.set(declared.name, snapshot.docs)\n })\n if ([...pages.values()].every((docs) => !docs.length)) {\n return { ...counts, complete: true, cursor: null }\n }\n await input.onFirstMarked?.()\n await ensurePatches(remaining)\n\n for (const declared of remaining) {\n let docs = pages.get(declared.name) ?? []\n let afterId = firstAfter(declared.name)\n while (docs.length) {\n if (deadline != null && Date.now() >= deadline) {\n return { ...counts, complete: false, cursor: { collection: declared.name, afterId } }\n }\n counts.marked += docs.length\n await eachConcurrently(docs, async (doc) => {\n try {\n await reconcileDocument(db, orgRef, declared, doc.ref, counts)\n } catch (error) {\n counts.failed += 1\n console.error(`[scope-sweep] ${declared.name}/${doc.id} in ${input.orgId} was not brought level`, error)\n }\n })\n afterId = docs[docs.length - 1].id\n if (docs.length < PAGE_SIZE) break\n docs = (await markedPage(orgRef.collection(declared.name), afterId)).docs\n }\n }\n return { ...counts, complete: true, cursor: null }\n}\n\n/**\n * What a change to a workspace's sites runs, once the change has committed.\n *\n * NEVER THROWS, because the site change is done and is what the person asked\n * for. Work it could not finish is left in a sweep document for the job, and\n * if even that write fails the weekly drift report finds what is behind.\n */\nexport async function sweepScopeSharingAfterSiteChange(input: {\n orgId: string\n reason: ScopeSweepReason\n hostId?: string\n firestore?: Firestore\n}): Promise<void> {\n const { orgId, reason, hostId } = input\n let sweepRef: DocumentReference | null = null\n const leaveForTheJob = async (cursor: ScopeSweepCursor | null, attempts: number) => {\n const db = input.firestore ?? platformFirestore()\n sweepRef ??= db.collection('orgs').doc(orgId).collection(SCOPE_SWEEPS_COLLECTION).doc(createResourceUid())\n await sweepRef.set({\n reason,\n ...(hostId ? { hostId } : {}),\n cursor,\n attempts,\n createdAtMs: Date.now(),\n })\n }\n try {\n const result = await runScopeSharingSweep({\n orgId,\n budgetMs: INLINE_BUDGET_MS,\n ...(input.firestore ? { firestore: input.firestore } : {}),\n onFirstMarked: () => leaveForTheJob(null, 0),\n })\n if (!result.complete) {\n await leaveForTheJob(result.cursor, 0)\n return\n }\n if (result.failed) {\n await leaveForTheJob(null, 1)\n return\n }\n await sweepRef?.delete()\n } catch (error) {\n console.error(`[scope-sweep] the sweep of ${orgId} after ${reason} did not finish`, error)\n await leaveForTheJob(null, 1).catch((writeError: unknown) => {\n console.error(`[scope-sweep] could not leave ${orgId}'s sweep for the job`, writeError)\n })\n }\n await runSiteChangeHooks({ orgId, reason, ...(hostId ? { hostId } : {}) })\n}\n\n/**\n * The plugins' own share of a site change (`registerPluginScopeSharingSiteChange`):\n * sharing kept somewhere the sweep does not walk, such as the CRM's grants.\n * Each gets {@link INLINE_BUDGET_MS} and finishes the rest itself. Never throws.\n * A hook registers with its plugin's server declarations, at boot.\n */\nasync function runSiteChangeHooks(input: {\n orgId: string\n reason: ScopeSweepReason\n hostId?: string\n}): Promise<void> {\n for (const { pluginId, hook } of listScopeSharingSiteChangeHooks()) {\n try {\n await hook({ ...input, budgetMs: INLINE_BUDGET_MS })\n } catch (error) {\n console.error(`[scope-sweep] ${pluginId}'s site-change hook failed for ${input.orgId}`, error)\n }\n }\n}\n\n/**\n * Carries on every unfinished sweep: the job's handler. A sweep document exists\n * only while work is left, so the unfiltered query needs no index and answers\n * nothing on a quiet beat, for one read.\n */\nexport async function resumeScopeSweeps(\n options: { budgetMs?: number; firestore?: Firestore } = {},\n): Promise<{ resumed: number; finished: number; droppedAfterFailing: number }> {\n const db = options.firestore ?? platformFirestore()\n const pending = await db.collectionGroup(SCOPE_SWEEPS_COLLECTION).limit(SWEEPS_PER_BEAT).get()\n const tally = { resumed: 0, finished: 0, droppedAfterFailing: 0 }\n const deadline = Date.now() + (options.budgetMs ?? JOB_BUDGET_MS)\n for (const sweep of pending.docs) {\n const budgetMs = deadline - Date.now()\n if (budgetMs <= 0) break\n tally.resumed += 1\n const orgRef = sweep.ref.parent.parent\n const attempts = Number(sweep.get('attempts') ?? 0)\n try {\n const org = orgRef ? await orgRef.get() : null\n // The workspace was erased after this was left. Nothing to bring level.\n if (!org?.exists) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n const result = await runScopeSharingSweep({\n orgId: org.id,\n budgetMs,\n from: (sweep.get('cursor') as ScopeSweepCursor | null | undefined) ?? null,\n firestore: db,\n })\n if (!result.complete) {\n await sweep.ref.update({ cursor: result.cursor })\n continue\n }\n if (!result.failed) {\n await sweep.ref.delete()\n tally.finished += 1\n continue\n }\n throw new Error(`${result.failed} document(s) failed`)\n } catch (error) {\n console.error(`[scope-sweep] ${sweep.ref.path} failed on attempt ${attempts + 1}`, error)\n if (attempts + 1 >= MAX_SWEEP_ATTEMPTS) {\n // Stops holding a place in the beat. What it left behind is what the\n // weekly drift report counts, and that report goes to staff.\n await sweep.ref.delete().catch(() => undefined)\n tally.droppedAfterFailing += 1\n } else {\n await sweep.ref.update({ attempts: attempts + 1, cursor: null }).catch(() => undefined)\n }\n }\n }\n return tally\n}\n\n/** What the weekly report asks of one workspace. Reads only. */\nexport interface ScopeSharingDrift {\n /** Marked documents read. */\n marked: number\n /** Should read differently from how they read: what a sweep would write. */\n stale: number\n /** Past their collection's limit. A known state, reported and not alarmed. */\n capped: number\n /** A marker that cannot be acted on. */\n invalid: number\n}\n\nexport function emptyScopeSharingDrift(): ScopeSharingDrift {\n return { marked: 0, stale: 0, capped: 0, invalid: 0 }\n}\n\n/**\n * How far one workspace's marked documents are from what a sweep would write,\n * with the same helper the sweep uses. One query per declared collection when\n * nothing is marked.\n */\nexport async function scopeSharingDriftForOrg(\n orgRef: DocumentReference,\n orgData: Readonly<Record<string, unknown>> | undefined,\n): Promise<ScopeSharingDrift> {\n const drift = emptyScopeSharingDrift()\n const hostIds = orgHostIdsFromDoc(orgData)\n await eachConcurrently(listScopeSharingCollections(), async (declared) => {\n let afterId: string | null = null\n for (;;) {\n const page: QuerySnapshot = await markedPage(orgRef.collection(declared.name), afterId)\n for (const doc of page.docs) {\n const data = doc.data() as Record<string, unknown>\n const answer = reconcileAllExcept(data, hostIds, {\n maxIncluded: declared.maxIncluded ?? null,\n keepHostIds: keptHostIds(declared, data),\n })\n drift.marked += 1\n if (answer.status === 'invalid') drift.invalid += 1\n if (answer.status === 'capped') drift.capped += 1\n if (answer.fields) drift.stale += 1\n }\n if (page.docs.length < PAGE_SIZE) return\n afterId = page.docs[page.docs.length - 1].id\n }\n })\n return drift\n}\n"],"names":["createResourceUid","reconcileAllExcept","SCOPE_MODE_ALL_EXCEPT","runPluginDeclarationsRepair","listScopeSharingCollections","listScopeSharingSiteChangeHooks","scopeSharingPatchFor","FieldPath","FieldValue","firebaseAdmin","SCOPE_SWEEPS_COLLECTION","PAGE_SIZE","CONCURRENCY","INLINE_BUDGET_MS","JOB_BUDGET_MS","SWEEPS_PER_BEAT","MAX_SWEEP_ATTEMPTS","emptyCounts","marked","changed","capped","invalid","failed","platformFirestore","app","firestore","orgHostIdsFromDoc","org","hosts","Array","isArray","Object","entries","filter","on","Boolean","map","hostId","keptHostIds","declared","doc","kept","field","keepSiteFields","value","push","id","markedPage","collectionRef","afterId","ordered","where","orderBy","documentId","startAfter","limit","get","eachConcurrently","items","work","next","Promise","all","from","length","Math","min","item","fieldsToWrite","fields","visibleTo","scopeMode","delete","scopeExcept","asStored","data","reconcileDocument","db","orgRef","docRef","counts","status","runTransaction","tx","getAll","exists","answer","maxIncluded","keepHostIds","patch","requiredPatch","name","update","collection","Error","ensurePatches","collections","every","row","catch","error","console","runScopeSharingSweep","input","orgId","startAt","max","findIndex","remaining","slice","deadline","budgetMs","Date","now","pages","Map","firstAfter","snapshot","set","docs","values","complete","cursor","onFirstMarked","ref","sweepScopeSharingAfterSiteChange","reason","sweepRef","leaveForTheJob","attempts","createdAtMs","result","writeError","runSiteChangeHooks","pluginId","hook","resumeScopeSweeps","options","pending","collectionGroup","tally","resumed","finished","droppedAfterFailing","sweep","parent","Number","path","undefined","emptyScopeSharingDrift","stale","scopeSharingDriftForOrg","orgData","drift","hostIds","page"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,kBAAkB,EAClBC,qBAAqB,QAEhB,sCAAqC;AAC5C,SAASC,2BAA2B,QAAQ,yDAAwD;AACpG,SACEC,2BAA2B,EAC3BC,+BAA+B,EAE/BC,oBAAoB,QACf,mDAAkD;AACzD,SAGEC,SAAS,EACTC,UAAU,QAIL,2BAA0B;AACjC,OAAOC,mBAAmB,sBAAkB;AAE5C,qDAAqD,GACrD,OAAO,MAAMC,0BAA0B,cAAa;AACpD,uDAAuD,GACvD,MAAMC,YAAY;AAClB,kCAAkC,GAClC,MAAMC,cAAc;AACpB,yDAAyD,GACzD,OAAO,MAAMC,mBAAmB,KAAK;AACrC,+DAA+D,GAC/D,OAAO,MAAMC,gBAAgB,MAAM;AACnC,2BAA2B,GAC3B,MAAMC,kBAAkB;AACxB,oFAAoF,GACpF,OAAO,MAAMC,qBAAqB,EAAC;AA8BnC,MAAMC,cAAc,IAAyB,CAAA;QAC3CC,QAAQ;QACRC,SAAS;QACTC,QAAQ;QACRC,SAAS;QACTC,QAAQ;IACV,CAAA;AAEA,MAAMC,oBAAoB,IAAMd,cAAce,GAAG,GAAGC,SAAS;AAE7D,0CAA0C,GAC1C,OAAO,SAASC,kBAAkBC,GAAkD;IAClF,MAAMC,QAAQD,uBAAAA,GAAK,CAAC,QAAQ;IAC5B,IAAI,CAACC,SAAS,OAAOA,UAAU,YAAYC,MAAMC,OAAO,CAACF,QAAQ,OAAO,EAAE;IAC1E,OAAOG,OAAOC,OAAO,CAACJ,OACnBK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roupSiteHold } from "@aglyn/aglyn/app-utils/consent-groups";
18
18
  import { holdsDedicatedSendingDomain } from "@aglyn/aglyn/app-utils/dedicated-sending-domain";
19
19
  import { checkQuota } from "@aglyn/aglyn/app-utils/plan-entitlements";
20
- import { hostScopeToken } from "@aglyn/aglyn/app-utils/scope-tokens";
20
+ import { hostScopeToken, SCOPE_MODE_ALL_EXCEPT } from "@aglyn/aglyn/app-utils/scope-tokens";
21
21
  import { resolveHostEnabledPlugins } from "@aglyn/aglyn/plugin-manager/enabled-plugins";
22
22
  import { listPluginOrgCollections } from "@aglyn/aglyn/plugin-manager/plugin-host-collections";
23
23
  import { normalizeSendingDomain } from "@aglyn/shared-util-email";
@@ -219,7 +219,21 @@ const consentHoldMessage = (hold)=>hold.reason === 'grouped' ? `The site is in t
219
219
  }
220
220
  plan.facts.mediaStaying = await count(db.collection('orgs').doc(fromOrgId).collection('media').where('visibleTo', 'array-contains', hostScopeToken(hostId))).catch(()=>0);
221
221
  if (plan.facts.mediaStaying) {
222
- warnings.push(`${plan.facts.mediaStaying} media file(s) stay in the old organization's library. The site keeps ` + 'showing them, but only the old organization can manage them — deleting them there removes them from this site.');
222
+ // A file shared with all of the old organization's sites except some
223
+ // reaches this site only while it is one of them: the sweep that runs
224
+ // when the site leaves takes it off every such file (AGL-4047). Only the
225
+ // marked files are read, so this costs nothing where none are.
226
+ const leaving = await db.collection('orgs').doc(fromOrgId).collection('media').where('scopeMode', '==', SCOPE_MODE_ALL_EXCEPT).select('visibleTo').get().then((marked)=>marked.docs.filter((doc)=>{
227
+ const visibleTo = doc.get('visibleTo');
228
+ return Array.isArray(visibleTo) && visibleTo.includes(hostScopeToken(hostId));
229
+ }).length).catch(()=>0);
230
+ const keeping = Math.max(plan.facts.mediaStaying - leaving, 0);
231
+ if (keeping) {
232
+ warnings.push(`${keeping} media file(s) stay in the old organization's library. The site keeps ` + 'showing them, but only the old organization can manage them — deleting them there removes them from this site.');
233
+ }
234
+ if (leaving) {
235
+ warnings.push(`${leaving} media file(s) the old organization shares with all of its sites except some stop ` + 'showing on this site when it moves, because the site is no longer one of those sites. A link ' + 'to one of them pasted into custom HTML or CSS on the site may keep loading.');
236
+ }
223
237
  }
224
238
  // Collaborators: old members who reached this site only through a grant.
225
239
  const members = await db.collection('orgs').doc(fromOrgId).collection('members').get();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/transfer-host.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type ConsentGroupSiteHold,\n consentGroupSiteHold,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport { holdsDedicatedSendingDomain } from '@aglyn/aglyn/app-utils/dedicated-sending-domain'\nimport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\nimport { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { resolveHostEnabledPlugins } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport { listPluginOrgCollections } from '@aglyn/aglyn/plugin-manager/plugin-host-collections'\nimport { normalizeSendingDomain } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport {\n deleteHostProjectionForAllMembers,\n syncHostProjectionForMembers,\n} from './host-memberships'\nimport { syncOrgAuthProjections } from './organizations'\nimport { sweepScopeSharingAfterSiteChange } from './scope-sharing-sweep'\nimport { SENDING_LABELS_COLLECTION } from './host-sending-domain'\nimport { SENDING_DOMAINS_COLLECTION } from './sending-domains'\nimport { TRACKING_HOSTS_COLLECTION } from './tracking-hosts'\n\n/*\n * MOVING A SITE TO ANOTHER ORGANIZATION (AGL-3381).\n *\n * A site's CONTENT lives under `hosts/{hostId}` and goes wherever the site\n * goes: pages, layouts, versions, forms and their submissions, its members,\n * collections, orders. What ties it to its organization is a handful of\n * pointers and projections, and those are what a transfer rewrites:\n *\n * hosts/{hostId} orgId, and memberRoles / memberPermissions\n * recomputed from the NEW roster (replaced whole,\n * so the old organization's people drop out)\n * hostIndex/{hostId} orgId — how routing resolves the owner\n * orgs/{from} hosts[hostId], and the site's paid seat pools\n * (registerAllocations, collaboratorAllocations)\n * released back to the old organization\n * orgs/{from}/members/* hostAccess[hostId], hostPermissions[hostId]\n * users/{uid}/hostMemberships/{hostId}\n * the old members' rows deleted, the new ones'\n * written\n * orgs/{to} hosts[hostId]\n *\n * The dedicated sending domain moves with it, because the reputation a\n * domain has earned is the site's: its record and its click-tracking host\n * move from `orgs/{from}` to `orgs/{to}`, and the label claim names the new\n * organization. It moves only to an organization whose plan may hold one.\n *\n * ## What stays with the old organization, and why\n *\n * Media `orgs/{from}/media`, stored under that organization's own\n * object prefix. Published pages reference it by address, so\n * the site keeps showing it; moving it would mean copying\n * objects and rewriting every page version that names them.\n * The plan counts it so staff can say so.\n * Records the site filed for its organization — CRM, datasets, lists —\n * are that organization's customer data.\n * Plugin documents a site OWNS on the organization (a declared\n * `siteField`, e.g. sends made as the site) stay as the old\n * organization's history: they name its lists, its\n * containers and the consent it relied on. A plugin that has\n * work still in flight on them (`holdsTransferWhile`) holds\n * the transfer until it lands or is cancelled.\n *\n * ## What refuses a transfer\n *\n * the site or either organization is missing, or it is already there;\n * the site is in a consent group, or a group change naming it is running\n * (its refusals are read by its siblings — it leaves the group first);\n * the destination is at its site limit, unless staff override it;\n * the site holds a dedicated sending domain the destination's plan\n * cannot hold (release it first);\n * a plugin reports work in flight on documents the site owns.\n */\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\n\nexport interface PlanHostTransferInput {\n hostId: string\n toOrgId: string\n /** Staff may place a site past the destination's site limit. */\n overrideSiteLimit?: boolean\n}\n\nconst count = async (query: FirebaseFirestore.Query): Promise<number> =>\n (await query.count().get()).data().count\n\nconst consentHoldMessage = (hold: ConsentGroupSiteHold): string =>\n hold.reason === 'grouped'\n ? `The site is in the consent group \"${hold.name}\". Remove it from the group first — its opt-outs are read by the other sites in it.`\n : 'A consent group change naming this site has not finished. Wait for it, then transfer.'\n\n/** How many sites an organization holds: its directory or its query, whichever is larger. */\nasync function sitesHeld(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n org: Record<string, unknown>,\n): Promise<number> {\n const directory = org['hosts']\n const mapped =\n directory && typeof directory === 'object'\n ? Object.values(directory as Record<string, unknown>).filter(Boolean).length\n : 0\n const queried = await count(db.collection('hosts').where('orgId', '==', orgId))\n return Math.max(mapped, queried)\n}\n\n/**\n * The transfer, worked out and not performed. Read only: safe to call for a\n * confirmation dialog, and called again by {@link transferHost} so what runs\n * is what was decided a moment ago, not what was true when the dialog opened.\n */\nexport async function planHostTransfer(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const db = firestore()\n const hostId = String(input.hostId ?? '').trim()\n const toOrgId = String(input.toOrgId ?? '').trim()\n const holds: HostTransferHold[] = []\n const warnings: string[] = []\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n const hostData = (host?.exists ? host.data() : null) ?? null\n const fromOrgId = typeof hostData?.['orgId'] === 'string' ? (hostData['orgId'] as string) : null\n const [fromOrg, toOrg] = await Promise.all([\n fromOrgId ? db.collection('orgs').doc(fromOrgId).get() : Promise.resolve(null),\n toOrgId ? db.collection('orgs').doc(toOrgId).get() : Promise.resolve(null),\n ])\n const fromData = (fromOrg?.exists ? fromOrg.data() : null) ?? null\n const toData = (toOrg?.exists ? toOrg.data() : null) ?? null\n\n const plan: HostTransferPlan = {\n hostId,\n siteName: (hostData?.['displayName'] as string | undefined) ?? null,\n fromOrgId,\n fromOrgName: (fromData?.['name'] as string | undefined) ?? null,\n toOrgId,\n toOrgName: (toData?.['name'] as string | undefined) ?? null,\n holds,\n warnings,\n facts: {\n mediaStaying: 0,\n ownedDocumentsStaying: [],\n collaboratorsLosingAccess: 0,\n sendingDomain: null,\n pluginsLost: [],\n siteLimit: { used: 0, limit: 0, allowed: true },\n },\n }\n\n if (!hostData) {\n holds.push({ code: 'no-site', message: 'There is no such site.' })\n return plan\n }\n if (!toData) {\n holds.push({ code: 'no-destination', message: 'There is no such destination organization.' })\n return plan\n }\n if (fromOrgId === toOrgId) {\n holds.push({ code: 'same-organization', message: 'The site already belongs to that organization.' })\n return plan\n }\n\n // Consent: the site's refusals are its siblings' too.\n const consentHold = fromData ? consentGroupSiteHold(fromData, hostId) : null\n if (consentHold) holds.push({ code: 'consent-group', message: consentHoldMessage(consentHold) })\n\n // The destination's site limit, counted the way site creation counts it.\n const used = await sitesHeld(db, toOrgId, toData)\n const quota = checkQuota(toData as never, 'hostLimit', used)\n plan.facts.siteLimit = { used, limit: quota.limit, allowed: quota.allowed }\n if (!quota.allowed) {\n if (input.overrideSiteLimit) {\n warnings.push(\n `The destination is at its site limit (${used} of ${quota.limit}); the transfer places this site past it.`,\n )\n } else {\n holds.push({\n code: 'site-limit',\n message: `The destination holds ${used} of its ${quota.limit} sites. Raise its limit, or override it.`,\n })\n }\n }\n\n // The dedicated sending domain moves only to a plan that may hold one.\n const sendingDomain = normalizeSendingDomain(String(hostData['sendingDomain'] ?? '')) || null\n const sendingLabel = String(hostData['sendingLabel'] ?? '').trim()\n if (sendingLabel || sendingDomain) {\n plan.facts.sendingDomain = sendingDomain ?? sendingLabel\n if (!holdsDedicatedSendingDomain(toData as never)) {\n holds.push({\n code: 'sending-domain',\n message:\n `The site sends as ${plan.facts.sendingDomain}, and the destination's plan cannot hold a ` +\n 'dedicated sending domain. Release it from the site first, or raise the destination’s plan.',\n })\n } else {\n warnings.push(`The dedicated sending domain ${plan.facts.sendingDomain} moves with the site.`)\n }\n }\n\n if (fromOrgId) {\n // Plugin documents the site owns on the old organization, and any still\n // in flight — each plugin's own declaration says which field and which\n // states, so no collection is named here.\n for (const declared of listPluginOrgCollections()) {\n if (!declared.siteField) continue\n const owned = db\n .collection('orgs')\n .doc(fromOrgId)\n .collection(declared.name)\n .where(declared.siteField, '==', hostId)\n const held = await count(owned).catch(() => 0)\n if (held) plan.facts.ownedDocumentsStaying.push({ collection: declared.name, count: held })\n const hold = declared.holdsTransferWhile\n if (held && hold) {\n const moving = await count(owned.where(hold.field, 'in', hold.values)).catch(() => 0)\n if (moving) {\n holds.push({\n code: 'in-flight',\n message:\n `${moving} ${declared.label ?? declared.name} of this site ${moving === 1 ? 'is' : 'are'} ` +\n `still ${hold.values.join(' or ')}. Let ${moving === 1 ? 'it' : 'them'} finish or cancel ` +\n `${moving === 1 ? 'it' : 'them'} first.`,\n })\n }\n }\n }\n if (plan.facts.ownedDocumentsStaying.length) {\n warnings.push(\n 'Records the site made for its old organization (' +\n plan.facts.ownedDocumentsStaying.map((row) => `${row.count} ${row.collection}`).join(', ') +\n ') stay there as its history.',\n )\n }\n\n plan.facts.mediaStaying = await count(\n db\n .collection('orgs')\n .doc(fromOrgId)\n .collection('media')\n .where('visibleTo', 'array-contains', hostScopeToken(hostId)),\n ).catch(() => 0)\n if (plan.facts.mediaStaying) {\n warnings.push(\n `${plan.facts.mediaStaying} media file(s) stay in the old organization's library. The site keeps ` +\n 'showing them, but only the old organization can manage them — deleting them there removes them from this site.',\n )\n }\n\n // Collaborators: old members who reached this site only through a grant.\n const members = await db.collection('orgs').doc(fromOrgId).collection('members').get()\n plan.facts.collaboratorsLosingAccess = members.docs.filter(\n (member) =>\n member.get('allHosts') !== true &&\n member.get('role') !== 'owner' &&\n Boolean((member.get('hostAccess') ?? {})[hostId]),\n ).length\n if (plan.facts.collaboratorsLosingAccess) {\n warnings.push(\n `${plan.facts.collaboratorsLosingAccess} collaborator(s) of the old organization lose access to the site.`,\n )\n }\n\n const before = resolveHostEnabledPlugins(fromData as never, hostData as never)\n const after = new Set(resolveHostEnabledPlugins(toData as never, hostData as never))\n plan.facts.pluginsLost = before.filter((id) => !after.has(id))\n if (plan.facts.pluginsLost.length) {\n warnings.push(\n `The destination does not enable ${plan.facts.pluginsLost.join(', ')}; what they draw on the site stops rendering.`,\n )\n }\n }\n\n if (toData['suspendedAt']) {\n warnings.push('The destination organization is suspended, so the site goes offline with it.')\n }\n return plan\n}\n\n/** A transfer refused by its plan: nothing was written. */\nexport class HostTransferRefusedError extends Error {\n readonly plan: HostTransferPlan\n\n constructor(plan: HostTransferPlan) {\n super(plan.holds.map((hold) => hold.message).join(' '))\n this.name = 'HostTransferRefusedError'\n this.plan = plan\n }\n}\n\n/** Move one document from one path to another, deleting the original. */\nasync function moveDocument(\n from: FirebaseFirestore.DocumentReference,\n to: FirebaseFirestore.DocumentReference,\n): Promise<boolean> {\n const snapshot = await from.get()\n if (!snapshot.exists) return false\n await to.set(snapshot.data() ?? {})\n await from.delete()\n return true\n}\n\n/**\n * Move a site to another organization (AGL-3381). Re-plans first and refuses\n * — writing nothing — when the plan holds; see the header for what moves,\n * what stays, and why.\n *\n * The ownership flip is one transaction over the site and both organization\n * documents, re-reading the site's organization inside it, so two transfers\n * of one site cannot both land. The site's access list is rebuilt straight\n * after it, before anything else. Everything after the flip is a projection\n * of it, recomputed from the documents rather than carried from the plan, so\n * a failure part-way is finished by running the projections again\n * ({@link syncOrgAuthProjections} and the membership sync).\n *\n * A site that belongs to no organization — left behind by a failed create or\n * a hand edit — is given one the same way, with nothing to release.\n */\nexport async function transferHost(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const plan = await planHostTransfer(input)\n if (plan.holds.length) throw new HostTransferRefusedError(plan)\n const db = firestore()\n const { hostId, toOrgId, fromOrgId } = plan\n const hostRef = db.collection('hosts').doc(hostId)\n const fromRef = fromOrgId ? db.collection('orgs').doc(fromOrgId) : null\n const toRef = db.collection('orgs').doc(toOrgId)\n\n await db.runTransaction(async (tx) => {\n const current = await tx.get(hostRef)\n if ((current.get('orgId') ?? null) !== fromOrgId) {\n throw new HostTransferRefusedError({\n ...plan,\n holds: [{ code: 'same-organization', message: 'The site changed organization while this ran.' }],\n })\n }\n if (fromRef) {\n tx.set(\n fromRef,\n {\n hosts: { [hostId]: FieldValue.delete() },\n registerAllocations: { [hostId]: FieldValue.delete() },\n collaboratorAllocations: { [hostId]: FieldValue.delete() },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n tx.set(\n toRef,\n { hosts: { [hostId]: true }, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n tx.update(hostRef, { orgId: toOrgId, updatedAt: FieldValue.serverTimestamp() })\n })\n\n // FIRST after the flip: the site's access list, rebuilt whole from the new\n // roster. Until this lands the old organization's people still hold the\n // keys the rules read, so nothing may run ahead of it.\n await syncOrgAuthProjections(toOrgId, hostId)\n // Routing names the new owner.\n await db.collection('hostIndex').doc(hostId).set({ orgId: toOrgId }, { merge: true })\n\n // Documents shared with all sites except some name their sites, and this\n // site just moved between the two lists they are worked out from. Both never\n // throw, and come before anything below that could.\n await sweepScopeSharingAfterSiteChange({ orgId: toOrgId, reason: 'site-added', hostId })\n if (fromOrgId) {\n await sweepScopeSharingAfterSiteChange({ orgId: fromOrgId, reason: 'site-removed', hostId })\n }\n\n if (fromRef && fromOrgId) {\n // The old roster's per-site grants on this site, then its projections.\n const grants = await fromRef.collection('members').get()\n for (let at = 0; at < grants.docs.length; at += 400) {\n const batch = db.batch()\n for (const member of grants.docs.slice(at, at + 400)) {\n const access = member.get('hostAccess') ?? {}\n const permissions = member.get('hostPermissions') ?? {}\n if (!(hostId in access) && !(hostId in permissions)) continue\n batch.update(member.ref, {\n [`hostAccess.${hostId}`]: FieldValue.delete(),\n [`hostPermissions.${hostId}`]: FieldValue.delete(),\n })\n }\n await batch.commit()\n }\n await deleteHostProjectionForAllMembers(fromOrgId, hostId)\n await syncOrgAuthProjections(fromOrgId)\n }\n await syncHostProjectionForMembers(toOrgId, hostId)\n\n // The dedicated sending domain and its click-tracking host.\n const current = await hostRef.get()\n const domain = normalizeSendingDomain(String(current.get('sendingDomain') ?? '')) || null\n const label = String(current.get('sendingLabel') ?? '').trim()\n if (domain && fromRef) {\n for (const collection of [SENDING_DOMAINS_COLLECTION, TRACKING_HOSTS_COLLECTION]) {\n await moveDocument(\n fromRef.collection(collection).doc(domain),\n toRef.collection(collection).doc(domain),\n )\n }\n }\n if (label) {\n const claim = db.collection(SENDING_LABELS_COLLECTION).doc(label)\n if ((await claim.get()).exists) await claim.update({ orgId: toOrgId })\n }\n\n return plan\n}\n"],"names":["consentGroupSiteHold","holdsDedicatedSendingDomain","checkQuota","hostScopeToken","resolveHostEnabledPlugins","listPluginOrgCollections","normalizeSendingDomain","FieldValue","firebaseAdmin","deleteHostProjectionForAllMembers","syncHostProjectionForMembers","syncOrgAuthProjections","sweepScopeSharingAfterSiteChange","SENDING_LABELS_COLLECTION","SENDING_DOMAINS_COLLECTION","TRACKING_HOSTS_COLLECTION","firestore","app","count","query","get","data","consentHoldMessage","hold","reason","name","sitesHeld","db","orgId","org","directory","mapped","Object","values","filter","Boolean","length","queried","collection","where","Math","max","planHostTransfer","input","host","fromOrg","toOrg","hostData","hostId","String","trim","toOrgId","holds","warnings","doc","exists","fromOrgId","Promise","all","resolve","fromData","toData","plan","siteName","fromOrgName","toOrgName","facts","mediaStaying","ownedDocumentsStaying","collaboratorsLosingAccess","sendingDomain","pluginsLost","siteLimit","used","limit","allowed","push","code","message","consentHold","quota","overrideSiteLimit","sendingLabel","declared","siteField","owned","held","catch","holdsTransferWhile","moving","field","label","join","map","row","members","docs","member","before","after","Set","id","has","HostTransferRefusedError","Error","moveDocument","from","to","snapshot","set","delete","transferHost","current","hostRef","fromRef","toRef","runTransaction","tx","hosts","registerAllocations","collaboratorAllocations","updatedAt","serverTimest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,CAAAA,UAAUiF,MAAK,KAAM,CAAEjF,CAAAA,UAAUkF,WAAU,GAAI;gBACrDH,MAAMH,MAAM,CAAC3B,OAAOkC,GAAG,EAAE;oBACvB,CAAC,CAAC,WAAW,EAAEnF,QAAQ,CAAC,EAAEzC,WAAWuG,MAAM;oBAC3C,CAAC,CAAC,gBAAgB,EAAE9D,QAAQ,CAAC,EAAEzC,WAAWuG,MAAM;gBAClD;YACF;YACA,MAAMiB,MAAMK,MAAM;QACpB;QACA,MAAM3H,kCAAkC+C,WAAWR;QACnD,MAAMrC,uBAAuB6C;IAC/B;IACA,MAAM9C,6BAA6ByC,SAASH;IAE5C,4DAA4D;IAC5D,MAAMgE,UAAU,MAAMC,QAAQ7F,GAAG;IACjC,MAAMiH,SAAS/H,uBAAuB2C,QAAO+D,eAAAA,QAAQ5F,GAAG,CAAC,4BAAZ4F,eAAgC,QAAQ;IACrF,MAAMrB,QAAQ1C,QAAO+D,gBAAAA,QAAQ5F,GAAG,CAAC,2BAAZ4F,gBAA+B,IAAI9D,IAAI;IAC5D,IAAImF,UAAUnB,SAAS;QACrB,KAAK,MAAM5E,cAAc;YAACxB;YAA4BC;SAA0B,CAAE;YAChF,MAAM0F,aACJS,QAAQ5E,UAAU,CAACA,YAAYgB,GAAG,CAAC+E,SACnClB,MAAM7E,UAAU,CAACA,YAAYgB,GAAG,CAAC+E;QAErC;IACF;IACA,IAAI1C,OAAO;QACT,MAAM2C,QAAQ3G,GAAGW,UAAU,CAACzB,2BAA2ByC,GAAG,CAACqC;QAC3D,IAAI,AAAC,CAAA,MAAM2C,MAAMlH,GAAG,EAAC,EAAGmC,MAAM,EAAE,MAAM+E,MAAMV,MAAM,CAAC;YAAEhG,OAAOuB;QAAQ;IACtE;IAEA,OAAOW;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/transfer-host.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type ConsentGroupSiteHold,\n consentGroupSiteHold,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport { holdsDedicatedSendingDomain } from '@aglyn/aglyn/app-utils/dedicated-sending-domain'\nimport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\nimport { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, SCOPE_MODE_ALL_EXCEPT } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { resolveHostEnabledPlugins } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport { listPluginOrgCollections } from '@aglyn/aglyn/plugin-manager/plugin-host-collections'\nimport { normalizeSendingDomain } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport {\n deleteHostProjectionForAllMembers,\n syncHostProjectionForMembers,\n} from './host-memberships'\nimport { syncOrgAuthProjections } from './organizations'\nimport { sweepScopeSharingAfterSiteChange } from './scope-sharing-sweep'\nimport { SENDING_LABELS_COLLECTION } from './host-sending-domain'\nimport { SENDING_DOMAINS_COLLECTION } from './sending-domains'\nimport { TRACKING_HOSTS_COLLECTION } from './tracking-hosts'\n\n/*\n * MOVING A SITE TO ANOTHER ORGANIZATION (AGL-3381).\n *\n * A site's CONTENT lives under `hosts/{hostId}` and goes wherever the site\n * goes: pages, layouts, versions, forms and their submissions, its members,\n * collections, orders. What ties it to its organization is a handful of\n * pointers and projections, and those are what a transfer rewrites:\n *\n * hosts/{hostId} orgId, and memberRoles / memberPermissions\n * recomputed from the NEW roster (replaced whole,\n * so the old organization's people drop out)\n * hostIndex/{hostId} orgId — how routing resolves the owner\n * orgs/{from} hosts[hostId], and the site's paid seat pools\n * (registerAllocations, collaboratorAllocations)\n * released back to the old organization\n * orgs/{from}/members/* hostAccess[hostId], hostPermissions[hostId]\n * users/{uid}/hostMemberships/{hostId}\n * the old members' rows deleted, the new ones'\n * written\n * orgs/{to} hosts[hostId]\n *\n * The dedicated sending domain moves with it, because the reputation a\n * domain has earned is the site's: its record and its click-tracking host\n * move from `orgs/{from}` to `orgs/{to}`, and the label claim names the new\n * organization. It moves only to an organization whose plan may hold one.\n *\n * ## What stays with the old organization, and why\n *\n * Media `orgs/{from}/media`, stored under that organization's own\n * object prefix. Published pages reference it by address, so\n * the site keeps showing it; moving it would mean copying\n * objects and rewriting every page version that names them.\n * The plan counts it so staff can say so.\n * Records the site filed for its organization — CRM, datasets, lists —\n * are that organization's customer data.\n * Plugin documents a site OWNS on the organization (a declared\n * `siteField`, e.g. sends made as the site) stay as the old\n * organization's history: they name its lists, its\n * containers and the consent it relied on. A plugin that has\n * work still in flight on them (`holdsTransferWhile`) holds\n * the transfer until it lands or is cancelled.\n *\n * ## What refuses a transfer\n *\n * the site or either organization is missing, or it is already there;\n * the site is in a consent group, or a group change naming it is running\n * (its refusals are read by its siblings — it leaves the group first);\n * the destination is at its site limit, unless staff override it;\n * the site holds a dedicated sending domain the destination's plan\n * cannot hold (release it first);\n * a plugin reports work in flight on documents the site owns.\n */\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type { HostTransferHold, HostTransferPlan } from '@aglyn/aglyn/app-utils/host-transfer'\n\nexport interface PlanHostTransferInput {\n hostId: string\n toOrgId: string\n /** Staff may place a site past the destination's site limit. */\n overrideSiteLimit?: boolean\n}\n\nconst count = async (query: FirebaseFirestore.Query): Promise<number> =>\n (await query.count().get()).data().count\n\nconst consentHoldMessage = (hold: ConsentGroupSiteHold): string =>\n hold.reason === 'grouped'\n ? `The site is in the consent group \"${hold.name}\". Remove it from the group first — its opt-outs are read by the other sites in it.`\n : 'A consent group change naming this site has not finished. Wait for it, then transfer.'\n\n/** How many sites an organization holds: its directory or its query, whichever is larger. */\nasync function sitesHeld(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n org: Record<string, unknown>,\n): Promise<number> {\n const directory = org['hosts']\n const mapped =\n directory && typeof directory === 'object'\n ? Object.values(directory as Record<string, unknown>).filter(Boolean).length\n : 0\n const queried = await count(db.collection('hosts').where('orgId', '==', orgId))\n return Math.max(mapped, queried)\n}\n\n/**\n * The transfer, worked out and not performed. Read only: safe to call for a\n * confirmation dialog, and called again by {@link transferHost} so what runs\n * is what was decided a moment ago, not what was true when the dialog opened.\n */\nexport async function planHostTransfer(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const db = firestore()\n const hostId = String(input.hostId ?? '').trim()\n const toOrgId = String(input.toOrgId ?? '').trim()\n const holds: HostTransferHold[] = []\n const warnings: string[] = []\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n const hostData = (host?.exists ? host.data() : null) ?? null\n const fromOrgId = typeof hostData?.['orgId'] === 'string' ? (hostData['orgId'] as string) : null\n const [fromOrg, toOrg] = await Promise.all([\n fromOrgId ? db.collection('orgs').doc(fromOrgId).get() : Promise.resolve(null),\n toOrgId ? db.collection('orgs').doc(toOrgId).get() : Promise.resolve(null),\n ])\n const fromData = (fromOrg?.exists ? fromOrg.data() : null) ?? null\n const toData = (toOrg?.exists ? toOrg.data() : null) ?? null\n\n const plan: HostTransferPlan = {\n hostId,\n siteName: (hostData?.['displayName'] as string | undefined) ?? null,\n fromOrgId,\n fromOrgName: (fromData?.['name'] as string | undefined) ?? null,\n toOrgId,\n toOrgName: (toData?.['name'] as string | undefined) ?? null,\n holds,\n warnings,\n facts: {\n mediaStaying: 0,\n ownedDocumentsStaying: [],\n collaboratorsLosingAccess: 0,\n sendingDomain: null,\n pluginsLost: [],\n siteLimit: { used: 0, limit: 0, allowed: true },\n },\n }\n\n if (!hostData) {\n holds.push({ code: 'no-site', message: 'There is no such site.' })\n return plan\n }\n if (!toData) {\n holds.push({ code: 'no-destination', message: 'There is no such destination organization.' })\n return plan\n }\n if (fromOrgId === toOrgId) {\n holds.push({ code: 'same-organization', message: 'The site already belongs to that organization.' })\n return plan\n }\n\n // Consent: the site's refusals are its siblings' too.\n const consentHold = fromData ? consentGroupSiteHold(fromData, hostId) : null\n if (consentHold) holds.push({ code: 'consent-group', message: consentHoldMessage(consentHold) })\n\n // The destination's site limit, counted the way site creation counts it.\n const used = await sitesHeld(db, toOrgId, toData)\n const quota = checkQuota(toData as never, 'hostLimit', used)\n plan.facts.siteLimit = { used, limit: quota.limit, allowed: quota.allowed }\n if (!quota.allowed) {\n if (input.overrideSiteLimit) {\n warnings.push(\n `The destination is at its site limit (${used} of ${quota.limit}); the transfer places this site past it.`,\n )\n } else {\n holds.push({\n code: 'site-limit',\n message: `The destination holds ${used} of its ${quota.limit} sites. Raise its limit, or override it.`,\n })\n }\n }\n\n // The dedicated sending domain moves only to a plan that may hold one.\n const sendingDomain = normalizeSendingDomain(String(hostData['sendingDomain'] ?? '')) || null\n const sendingLabel = String(hostData['sendingLabel'] ?? '').trim()\n if (sendingLabel || sendingDomain) {\n plan.facts.sendingDomain = sendingDomain ?? sendingLabel\n if (!holdsDedicatedSendingDomain(toData as never)) {\n holds.push({\n code: 'sending-domain',\n message:\n `The site sends as ${plan.facts.sendingDomain}, and the destination's plan cannot hold a ` +\n 'dedicated sending domain. Release it from the site first, or raise the destination’s plan.',\n })\n } else {\n warnings.push(`The dedicated sending domain ${plan.facts.sendingDomain} moves with the site.`)\n }\n }\n\n if (fromOrgId) {\n // Plugin documents the site owns on the old organization, and any still\n // in flight — each plugin's own declaration says which field and which\n // states, so no collection is named here.\n for (const declared of listPluginOrgCollections()) {\n if (!declared.siteField) continue\n const owned = db\n .collection('orgs')\n .doc(fromOrgId)\n .collection(declared.name)\n .where(declared.siteField, '==', hostId)\n const held = await count(owned).catch(() => 0)\n if (held) plan.facts.ownedDocumentsStaying.push({ collection: declared.name, count: held })\n const hold = declared.holdsTransferWhile\n if (held && hold) {\n const moving = await count(owned.where(hold.field, 'in', hold.values)).catch(() => 0)\n if (moving) {\n holds.push({\n code: 'in-flight',\n message:\n `${moving} ${declared.label ?? declared.name} of this site ${moving === 1 ? 'is' : 'are'} ` +\n `still ${hold.values.join(' or ')}. Let ${moving === 1 ? 'it' : 'them'} finish or cancel ` +\n `${moving === 1 ? 'it' : 'them'} first.`,\n })\n }\n }\n }\n if (plan.facts.ownedDocumentsStaying.length) {\n warnings.push(\n 'Records the site made for its old organization (' +\n plan.facts.ownedDocumentsStaying.map((row) => `${row.count} ${row.collection}`).join(', ') +\n ') stay there as its history.',\n )\n }\n\n plan.facts.mediaStaying = await count(\n db\n .collection('orgs')\n .doc(fromOrgId)\n .collection('media')\n .where('visibleTo', 'array-contains', hostScopeToken(hostId)),\n ).catch(() => 0)\n if (plan.facts.mediaStaying) {\n // A file shared with all of the old organization's sites except some\n // reaches this site only while it is one of them: the sweep that runs\n // when the site leaves takes it off every such file (AGL-4047). Only the\n // marked files are read, so this costs nothing where none are.\n const leaving = await db\n .collection('orgs')\n .doc(fromOrgId)\n .collection('media')\n .where('scopeMode', '==', SCOPE_MODE_ALL_EXCEPT)\n .select('visibleTo')\n .get()\n .then(\n (marked) =>\n marked.docs.filter((doc) => {\n const visibleTo = doc.get('visibleTo')\n return Array.isArray(visibleTo) && visibleTo.includes(hostScopeToken(hostId))\n }).length,\n )\n .catch(() => 0)\n const keeping = Math.max(plan.facts.mediaStaying - leaving, 0)\n if (keeping) {\n warnings.push(\n `${keeping} media file(s) stay in the old organization's library. The site keeps ` +\n 'showing them, but only the old organization can manage them — deleting them there removes them from this site.',\n )\n }\n if (leaving) {\n warnings.push(\n `${leaving} media file(s) the old organization shares with all of its sites except some stop ` +\n 'showing on this site when it moves, because the site is no longer one of those sites. A link ' +\n 'to one of them pasted into custom HTML or CSS on the site may keep loading.',\n )\n }\n }\n\n // Collaborators: old members who reached this site only through a grant.\n const members = await db.collection('orgs').doc(fromOrgId).collection('members').get()\n plan.facts.collaboratorsLosingAccess = members.docs.filter(\n (member) =>\n member.get('allHosts') !== true &&\n member.get('role') !== 'owner' &&\n Boolean((member.get('hostAccess') ?? {})[hostId]),\n ).length\n if (plan.facts.collaboratorsLosingAccess) {\n warnings.push(\n `${plan.facts.collaboratorsLosingAccess} collaborator(s) of the old organization lose access to the site.`,\n )\n }\n\n const before = resolveHostEnabledPlugins(fromData as never, hostData as never)\n const after = new Set(resolveHostEnabledPlugins(toData as never, hostData as never))\n plan.facts.pluginsLost = before.filter((id) => !after.has(id))\n if (plan.facts.pluginsLost.length) {\n warnings.push(\n `The destination does not enable ${plan.facts.pluginsLost.join(', ')}; what they draw on the site stops rendering.`,\n )\n }\n }\n\n if (toData['suspendedAt']) {\n warnings.push('The destination organization is suspended, so the site goes offline with it.')\n }\n return plan\n}\n\n/** A transfer refused by its plan: nothing was written. */\nexport class HostTransferRefusedError extends Error {\n readonly plan: HostTransferPlan\n\n constructor(plan: HostTransferPlan) {\n super(plan.holds.map((hold) => hold.message).join(' '))\n this.name = 'HostTransferRefusedError'\n this.plan = plan\n }\n}\n\n/** Move one document from one path to another, deleting the original. */\nasync function moveDocument(\n from: FirebaseFirestore.DocumentReference,\n to: FirebaseFirestore.DocumentReference,\n): Promise<boolean> {\n const snapshot = await from.get()\n if (!snapshot.exists) return false\n await to.set(snapshot.data() ?? {})\n await from.delete()\n return true\n}\n\n/**\n * Move a site to another organization (AGL-3381). Re-plans first and refuses\n * — writing nothing — when the plan holds; see the header for what moves,\n * what stays, and why.\n *\n * The ownership flip is one transaction over the site and both organization\n * documents, re-reading the site's organization inside it, so two transfers\n * of one site cannot both land. The site's access list is rebuilt straight\n * after it, before anything else. Everything after the flip is a projection\n * of it, recomputed from the documents rather than carried from the plan, so\n * a failure part-way is finished by running the projections again\n * ({@link syncOrgAuthProjections} and the membership sync).\n *\n * A site that belongs to no organization — left behind by a failed create or\n * a hand edit — is given one the same way, with nothing to release.\n */\nexport async function transferHost(input: PlanHostTransferInput): Promise<HostTransferPlan> {\n const plan = await planHostTransfer(input)\n if (plan.holds.length) throw new HostTransferRefusedError(plan)\n const db = firestore()\n const { hostId, toOrgId, fromOrgId } = plan\n const hostRef = db.collection('hosts').doc(hostId)\n const fromRef = fromOrgId ? db.collection('orgs').doc(fromOrgId) : null\n const toRef = db.collection('orgs').doc(toOrgId)\n\n await db.runTransaction(async (tx) => {\n const current = await tx.get(hostRef)\n if ((current.get('orgId') ?? null) !== fromOrgId) {\n throw new HostTransferRefusedError({\n ...plan,\n holds: [{ code: 'same-organization', message: 'The site changed organization while this ran.' }],\n })\n }\n if (fromRef) {\n tx.set(\n fromRef,\n {\n hosts: { [hostId]: FieldValue.delete() },\n registerAllocations: { [hostId]: FieldValue.delete() },\n collaboratorAllocations: { [hostId]: FieldValue.delete() },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n tx.set(\n toRef,\n { hosts: { [hostId]: true }, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n tx.update(hostRef, { orgId: toOrgId, updatedAt: FieldValue.serverTimestamp() })\n })\n\n // FIRST after the flip: the site's access list, rebuilt whole from the new\n // roster. Until this lands the old organization's people still hold the\n // keys the rules read, so nothing may run ahead of it.\n await syncOrgAuthProjections(toOrgId, hostId)\n // Routing names the new owner.\n await db.collection('hostIndex').doc(hostId).set({ orgId: toOrgId }, { merge: true })\n\n // Documents shared with all sites except some name their sites, and this\n // site just moved between the two lists they are worked out from. Both never\n // throw, and come before anything below that could.\n await sweepScopeSharingAfterSiteChange({ orgId: toOrgId, reason: 'site-added', hostId })\n if (fromOrgId) {\n await sweepScopeSharingAfterSiteChange({ orgId: fromOrgId, reason: 'site-removed', hostId })\n }\n\n if (fromRef && fromOrgId) {\n // The old roster's per-site grants on this site, then its projections.\n const grants = await fromRef.collection('members').get()\n for (let at = 0; at < grants.docs.length; at += 400) {\n const batch = db.batch()\n for (const member of grants.docs.slice(at, at + 400)) {\n const access = member.get('hostAccess') ?? {}\n const permissions = member.get('hostPermissions') ?? {}\n if (!(hostId in access) && !(hostId in permissions)) continue\n batch.update(member.ref, {\n [`hostAccess.${hostId}`]: FieldValue.delete(),\n [`hostPermissions.${hostId}`]: FieldValue.delete(),\n })\n }\n await batch.commit()\n }\n await deleteHostProjectionForAllMembers(fromOrgId, hostId)\n await syncOrgAuthProjections(fromOrgId)\n }\n await syncHostProjectionForMembers(toOrgId, hostId)\n\n // The dedicated sending domain and its click-tracking host.\n const current = await hostRef.get()\n const domain = normalizeSendingDomain(String(current.get('sendingDomain') ?? '')) || null\n const label = String(current.get('sendingLabel') ?? '').trim()\n if (domain && fromRef) {\n for (const collection of [SENDING_DOMAINS_COLLECTION, TRACKING_HOSTS_COLLECTION]) {\n await moveDocument(\n fromRef.collection(collection).doc(domain),\n toRef.collection(collection).doc(domain),\n )\n }\n }\n if (label) {\n const claim = db.collection(SENDING_LABELS_COLLECTION).doc(label)\n if ((await claim.get()).exists) await claim.update({ orgId: toOrgId })\n }\n\n return plan\n}\n"],"names":["consentGroupSiteHold","holdsDedicatedSendingDomain","checkQuota","hostScopeToken","SCOPE_MODE_ALL_EXCEPT","resolveHostEnabledPlugins","listPluginOrgCollections","normalizeSendingDomain","FieldValue","firebaseAdmin","deleteHostProjectionForAllMembers","syncHostProjectionForMembers","syncOrgAuthProjections","sweepScopeSharingAfterSiteChange","SENDING_LABELS_COLLECTION","SENDING_DOMAINS_COLLECTION","TRACKING_HOSTS_COLLECTION","firestore","app","count","query","get","data","consentHoldMessage","hold","reason","name","sitesHeld","db","orgId","org","directory","mapped","Object","values","filter","Boolean","length","queried","collection","where","Math","max","planHostTransfer","input","host","fromOrg","toOrg","hostData","hostId","String","trim","toOrgId","holds","warnings","doc","exists","fromOrgId","Promise","all","resolve","fromData","toData","plan","siteName","fromOrgName","toOrgName","facts","mediaStaying","ownedDocumentsStaying","collaboratorsLosingAccess","sendingDomain","pluginsLost","siteLimit","used","limit","allowed","push","code","message","consentHold","quota","overrideSiteLimit","sendingLabel","declared","siteField","owned","held","catch","holdsTransferWhile","moving","field","label","join","map","row","leaving","select","then","marked","docs","visibleTo","Array","isArray","includes","keeping","members","member","before","after","Set","id","has","HostTransferRefusedError","Error","moveDocument","from","to","snapshot","set","delete","transferHost","current","hostRef","fromRef","toRef","runTransaction","tx","hosts","registerAllocations","collaboratorAllocations","updatedAt","serverTimestamp","merge","update","grants","at","batch","slice","access","permissions","ref","commit","domain","claim"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,oBAAoB,QACf,wCAAuC;AAC9C,SAASC,2BAA2B,QAAQ,kDAAiD;AAE7F,SAASC,UAAU,QAAQ,2CAA0C;AACrE,SAASC,cAAc,EAAEC,qBAAqB,QAAQ,sCAAqC;AAC3F,SAASC,yBAAyB,QAAQ,8CAA6C;AACvF,SAASC,wBAAwB,QAAQ,sDAAqD;AAC9F,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,iCAAiC,EACjCC,4BAA4B,QACvB,wBAAoB;AAC3B,SAASC,sBAAsB,QAAQ,qBAAiB;AACxD,SAASC,gCAAgC,QAAQ,2BAAuB;AACxE,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,0BAA0B,QAAQ,uBAAmB;AAC9D,SAASC,yBAAyB,QAAQ,sBAAkB;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmDC,GAED,MAAMC,YAAY,IAAMR,cAAcS,GAAG,GAAGD,SAAS;AAWrD,MAAME,QAAQ,OAAOC,QACnB,AAAC,CAAA,MAAMA,MAAMD,KAAK,GAAGE,GAAG,EAAC,EAAGC,IAAI,GAAGH,KAAK;AAE1C,MAAMI,qBAAqB,CAACC,OAC1BA,KAAKC,MAAM,KAAK,YACZ,CAAC,kCAAkC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CAAkC+C,WAAWR;QACnD,MAAMrC,uBAAuB6C;IAC/B;IACA,MAAM9C,6BAA6ByC,SAASH;IAE5C,4DAA4D;IAC5D,MAAMyE,UAAU,MAAMC,QAAQtG,GAAG;IACjC,MAAM0H,SAASxI,uBAAuB2C,QAAOwE,eAAAA,QAAQrG,GAAG,CAAC,4BAAZqG,eAAgC,QAAQ;IACrF,MAAM9B,QAAQ1C,QAAOwE,gBAAAA,QAAQrG,GAAG,CAAC,2BAAZqG,gBAA+B,IAAIvE,IAAI;IAC5D,IAAI4F,UAAUnB,SAAS;QACrB,KAAK,MAAMrF,cAAc;YAACxB;YAA4BC;SAA0B,CAAE;YAChF,MAAMmG,aACJS,QAAQrF,UAAU,CAACA,YAAYgB,GAAG,CAACwF,SACnClB,MAAMtF,UAAU,CAACA,YAAYgB,GAAG,CAACwF;QAErC;IACF;IACA,IAAInD,OAAO;QACT,MAAMoD,QAAQpH,GAAGW,UAAU,CAACzB,2BAA2ByC,GAAG,CAACqC;QAC3D,IAAI,AAAC,CAAA,MAAMoD,MAAM3H,GAAG,EAAC,EAAGmC,MAAM,EAAE,MAAMwF,MAAMV,MAAM,CAAC;YAAEzG,OAAOuB;QAAQ;IACtE;IAEA,OAAOW;AACT"}
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { CAPTURED_BY_HOST_FIELD, checkCrmRecordsQuota, composeContactName, CONTACT_EXTRA_PHONE_FIELDS, consentGroupScope, crmDefaultScopeOf, CONTACT_FACETS_FIELD, CONTACT_FORM_IDS_CAP, CONTACT_FORM_IDS_FIELD, marketingConsentFieldsForGroup, mergeContactInteraction, normalizeContactBirthdate, normalizeContainerIds, readContactFacet, normalizeContactEmail, ORG_SCOPE_TOKEN } from "@aglyn/aglyn/server";
17
+ */ import { CAPTURED_BY_HOST_FIELD, checkCrmRecordsQuota, composeContactName, CONTACT_EXTRA_PHONE_FIELDS, consentGroupScope, crmScopeFields, CONTACT_FACETS_FIELD, CONTACT_FORM_IDS_CAP, CONTACT_FORM_IDS_FIELD, marketingConsentFieldsForGroup, mergeContactInteraction, normalizeContactBirthdate, normalizeContainerIds, readContactFacet, normalizeContactEmail } from "@aglyn/aglyn/server";
18
18
  import { FieldValue } from "firebase-admin/firestore";
19
19
  import { firebaseAdmin } from "./firebase-admin.js";
20
20
  import { countCrmRecords, restampCrmListFieldsAt } from "./crm-records.js";
@@ -528,24 +528,7 @@ export async function upsertHostContact(options) {
528
528
  [CONTACT_FORM_IDS_FIELD]: [
529
529
  interaction.formId
530
530
  ]
531
- } : {}, {
532
- /*
533
- * THE CAPTURING GROUP, not the whole org.
534
- *
535
- * Stamping `['org']` here made every contact readable by every site in
536
- * the account on the day it was created — so an agency's twelve clients
537
- * shared one address book by default, and closing the missing-field
538
- * fail-open would not have touched it, because the field was present
539
- * and said so.
540
- *
541
- * A group of one — the default — is this site alone. A declared group
542
- * is the sites that already present as one sender. Widening beyond that
543
- * is available and is an ACT: an org may set its CRM default
544
- * (`crmDefaultScopeOf`) to `'org'`, or a later capture on a sibling
545
- * site unions that site in.
546
- */ visibleTo: crmDefaultScopeOf(orgBilling == null ? void 0 : orgBilling.org) === 'org' ? [
547
- ORG_SCOPE_TOKEN
548
- ] : consentGroupScope(group),
531
+ } : {}, crmScopeFields(orgBilling == null ? void 0 : orgBilling.org, group), {
549
532
  email
550
533
  }, canonicalName ? nameSearchFields(canonicalName) : {}, profile.phone || profile.mobilePhone ? {
551
534
  phone: profile.phone || profile.mobilePhone