@aglyn/plugins-data 1.12.0 → 1.14.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.
Files changed (43) hide show
  1. package/package.json +10 -10
  2. package/src/lib/artifact/dataset-schema-artifact.server.js +6 -3
  3. package/src/lib/artifact/dataset-schema-artifact.server.js.map +1 -1
  4. package/src/lib/components/dataset-schema-dialog.component.d.ts +14 -0
  5. package/src/lib/components/dataset-schema-dialog.component.js +317 -239
  6. package/src/lib/components/dataset-schema-dialog.component.js.map +1 -1
  7. package/src/lib/components/host-datasets-card.component.js +71 -34
  8. package/src/lib/components/host-datasets-card.component.js.map +1 -1
  9. package/src/lib/components/use-dataset-writes-blocked.d.ts +50 -12
  10. package/src/lib/components/use-dataset-writes-blocked.js +86 -19
  11. package/src/lib/components/use-dataset-writes-blocked.js.map +1 -1
  12. package/src/lib/declarations.d.ts +25 -0
  13. package/src/lib/declarations.js +37 -0
  14. package/src/lib/declarations.js.map +1 -0
  15. package/src/lib/model/data-permissions.d.ts +34 -0
  16. package/src/lib/model/data-permissions.js +108 -0
  17. package/src/lib/model/data-permissions.js.map +1 -0
  18. package/src/lib/model/dataset-access.d.ts +22 -0
  19. package/src/lib/model/dataset-access.js +30 -0
  20. package/src/lib/model/dataset-access.js.map +1 -0
  21. package/src/lib/model/dataset-record.js +8 -3
  22. package/src/lib/model/dataset-record.js.map +1 -1
  23. package/src/lib/plugin.js +4 -1
  24. package/src/lib/plugin.js.map +1 -1
  25. package/src/lib/server/dataset-access.server.d.ts +41 -0
  26. package/src/lib/server/dataset-access.server.js +49 -0
  27. package/src/lib/server/dataset-access.server.js.map +1 -0
  28. package/src/lib/server/dataset-figures.js +12 -0
  29. package/src/lib/server/dataset-figures.js.map +1 -1
  30. package/src/lib/server/dataset-site-erasure.d.ts +2 -2
  31. package/src/lib/server/dataset-site-erasure.js +4 -26
  32. package/src/lib/server/dataset-site-erasure.js.map +1 -1
  33. package/src/lib/server/datasets-route.d.ts +2 -0
  34. package/src/lib/server/datasets-route.js +178 -27
  35. package/src/lib/server/datasets-route.js.map +1 -1
  36. package/src/lib/site-bundle/datasets-site-bundle.server.d.ts +4 -2
  37. package/src/lib/site-bundle/datasets-site-bundle.server.js +8 -4
  38. package/src/lib/site-bundle/datasets-site-bundle.server.js.map +1 -1
  39. package/src/lib/transfer/dataset-transfer-access.server.d.ts +23 -0
  40. package/src/lib/transfer/dataset-transfer-access.server.js +45 -0
  41. package/src/lib/transfer/dataset-transfer-access.server.js.map +1 -0
  42. package/src/lib/transfer/dataset-transfer-resource.js +2 -1
  43. package/src/lib/transfer/dataset-transfer-resource.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/datasets-route.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 defaultScopeForNewResource,\n newResourceScopeFields,\n pluginRequestFromWeb,\n type PluginWebApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n createResourceUid,\n ensureDeclaredCustomFieldTypes,\n memberCanSee,\n} from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n dataStorageRefusal,\n isImpersonationSession,\n isServerReleaseFlagOnForOrg,\n lockdownRefusal,\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { permissionRefusalText } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { announceDatasetRecords as announceDatasetChange } from './announce-dataset-records'\nimport { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from '../model/dataset-models'\nimport { defaultDatasetFieldId } from '../model/datasets'\nimport { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from '../model/dataset-record-delete-plan'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n fillRecordAddresses,\n isRecordAddressField,\n recordAddressFieldIds,\n recordAddressOf,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * `dataStorageMbPerOrg` for this route, rendered as the console's 403.\n *\n * The VERDICT moved to `utils/server/data-storage-gate` (AGL-2253) — it was\n * defined here, so `/v1` and the tenant form path, which write dataset bytes\n * through their own code, enforced nothing. Only the console wording is left\n * behind, because the other two callers answer different shapes.\n */\nasync function refuseIfDataStorageBlocked(\n org: unknown,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Response | null> {\n const refusal = await dataStorageRefusal(org, orgRef)\n if (!refusal) return null\n return Response.json(\n {\n error:\n refusal.basis === 'always'\n ? 'Dataset storage is not included on this plan — upgrade in Billing'\n : `Dataset storage limit reached (${refusal.includedMb} MB) — ` +\n 'upgrade in Billing',\n },\n { status: 403 },\n )\n}\n\n/**\n * The key every action here asks (AGL-4047): \"Manage data\", whose default is\n * the owner, admin and editor, as the rules' `canWriteOrgDatasets()` asks it.\n */\nconst DATASETS_PERMISSION = 'data.manage'\n\n/** The 403 for a member without it, naming the permission, never a role. */\nfunction datasetsPermissionRefusal(): Response {\n return Response.json(\n {\n error: permissionRefusalText(DATASETS_PERMISSION),\n reason: 'permission',\n permission: DATASETS_PERMISSION,\n },\n { status: 403 },\n )\n}\n\n/**\n * Rows written per import transaction.\n *\n * Firestore allows at most 500 writes in one transaction, and this is the\n * chunk size the route already used for its batches, so nothing about the\n * shape of an import changed when the batches became transactions (AGL-2371).\n */\nconst IMPORT_CHUNK = 400\n\n/**\n * How many records one \"give it page addresses\" call fills (AGL-3475). Far\n * past a services or locations dataset; a larger one reports `truncated`, and\n * the next call fills the next records, since a filled record is skipped.\n */\nconst ADDRESS_FILL_MAX = 5000\n\n/**\n * Dataset/record creation API (AGL-473): creates moved out of the client\n * SDK so quotas and entitlements are enforced server-side — Firestore\n * rules deny client-side `create` on `orgs/{orgId}/datasets/**` (updates\n * and deletes stay client-direct, they don't consume quota). Actions:\n *\n * - `create-dataset`: `dataStore` entitlement + `checkDatasetQuota`\n * (addon-aware, org-scoped). An optional `hostId` names the site the\n * dataset is created from, which the org's Default sharing can narrow it\n * to.\n * - `create-record`: `recordsPerDataset` quota; values are re-coerced\n * and re-validated against the dataset's model server-side.\n * - `import-records`: batch create with the whole batch fitting the cap.\n * - `add-address-field`: a \"Page address\" field that fills in from a text\n * field, and a unique address on every record that has none (AGL-3475).\n * - `update-record` / `delete-record`: the Data card's record edit and\n * delete (with its reference integrity) for the native apps, which have no\n * browser to write from (AGL-3668).\n *\n * Since AGL-2163 both record actions ALSO enforce `checkDataStorageQuota`.\n * See {@link refuseIfDataStorageBlocked}: that check's `allowed` field had no\n * reader anywhere in the platform while its docblock said free \"hard-blocks\n * at the included size\", so the byte band was documentation. `recordsPerDataset`\n * counts ROWS and does not bound their size, so it was never the same limit.\n */\nexport const datasetsHandler: PluginWebApiHandler = async (request) => {\n const { method, body, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n\n const orgId = String(body?.orgId ?? '')\n const action = String(body?.action ?? '')\n if (!orgId) return Response.json({ error: 'Missing orgId' }, { status: 400 })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const member = membership?.member as any\n if (!member) return datasetsPermissionRefusal()\n /*==========================================\n * \"Manage data\" (`data.manage`), and nothing about the role (AGL-2444,\n * AGL-4047).\n *\n * `data.manage` had ZERO consumers: an owner could build a custom role\n * with \"Manage data\" unticked, assign it, and the member kept creating,\n * editing and deleting datasets — because this gate read the raw role,\n * exactly the defect AGL-2350 fixed one route over on `hosts.create`.\n *\n * It then sat BESIDE a role gate (owner, admin or editor), so the key\n * could narrow but never widen: a viewer granted it was still refused.\n * The key's default is exactly those three roles, so with no custom role\n * or override deciding it nobody's access moves; a grant now opens the\n * route as it opens the rules' `canWriteOrgDatasets()`, and a refusal\n * names the permission. Staff keep their bypass, as the rules' `isStaff()`\n * does, and still need a membership.\n *=========================================*/\n if (\n decoded['staff'] !== true &&\n !(await memberHasOrgPermission(orgId, member, DATASETS_PERMISSION))\n ) {\n return datasetsPermissionRefusal()\n }\n\n // Release gate (AGL-1653). `<FeatureGate flag=\"release_data_store\">` on\n // the org Data page was the only gate, so org-level dataset\n // administration kept working with the flag off — the milder sibling of\n // the add-on store leak above it in the same issue. Same staff bypass as\n // `FeatureGate`'s `visible`, same 404: released-off means absent.\n if (\n decoded['staff'] !== true &&\n !(await isServerReleaseFlagOnForOrg('release_data_store', orgId))\n ) {\n return Response.json({ error: 'Not available' }, { status: 404 })\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const orgSnapshot = await orgRef.get()\n if (!orgSnapshot.exists) {\n return Response.json({ error: 'Unknown organization' }, { status: 404 })\n }\n const org = orgSnapshot.data() as any\n\n // Lockdown verdict (AGL-1506): subsumes the bare `orgSuspended`\n // projection check this route used to make — the org doc is read just\n // above anyway, so the full verdict (platform/org/user scopes, staff\n // bypass, distinct 423 body) costs no extra org read here.\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org,\n })\n if (locked) return locked\n\n if (action === 'create-dataset') {\n if (!checkEntitlement(org, 'dataStore')) {\n return Response.json({\n error: 'Datasets require a Starter plan or higher',\n }, { status: 403 })\n }\n const displayName = String(body?.displayName ?? '').trim().slice(0, 120)\n const fields = Array.isArray(body?.fields)\n ? (body.fields as unknown[]).map((field) => String(field)).slice(0, 100)\n : []\n if (!displayName || fields.length === 0) {\n return Response.json({ error: 'Missing displayName or fields' }, { status: 400 })\n }\n /**\n * The site the dataset is created from — null on the organization Data\n * page, which has none.\n *\n * It reaches the document only through the org's Default sharing: with\n * `defaultResourceScope: 'host'` the new dataset is visible to this site\n * alone. That makes it a client claim deciding who can see the result,\n * so it is honored only when it holds on both counts:\n *\n * * The site is one of THIS org's. `hostIndex` is the mirror the Data\n * card resolved `orgId` from in the first place, so a create made\n * from a real site page cannot disagree with it. Another org's site\n * would stamp a token that no site and no scoped member of this org\n * holds: a dataset only the org's admins could ever find.\n * * The caller's own access reaches the scope it produces. A scoped\n * member naming a site outside their access would create a dataset\n * they cannot see afterwards, which is the create the rules'\n * `canCreateScoped()` refuses on the collections clients create.\n *\n * Both are refused rather than widened to All sites. Widening is the\n * direction that shows a dataset to sites nobody chose.\n */\n const hostId = String(body?.hostId ?? '').trim() || null\n if (\n hostId &&\n (hostId.includes('/') || (await resolveOrgIdForHost(hostId)) !== orgId)\n ) {\n return Response.json(\n { error: 'That site is not one of this organization’s' },\n { status: 400 },\n )\n }\n // Honors the org's `defaultResourceScope` (AGL-1048), falling back to\n // org-wide — which is also the only answer with no site in context.\n const visibleTo = defaultScopeForNewResource({\n defaultResourceScope: (org as {\n defaultResourceScope?: 'org' | 'host'\n })?.defaultResourceScope,\n hostId,\n })\n if (\n hostId &&\n decoded['staff'] !== true &&\n !memberCanSee(member, visibleTo)\n ) {\n return Response.json(\n { error: 'Your access to this organization does not reach that site' },\n { status: 403 },\n )\n }\n const datasetsRef = orgRef.collection('datasets')\n const overDatasetQuota = (quota: ReturnType<typeof checkDatasetQuota>) =>\n quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets ` +\n `for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n // The fast refusal. NOT the enforcement point — that is the transaction\n // below — but it answers a caller who is simply over their limit before\n // the request builds anything.\n const quota = checkDatasetQuota(\n org,\n (await datasetsRef.count().get()).data().count,\n )\n if (!quota.allowed) {\n return Response.json({ error: overDatasetQuota(quota) }, { status: 403 })\n }\n const id = createResourceUid()\n // The model rides from the console (deriveModelFromFields output or\n // the join-collection template). `model` is independent of `fields`,\n // so cap its serialized size explicitly (a legit model is well under\n // this — 64 KB covers hundreds of typed fields).\n const model = body?.model && typeof body.model === 'object' ? body.model : null\n if (model && JSON.stringify(model).length > 64 * 1024) {\n return Response.json({ error: 'Dataset model too large' }, { status: 413 })\n }\n /**\n * THE ENFORCEMENT POINT (AGL-2371, the AGL-2231 treatment): the count,\n * the decision and the create in ONE transaction.\n *\n * The check above counted, then the request went on awaiting, and only\n * then created — and every await is a yield, so N concurrent creates\n * each read the same pre-count, each found room, and each landed.\n * Nothing re-counts afterwards, so the extra datasets were permanent and\n * billed nothing. `tx.get` on the aggregate takes a pessimistic lock on\n * the documents the query matched, so the loser of a race retries,\n * re-reads the higher count and is refused.\n *\n * The ORG document is deliberately read outside: the plan and the\n * purchased add-ons are the other input to this decision, but neither is\n * client-writable, so locking the org doc on every dataset create would\n * buy contention rather than correctness. That is the AGL-2369 lesson\n * applied, not skipped — there the routing map *was* client-writable and\n * *did* change the count.\n *\n * The refusal comes back as data and is rendered outside: building a\n * response inside a body that can run several times reads as if the\n * transaction were a place effects happen.\n */\n const refusal = await firestore.runTransaction<string | null>(\n async (tx) => {\n const live = (await tx.get(datasetsRef.count())).data().count\n const authoritative = checkDatasetQuota(org, live)\n if (!authoritative.allowed) return overDatasetQuota(authoritative)\n tx.create(datasetsRef.doc(id), {\n displayName,\n fields,\n ...(model ? { model } : {}),\n // The scope decided above. Stamping SOMETHING is mandatory: an\n // `array-contains-any` matches nothing on a doc missing the field,\n // so an unstamped dataset renders on no site at all (AGL-1044).\n //\n // Through `newResourceScopeFields` since AGL-1484: AGL-1478 built\n // that helper as the type-level gate for exactly the collections\n // with no document constructor of their own — `datasets` named\n // first among them — and then only the marketplace fork used it,\n // while the two ordinary dataset creates went on writing the field\n // by hand. A required argument that three of four callers bypass\n // is a convention, not a guarantee.\n ...newResourceScopeFields(visibleTo),\n createdAt: Timestamp.now(),\n })\n return null\n },\n )\n if (refusal) return Response.json({ error: refusal }, { status: 403 })\n return Response.json({ ok: true, id }, { status: 200 })\n }\n\n if (\n action === 'create-record' ||\n action === 'import-records' ||\n action === 'announce-records' ||\n action === 'add-address-field' ||\n action === 'update-record' ||\n action === 'delete-record'\n ) {\n const datasetId = String(body?.datasetId ?? '')\n if (!datasetId) {\n return Response.json({ error: 'Missing datasetId' }, { status: 400 })\n }\n const datasetRef = orgRef.collection('datasets').doc(datasetId)\n const datasetSnapshot = await datasetRef.get()\n if (!datasetSnapshot.exists) {\n return Response.json({ error: 'Unknown dataset' }, { status: 404 })\n }\n /**\n * The caller has to be able to SEE the dataset they add rows to.\n *\n * The `data.manage` gate above is about the org, and a member scoped\n * to one site can pass it. The rules hold every record update and\n * delete to the parent dataset being visible (`parentDatasetVisible()`),\n * and refuse client record creates outright, so this route is the one\n * place a member's create can be held to the same condition. Without it,\n * a collaborator on one client's site could add rows, by id alone, to an\n * internal dataset shared only with other sites.\n *\n * The Admin SDK evaluates no rules, so `memberCanSee` IS the enforcement\n * here, as on the export route beside this one. Answered with the same\n * 404 as a dataset that does not exist: whether one outside the caller's\n * reach exists is not theirs to learn either.\n */\n if (\n decoded['staff'] !== true &&\n !memberCanSee(\n member,\n (datasetSnapshot.data() as { visibleTo?: string[] } | undefined)\n ?.visibleTo,\n )\n ) {\n return Response.json({ error: 'Unknown dataset' }, { status: 404 })\n }\n /**\n * A record the BROWSER wrote, announcing itself (AGL-3113).\n *\n * Record edits and deletes stay client-direct on purpose — they consume\n * no quota, so AGL-473 left them out of the server leg — which also left\n * them with nothing to announce from. They are the same staleness as a\n * create: a page listing the rows goes on showing the old one.\n *\n * A drop, and only a drop. It moves no pointer, writes nothing and\n * registers no route, so it grants nothing the rules withhold — and it\n * is gated by the same org membership and the same `memberCanSee` the\n * create is, which is what stops a collaborator on one site from\n * learning that another site's dataset exists.\n */\n if (action === 'announce-records') {\n const announced = await announceDatasetChange({\n firestore,\n orgId,\n datasetId,\n })\n return Response.json({ ok: true, announced }, { status: 200 })\n }\n const model = effectiveDatasetModel(datasetSnapshot.data() as any)\n /**\n * Gives the dataset a page address (AGL-3475): a \"Page address\" field\n * that fills in from `sourceField`, and an address on every record that\n * has none yet, unique within the dataset (`roofing`, `roofing-2`).\n *\n * Server-side because it writes every record, and each write has to\n * carry the filter fields the record template's lookup reads — the\n * address is found through `filterValues`, so a record written without\n * them would have a page nobody can reach. A dataset that already has\n * an address field keeps it: the call fills that field's empty\n * addresses instead of adding a second one.\n */\n if (action === 'add-address-field') {\n const sourceField = String(body?.sourceField ?? '').trim()\n const source = model.fields[sourceField]\n if (!source || source.type !== 'text' || isRecordAddressField(source)) {\n return Response.json(\n { error: 'Pick a text field to fill page addresses from' },\n { status: 400 },\n )\n }\n const held = recordAddressFieldIds(model)[0]\n const fieldId = held ?? defaultDatasetFieldId('slug', new Set(model.order))\n const nextModel = held\n ? model\n : {\n fields: {\n ...model.fields,\n [fieldId]: {\n name: 'Page address',\n type: 'text' as const,\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceField,\n },\n },\n order: [...model.order, fieldId],\n }\n if (!held) {\n await datasetRef.update({ model: nextModel, updatedAt: Timestamp.now() })\n }\n const snapshot = await datasetRef\n .collection('records')\n .orderBy(FieldPath.documentId())\n .limit(ADDRESS_FILL_MAX + 1)\n .get()\n const docs = snapshot.docs.slice(0, ADDRESS_FILL_MAX)\n const valuesOf = (doc: FirebaseFirestore.QueryDocumentSnapshot) =>\n (doc.get('values') ?? {}) as Record<string, unknown>\n const taken = docs\n .map((doc) => recordAddressOf(valuesOf(doc), fieldId))\n .filter(Boolean)\n const assigned = uniqueRecordAddresses(\n docs\n .filter((doc) => !recordAddressOf(valuesOf(doc), fieldId))\n .map((doc) => ({ id: doc.id, source: valuesOf(doc)[sourceField] })),\n taken,\n )\n const writes = docs.filter((doc) => assigned.has(doc.id))\n for (let start = 0; start < writes.length; start += IMPORT_CHUNK) {\n const batch = firestore.batch()\n for (const doc of writes.slice(start, start + IMPORT_CHUNK)) {\n const values = { ...valuesOf(doc), [fieldId]: assigned.get(doc.id) }\n batch.update(doc.ref, {\n values,\n ...datasetIntegrityUpdate(nextModel, values, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n }\n await batch.commit()\n }\n if (writes.length || !held) {\n await announceDatasetChange({ firestore, orgId, datasetId })\n }\n return Response.json(\n {\n ok: true,\n fieldId,\n filled: writes.length,\n truncated: snapshot.docs.length > ADDRESS_FILL_MAX,\n },\n { status: 200 },\n )\n }\n // Before either validation below: a plugin's field validator only runs\n // once its plugin's server entry has registered it.\n await ensureDeclaredCustomFieldTypes(model)\n const recordsRef = datasetRef.collection('records')\n\n /**\n * A record edit (AGL-3668): the Data card's Save on an existing record,\n * for a caller that is not a browser. The card writes it straight to\n * Firestore — it consumes no quota — with the values coerced, filled\n * and validated against the model and the integrity and filter index\n * moved with them; the native apps reach the same write here, under\n * the same `data.manage` and visibility gates as a create.\n * `values` is replaced whole, so a removed field's value strips here,\n * as it does on the card (the AGL-178 policy).\n */\n if (action === 'update-record') {\n const recordId = String(body?.recordId ?? '')\n if (!recordId) {\n return Response.json({ error: 'Missing recordId' }, { status: 400 })\n }\n const recordRef = recordsRef.doc(recordId)\n if (!(await recordRef.get()).exists) {\n return Response.json({ error: 'Unknown record' }, { status: 404 })\n }\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, body?.values ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return Response.json({ error: 'Record failed validation', errors }, { status: 400 })\n }\n await recordRef.update({\n values: coerced,\n ...datasetIntegrityUpdate(model, coerced, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n const announced = await announceDatasetChange({ firestore, orgId, datasetId })\n return Response.json({ ok: true, id: recordId, announced }, { status: 200 })\n }\n\n /**\n * A record delete (AGL-3668), with the card's delete integrity\n * (AGL-180): every dataset the caller can see whose model references\n * this one is asked, by its `referencedIds` index, whether it still\n * points at the record. `restrict` refuses the delete and writes\n * nothing; `setNull` strips the reference from each holder first. The\n * verdict is `planReferenceFixups`, the one the card applies. The\n * datasets consulted are the ones the caller can see, exactly the set\n * the card reads, so the app is refused exactly when the console is.\n */\n if (action === 'delete-record') {\n const recordId = String(body?.recordId ?? '')\n if (!recordId) {\n return Response.json({ error: 'Missing recordId' }, { status: 400 })\n }\n const recordRef = recordsRef.doc(recordId)\n if (!(await recordRef.get()).exists) {\n return Response.json({ error: 'Unknown record' }, { status: 404 })\n }\n const others = (await orgRef.collection('datasets').get()).docs.filter(\n (other) =>\n decoded['staff'] === true ||\n memberCanSee(member, (other.data() as { visibleTo?: string[] }).visibleTo),\n )\n const fixups: Array<{ datasetId: string; model: ReturnType<typeof effectiveDatasetModel>; updates: Array<{ id: string; values: Record<string, unknown> }> }> = []\n for (const other of others) {\n const otherModel = effectiveDatasetModel(other.data() as any)\n if (!referencingFieldIds(otherModel, datasetId).length) continue\n const holders = await other.ref\n .collection('records')\n .where('referencedIds', 'array-contains', recordId)\n .get()\n const plan = planReferenceFixups(\n otherModel,\n datasetId,\n recordId,\n holders.docs.map((holder) => ({ id: holder.id, values: holder.get('values') })),\n )\n if (plan.kind === 'restricted') {\n const name = String((other.data() as any)?.displayName ?? (other.data() as any)?.name ?? '').trim()\n return Response.json(\n { error: restrictedDeleteMessage(plan.holders, name) },\n { status: 409 },\n )\n }\n if (plan.kind === 'strip') fixups.push({ datasetId: other.id, model: otherModel, updates: plan.updates })\n }\n for (const fixup of fixups) {\n const holdersRef = orgRef.collection('datasets').doc(fixup.datasetId).collection('records')\n for (let start = 0; start < fixup.updates.length; start += IMPORT_CHUNK) {\n const batch = firestore.batch()\n for (const update of fixup.updates.slice(start, start + IMPORT_CHUNK)) {\n batch.update(holdersRef.doc(update.id), {\n values: update.values,\n ...datasetIntegrityUpdate(fixup.model, update.values, FieldValue.delete()),\n })\n }\n await batch.commit()\n }\n }\n await recordRef.delete()\n for (const changed of [datasetId, ...fixups.map((fixup) => fixup.datasetId)]) {\n await announceDatasetChange({ firestore, orgId, datasetId: changed })\n }\n return Response.json(\n { ok: true, id: recordId, fixed: fixups.reduce((total, fixup) => total + fixup.updates.length, 0) },\n { status: 200 },\n )\n }\n\n const recordCount = (await recordsRef.count().get()).data().count\n const overRecordQuota = (limit: number) =>\n `Record limit reached (${limit}) — upgrade in Billing`\n\n if (action === 'create-record') {\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, body?.values ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return Response.json({ error: 'Record failed validation', errors }, { status: 400 })\n }\n // The fast refusal. NOT the enforcement point — that is the\n // transaction below — but it keeps the refusal ORDER on this route\n // intact: a caller over BOTH the row cap and the byte band is told\n // about the rows, as they always were.\n const quota = checkQuota(org, 'recordsPerDataset', recordCount)\n if (!quota.allowed) {\n return Response.json({\n error: overRecordQuota(quota.limit),\n }, { status: 403 })\n }\n // Bytes, not rows (AGL-2163). Before the write, like every other\n // quota on this route.\n const storageRefusal = await refuseIfDataStorageBlocked(org, orgRef)\n if (storageRefusal) return storageRefusal\n const id = createResourceUid()\n /**\n * THE ENFORCEMENT POINT (AGL-2371, the AGL-2231 treatment): the count,\n * the decision and the create in ONE transaction.\n *\n * The check above counted, then `refuseIfDataStorageBlocked` awaited,\n * and only then did the row land. Every await is a yield, so N\n * concurrent creates each read the same pre-count, each found room,\n * and each landed — permanently, since nothing re-counts afterwards. A\n * free-with-rows-granted org's thousand rows became twenty thousand by\n * sending twenty requests at once.\n *\n * `tx.get` on the aggregate takes a pessimistic lock on the documents\n * the query matched, so the loser retries, re-reads the higher count\n * and is refused. `order` is taken from the transaction's own count\n * for the same reason: the pre-count is what made two concurrent rows\n * share an order.\n *\n * The BYTE gate stays outside. It is a different quota with its own\n * reads, it is not a function of the rows this transaction writes, and\n * re-running it on every retry attempt would put a multi-document read\n * inside a lock.\n */\n const refusal = await firestore.runTransaction<string | null>(\n async (tx) => {\n const live = (await tx.get(recordsRef.count())).data().count\n const authoritative = checkQuota(org, 'recordsPerDataset', live)\n if (!authoritative.allowed) return overRecordQuota(authoritative.limit)\n tx.create(recordsRef.doc(id), {\n values: coerced,\n // The integrity index the delete check queries. Written on the\n // same write as the values it describes — an index that lags\n // them reports a reference the record no longer holds, or\n // misses one it does.\n ...datasetIntegrityFields(model, coerced),\n order: live,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n return null\n },\n )\n if (refusal) return Response.json({ error: refusal }, { status: 403 })\n // The record is stored; now the pages that repeat over it are told\n // (AGL-3113). Awaited so the site is already serving the new row by the\n // time the editor's save returns, and reported so a refused drop can\n // say the live pages are behind rather than leaving it to be noticed.\n const announced = await announceDatasetChange({\n firestore,\n orgId,\n datasetId,\n })\n return Response.json({ ok: true, id, announced }, { status: 200 })\n }\n\n // import-records: the console sends only the NEW rows (updates to\n // existing ids stay client-direct — they don't consume quota).\n const rows = Array.isArray(body?.records)\n ? (body.records as Array<{ values?: unknown }>)\n : []\n if (rows.length === 0) {\n return Response.json({ error: 'No records to import' }, { status: 400 })\n }\n const overImportQuota = (limit: number, needed: number) =>\n `This import needs ${needed} record slots — your plan ` +\n `allows ${limit} per dataset. See Billing to upgrade.`\n // The fast refusal, on the whole import. NOT the enforcement point —\n // that is the per-chunk transaction below — but it is what answers an\n // import that never fitted, before a single row is written.\n const quota = checkQuota(\n org,\n 'recordsPerDataset',\n recordCount + rows.length - 1,\n )\n if (!quota.allowed) {\n return Response.json({\n error: overImportQuota(quota.limit, rows.length),\n }, { status: 403 })\n }\n // Bytes, not rows (AGL-2163). An import is the path that moves the\n // most bytes in one request, so leaving it out would have left the\n // enforcement exactly where the customer does not meet it.\n const importStorageRefusal = await refuseIfDataStorageBlocked(org, orgRef)\n if (importStorageRefusal) return importStorageRefusal\n const prepared = rows.map((row, index) => {\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(\n model,\n (row?.values ?? {}) as Record<string, unknown>,\n ),\n )\n const errors = validateDocument(model, coerced)\n return { index, coerced, valid: Object.keys(errors).length === 0 }\n })\n const invalid = prepared.filter((row) => !row.valid)\n if (invalid.length) {\n return Response.json({\n error: `${invalid.length} rows failed validation`,\n rows: invalid.map((row) => row.index),\n }, { status: 400 })\n }\n /**\n * THE ENFORCEMENT POINT (AGL-2371): each chunk counts, decides and\n * writes inside ONE transaction.\n *\n * The import used to count once, decide once, and then commit a series\n * of `WriteBatch`es. A batch is atomic but NOT conditional on a read\n * taken before it, so two concurrent imports each priced themselves off\n * the same pre-count and both landed in full — the create leg's defect,\n * multiplied by the batch size.\n *\n * It cannot be ONE transaction for every import the way the single-row\n * create can: `recordsPerDataset` runs to a million, and a transaction\n * carries at most 500 writes. So the chunk is the unit, and each chunk's\n * count is re-read under the lock and re-checked against the plan. The\n * cap therefore holds ABSOLUTELY at every size — what a race can cost is\n * a partial import, not an overshoot, and a partial import was already\n * possible the moment a mid-import batch could fail.\n *\n * The ids are minted before the transaction so a retry re-creates the\n * SAME documents rather than a second copy of the chunk.\n *\n * This is not AGL-2370's problem in miniature. There the whole bundle\n * must land or none of it, so chunking cannot be the unit and a lease is\n * needed; here rows are independent and \"fewer rows than asked for\" is a\n * reportable outcome.\n */\n const ids: string[] = []\n let refusedAt: string | null = null\n for (\n let start = 0;\n start < prepared.length && refusedAt === null;\n start += IMPORT_CHUNK\n ) {\n const chunk = prepared.slice(start, start + IMPORT_CHUNK)\n const chunkIds = chunk.map(() => createResourceUid())\n refusedAt = await firestore.runTransaction<string | null>(async (tx) => {\n const live = (await tx.get(recordsRef.count())).data().count\n const authoritative = checkQuota(\n org,\n 'recordsPerDataset',\n live + chunk.length - 1,\n )\n if (!authoritative.allowed) {\n return overImportQuota(authoritative.limit, rows.length)\n }\n chunk.forEach((row, offset) => {\n tx.create(recordsRef.doc(chunkIds[offset]), {\n values: row.coerced,\n ...datasetIntegrityFields(model, row.coerced),\n order: live + offset,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n })\n return null\n })\n if (refusedAt === null) ids.push(...chunkIds)\n }\n /**\n * ONE announce for the whole import, after the loop (AGL-3113).\n *\n * Not per chunk and certainly not per row: a thousand rows arrive as one\n * import and make the same pages stale once, so the pages are worked out\n * once and dropped once. The refusal path announces too — rows that\n * landed before the quota bit are live records, and leaving them out of\n * the refresh would make a partial import look like no import at all.\n */\n if (ids.length) {\n await announceDatasetChange({ firestore, orgId, datasetId })\n }\n if (refusedAt !== null) {\n // What landed is reported alongside the refusal. Rows are independent,\n // so silently discarding the created ids would tell the caller nothing\n // was written while the dataset says otherwise.\n return Response.json(\n { error: refusedAt, ids, created: ids.length },\n { status: 403 },\n )\n }\n return Response.json({ ok: true, ids, created: ids.length }, { status: 200 })\n }\n\n return Response.json({ error: 'Unknown action' }, { status: 400 })\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993); anything\n // else keeps the answer below.\n if (isRefusedIdToken(error)) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n console.error(error)\n return Response.json({ error: 'Dataset operation failed' }, { status: 500 })\n }\n}\n"],"names":["defaultScopeForNewResource","newResourceScopeFields","pluginRequestFromWeb","checkDatasetQuota","checkEntitlement","checkQuota","createResourceUid","ensureDeclaredCustomFieldTypes","memberCanSee","emailUnverifiedResponse","firebaseAdmin","dataStorageRefusal","isImpersonationSession","isServerReleaseFlagOnForOrg","lockdownRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isRefusedIdToken","permissionRefusalText","FieldPath","FieldValue","Timestamp","announceDatasetRecords","announceDatasetChange","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","effectiveDatasetModel","validateDocument","defaultDatasetFieldId","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","RECORD_PAGE_ADDRESS_FIELD_TYPE","fillRecordAddresses","isRecordAddressField","recordAddressFieldIds","recordAddressOf","uniqueRecordAddresses","refuseIfDataStorageBlocked","org","orgRef","refusal","Response","json","error","basis","includedMb","status","DATASETS_PERMISSION","datasetsPermissionRefusal","reason","permission","IMPORT_CHUNK","ADDRESS_FILL_MAX","datasetsHandler","request","headers","method","body","rawHeaders","authorization","idToken","startsWith","slice","length","undefined","orgId","String","action","decoded","app","auth","verifyIdToken","email_verified","membership","uid","member","firestore","collection","doc","orgSnapshot","get","exists","data","locked","staff","displayName","trim","fields","Array","isArray","map","field","hostId","includes","visibleTo","defaultResourceScope","datasetsRef","overDatasetQuota","quota","upgradeRequired","limit","addonPriceUsd","count","allowed","id","model","JSON","stringify","runTransaction","tx","live","authoritative","create","createdAt","now","ok","datasetSnapshot","datasetId","datasetRef","announced","sourceField","source","type","held","fieldId","Set","order","nextModel","name","customType","slugFrom","update","updatedAt","snapshot","orderBy","documentId","docs","valuesOf","taken","filter","Boolean","assigned","writes","has","start","batch","values","ref","delete","commit","filled","truncated","recordsRef","recordId","recordRef","coerced","errors","Object","keys","others","other","fixups","otherModel","holders","where","plan","holder","kind","push","updates","fixup","holdersRef","changed","fixed","reduce","total","recordCount","overRecordQuota","storageRefusal","rows","records","overImportQuota","needed","importStorageRefusal","prepared","row","index","valid","invalid","ids","refusedAt","chunk","chunkIds","forEach","offset","created","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,0BAA0B,EAC1BC,sBAAsB,EACtBC,oBAAoB,QAEf,sBAAqB;AAC5B,SACEC,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,GAAG,CAACkH,QAAQ,CAACE,OAAO,GAAG;4BAC1ChD,QAAQuC,IAAI9B,OAAO;2BAChBpI,uBAAuBkF,OAAOgF,IAAI9B,OAAO;4BAC5C7B,OAAOhB,OAAOoF;4BACdjF,WAAW9F,UAAU+F,GAAG;4BACxBkB,WAAWjH,UAAU+F,GAAG;;oBAE5B;oBACA,OAAO;gBACT;gBACA,IAAI4E,cAAc,MAAMD,IAAIrB,IAAI,IAAIwB;YACtC;YACA;;;;;;;;OAQC,GACD,IAAIH,IAAI9H,MAAM,EAAE;gBACd,MAAM1C,sBAAsB;oBAAEuD;oBAAWX;oBAAOoD;gBAAU;YAC5D;YACA,IAAIyE,cAAc,MAAM;gBACtB,uEAAuE;gBACvE,uEAAuE;gBACvE,gDAAgD;gBAChD,OAAOrJ,SAASC,IAAI,CAClB;oBAAEC,OAAOmJ;oBAAWD;oBAAKM,SAASN,IAAI9H,MAAM;gBAAC,GAC7C;oBAAEjB,QAAQ;gBAAI;YAElB;YACA,OAAOL,SAASC,IAAI,CAAC;gBAAEyE,IAAI;gBAAM0E;gBAAKM,SAASN,IAAI9H,MAAM;YAAC,GAAG;gBAAEjB,QAAQ;YAAI;QAC7E;QAEA,OAAOL,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiB,GAAG;YAAEG,QAAQ;QAAI;IAClE,EAAE,OAAOH,OAAO;QACd,0EAA0E;QAC1E,+BAA+B;QAC/B,IAAI5B,iBAAiB4B,QAAQ;YAC3B,OAAOF,SAASC,IAAI,CAAC;gBAAEC,OAAO;YAAkB,GAAG;gBAAEG,QAAQ;YAAI;QACnE;QACAsJ,QAAQzJ,KAAK,CAACA;QACd,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAA2B,GAAG;YAAEG,QAAQ;QAAI;IAC5E;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/datasets-route.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 { isOrgWideMember } from '@aglyn/aglyn/app-utils/organizations'\nimport { type ScopeSharingChoice, sharingFromChoice } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n defaultScopeForNewResource,\n newResourceScopeFields,\n pluginRequestFromWeb,\n type PluginWebApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n createResourceUid,\n ensureDeclaredCustomFieldTypes,\n memberCanSee,\n} from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n dataStorageRefusal,\n isImpersonationSession,\n isServerReleaseFlagOnForOrg,\n lockdownRefusal,\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { fieldsToWrite, orgHostIdsFromDoc } from '@aglyn/tenant-data-admin/server/scope-sharing-sweep'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { dataPermissionRefusal } from '../model/dataset-access'\nimport { announceDatasetRecords as announceDatasetChange } from './announce-dataset-records'\nimport { datasetRefusalPermission, memberMayActOnDataset } from './dataset-access.server'\nimport { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from '../model/dataset-models'\nimport { defaultDatasetFieldId } from '../model/datasets'\nimport { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from '../model/dataset-record-delete-plan'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n fillRecordAddresses,\n isRecordAddressField,\n recordAddressFieldIds,\n recordAddressOf,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * `dataStorageMbPerOrg` for this route, rendered as the console's 403.\n *\n * The VERDICT moved to `utils/server/data-storage-gate` (AGL-2253) — it was\n * defined here, so `/v1` and the tenant form path, which write dataset bytes\n * through their own code, enforced nothing. Only the console wording is left\n * behind, because the other two callers answer different shapes.\n */\nasync function refuseIfDataStorageBlocked(\n org: unknown,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Response | null> {\n const refusal = await dataStorageRefusal(org, orgRef)\n if (!refusal) return null\n return Response.json(\n {\n error:\n refusal.basis === 'always'\n ? 'Dataset storage is not included on this plan — upgrade in Billing'\n : `Dataset storage limit reached (${refusal.includedMb} MB) — ` +\n 'upgrade in Billing',\n },\n { status: 403 },\n )\n}\n\n/**\n * The key every action here asks (AGL-4047): \"Manage data\", whose default is\n * the owner, admin and editor, as the rules' `canWriteOrgDatasets()` asks it.\n */\nconst DATASETS_PERMISSION = 'data.manage'\n\n/** The 403 for a member without it, naming the permission, never a role. */\nfunction datasetsPermissionRefusal(permission: string = DATASETS_PERMISSION): Response {\n return Response.json(\n {\n error: dataPermissionRefusal(permission),\n reason: 'permission',\n permission,\n },\n { status: 403 },\n )\n}\n\n/**\n * The actions on one existing dataset, whose answer depends on where it is\n * placed (AGL-4047): `memberMayActOnDataset`, asked once the dataset is read.\n * Every other action asks \"Manage data\" up front.\n */\nconst DATASET_ACTIONS: ReadonlySet<string> = new Set([\n 'create-record',\n 'import-records',\n 'announce-records',\n 'add-address-field',\n 'update-record',\n 'delete-record',\n])\n\n/** The most site ids one sharing choice may name: far past any workspace. */\nconst SHARING_CHOICE_MAX_IDS = 1000\n\n/** A sharing choice off the wire, or null for anything else. Ids are checked against the workspace after. */\nfunction sharingChoiceFrom(value: unknown): ScopeSharingChoice | null {\n const choice = (value ?? {}) as { mode?: unknown; hostIds?: unknown; exceptHostIds?: unknown }\n const ids = (list: unknown): string[] | null =>\n Array.isArray(list) &&\n list.length <= SHARING_CHOICE_MAX_IDS &&\n list.every((id) => typeof id === 'string' && /^[^:/]+$/.test(id))\n ? (list as string[])\n : null\n if (choice.mode === 'all') return { mode: 'all' }\n if (choice.mode === 'selected') {\n const hostIds = ids(choice.hostIds)\n return hostIds && { mode: 'selected', hostIds }\n }\n if (choice.mode === 'allExcept') {\n const exceptHostIds = ids(choice.exceptHostIds)\n return exceptHostIds && { mode: 'allExcept', exceptHostIds }\n }\n return null\n}\n\n/**\n * Rows written per import transaction.\n *\n * Firestore allows at most 500 writes in one transaction, and this is the\n * chunk size the route already used for its batches, so nothing about the\n * shape of an import changed when the batches became transactions (AGL-2371).\n */\nconst IMPORT_CHUNK = 400\n\n/**\n * How many records one \"give it page addresses\" call fills (AGL-3475). Far\n * past a services or locations dataset; a larger one reports `truncated`, and\n * the next call fills the next records, since a filled record is skipped.\n */\nconst ADDRESS_FILL_MAX = 5000\n\n/**\n * Dataset/record creation API (AGL-473): creates moved out of the client\n * SDK so quotas and entitlements are enforced server-side — Firestore\n * rules deny client-side `create` on `orgs/{orgId}/datasets/**` (updates\n * and deletes stay client-direct, they don't consume quota). Actions:\n *\n * - `create-dataset`: `dataStore` entitlement + `checkDatasetQuota`\n * (addon-aware, org-scoped). An optional `hostId` names the site the\n * dataset is created from, which the org's Default sharing can narrow it\n * to.\n * - `create-record`: `recordsPerDataset` quota; values are re-coerced\n * and re-validated against the dataset's model server-side.\n * - `import-records`: batch create with the whole batch fitting the cap.\n * - `add-address-field`: a \"Page address\" field that fills in from a text\n * field, and a unique address on every record that has none (AGL-3475).\n * - `update-record` / `delete-record`: the Data card's record edit and\n * delete (with its reference integrity) for the native apps, which have no\n * browser to write from (AGL-3668).\n * - `set-sharing`: who a dataset is shared with: all sites, the sites chosen, or\n * all sites except some (AGL-4047).\n *\n * Since AGL-2163 both record actions ALSO enforce `checkDataStorageQuota`.\n * See {@link refuseIfDataStorageBlocked}: that check's `allowed` field had no\n * reader anywhere in the platform while its docblock said free \"hard-blocks\n * at the included size\", so the byte band was documentation. `recordsPerDataset`\n * counts ROWS and does not bound their size, so it was never the same limit.\n */\nexport const datasetsHandler: PluginWebApiHandler = async (request) => {\n const { method, body, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n\n const orgId = String(body?.orgId ?? '')\n const action = String(body?.action ?? '')\n if (!orgId) return Response.json({ error: 'Missing orgId' }, { status: 400 })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const member = membership?.member as any\n if (!member) return datasetsPermissionRefusal()\n /*==========================================\n * \"Manage data\" (`data.manage`), and nothing about the role (AGL-2444,\n * AGL-4047).\n *\n * `data.manage` had ZERO consumers: an owner could build a custom role\n * with \"Manage data\" unticked, assign it, and the member kept creating,\n * editing and deleting datasets — because this gate read the raw role,\n * exactly the defect AGL-2350 fixed one route over on `hosts.create`.\n *\n * It then sat BESIDE a role gate (owner, admin or editor), so the key\n * could narrow but never widen: a viewer granted it was still refused.\n * The key's default is exactly those three roles, so with no custom role\n * or override deciding it nobody's access moves; a grant now opens the\n * route as it opens the rules' `canWriteOrgDatasets()`, and a refusal\n * names the permission. Staff keep their bypass, as the rules' `isStaff()`\n * does, and still need a membership.\n *\n * The actions on one dataset ask below, once it is read (AGL-4047): a\n * dataset placed on one site answers to that site as well.\n *=========================================*/\n if (\n decoded['staff'] !== true &&\n !DATASET_ACTIONS.has(action) &&\n !(await memberHasOrgPermission(orgId, member, DATASETS_PERMISSION))\n ) {\n return datasetsPermissionRefusal()\n }\n\n // Release gate (AGL-1653). `<FeatureGate flag=\"release_data_store\">` on\n // the org Data page was the only gate, so org-level dataset\n // administration kept working with the flag off — the milder sibling of\n // the add-on store leak above it in the same issue. Same staff bypass as\n // `FeatureGate`'s `visible`, same 404: released-off means absent.\n if (\n decoded['staff'] !== true &&\n !(await isServerReleaseFlagOnForOrg('release_data_store', orgId))\n ) {\n return Response.json({ error: 'Not available' }, { status: 404 })\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const orgSnapshot = await orgRef.get()\n if (!orgSnapshot.exists) {\n return Response.json({ error: 'Unknown organization' }, { status: 404 })\n }\n const org = orgSnapshot.data() as any\n\n // Lockdown verdict (AGL-1506): subsumes the bare `orgSuspended`\n // projection check this route used to make — the org doc is read just\n // above anyway, so the full verdict (platform/org/user scopes, staff\n // bypass, distinct 423 body) costs no extra org read here.\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org,\n })\n if (locked) return locked\n\n if (action === 'create-dataset') {\n if (!checkEntitlement(org, 'dataStore')) {\n return Response.json({\n error: 'Datasets require a Starter plan or higher',\n }, { status: 403 })\n }\n const displayName = String(body?.displayName ?? '').trim().slice(0, 120)\n const fields = Array.isArray(body?.fields)\n ? (body.fields as unknown[]).map((field) => String(field)).slice(0, 100)\n : []\n if (!displayName || fields.length === 0) {\n return Response.json({ error: 'Missing displayName or fields' }, { status: 400 })\n }\n /**\n * The site the dataset is created from — null on the organization Data\n * page, which has none.\n *\n * It reaches the document only through the org's Default sharing: with\n * `defaultResourceScope: 'host'` the new dataset is visible to this site\n * alone. That makes it a client claim deciding who can see the result,\n * so it is honored only when it holds on both counts:\n *\n * * The site is one of THIS org's. `hostIndex` is the mirror the Data\n * card resolved `orgId` from in the first place, so a create made\n * from a real site page cannot disagree with it. Another org's site\n * would stamp a token that no site and no scoped member of this org\n * holds: a dataset only the org's admins could ever find.\n * * The caller's own access reaches the scope it produces. A scoped\n * member naming a site outside their access would create a dataset\n * they cannot see afterwards, which is the create the rules'\n * `canCreateScoped()` refuses on the collections clients create.\n *\n * Both are refused rather than widened to All sites. Widening is the\n * direction that shows a dataset to sites nobody chose.\n */\n const hostId = String(body?.hostId ?? '').trim() || null\n if (\n hostId &&\n (hostId.includes('/') || (await resolveOrgIdForHost(hostId)) !== orgId)\n ) {\n return Response.json(\n { error: 'That site is not one of this organization’s' },\n { status: 400 },\n )\n }\n // Honors the org's `defaultResourceScope` (AGL-1048), falling back to\n // org-wide — which is also the only answer with no site in context.\n const visibleTo = defaultScopeForNewResource({\n defaultResourceScope: (org as {\n defaultResourceScope?: 'org' | 'host'\n })?.defaultResourceScope,\n hostId,\n })\n if (\n hostId &&\n decoded['staff'] !== true &&\n !memberCanSee(member, visibleTo)\n ) {\n return Response.json(\n { error: 'Your access to this organization does not reach that site' },\n { status: 403 },\n )\n }\n const datasetsRef = orgRef.collection('datasets')\n const overDatasetQuota = (quota: ReturnType<typeof checkDatasetQuota>) =>\n quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets ` +\n `for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n // The fast refusal. NOT the enforcement point — that is the transaction\n // below — but it answers a caller who is simply over their limit before\n // the request builds anything.\n const quota = checkDatasetQuota(\n org,\n (await datasetsRef.count().get()).data().count,\n )\n if (!quota.allowed) {\n return Response.json({ error: overDatasetQuota(quota) }, { status: 403 })\n }\n const id = createResourceUid()\n // The model rides from the console (deriveModelFromFields output or\n // the join-collection template). `model` is independent of `fields`,\n // so cap its serialized size explicitly (a legit model is well under\n // this — 64 KB covers hundreds of typed fields).\n const model = body?.model && typeof body.model === 'object' ? body.model : null\n if (model && JSON.stringify(model).length > 64 * 1024) {\n return Response.json({ error: 'Dataset model too large' }, { status: 413 })\n }\n /**\n * THE ENFORCEMENT POINT (AGL-2371, the AGL-2231 treatment): the count,\n * the decision and the create in ONE transaction.\n *\n * The check above counted, then the request went on awaiting, and only\n * then created — and every await is a yield, so N concurrent creates\n * each read the same pre-count, each found room, and each landed.\n * Nothing re-counts afterwards, so the extra datasets were permanent and\n * billed nothing. `tx.get` on the aggregate takes a pessimistic lock on\n * the documents the query matched, so the loser of a race retries,\n * re-reads the higher count and is refused.\n *\n * The ORG document is deliberately read outside: the plan and the\n * purchased add-ons are the other input to this decision, but neither is\n * client-writable, so locking the org doc on every dataset create would\n * buy contention rather than correctness. That is the AGL-2369 lesson\n * applied, not skipped — there the routing map *was* client-writable and\n * *did* change the count.\n *\n * The refusal comes back as data and is rendered outside: building a\n * response inside a body that can run several times reads as if the\n * transaction were a place effects happen.\n */\n const refusal = await firestore.runTransaction<string | null>(\n async (tx) => {\n const live = (await tx.get(datasetsRef.count())).data().count\n const authoritative = checkDatasetQuota(org, live)\n if (!authoritative.allowed) return overDatasetQuota(authoritative)\n tx.create(datasetsRef.doc(id), {\n displayName,\n fields,\n ...(model ? { model } : {}),\n // The scope decided above. Stamping SOMETHING is mandatory: an\n // `array-contains-any` matches nothing on a doc missing the field,\n // so an unstamped dataset renders on no site at all (AGL-1044).\n //\n // Through `newResourceScopeFields` since AGL-1484: AGL-1478 built\n // that helper as the type-level gate for exactly the collections\n // with no document constructor of their own — `datasets` named\n // first among them — and then only the marketplace fork used it,\n // while the two ordinary dataset creates went on writing the field\n // by hand. A required argument that three of four callers bypass\n // is a convention, not a guarantee.\n ...newResourceScopeFields(visibleTo),\n createdAt: Timestamp.now(),\n })\n return null\n },\n )\n if (refusal) return Response.json({ error: refusal }, { status: 403 })\n return Response.json({ ok: true, id }, { status: 200 })\n }\n\n /**\n * Who a dataset is shared with (AGL-4047).\n *\n * Who may do it is what the rule on a client's `visibleTo` write asks: \"Manage\n * data\", asked above, with every site in reach. A site's verdict writes a\n * dataset and never moves it.\n *\n * The `scopeMode` and `scopeExcept` of a dataset shared with all sites except\n * some are the server's alone (the rules' `scopeMarkerUnchanged`), so this is\n * the one door that sets or removes them, and removing them is a field delete.\n *\n * The workspace's sites are read in the transaction: a site being created\n * writes the same document, so it either lands first and is on this list, or\n * lands after and its sweep finds this dataset. A sweep can't miss it.\n *\n * A site this workspace doesn't hold is dropped from a choice, never refused\n * and never stored: it may be one that has just gone, and a token no site\n * holds would make a dataset nobody could reach.\n */\n if (action === 'set-sharing') {\n if (decoded['staff'] !== true && !isOrgWideMember(member)) {\n return Response.json(\n { error: 'Changing who a dataset is shared with takes access to every site in the workspace.', reason: 'reach' },\n { status: 403 },\n )\n }\n const datasetId = String(body?.datasetId ?? '')\n const choice = sharingChoiceFrom(body?.choice)\n if (!datasetId || datasetId.includes('/') || !choice) {\n return Response.json({ error: 'Missing datasetId or sharing choice' }, { status: 400 })\n }\n const datasetRef = orgRef.collection('datasets').doc(datasetId)\n const answer = await firestore.runTransaction(async (tx) => {\n const [liveOrg, dataset] = await tx.getAll(orgRef, datasetRef)\n if (!dataset.exists) return { status: 404, error: 'Unknown dataset' }\n const orgHostIds = orgHostIdsFromDoc(liveOrg.data())\n const shared = sharingFromChoice(\n choice.mode === 'selected'\n ? { mode: 'selected', hostIds: choice.hostIds.filter((id) => orgHostIds.includes(id)) }\n : choice,\n orgHostIds,\n )\n if (!shared.fields) return { status: 400, error: shared.problem }\n tx.update(datasetRef, { ...fieldsToWrite(shared.fields), updatedAt: Timestamp.now() })\n return { status: 200, visibleTo: shared.fields.visibleTo, scopeExcept: shared.fields.scopeExcept }\n })\n if (answer.status !== 200) {\n return Response.json({ error: answer.error }, { status: answer.status })\n }\n return Response.json({ ok: true, visibleTo: answer.visibleTo, scopeExcept: answer.scopeExcept }, { status: 200 })\n }\n\n if (DATASET_ACTIONS.has(action)) {\n const datasetId = String(body?.datasetId ?? '')\n if (!datasetId) {\n return Response.json({ error: 'Missing datasetId' }, { status: 400 })\n }\n const datasetRef = orgRef.collection('datasets').doc(datasetId)\n const datasetSnapshot = await datasetRef.get()\n if (!datasetSnapshot.exists) {\n return Response.json({ error: 'Unknown dataset' }, { status: 404 })\n }\n /**\n * The caller has to be able to SEE the dataset they add rows to.\n *\n * \"Manage data\" is about the org, and a member scoped to one site can\n * hold it. The rules hold every record update and\n * delete to the parent dataset being visible (`parentDatasetVisible()`),\n * and refuse client record creates outright, so this route is the one\n * place a member's create can be held to the same condition. Without it,\n * a collaborator on one client's site could add rows, by id alone, to an\n * internal dataset shared only with other sites.\n *\n * The Admin SDK evaluates no rules, so `memberCanSee` IS the enforcement\n * here, as on the export route beside this one. Answered with the same\n * 404 as a dataset that does not exist: whether one outside the caller's\n * reach exists is not theirs to learn either.\n */\n if (\n decoded['staff'] !== true &&\n !memberCanSee(\n member,\n (datasetSnapshot.data() as { visibleTo?: string[] } | undefined)\n ?.visibleTo,\n )\n ) {\n return Response.json({ error: 'Unknown dataset' }, { status: 404 })\n }\n /**\n * Who may write THIS dataset (AGL-4047), the rules' `canWriteDatasetOn`:\n * \"Manage data\", unless a site narrows the member on the one site it is\n * placed on; or that one site's verdict.\n */\n const placedOn = datasetSnapshot.data()\n if (\n decoded['staff'] !== true &&\n !(await memberMayActOnDataset({ firestore, orgId, uid: decoded.uid, member, dataset: placedOn, act: 'write' }))\n ) {\n return datasetsPermissionRefusal(datasetRefusalPermission('write', placedOn))\n }\n /**\n * A record the BROWSER wrote, announcing itself (AGL-3113).\n *\n * Record edits and deletes stay client-direct on purpose — they consume\n * no quota, so AGL-473 left them out of the server leg — which also left\n * them with nothing to announce from. They are the same staleness as a\n * create: a page listing the rows goes on showing the old one.\n *\n * A drop, and only a drop. It moves no pointer, writes nothing and\n * registers no route, so it grants nothing the rules withhold — and it\n * is gated by the same org membership and the same `memberCanSee` the\n * create is, which is what stops a collaborator on one site from\n * learning that another site's dataset exists.\n */\n if (action === 'announce-records') {\n const announced = await announceDatasetChange({\n firestore,\n orgId,\n datasetId,\n })\n return Response.json({ ok: true, announced }, { status: 200 })\n }\n const model = effectiveDatasetModel(datasetSnapshot.data() as any)\n /**\n * Gives the dataset a page address (AGL-3475): a \"Page address\" field\n * that fills in from `sourceField`, and an address on every record that\n * has none yet, unique within the dataset (`roofing`, `roofing-2`).\n *\n * Server-side because it writes every record, and each write has to\n * carry the filter fields the record template's lookup reads — the\n * address is found through `filterValues`, so a record written without\n * them would have a page nobody can reach. A dataset that already has\n * an address field keeps it: the call fills that field's empty\n * addresses instead of adding a second one.\n */\n if (action === 'add-address-field') {\n const sourceField = String(body?.sourceField ?? '').trim()\n const source = model.fields[sourceField]\n if (!source || source.type !== 'text' || isRecordAddressField(source)) {\n return Response.json(\n { error: 'Pick a text field to fill page addresses from' },\n { status: 400 },\n )\n }\n const held = recordAddressFieldIds(model)[0]\n const fieldId = held ?? defaultDatasetFieldId('slug', new Set(model.order))\n const nextModel = held\n ? model\n : {\n fields: {\n ...model.fields,\n [fieldId]: {\n name: 'Page address',\n type: 'text' as const,\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceField,\n },\n },\n order: [...model.order, fieldId],\n }\n if (!held) {\n await datasetRef.update({ model: nextModel, updatedAt: Timestamp.now() })\n }\n const snapshot = await datasetRef\n .collection('records')\n .orderBy(FieldPath.documentId())\n .limit(ADDRESS_FILL_MAX + 1)\n .get()\n const docs = snapshot.docs.slice(0, ADDRESS_FILL_MAX)\n const valuesOf = (doc: FirebaseFirestore.QueryDocumentSnapshot) =>\n (doc.get('values') ?? {}) as Record<string, unknown>\n const taken = docs\n .map((doc) => recordAddressOf(valuesOf(doc), fieldId))\n .filter(Boolean)\n const assigned = uniqueRecordAddresses(\n docs\n .filter((doc) => !recordAddressOf(valuesOf(doc), fieldId))\n .map((doc) => ({ id: doc.id, source: valuesOf(doc)[sourceField] })),\n taken,\n )\n const writes = docs.filter((doc) => assigned.has(doc.id))\n for (let start = 0; start < writes.length; start += IMPORT_CHUNK) {\n const batch = firestore.batch()\n for (const doc of writes.slice(start, start + IMPORT_CHUNK)) {\n const values = { ...valuesOf(doc), [fieldId]: assigned.get(doc.id) }\n batch.update(doc.ref, {\n values,\n ...datasetIntegrityUpdate(nextModel, values, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n }\n await batch.commit()\n }\n if (writes.length || !held) {\n await announceDatasetChange({ firestore, orgId, datasetId })\n }\n return Response.json(\n {\n ok: true,\n fieldId,\n filled: writes.length,\n truncated: snapshot.docs.length > ADDRESS_FILL_MAX,\n },\n { status: 200 },\n )\n }\n // Before either validation below: a plugin's field validator only runs\n // once its plugin's server entry has registered it.\n await ensureDeclaredCustomFieldTypes(model)\n const recordsRef = datasetRef.collection('records')\n\n /**\n * A record edit (AGL-3668): the Data card's Save on an existing record,\n * for a caller that is not a browser. The card writes it straight to\n * Firestore — it consumes no quota — with the values coerced, filled\n * and validated against the model and the integrity and filter index\n * moved with them; the native apps reach the same write here, under\n * the same write and visibility gates as a create.\n * `values` is replaced whole, so a removed field's value strips here,\n * as it does on the card (the AGL-178 policy).\n */\n if (action === 'update-record') {\n const recordId = String(body?.recordId ?? '')\n if (!recordId) {\n return Response.json({ error: 'Missing recordId' }, { status: 400 })\n }\n const recordRef = recordsRef.doc(recordId)\n if (!(await recordRef.get()).exists) {\n return Response.json({ error: 'Unknown record' }, { status: 404 })\n }\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, body?.values ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return Response.json({ error: 'Record failed validation', errors }, { status: 400 })\n }\n await recordRef.update({\n values: coerced,\n ...datasetIntegrityUpdate(model, coerced, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n const announced = await announceDatasetChange({ firestore, orgId, datasetId })\n return Response.json({ ok: true, id: recordId, announced }, { status: 200 })\n }\n\n /**\n * A record delete (AGL-3668), with the card's delete integrity\n * (AGL-180): every dataset the caller can see whose model references\n * this one is asked, by its `referencedIds` index, whether it still\n * points at the record. `restrict` refuses the delete and writes\n * nothing; `setNull` strips the reference from each holder first. The\n * verdict is `planReferenceFixups`, the one the card applies. The\n * datasets consulted are the ones the caller can see, exactly the set\n * the card reads, so the app is refused exactly when the console is.\n */\n if (action === 'delete-record') {\n const recordId = String(body?.recordId ?? '')\n if (!recordId) {\n return Response.json({ error: 'Missing recordId' }, { status: 400 })\n }\n const recordRef = recordsRef.doc(recordId)\n if (!(await recordRef.get()).exists) {\n return Response.json({ error: 'Unknown record' }, { status: 404 })\n }\n const others = (await orgRef.collection('datasets').get()).docs.filter(\n (other) =>\n decoded['staff'] === true ||\n memberCanSee(member, (other.data() as { visibleTo?: string[] }).visibleTo),\n )\n const fixups: Array<{ datasetId: string; model: ReturnType<typeof effectiveDatasetModel>; updates: Array<{ id: string; values: Record<string, unknown> }> }> = []\n for (const other of others) {\n const otherModel = effectiveDatasetModel(other.data() as any)\n if (!referencingFieldIds(otherModel, datasetId).length) continue\n const holders = await other.ref\n .collection('records')\n .where('referencedIds', 'array-contains', recordId)\n .get()\n const plan = planReferenceFixups(\n otherModel,\n datasetId,\n recordId,\n holders.docs.map((holder) => ({ id: holder.id, values: holder.get('values') })),\n )\n if (plan.kind === 'restricted') {\n const name = String((other.data() as any)?.displayName ?? (other.data() as any)?.name ?? '').trim()\n return Response.json(\n { error: restrictedDeleteMessage(plan.holders, name) },\n { status: 409 },\n )\n }\n if (plan.kind === 'strip') {\n // Stripping a reference writes THAT dataset, so it asks what writing\n // it asks, as the card's client-direct batch does at the rule (AGL-4047).\n const otherPlacedOn = other.data()\n if (\n decoded['staff'] !== true &&\n !(await memberMayActOnDataset({ firestore, orgId, uid: decoded.uid, member, dataset: otherPlacedOn, act: 'write' }))\n ) {\n return datasetsPermissionRefusal(datasetRefusalPermission('write', otherPlacedOn))\n }\n fixups.push({ datasetId: other.id, model: otherModel, updates: plan.updates })\n }\n }\n for (const fixup of fixups) {\n const holdersRef = orgRef.collection('datasets').doc(fixup.datasetId).collection('records')\n for (let start = 0; start < fixup.updates.length; start += IMPORT_CHUNK) {\n const batch = firestore.batch()\n for (const update of fixup.updates.slice(start, start + IMPORT_CHUNK)) {\n batch.update(holdersRef.doc(update.id), {\n values: update.values,\n ...datasetIntegrityUpdate(fixup.model, update.values, FieldValue.delete()),\n })\n }\n await batch.commit()\n }\n }\n await recordRef.delete()\n for (const changed of [datasetId, ...fixups.map((fixup) => fixup.datasetId)]) {\n await announceDatasetChange({ firestore, orgId, datasetId: changed })\n }\n return Response.json(\n { ok: true, id: recordId, fixed: fixups.reduce((total, fixup) => total + fixup.updates.length, 0) },\n { status: 200 },\n )\n }\n\n const recordCount = (await recordsRef.count().get()).data().count\n const overRecordQuota = (limit: number) =>\n `Record limit reached (${limit}) — upgrade in Billing`\n\n if (action === 'create-record') {\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, body?.values ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return Response.json({ error: 'Record failed validation', errors }, { status: 400 })\n }\n // The fast refusal. NOT the enforcement point — that is the\n // transaction below — but it keeps the refusal ORDER on this route\n // intact: a caller over BOTH the row cap and the byte band is told\n // about the rows, as they always were.\n const quota = checkQuota(org, 'recordsPerDataset', recordCount)\n if (!quota.allowed) {\n return Response.json({\n error: overRecordQuota(quota.limit),\n }, { status: 403 })\n }\n // Bytes, not rows (AGL-2163). Before the write, like every other\n // quota on this route.\n const storageRefusal = await refuseIfDataStorageBlocked(org, orgRef)\n if (storageRefusal) return storageRefusal\n const id = createResourceUid()\n /**\n * THE ENFORCEMENT POINT (AGL-2371, the AGL-2231 treatment): the count,\n * the decision and the create in ONE transaction.\n *\n * The check above counted, then `refuseIfDataStorageBlocked` awaited,\n * and only then did the row land. Every await is a yield, so N\n * concurrent creates each read the same pre-count, each found room,\n * and each landed — permanently, since nothing re-counts afterwards. A\n * free-with-rows-granted org's thousand rows became twenty thousand by\n * sending twenty requests at once.\n *\n * `tx.get` on the aggregate takes a pessimistic lock on the documents\n * the query matched, so the loser retries, re-reads the higher count\n * and is refused. `order` is taken from the transaction's own count\n * for the same reason: the pre-count is what made two concurrent rows\n * share an order.\n *\n * The BYTE gate stays outside. It is a different quota with its own\n * reads, it is not a function of the rows this transaction writes, and\n * re-running it on every retry attempt would put a multi-document read\n * inside a lock.\n */\n const refusal = await firestore.runTransaction<string | null>(\n async (tx) => {\n const live = (await tx.get(recordsRef.count())).data().count\n const authoritative = checkQuota(org, 'recordsPerDataset', live)\n if (!authoritative.allowed) return overRecordQuota(authoritative.limit)\n tx.create(recordsRef.doc(id), {\n values: coerced,\n // The integrity index the delete check queries. Written on the\n // same write as the values it describes — an index that lags\n // them reports a reference the record no longer holds, or\n // misses one it does.\n ...datasetIntegrityFields(model, coerced),\n order: live,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n return null\n },\n )\n if (refusal) return Response.json({ error: refusal }, { status: 403 })\n // The record is stored; now the pages that repeat over it are told\n // (AGL-3113). Awaited so the site is already serving the new row by the\n // time the editor's save returns, and reported so a refused drop can\n // say the live pages are behind rather than leaving it to be noticed.\n const announced = await announceDatasetChange({\n firestore,\n orgId,\n datasetId,\n })\n return Response.json({ ok: true, id, announced }, { status: 200 })\n }\n\n // import-records: the console sends only the NEW rows (updates to\n // existing ids stay client-direct — they don't consume quota).\n const rows = Array.isArray(body?.records)\n ? (body.records as Array<{ values?: unknown }>)\n : []\n if (rows.length === 0) {\n return Response.json({ error: 'No records to import' }, { status: 400 })\n }\n const overImportQuota = (limit: number, needed: number) =>\n `This import needs ${needed} record slots — your plan ` +\n `allows ${limit} per dataset. See Billing to upgrade.`\n // The fast refusal, on the whole import. NOT the enforcement point —\n // that is the per-chunk transaction below — but it is what answers an\n // import that never fitted, before a single row is written.\n const quota = checkQuota(\n org,\n 'recordsPerDataset',\n recordCount + rows.length - 1,\n )\n if (!quota.allowed) {\n return Response.json({\n error: overImportQuota(quota.limit, rows.length),\n }, { status: 403 })\n }\n // Bytes, not rows (AGL-2163). An import is the path that moves the\n // most bytes in one request, so leaving it out would have left the\n // enforcement exactly where the customer does not meet it.\n const importStorageRefusal = await refuseIfDataStorageBlocked(org, orgRef)\n if (importStorageRefusal) return importStorageRefusal\n const prepared = rows.map((row, index) => {\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(\n model,\n (row?.values ?? {}) as Record<string, unknown>,\n ),\n )\n const errors = validateDocument(model, coerced)\n return { index, coerced, valid: Object.keys(errors).length === 0 }\n })\n const invalid = prepared.filter((row) => !row.valid)\n if (invalid.length) {\n return Response.json({\n error: `${invalid.length} rows failed validation`,\n rows: invalid.map((row) => row.index),\n }, { status: 400 })\n }\n /**\n * THE ENFORCEMENT POINT (AGL-2371): each chunk counts, decides and\n * writes inside ONE transaction.\n *\n * The import used to count once, decide once, and then commit a series\n * of `WriteBatch`es. A batch is atomic but NOT conditional on a read\n * taken before it, so two concurrent imports each priced themselves off\n * the same pre-count and both landed in full — the create leg's defect,\n * multiplied by the batch size.\n *\n * It cannot be ONE transaction for every import the way the single-row\n * create can: `recordsPerDataset` runs to a million, and a transaction\n * carries at most 500 writes. So the chunk is the unit, and each chunk's\n * count is re-read under the lock and re-checked against the plan. The\n * cap therefore holds ABSOLUTELY at every size — what a race can cost is\n * a partial import, not an overshoot, and a partial import was already\n * possible the moment a mid-import batch could fail.\n *\n * The ids are minted before the transaction so a retry re-creates the\n * SAME documents rather than a second copy of the chunk.\n *\n * This is not AGL-2370's problem in miniature. There the whole bundle\n * must land or none of it, so chunking cannot be the unit and a lease is\n * needed; here rows are independent and \"fewer rows than asked for\" is a\n * reportable outcome.\n */\n const ids: string[] = []\n let refusedAt: string | null = null\n for (\n let start = 0;\n start < prepared.length && refusedAt === null;\n start += IMPORT_CHUNK\n ) {\n const chunk = prepared.slice(start, start + IMPORT_CHUNK)\n const chunkIds = chunk.map(() => createResourceUid())\n refusedAt = await firestore.runTransaction<string | null>(async (tx) => {\n const live = (await tx.get(recordsRef.count())).data().count\n const authoritative = checkQuota(\n org,\n 'recordsPerDataset',\n live + chunk.length - 1,\n )\n if (!authoritative.allowed) {\n return overImportQuota(authoritative.limit, rows.length)\n }\n chunk.forEach((row, offset) => {\n tx.create(recordsRef.doc(chunkIds[offset]), {\n values: row.coerced,\n ...datasetIntegrityFields(model, row.coerced),\n order: live + offset,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n })\n return null\n })\n if (refusedAt === null) ids.push(...chunkIds)\n }\n /**\n * ONE announce for the whole import, after the loop (AGL-3113).\n *\n * Not per chunk and certainly not per row: a thousand rows arrive as one\n * import and make the same pages stale once, so the pages are worked out\n * once and dropped once. The refusal path announces too — rows that\n * landed before the quota bit are live records, and leaving them out of\n * the refresh would make a partial import look like no import at all.\n */\n if (ids.length) {\n await announceDatasetChange({ firestore, orgId, datasetId })\n }\n if (refusedAt !== null) {\n // What landed is reported alongside the refusal. Rows are independent,\n // so silently discarding the created ids would tell the caller nothing\n // was written while the dataset says otherwise.\n return Response.json(\n { error: refusedAt, ids, created: ids.length },\n { status: 403 },\n )\n }\n return Response.json({ ok: true, ids, created: ids.length }, { status: 200 })\n }\n\n return Response.json({ error: 'Unknown action' }, { status: 400 })\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993); anything\n // else keeps the answer below.\n if (isRefusedIdToken(error)) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n console.error(error)\n return Response.json({ error: 'Dataset operation failed' }, { status: 500 })\n }\n}\n"],"names":["isOrgWideMember","sharingFromChoice","defaultScopeForNewResource","newResourceScopeFields","pluginRequestFromWeb","checkDatasetQuota","checkEntitlement","checkQuota","createResourceUid","ensureDeclaredCustomFieldTypes","memberCanSee","emailUnverifiedResponse","firebaseAdmin","dataStorageRefusal","isImpersonationSession","isServerReleaseFlagOnForOrg","lockdownRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isRefusedIdToken","fieldsToWrite","orgHostIdsFromDoc","FieldPath","FieldValue","Timestamp","dataPermissionRefusal","announceDatasetRecords","announceDatasetChange","datasetRefusalPermission","memberMayActOnDataset","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","effectiveDatasetModel","validateDocument","defaultDatasetFieldId","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","RECORD_PAGE_ADDRESS_FIELD_TYPE","fillRecordAddresses","isRecordAddressField","recordAddressFieldIds","recordAddressOf","uniqueRecordAddresses","refuseIfDataStorageBlocked","org","orgRef","refusal","Response","json","error","basis","includedMb","status","DATASETS_PERMISSION","datasetsPermissionRefusal","permission","reason","DATASET_ACTIONS","Set","SHARING_CHOICE_MAX_IDS","sharingChoiceFrom","value","choice","ids","list","Array","isArray","length","every","id","test","mode","hostIds","exceptHostIds","IMPORT_CHUNK","ADDRESS_FILL_MAX","datasetsHandler","request","headers","method","body","rawHeaders","authorization","idToken","startsWith","slice","undefined","orgId","String","action","decoded","app","auth","verifyIdToken","email_verified","membership","uid","member","has","firestore","collection","doc","orgSnapshot","get","exists","data","locked","staff","displayName","trim","fields","map","field","hostId","includes","visibleTo","defaultResourceScope","datasetsRef","overDatasetQuota","quota","upgradeRequired","limit","addonPriceUsd","count","allowed","model","JSON","stringify","runTransaction","tx","live","authoritative","create","createdAt","now","ok","datasetId","datasetRef","answer","liveOrg","dataset","getAll","orgHostIds","shared","filter","problem","update","updatedAt","scopeExcept","datasetSnapshot","placedOn","act","announced","sourceField","source","type","held","fieldId","order","nextModel","name","customType","slugFrom","snapshot","orderBy","documentId","docs","valuesOf","taken","Boolean","assigned","writes","start","batch","values","ref","delete","commit","filled","truncated","recordsRef","recordId","recordRef","coerced","errors","Object","keys","others","other","fixups","otherModel","holders","where","plan","holder","kind","otherPlacedOn","push","updates","fixup","holdersRef","changed","fixed","reduce","total","recordCount","overRecordQuota","storageRefusal","rows","records","overImportQuota","needed","importStorageRefusal","prepared","row","index","valid","invalid","refusedAt","chunk","chunkIds","forEach","offset","created","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAQ,uCAAsC;AACtE,SAAkCC,iBAAiB,QAAQ,sCAAqC;AAChG,SACEC,0BAA0B,EAC1BC,s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KgK,SAAShK,IAAII,MAAM;gBAAC,GAC7C;oBAAEf,QAAQ;gBAAI;YAElB;YACA,OAAOL,SAASC,IAAI,CAAC;gBAAEuF,IAAI;gBAAMxE;gBAAKgK,SAAShK,IAAII,MAAM;YAAC,GAAG;gBAAEf,QAAQ;YAAI;QAC7E;QAEA,OAAOL,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiB,GAAG;YAAEG,QAAQ;QAAI;IAClE,EAAE,OAAOH,OAAO;QACd,0EAA0E;QAC1E,+BAA+B;QAC/B,IAAIhC,iBAAiBgC,QAAQ;YAC3B,OAAOF,SAASC,IAAI,CAAC;gBAAEC,OAAO;YAAkB,GAAG;gBAAEG,QAAQ;YAAI;QACnE;QACA4K,QAAQ/K,KAAK,CAACA;QACd,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAA2B,GAAG;YAAEG,QAAQ;QAAI;IAC5E;AACF,EAAC"}
@@ -32,7 +32,8 @@ export declare const DATASET_BUNDLE_RECORD_LIMIT = 1000;
32
32
  * left off is ERASED. `visibleTo` is never on it — the restore assigns a fresh
33
33
  * scope for the site it restores into, since a bundle is portable and an
34
34
  * embedded `['org']` would publish one organization's data across another's
35
- * whole client roster.
35
+ * whole client roster. Nor is the all-sites-except marker, `scopeMode` and
36
+ * `scopeExcept` (AGL-4047), which names sites of the workspace it came from.
36
37
  */
37
38
  export declare const DATASET_RESTORE_FIELDS: readonly string[];
38
39
  /**
@@ -52,7 +53,8 @@ export declare const RECORD_RESTORE_FIELDS: readonly string[];
52
53
  *
53
54
  * `visibleTo` is stripped on the way out. Its `host:` tokens name sites of
54
55
  * THIS organization, so they are noise at best and a dangling reference once
55
- * the bundle is restored elsewhere; the restore assigns a fresh scope.
56
+ * the bundle is restored elsewhere; the restore assigns a fresh scope. The
57
+ * all-sites-except marker goes with it, for the same reason (AGL-4047).
56
58
  */
57
59
  export declare function exportSiteDatasets({ hostId, orgId, limit, }: SiteBundleRequest): Promise<SiteBundleItem[]>;
58
60
  /**
@@ -35,7 +35,8 @@ import { datasetIntegrityFields, effectiveDatasetModel, validateDocument } from
35
35
  * left off is ERASED. `visibleTo` is never on it — the restore assigns a fresh
36
36
  * scope for the site it restores into, since a bundle is portable and an
37
37
  * embedded `['org']` would publish one organization's data across another's
38
- * whole client roster.
38
+ * whole client roster. Nor is the all-sites-except marker, `scopeMode` and
39
+ * `scopeExcept` (AGL-4047), which names sites of the workspace it came from.
39
40
  */ export const DATASET_RESTORE_FIELDS = [
40
41
  'displayName',
41
42
  // Pre-AGL-536 human name, still read as a fallback by site search.
@@ -86,14 +87,17 @@ const datasetsOf = (orgId)=>firebaseAdmin.app().firestore().collection('orgs').d
86
87
  *
87
88
  * `visibleTo` is stripped on the way out. Its `host:` tokens name sites of
88
89
  * THIS organization, so they are noise at best and a dangling reference once
89
- * the bundle is restored elsewhere; the restore assigns a fresh scope.
90
+ * the bundle is restored elsewhere; the restore assigns a fresh scope. The
91
+ * all-sites-except marker goes with it, for the same reason (AGL-4047).
90
92
  */ export async function exportSiteDatasets({ hostId, orgId, limit }) {
91
93
  if (!orgId) return [];
92
94
  const snapshot = await scopedToHost(datasetsOf(orgId), hostId).limit(limit).get();
93
95
  const live = snapshot.docs.filter((doc)=>!doc.get('deletedAt'));
94
96
  return Promise.all(live.map(async (doc)=>{
95
- const _doc_data = doc.data(), { visibleTo: _visibleTo } = _doc_data, data = _object_without_properties_loose(_doc_data, [
96
- "visibleTo"
97
+ const _doc_data = doc.data(), { visibleTo: _visibleTo, scopeMode: _scopeMode, scopeExcept: _scopeExcept } = _doc_data, data = _object_without_properties_loose(_doc_data, [
98
+ "visibleTo",
99
+ "scopeMode",
100
+ "scopeExcept"
97
101
  ]);
98
102
  const records = await doc.ref.collection('records').limit(DATASET_BUNDLE_RECORD_LIMIT).get();
99
103
  return _extends({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/site-bundle/datasets-site-bundle.server.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 { checkDatasetQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type {\n SiteBundleImportRequest,\n SiteBundleItem,\n SiteBundleReportRow,\n SiteBundleRequest,\n SiteBundleRestoreRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-site-bundle'\nimport { firebaseAdmin, scopedToHost } from '@aglyn/tenant-data-admin'\nimport { loadCustomFieldTypes } from '../server/custom-field-types'\nimport { datasetIntegrityFields, effectiveDatasetModel, validateDocument } from '../model/dataset-models'\n\n/**\n * A site's datasets in its whole-site backup (AGL-163), answered by the plugin\n * that keeps them (AGL-3080).\n *\n * Datasets are ORG-owned (AGL-237) and shared with sites by scope, so a site's\n * backup carries the datasets that site may see (AGL-1046) — each with its\n * records — and a restore writes them back into the owning organization,\n * scoped to the site it restores into.\n */\n\n/** The records one dataset carries in a bundle, and the most a restore writes back. */\nexport const DATASET_BUNDLE_RECORD_LIMIT = 1000\n\n/**\n * The keys a restore writes back on a dataset (AGL-1382): every key a live\n * dataset carries, because the restore writes with `merge: false` and a key\n * left off is ERASED. `visibleTo` is never on it — the restore assigns a fresh\n * scope for the site it restores into, since a bundle is portable and an\n * embedded `['org']` would publish one organization's data across another's\n * whole client roster.\n */\nexport const DATASET_RESTORE_FIELDS: readonly string[] = [\n 'displayName',\n // Pre-AGL-536 human name, still read as a fallback by site search.\n 'name',\n 'fields',\n // The typed DatasetModel, and exactly what `effectiveDatasetModel` reads\n // below. Drop it and every restored dataset silently degrades to the\n // derived all-text v1 model, losing types, `required`, `validation`,\n // `default` and every `reference` link (AGL-180).\n 'model',\n 'names',\n 'description',\n 'source',\n 'installedFrom',\n 'detachedFrom',\n]\n\n/**\n * The keys a restore writes back on a record. `order` is what\n * `sortDatasetRecords` sorts by, so dropping it reorders every repeatable on\n * the restored site. The integrity index is DERIVED on the way in, never\n * carried (see {@link importSiteDatasets}).\n */\nexport const RECORD_RESTORE_FIELDS: readonly string[] = ['values', 'order']\n\n/** One of a bundle's documents, reduced to the keys a restore may write. */\nfunction restorable(fields: readonly string[], input: SiteBundleItem): Record<string, unknown> {\n const allowed = new Set(fields)\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input ?? {})) {\n // Only `undefined` is absence — Firestore rejects it outright.\n if (allowed.has(key) && value !== undefined) out[key] = value\n }\n return out\n}\n\n/** The ids a bundle would write — distinct, since two items sharing one are one document. */\nfunction bundleIds(items: readonly SiteBundleItem[]): Set<string> {\n const ids = new Set<string>()\n for (const item of items) if (item?.$id) ids.add(String(item.$id))\n return ids\n}\n\nconst datasetsOf = (orgId: string) =>\n firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('datasets')\n\n/**\n * The site's share: the datasets the site may see, each with its records.\n *\n * A site with no organization genuinely has no datasets — a known-empty\n * answer. Everything else THROWS: a catch-all would ship a silently empty,\n * still-successful \"backup\" that nobody discovers until they restore it. An\n * export that fails loudly is recoverable; one that lies is not.\n *\n * `visibleTo` is stripped on the way out. Its `host:` tokens name sites of\n * THIS organization, so they are noise at best and a dangling reference once\n * the bundle is restored elsewhere; the restore assigns a fresh scope.\n */\nexport async function exportSiteDatasets({\n hostId,\n orgId,\n limit,\n}: SiteBundleRequest): Promise<SiteBundleItem[]> {\n if (!orgId) return []\n const snapshot = await scopedToHost(datasetsOf(orgId), hostId).limit(limit).get()\n const live = snapshot.docs.filter((doc) => !doc.get('deletedAt'))\n return Promise.all(\n live.map(async (doc) => {\n const { visibleTo: _visibleTo, ...data } = doc.data()\n const records = await doc.ref.collection('records').limit(DATASET_BUNDLE_RECORD_LIMIT).get()\n return {\n $id: doc.id,\n ...data,\n records: records.docs.map((record) => ({ $id: record.id, ...record.data() })),\n }\n }),\n )\n}\n\n/**\n * Refuse a bundle that would put the workspace over the datasets it may hold\n * (AGL-1403) — decided before the restore writes anything.\n *\n * Datasets are SOLD: the plan includes some and the workspace buys more as\n * add-ons, so `checkDatasetQuota` decides, never the plan's included number —\n * a workspace that paid for extra datasets is entitled to them, and refusing\n * its own backup after taking its money for the room would be wrong.\n *\n * A restore is identified by id COLLISION, never by the bundle's own claim of\n * where it came from (an unsigned string in a file the metered party\n * uploads). The meter is per organization, so a collision here means the\n * WORKSPACE already holds the dataset: restoring into a sibling site of the\n * same workspace rewrites datasets it already pays for and raises nothing,\n * while a copy into a different workspace collides on nothing and is refused\n * when it lands that workspace over. What is refused is the RAISE, never the\n * state of being over — a workspace already over its limit may still restore\n * its own backup.\n */\nexport async function siteDatasetsRefusal({\n orgId,\n org,\n items,\n}: SiteBundleRestoreRequest): Promise<string | null> {\n const bundled = bundleIds(items)\n if (!orgId || !bundled.size) return null\n if (!Number.isFinite(checkDatasetQuota(org as any, 0).limit)) return null\n\n // A field mask with no fields projects to the document id alone.\n const held = await datasetsOf(orgId).select().get()\n const existing = new Set(held.docs.map((doc) => doc.id))\n const next = new Set([...existing, ...bundled]).size\n // `allowed` asks \"may I add one more to N\", so the post state N is checked\n // as `N - 1` — the idiom the dataset routes' own bulk paths use.\n const quota = checkDatasetQuota(org as any, next - 1)\n if (next <= existing.size || quota.allowed) return null\n\n return (\n `This backup holds ${bundled.size} datasets and this workspace ` +\n `has ${existing.size}, which would put it at ${next} of ${quota.limit} ` +\n 'datasets. Nothing was imported — ' +\n (quota.upgradeRequired\n ? 'upgrade in Billing.'\n : `add extra datasets for $${quota.addonPriceUsd}/mo each, or ` +\n 'upgrade in Billing.')\n )\n}\n\n/**\n * Writes the bundle's datasets into the owning organization, scoped to the\n * site restored into (AGL-237, AGL-1046), each with its records.\n *\n * Non-conforming records are restored AND reported (AGL-182): data is never\n * silently dropped, and the report tells the owner what to fix. A bundle from\n * before typed models validates through the derived text model, as the live\n * migration does, so everything in it passes.\n */\nexport async function importSiteDatasets(\n request: SiteBundleImportRequest,\n): Promise<SiteBundleReportRow[]> {\n const { hostId, orgId, items, write, stamps } = request\n if (!orgId) return []\n // Through the scoped-create gate (AGL-1478, AGL-1484): a restore CREATES\n // datasets, and a dataset is born scoped to the site it lands in.\n const scope = newResourceScopeFields([hostScopeToken(hostId)])\n const report: SiteBundleReportRow[] = []\n for (const item of items) {\n if (!item?.$id) continue\n const path = `orgs/${orgId}/datasets/${String(item.$id)}`\n await write(path, { ...restorable(DATASET_RESTORE_FIELDS, item), ...stamps(), ...scope })\n const model = effectiveDatasetModel(item)\n await loadCustomFieldTypes(model, request.loadPluginSurfaces)\n const records: SiteBundleItem[] = Array.isArray(item['records']) ? item['records'] : []\n for (const record of records.slice(0, DATASET_BUNDLE_RECORD_LIMIT)) {\n if (!record?.$id) continue\n const errors = validateDocument(model, record['values'] ?? {})\n if (Object.keys(errors).length) {\n report.push({ datasetId: String(item.$id), recordId: String(record.$id), errors })\n }\n await write(`${path}/records/${String(record.$id)}`, {\n ...restorable(RECORD_RESTORE_FIELDS, record),\n ...stamps(),\n // DERIVED here rather than carried in the bundle. The integrity\n // index the delete check queries must describe the values just\n // restored, and a bundle written before the field existed carries\n // none — accepting the bundle's copy would restore records the check\n // cannot reach. Records keep their original ids, so the ids it holds\n // still resolve.\n ...datasetIntegrityFields(model, record['values'] ?? {}),\n })\n }\n }\n return report\n}\n"],"names":["checkDatasetQuota","hostScopeToken","newResourceScopeFields","firebaseAdmin","scopedToHost","loadCustomFieldTypes","datasetIntegrityFields","effectiveDatasetModel","validateDocument","DATASET_BUNDLE_RECORD_LIMIT","DATASET_RESTORE_FIELDS","RECORD_RESTORE_FIELDS","restorable","fields","input","allowed","Set","out","key","value","Object","entries","has","undefined","bundleIds","items","ids","item","$id","add","String","datasetsOf","orgId","app","firestore","collection","doc","exportSiteDatasets","hostId","limit","snapshot","get","live","docs","filter","Promise","all","map","data","visibleTo","_visibleTo","records","ref","id","record","siteDatasetsRefusal","org","bundled","size","Number","isFinite","held","select","existing","next","quota","upgradeRequired","addonPriceUsd","importSiteDatasets","request","write","stamps","scope","report","path","model","loadPluginSurfaces","Array","isArray","slice","errors","keys","length","push","datasetId","recordId"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,2CAA0C;AAC5E,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,sCAAqC;AAQ5F,SAASC,aAAa,EAAEC,YAAY,QAAQ,2BAA0B;AACtE,SAASC,oBAAoB,QAAQ,kCAA8B;AACnE,SAASC,sBAAsB,EAAEC,qBAAqB,EAAEC,gBAAgB,QAAQ,6BAAyB;AAEzG;;;;;;;;CAQC,GAED,qFAAqF,GACrF,OAAO,MAAMC,8BAA8B,KAAI;AAE/C;;;;;;;CAOC,GACD,OAAO,MAAMC,yBAA4C;IACvD;IACA,mEAAmE;IACnE;IACA;IACA,yEAAyE;IACzE,qEAAqE;IACrE,qEAAqE;IACrE,kDAAkD;IAClD;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;CAKC,GACD,OAAO,MAAMC,wBAA2C;IAAC;IAAU;CAAQ,CAAA;AAE3E,0EAA0E,GAC1E,SAASC,WAAWC,MAAyB,EAAEC,KAAqB;IAClE,MAAMC,UAAU,IAAIC,IAAIH;IACxB,MAAMI,MAA+B,CAAC;IACtC,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACP,gBAAAA,QAAS,CAAC,GAAI;QACtD,+DAA+D;QAC/D,IAAIC,QAAQO,GAAG,CAACJ,QAAQC,UAAUI,WAAWN,GAAG,CAACC,IAAI,GAAGC;IAC1D;IACA,OAAOF;AACT;AAEA,2FAA2F,GAC3F,SAASO,UAAUC,KAAgC;IACjD,M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AWF,wBAAwBiB,OAAU4C,UAAaC;QACjF,MAAMG,QAAQpE,sBAAsBoB;QACpC,MAAMtB,qBAAqBsE,OAAON,QAAQO,kBAAkB;QAC5D,MAAMzB,UAA4B0B,MAAMC,OAAO,CAACnD,IAAI,CAAC,UAAU,IAAIA,IAAI,CAAC,UAAU,GAAG,EAAE;QACvF,KAAK,MAAM2B,UAAUH,QAAQ4B,KAAK,CAAC,GAAGtE,6BAA8B;gBAE3B6C,gBAaJA;YAdnC,IAAI,EAACA,0BAAAA,OAAQ1B,GAAG,GAAE;YAClB,MAAMoD,SAASxE,iBAAiBmE,QAAOrB,iBAAAA,MAAM,CAAC,SAAS,YAAhBA,iBAAoB,CAAC;YAC5D,IAAIlC,OAAO6D,IAAI,CAACD,QAAQE,MAAM,EAAE;gBAC9BT,OAAOU,IAAI,CAAC;oBAAEC,WAAWtD,OAAOH,KAAKC,GAAG;oBAAGyD,UAAUvD,OAAOwB,OAAO1B,GAAG;oBAAGoD;gBAAO;YAClF;YACA,MAAMV,MAAM,GAAGI,KAAK,SAAS,EAAE5C,OAAOwB,OAAO1B,GAAG,GAAG,EAAE,aAChDhB,WAAWD,uBAAuB2C,SAClCiB,UAOAjE,uBAAuBqE,QAAOrB,kBAAAA,MAAM,CAAC,SAAS,YAAhBA,kBAAoB,CAAC;QAE1D;IACF;IACA,OAAOmB;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/site-bundle/datasets-site-bundle.server.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 { checkDatasetQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type {\n SiteBundleImportRequest,\n SiteBundleItem,\n SiteBundleReportRow,\n SiteBundleRequest,\n SiteBundleRestoreRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-site-bundle'\nimport { firebaseAdmin, scopedToHost } from '@aglyn/tenant-data-admin'\nimport { loadCustomFieldTypes } from '../server/custom-field-types'\nimport { datasetIntegrityFields, effectiveDatasetModel, validateDocument } from '../model/dataset-models'\n\n/**\n * A site's datasets in its whole-site backup (AGL-163), answered by the plugin\n * that keeps them (AGL-3080).\n *\n * Datasets are ORG-owned (AGL-237) and shared with sites by scope, so a site's\n * backup carries the datasets that site may see (AGL-1046) — each with its\n * records — and a restore writes them back into the owning organization,\n * scoped to the site it restores into.\n */\n\n/** The records one dataset carries in a bundle, and the most a restore writes back. */\nexport const DATASET_BUNDLE_RECORD_LIMIT = 1000\n\n/**\n * The keys a restore writes back on a dataset (AGL-1382): every key a live\n * dataset carries, because the restore writes with `merge: false` and a key\n * left off is ERASED. `visibleTo` is never on it — the restore assigns a fresh\n * scope for the site it restores into, since a bundle is portable and an\n * embedded `['org']` would publish one organization's data across another's\n * whole client roster. Nor is the all-sites-except marker, `scopeMode` and\n * `scopeExcept` (AGL-4047), which names sites of the workspace it came from.\n */\nexport const DATASET_RESTORE_FIELDS: readonly string[] = [\n 'displayName',\n // Pre-AGL-536 human name, still read as a fallback by site search.\n 'name',\n 'fields',\n // The typed DatasetModel, and exactly what `effectiveDatasetModel` reads\n // below. Drop it and every restored dataset silently degrades to the\n // derived all-text v1 model, losing types, `required`, `validation`,\n // `default` and every `reference` link (AGL-180).\n 'model',\n 'names',\n 'description',\n 'source',\n 'installedFrom',\n 'detachedFrom',\n]\n\n/**\n * The keys a restore writes back on a record. `order` is what\n * `sortDatasetRecords` sorts by, so dropping it reorders every repeatable on\n * the restored site. The integrity index is DERIVED on the way in, never\n * carried (see {@link importSiteDatasets}).\n */\nexport const RECORD_RESTORE_FIELDS: readonly string[] = ['values', 'order']\n\n/** One of a bundle's documents, reduced to the keys a restore may write. */\nfunction restorable(fields: readonly string[], input: SiteBundleItem): Record<string, unknown> {\n const allowed = new Set(fields)\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input ?? {})) {\n // Only `undefined` is absence — Firestore rejects it outright.\n if (allowed.has(key) && value !== undefined) out[key] = value\n }\n return out\n}\n\n/** The ids a bundle would write — distinct, since two items sharing one are one document. */\nfunction bundleIds(items: readonly SiteBundleItem[]): Set<string> {\n const ids = new Set<string>()\n for (const item of items) if (item?.$id) ids.add(String(item.$id))\n return ids\n}\n\nconst datasetsOf = (orgId: string) =>\n firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('datasets')\n\n/**\n * The site's share: the datasets the site may see, each with its records.\n *\n * A site with no organization genuinely has no datasets — a known-empty\n * answer. Everything else THROWS: a catch-all would ship a silently empty,\n * still-successful \"backup\" that nobody discovers until they restore it. An\n * export that fails loudly is recoverable; one that lies is not.\n *\n * `visibleTo` is stripped on the way out. Its `host:` tokens name sites of\n * THIS organization, so they are noise at best and a dangling reference once\n * the bundle is restored elsewhere; the restore assigns a fresh scope. The\n * all-sites-except marker goes with it, for the same reason (AGL-4047).\n */\nexport async function exportSiteDatasets({\n hostId,\n orgId,\n limit,\n}: SiteBundleRequest): Promise<SiteBundleItem[]> {\n if (!orgId) return []\n const snapshot = await scopedToHost(datasetsOf(orgId), hostId).limit(limit).get()\n const live = snapshot.docs.filter((doc) => !doc.get('deletedAt'))\n return Promise.all(\n live.map(async (doc) => {\n const { visibleTo: _visibleTo, scopeMode: _scopeMode, scopeExcept: _scopeExcept, ...data } = doc.data()\n const records = await doc.ref.collection('records').limit(DATASET_BUNDLE_RECORD_LIMIT).get()\n return {\n $id: doc.id,\n ...data,\n records: records.docs.map((record) => ({ $id: record.id, ...record.data() })),\n }\n }),\n )\n}\n\n/**\n * Refuse a bundle that would put the workspace over the datasets it may hold\n * (AGL-1403) — decided before the restore writes anything.\n *\n * Datasets are SOLD: the plan includes some and the workspace buys more as\n * add-ons, so `checkDatasetQuota` decides, never the plan's included number —\n * a workspace that paid for extra datasets is entitled to them, and refusing\n * its own backup after taking its money for the room would be wrong.\n *\n * A restore is identified by id COLLISION, never by the bundle's own claim of\n * where it came from (an unsigned string in a file the metered party\n * uploads). The meter is per organization, so a collision here means the\n * WORKSPACE already holds the dataset: restoring into a sibling site of the\n * same workspace rewrites datasets it already pays for and raises nothing,\n * while a copy into a different workspace collides on nothing and is refused\n * when it lands that workspace over. What is refused is the RAISE, never the\n * state of being over — a workspace already over its limit may still restore\n * its own backup.\n */\nexport async function siteDatasetsRefusal({\n orgId,\n org,\n items,\n}: SiteBundleRestoreRequest): Promise<string | null> {\n const bundled = bundleIds(items)\n if (!orgId || !bundled.size) return null\n if (!Number.isFinite(checkDatasetQuota(org as any, 0).limit)) return null\n\n // A field mask with no fields projects to the document id alone.\n const held = await datasetsOf(orgId).select().get()\n const existing = new Set(held.docs.map((doc) => doc.id))\n const next = new Set([...existing, ...bundled]).size\n // `allowed` asks \"may I add one more to N\", so the post state N is checked\n // as `N - 1` — the idiom the dataset routes' own bulk paths use.\n const quota = checkDatasetQuota(org as any, next - 1)\n if (next <= existing.size || quota.allowed) return null\n\n return (\n `This backup holds ${bundled.size} datasets and this workspace ` +\n `has ${existing.size}, which would put it at ${next} of ${quota.limit} ` +\n 'datasets. Nothing was imported — ' +\n (quota.upgradeRequired\n ? 'upgrade in Billing.'\n : `add extra datasets for $${quota.addonPriceUsd}/mo each, or ` +\n 'upgrade in Billing.')\n )\n}\n\n/**\n * Writes the bundle's datasets into the owning organization, scoped to the\n * site restored into (AGL-237, AGL-1046), each with its records.\n *\n * Non-conforming records are restored AND reported (AGL-182): data is never\n * silently dropped, and the report tells the owner what to fix. A bundle from\n * before typed models validates through the derived text model, as the live\n * migration does, so everything in it passes.\n */\nexport async function importSiteDatasets(\n request: SiteBundleImportRequest,\n): Promise<SiteBundleReportRow[]> {\n const { hostId, orgId, items, write, stamps } = request\n if (!orgId) return []\n // Through the scoped-create gate (AGL-1478, AGL-1484): a restore CREATES\n // datasets, and a dataset is born scoped to the site it lands in.\n const scope = newResourceScopeFields([hostScopeToken(hostId)])\n const report: SiteBundleReportRow[] = []\n for (const item of items) {\n if (!item?.$id) continue\n const path = `orgs/${orgId}/datasets/${String(item.$id)}`\n await write(path, { ...restorable(DATASET_RESTORE_FIELDS, item), ...stamps(), ...scope })\n const model = effectiveDatasetModel(item)\n await loadCustomFieldTypes(model, request.loadPluginSurfaces)\n const records: SiteBundleItem[] = Array.isArray(item['records']) ? item['records'] : []\n for (const record of records.slice(0, DATASET_BUNDLE_RECORD_LIMIT)) {\n if (!record?.$id) continue\n const errors = validateDocument(model, record['values'] ?? {})\n if (Object.keys(errors).length) {\n report.push({ datasetId: String(item.$id), recordId: String(record.$id), errors })\n }\n await write(`${path}/records/${String(record.$id)}`, {\n ...restorable(RECORD_RESTORE_FIELDS, record),\n ...stamps(),\n // DERIVED here rather than carried in the bundle. The integrity\n // index the delete check queries must describe the values just\n // restored, and a bundle written before the field existed carries\n // none — accepting the bundle's copy would restore records the check\n // cannot reach. Records keep their original ids, so the ids it holds\n // still resolve.\n ...datasetIntegrityFields(model, record['values'] ?? {}),\n })\n }\n }\n return report\n}\n"],"names":["checkDatasetQuota","hostScopeToken","newResourceScopeFields","firebaseAdmin","scopedToHost","loadCustomFieldTypes","datasetIntegrityFields","effectiveDatasetModel","validateDocument","DATASET_BUNDLE_RECORD_LIMIT","DATASET_RESTORE_FIELDS","RECORD_RESTORE_FIELDS","restorable","fields","input","allowed","Set","out","key","value","Object","entries","has","undefined","bundleIds","items","ids","item","$id","add","String","datasetsOf","orgId","app","firestore","collection","doc","exportSiteDatasets","hostId","limit","snapshot","get","live","docs","filter","Promise","all","map","data","visibleTo","_visibleTo","scopeMode","_scopeMode","scopeExcept","_scopeExcept","records","ref","id","record","siteDatasetsRefusal","org","bundled","size","Number","isFinite","held","select","existing","next","quota","upgradeRequired","addonPriceUsd","importSiteDatasets","request","write","stamps","scope","report","path","model","loadPluginSurfaces","Array","isArray","slice","errors","keys","length","push","datasetId","recordId"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,2CAA0C;AAC5E,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,sCAAqC;AAQ5F,SAASC,aAAa,EAAEC,YAAY,QAAQ,2BAA0B;AACtE,SAASC,oBAAoB,QAAQ,kCAA8B;AACnE,SAASC,sBAAsB,EAAEC,qBAAqB,EAAEC,gBAAgB,QAAQ,6BAAyB;AAEzG;;;;;;;;CAQC,GAED,qFAAqF,GACrF,OAAO,MAAMC,8BAA8B,KAAI;AAE/C;;;;;;;;CAQC,GACD,OAAO,MAAMC,yBAA4C;IACvD;IACA,mEAAmE;IACnE;IACA;IACA,yEAAyE;IACzE,qEAAqE;IACrE,qEAAqE;IACrE,kDAAkD;IAClD;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;CAKC,GACD,OAAO,MAAMC,wBAA2C;IAAC;IAAU;CAAQ,CAAA;AAE3E,0EAA0E,GAC1E,SAASC,WAAWC,MAAyB,EAAEC,KAAqB;IAClE,MAAMC,UAAU,IAAIC,IAAIH;IACxB,MAAMI,MAA+B,CAAC;IACtC,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACP,gBAAAA,QAAS,CAAC,GAAI;QACtD,+DAA+D;QAC/D,IAAIC,QAAQO,GAAG,CAACJ,QAAQC,UAAUI,WAAWN,GAAG,CAACC,IAAI,GAAGC;IAC1D;IACA,OAAOF;AACT;AAEA,2FAA2F,GAC3F,SAASO,UAAUC,KAAgC;IACjD,MAAMC,MAAM,IAAIV;IAChB,KAAK,MAAMW,QAAQF,MAAO,IAAIE,wBAAAA,KAAMC,GAAG,EAAEF,IAAIG,GAAG,CAACC,OAAOH,KAAK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MAAMtB,qBAAqB0E,OAAON,QAAQO,kBAAkB;QAC5D,MAAMzB,UAA4B0B,MAAMC,OAAO,CAACvD,IAAI,CAAC,UAAU,IAAIA,IAAI,CAAC,UAAU,GAAG,EAAE;QACvF,KAAK,MAAM+B,UAAUH,QAAQ4B,KAAK,CAAC,GAAG1E,6BAA8B;gBAE3BiD,gBAaJA;YAdnC,IAAI,EAACA,0BAAAA,OAAQ9B,GAAG,GAAE;YAClB,MAAMwD,SAAS5E,iBAAiBuE,QAAOrB,iBAAAA,MAAM,CAAC,SAAS,YAAhBA,iBAAoB,CAAC;YAC5D,IAAItC,OAAOiE,IAAI,CAACD,QAAQE,MAAM,EAAE;gBAC9BT,OAAOU,IAAI,CAAC;oBAAEC,WAAW1D,OAAOH,KAAKC,GAAG;oBAAG6D,UAAU3D,OAAO4B,OAAO9B,GAAG;oBAAGwD;gBAAO;YAClF;YACA,MAAMV,MAAM,GAAGI,KAAK,SAAS,EAAEhD,OAAO4B,OAAO9B,GAAG,GAAG,EAAE,aAChDhB,WAAWD,uBAAuB+C,SAClCiB,UAOArE,uBAAuByE,QAAOrB,kBAAAA,MAAM,CAAC,SAAS,YAAhBA,kBAAoB,CAAC;QAE1D;IACF;IACA,OAAOmB;AACT"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { TransferImportAccessSubject, TransferImportAccessVerdict } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources';
18
+ /**
19
+ * Who may import into one dataset (AGL-4047): whoever may write it, by where it
20
+ * is placed. A dataset the member cannot see, or that is gone, is the resource's
21
+ * own 404 once the engine reads it, so it answers here as the workspace key does.
22
+ */
23
+ export declare function datasetImportAccess(subject: TransferImportAccessSubject): Promise<TransferImportAccessVerdict>;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { parseTransferResourceKey } from "@aglyn/aglyn/data-transfer";
17
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
18
+ import { datasetRefusalPermission, memberMayActOnDataset } from "../server/dataset-access.server.js";
19
+ /**
20
+ * Who may import into one dataset (AGL-4047): whoever may write it, by where it
21
+ * is placed. A dataset the member cannot see, or that is gone, is the resource's
22
+ * own 404 once the engine reads it, so it answers here as the workspace key does.
23
+ */ export async function datasetImportAccess(subject) {
24
+ var _parseTransferResourceKey_instance;
25
+ const firestore = firebaseAdmin.app().firestore();
26
+ const datasetId = (_parseTransferResourceKey_instance = parseTransferResourceKey(subject.resource).instance) != null ? _parseTransferResourceKey_instance : '';
27
+ const dataset = datasetId ? await firestore.collection('orgs').doc(subject.orgId).collection('datasets').doc(datasetId).get() : null;
28
+ const placed = (dataset == null ? void 0 : dataset.exists) ? dataset.data() : undefined;
29
+ const allowed = await memberMayActOnDataset({
30
+ firestore,
31
+ orgId: subject.orgId,
32
+ uid: subject.uid,
33
+ member: subject.member,
34
+ dataset: placed,
35
+ act: 'write'
36
+ });
37
+ return allowed ? {
38
+ allowed: true
39
+ } : {
40
+ allowed: false,
41
+ permission: datasetRefusalPermission('write', placed)
42
+ };
43
+ }
44
+
45
+ //# sourceMappingURL=dataset-transfer-access.server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/transfer/dataset-transfer-access.server.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 { parseTransferResourceKey } from '@aglyn/aglyn/data-transfer'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type {\n TransferImportAccessSubject,\n TransferImportAccessVerdict,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { datasetRefusalPermission, memberMayActOnDataset } from '../server/dataset-access.server'\n\n/**\n * Who may import into one dataset (AGL-4047): whoever may write it, by where it\n * is placed. A dataset the member cannot see, or that is gone, is the resource's\n * own 404 once the engine reads it, so it answers here as the workspace key does.\n */\nexport async function datasetImportAccess(subject: TransferImportAccessSubject): Promise<TransferImportAccessVerdict> {\n const firestore = firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore\n const datasetId = parseTransferResourceKey(subject.resource).instance ?? ''\n const dataset = datasetId\n ? await firestore.collection('orgs').doc(subject.orgId).collection('datasets').doc(datasetId).get()\n : null\n const placed = dataset?.exists ? dataset.data() : undefined\n const allowed = await memberMayActOnDataset({\n firestore,\n orgId: subject.orgId,\n uid: subject.uid,\n member: subject.member as Partial<AglynOrgMember>,\n dataset: placed,\n act: 'write',\n })\n return allowed ? { allowed: true } : { allowed: false, permission: datasetRefusalPermission('write', placed) }\n}\n"],"names":["parseTransferResourceKey","firebaseAdmin","datasetRefusalPermission","memberMayActOnDataset","datasetImportAccess","subject","firestore","app","datasetId","resource","instance","dataset","collection","doc","orgId","get","placed","exists","data","undefined","allowed","uid","member","act","permission"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,wBAAwB,QAAQ,6BAA4B;AAMrE,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,wBAAwB,EAAEC,qBAAqB,QAAQ,qCAAiC;AAEjG;;;;CAIC,GACD,OAAO,eAAeC,oBAAoBC,OAAoC;QAE1DL;IADlB,MAAMM,YAAYL,cAAcM,GAAG,GAAGD,SAAS;IAC/C,MAAME,aAAYR,qCAAAA,yBAAyBK,QAAQI,QAAQ,EAAEC,QAAQ,YAAnDV,qCAAuD;IACzE,MAAMW,UAAUH,YACZ,MAAMF,UAAUM,UAAU,CAAC,QAAQC,GAAG,CAACR,QAAQS,KAAK,EAAEF,UAAU,CAAC,YAAYC,GAAG,CAACL,WAAWO,GAAG,KAC/F;IACJ,MAAMC,SAASL,CAAAA,2BAAAA,QAASM,MAAM,IAAGN,QAAQO,IAAI,KAAKC;IAClD,MAAMC,UAAU,MAAMjB,sBAAsB;QAC1CG;QACAQ,OAAOT,QAAQS,KAAK;QACpBO,KAAKhB,QAAQgB,GAAG;QAChBC,QAAQjB,QAAQiB,MAAM;QACtBX,SAASK;QACTO,KAAK;IACP;IACA,OAAOH,UAAU;QAAEA,SAAS;IAAK,IAAI;QAAEA,SAAS;QAAOI,YAAYtB,yBAAyB,SAASc;IAAQ;AAC/G"}
@@ -35,7 +35,8 @@ export const DATASET_TRANSFER_HOOKS = {
35
35
  addPicklistValues: async (ctx, picklistId, values)=>(await hooks()).addPicklistValues(ctx, picklistId, values),
36
36
  plan: async (ctx, input)=>(await hooks()).plan(ctx, input),
37
37
  apply: async (ctx, chunk, writer)=>(await hooks()).apply(ctx, chunk, writer),
38
- revert: async (ctx, snapshot, decisions)=>(await hooks()).revert(ctx, snapshot, decisions)
38
+ revert: async (ctx, snapshot, decisions)=>(await hooks()).revert(ctx, snapshot, decisions),
39
+ importAccess: async (subject)=>(await import("./dataset-transfer-access.server.js")).datasetImportAccess(subject)
39
40
  };
40
41
 
41
42
  //# sourceMappingURL=dataset-transfer-resource.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/transfer/dataset-transfer-resource.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 type {\n PluginTransferResource,\n TransferRecordsHooks,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\n\n/**\n * The `data.dataset` server half (AGL-3530) as the console registers it at\n * boot: every hook loads `dataset-transfer.server.ts` — and the Admin SDK and\n * the job engine with it — on its first call, so a console process that\n * never imports or exports a dataset pays nothing for it.\n */\nconst hooks = async (): Promise<TransferRecordsHooks> =>\n (await import('./dataset-transfer.server')).datasetTransferHooks()\n\nexport const DATASET_TRANSFER_HOOKS: PluginTransferResource = {\n fields: async (ctx) => (await hooks()).fields(ctx),\n matchKeys: async (ctx) => {\n const matchKeys = (await hooks()).matchKeys\n return typeof matchKeys === 'function' ? matchKeys(ctx) : { keys: matchKeys }\n },\n count: async (ctx, options) => ((await hooks()).count as NonNullable<TransferRecordsHooks['count']>)(ctx, options),\n readPage: async (ctx, cursor, fieldIds, options) => (await hooks()).readPage(ctx, cursor, fieldIds, options),\n lookup: async (ctx, requests) => (await hooks()).lookup(ctx, requests),\n suggest: async (ctx, request) =>\n ((await hooks()).suggest as NonNullable<TransferRecordsHooks['suggest']>)(ctx, request),\n picklists: async (ctx, picklistIds) =>\n ((await hooks()).picklists as NonNullable<TransferRecordsHooks['picklists']>)(ctx, picklistIds),\n addPicklistValues: async (ctx, picklistId, values) =>\n ((await hooks()).addPicklistValues as NonNullable<TransferRecordsHooks['addPicklistValues']>)(ctx, picklistId, values),\n plan: async (ctx, input) => ((await hooks()).plan as NonNullable<TransferRecordsHooks['plan']>)(ctx, input),\n apply: async (ctx, chunk, writer) => (await hooks()).apply(ctx, chunk, writer),\n revert: async (ctx, snapshot, decisions) => (await hooks()).revert(ctx, snapshot, decisions),\n}\n"],"names":["hooks","datasetTransferHooks","DATASET_TRANSFER_HOOKS","fields","ctx","matchKeys","keys","count","options","readPage","cursor","fieldIds","lookup","requests","suggest","request","picklists","picklistIds","addPicklistValues","picklistId","values","plan","input","apply","chunk","writer","revert","snapshot","decisions"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAOD;;;;;CAKC,GACD,MAAMA,QAAQ,UACZ,AAAC,CAAA,MAAM,MAAM,CAAC,+BAA2B,EAAGC,oBAAoB;AAElE,OAAO,MAAMC,yBAAiD;IAC5DC,QAAQ,OAAOC,MAAQ,AAAC,CAAA,MAAMJ,OAAM,EAAGG,MAAM,CAACC;IAC9CC,WAAW,OAAOD;QAChB,MAAMC,YAAY,AAAC,CAAA,MAAML,OAAM,EAAGK,SAAS;QAC3C,OAAO,OAAOA,cAAc,aAAaA,UAAUD,OAAO;YAAEE,MAAMD;QAAU;IAC9E;IACAE,OAAO,OAAOH,KAAKI,UAAY,AAAC,AAAC,CAAA,MAAMR,OAAM,EAAGO,KAAK,CAAgDH,KAAKI;IAC1GC,UAAU,OAAOL,KAAKM,QAAQC,UAAUH,UAAY,AAAC,CAAA,MAAMR,OAAM,EAAGS,QAAQ,CAACL,KAAKM,QAAQC,UAAUH;IACpGI,QAAQ,OAAOR,KAAKS,WAAa,AAAC,CAAA,MAAMb,OAAM,EAAGY,MAAM,CAACR,KAAKS;IAC7DC,SAAS,OAAOV,KAAKW,UACnB,AAAC,AAAC,CAAA,MAAMf,OAAM,EAAGc,OAAO,CAAkDV,KAAKW;IACjFC,WAAW,OAAOZ,KAAKa,cACrB,AAAC,AAAC,CAAA,MAAMjB,OAAM,EAAGgB,SAAS,CAAoDZ,KAAKa;IACrFC,mBAAmB,OAAOd,KAAKe,YAAYC,SACzC,AAAC,AAAC,CAAA,MAAMpB,OAAM,EAAGkB,iBAAiB,CAA4Dd,KAAKe,YAAYC;IACjHC,MAAM,OAAOjB,KAAKkB,QAAU,AAAC,AAAC,CAAA,MAAMtB,OAAM,EAAGqB,IAAI,CAA+CjB,KAAKkB;IACrGC,OAAO,OAAOnB,KAAKoB,OAAOC,SAAW,AAAC,CAAA,MAAMzB,OAAM,EAAGuB,KAAK,CAACnB,KAAKoB,OAAOC;IACvEC,QAAQ,OAAOtB,KAAKuB,UAAUC,YAAc,AAAC,CAAA,MAAM5B,OAAM,EAAG0B,MAAM,CAACtB,KAAKuB,UAAUC;AACpF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/transfer/dataset-transfer-resource.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 type {\n PluginTransferResource,\n TransferRecordsHooks,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\n\n/**\n * The `data.dataset` server half (AGL-3530) as the console registers it at\n * boot: every hook loads `dataset-transfer.server.ts` — and the Admin SDK and\n * the job engine with it — on its first call, so a console process that\n * never imports or exports a dataset pays nothing for it.\n */\nconst hooks = async (): Promise<TransferRecordsHooks> =>\n (await import('./dataset-transfer.server')).datasetTransferHooks()\n\nexport const DATASET_TRANSFER_HOOKS: PluginTransferResource = {\n fields: async (ctx) => (await hooks()).fields(ctx),\n matchKeys: async (ctx) => {\n const matchKeys = (await hooks()).matchKeys\n return typeof matchKeys === 'function' ? matchKeys(ctx) : { keys: matchKeys }\n },\n count: async (ctx, options) => ((await hooks()).count as NonNullable<TransferRecordsHooks['count']>)(ctx, options),\n readPage: async (ctx, cursor, fieldIds, options) => (await hooks()).readPage(ctx, cursor, fieldIds, options),\n lookup: async (ctx, requests) => (await hooks()).lookup(ctx, requests),\n suggest: async (ctx, request) =>\n ((await hooks()).suggest as NonNullable<TransferRecordsHooks['suggest']>)(ctx, request),\n picklists: async (ctx, picklistIds) =>\n ((await hooks()).picklists as NonNullable<TransferRecordsHooks['picklists']>)(ctx, picklistIds),\n addPicklistValues: async (ctx, picklistId, values) =>\n ((await hooks()).addPicklistValues as NonNullable<TransferRecordsHooks['addPicklistValues']>)(ctx, picklistId, values),\n plan: async (ctx, input) => ((await hooks()).plan as NonNullable<TransferRecordsHooks['plan']>)(ctx, input),\n apply: async (ctx, chunk, writer) => (await hooks()).apply(ctx, chunk, writer),\n revert: async (ctx, snapshot, decisions) => (await hooks()).revert(ctx, snapshot, decisions),\n importAccess: async (subject) => (await import('./dataset-transfer-access.server')).datasetImportAccess(subject),\n}\n"],"names":["hooks","datasetTransferHooks","DATASET_TRANSFER_HOOKS","fields","ctx","matchKeys","keys","count","options","readPage","cursor","fieldIds","lookup","requests","suggest","request","picklists","picklistIds","addPicklistValues","picklistId","values","plan","input","apply","chunk","writer","revert","snapshot","decisions","importAccess","subject","datasetImportAccess"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAOD;;;;;CAKC,GACD,MAAMA,QAAQ,UACZ,AAAC,CAAA,MAAM,MAAM,CAAC,+BAA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