@aglyn/plugins-data 1.13.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 (26) 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.js +173 -128
  5. package/src/lib/components/dataset-schema-dialog.component.js.map +1 -1
  6. package/src/lib/components/host-datasets-card.component.js +1 -1
  7. package/src/lib/components/host-datasets-card.component.js.map +1 -1
  8. package/src/lib/components/use-dataset-writes-blocked.d.ts +5 -4
  9. package/src/lib/components/use-dataset-writes-blocked.js +11 -12
  10. package/src/lib/components/use-dataset-writes-blocked.js.map +1 -1
  11. package/src/lib/model/dataset-record.js +8 -3
  12. package/src/lib/model/dataset-record.js.map +1 -1
  13. package/src/lib/server/dataset-access.server.d.ts +4 -3
  14. package/src/lib/server/dataset-access.server.js +7 -5
  15. package/src/lib/server/dataset-access.server.js.map +1 -1
  16. package/src/lib/server/dataset-site-erasure.d.ts +2 -2
  17. package/src/lib/server/dataset-site-erasure.js +4 -26
  18. package/src/lib/server/dataset-site-erasure.js.map +1 -1
  19. package/src/lib/server/datasets-route.d.ts +2 -0
  20. package/src/lib/server/datasets-route.js +123 -18
  21. package/src/lib/server/datasets-route.js.map +1 -1
  22. package/src/lib/site-bundle/datasets-site-bundle.server.d.ts +4 -2
  23. package/src/lib/site-bundle/datasets-site-bundle.server.js +8 -4
  24. package/src/lib/site-bundle/datasets-site-bundle.server.js.map +1 -1
  25. package/src/lib/transfer/dataset-transfer-access.server.js +3 -3
  26. package/src/lib/transfer/dataset-transfer-access.server.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-data",
3
- "version": "1.13.0",
3
+ "version": "1.14.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,15 +25,15 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.13.0",
29
- "@aglyn/shared-data-mdi": "1.13.0",
30
- "@aglyn/shared-ui-jsx": "1.13.0",
31
- "@aglyn/shared-ui-snackstack": "1.13.0",
32
- "@aglyn/shared-util-http": "1.13.0",
33
- "@aglyn/shared-util-timestamp": "1.13.0",
34
- "@aglyn/tenant-data-admin": "1.13.0",
35
- "@aglyn/tenant-feature-instance": "1.13.0",
36
- "@aglyn/tenant-runtime": "1.13.0",
28
+ "@aglyn/aglyn": "1.14.0",
29
+ "@aglyn/shared-data-mdi": "1.14.0",
30
+ "@aglyn/shared-ui-jsx": "1.14.0",
31
+ "@aglyn/shared-ui-snackstack": "1.14.0",
32
+ "@aglyn/shared-util-http": "1.14.0",
33
+ "@aglyn/shared-util-timestamp": "1.14.0",
34
+ "@aglyn/tenant-data-admin": "1.14.0",
35
+ "@aglyn/tenant-feature-instance": "1.14.0",
36
+ "@aglyn/tenant-runtime": "1.14.0",
37
37
  "@swc/helpers": "0.5.23"
38
38
  },
39
39
  "peerDependencies": {
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { checkDatasetQuota, checkEntitlement, createResourceUid, defaultScopeForNewResource, newResourceScopeFields, scopeCovers } from "@aglyn/aglyn/server";
17
+ */ import { checkDatasetQuota, checkEntitlement, createResourceUid, defaultScopeForNewResource, newResourceScopeFields } from "@aglyn/aglyn/server";
18
+ import { sharingCovers } from "@aglyn/aglyn/app-utils/scope-tokens";
18
19
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
20
  import { resolveInstalledDatasetSchema, sanitizeDatasetSchema, summarizeSchemaChange } from "./dataset-schema.js";
20
21
  /**
@@ -157,7 +158,7 @@ const overDatasetQuota = (limit)=>refuse(403, `Dataset limit reached (${limit})
157
158
  // Relink reference fields onto this org's datasets by display name; what
158
159
  // can't be relinked degrades to text and is reported to the installer.
159
160
  // A candidate has to be visible everywhere the new dataset is, which is
160
- // the rule every reference answers to (`scopeCovers`, AGL-1044): one
161
+ // the rule every reference answers to (`sharingCovers`, AGL-1044): one
161
162
  // pointing at a dataset some of those sites cannot see resolves to nothing
162
163
  // there, and nothing says why. That is also what keeps an install from
163
164
  // binding its reference fields to an agency's internal dataset of the same
@@ -166,7 +167,9 @@ const overDatasetQuota = (limit)=>refuse(403, `Dataset limit reached (${limit})
166
167
  const byLabel = {};
167
168
  for (const entry of datasets.docs){
168
169
  var _entry_get;
169
- if (!scopeCovers(entry.get('visibleTo'), visibleTo)) continue;
170
+ if (!sharingCovers(entry.data(), {
171
+ visibleTo
172
+ })) continue;
170
173
  const label = String((_entry_get = entry.get('displayName')) != null ? _entry_get : '').toLowerCase();
171
174
  if (label && !byLabel[label]) byLabel[label] = entry.id;
172
175
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/artifact/dataset-schema-artifact.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 {\n checkDatasetQuota,\n checkEntitlement,\n createResourceUid,\n defaultScopeForNewResource,\n newResourceScopeFields,\n scopeCovers,\n} from '@aglyn/aglyn/server'\nimport type {\n ArtifactInstallRequest,\n ArtifactLocateRequest,\n ArtifactRefusal,\n ArtifactSnapshot,\n ArtifactSnapshotRequest,\n ArtifactWorkspace,\n InstalledArtifactCopy,\n PluginArtifactOwner,\n PreparedArtifactInstall,\n} from '@aglyn/aglyn/plugin-manager/plugin-artifact-types'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n resolveInstalledDatasetSchema,\n sanitizeDatasetSchema,\n summarizeSchemaChange,\n type PublishedDatasetSchema,\n} from './dataset-schema'\n\n/**\n * A dataset's schema as an installable artifact (AGL-657), answered by the\n * plugin that keeps datasets (AGL-3080).\n *\n * The installer (the marketplace) owns the listing, who may act on it, the\n * purchase, the provenance stamp and the tally, and asks these four answers\n * for everything that touches `orgs/{orgId}/datasets`, which it never reads.\n * Registered from `declarations.console-server.ts` and loaded with the first\n * publish, install or update.\n */\n\nconst refuse = (status: number, error: string): ArtifactRefusal => ({\n ok: false,\n status,\n error,\n})\n\nconst datasetsOf = (orgId: string) =>\n firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('datasets')\n\nconst overDatasetQuota = (limit: number): ArtifactRefusal =>\n refuse(403, `Dataset limit reached (${limit}) — see Billing to upgrade.`)\n\n/**\n * PUBLISHING: an org dataset's SCHEMA, reduced to what travels.\n *\n * Datasets live at `orgs/{orgId}/datasets/{id}` and are org-shared (AGL-237),\n * so the source is named by the publishing org and the dataset's id.\n *\n * Records NEVER travel: `sanitizeDatasetSchema` reads the model, and nothing\n * here touches the `records` subcollection. A dataset's rows are the org's\n * customer data; only the shape is publishable.\n */\nexport async function snapshotDatasetSchema(\n request: ArtifactSnapshotRequest,\n): Promise<ArtifactSnapshot | ArtifactRefusal> {\n const datasets = datasetsOf(request.orgId)\n const datasetSnapshot = await datasets.doc(request.sourceId).get()\n const dataset = datasetSnapshot.data() as any\n if (!datasetSnapshot.exists || dataset?.deletedAt) {\n return refuse(404, 'Unknown dataset')\n }\n // v1 datasets carry a flat `fields: string[]` with no model; publish the\n // derived shape so unmigrated datasets are publishable too (AGL-102 shim,\n // inlined rather than importing core's deriveModelFromFields to keep the\n // sanitizer's input one plain shape).\n const model = dataset?.model?.fields\n ? dataset.model\n : {\n fields: Object.fromEntries(\n (Array.isArray(dataset?.fields) ? dataset.fields : []).map(\n (name: unknown) => [String(name), { name: String(name), type: 'text' }],\n ),\n ),\n order: (Array.isArray(dataset?.fields) ? dataset.fields : []).map(String),\n }\n\n const sanitized = sanitizeDatasetSchema(model)\n if (sanitized.ok === false) return refuse(422, sanitized.error)\n\n // Reference fields name a dataset id that means nothing outside this org,\n // so resolve each target's display name now: the installer relinks by that\n // label (see resolveInstalledDatasetSchema).\n const referenced = new Set(\n Object.values(sanitized.schema.fields)\n .map((field) => field.reference?.datasetId)\n .filter((id): id is string => Boolean(id)),\n )\n if (referenced.size) {\n const labels = new Map<string, string>()\n await Promise.all(\n [...referenced].map(async (id) => {\n const snapshot = await datasets.doc(id).get()\n const label = snapshot.get('displayName')\n if (label) labels.set(id, String(label))\n }),\n )\n for (const field of Object.values(sanitized.schema.fields)) {\n const target = field.reference?.datasetId\n if (target && labels.has(target)) {\n field.reference = {\n ...field.reference,\n datasetLabel: labels.get(target),\n }\n }\n }\n }\n return {\n ok: true,\n content: sanitized.schema,\n facts: { fieldCount: sanitized.schema.order.length },\n }\n}\n\n/** INSTALLING, before the listing is read: datasets are a plan feature. */\nexport async function admitsDatasetSchema(\n workspace: ArtifactWorkspace,\n): Promise<ArtifactRefusal | null> {\n if (!checkEntitlement(workspace.org as any, 'dataStore')) {\n return refuse(403, 'Datasets require a Starter plan or higher')\n }\n return null\n}\n\n/**\n * INSTALLING: a NEW, EMPTY dataset made from the published model.\n *\n * Installing never merges into an existing dataset, because a schema change\n * on a dataset that already holds rows would silently reinterpret live data.\n * Re-installing makes another dataset rather than replacing one, for the same\n * reason.\n *\n * Nothing is written until `commit`, which the installer calls once it has\n * recorded the provenance of exactly the content prepared here.\n */\nexport async function prepareDatasetSchemaInstall(\n request: ArtifactInstallRequest,\n): Promise<PreparedArtifactInstall | ArtifactRefusal> {\n const published = request.published as PublishedDatasetSchema | undefined\n if (!published?.order?.length) {\n return refuse(500, 'Dataset schema version missing')\n }\n const org = request.org as any\n const datasetsRef = datasetsOf(request.orgId)\n\n // Creating a dataset consumes org quota exactly like the console's own\n // create path (AGL-473): installing must not be a way around it.\n // Deliberately counts EVERY dataset the org owns, not the visible ones\n // (AGL-1046). Scoping decides who can see a dataset, never who pays for\n // it: the org owns all of them. Counting per scope would also make a\n // collaborator's remaining quota disagree with the admin's.\n //\n // This is the early answer, so a workspace already at its cap is refused\n // before the installer records any provenance. The one that holds is in\n // `commit`, below.\n const datasets = await datasetsRef.get()\n const quota = checkDatasetQuota(org, datasets.size)\n if (!quota.allowed) return overDatasetQuota(quota.limit)\n\n /**\n * Who the new dataset is shared with. Decided before relinking, because\n * it also decides what a reference field may point at.\n *\n * A dataset schema installs at ORGANIZATION scope and nowhere else\n * (`INSTALL_TARGETS.datasetSchema`), from the organization Marketplace, the\n * one surface that installs anything. The site that surface acts THROUGH\n * only finds the org: the org's first site, not a site anyone is working\n * in, and it never reaches here. So no site is in context, and the dataset\n * starts where a create on an organization page starts: All sites, whatever\n * the org's Default sharing says. Honoring the acting site instead would\n * hide the dataset from every other site, under an install dialog that\n * says it lands on \"the whole organization — every site\" (AGL-2891).\n */\n const visibleTo = defaultScopeForNewResource({\n defaultResourceScope: org?.defaultResourceScope,\n hostId: null,\n })\n\n // Relink reference fields onto this org's datasets by display name; what\n // can't be relinked degrades to text and is reported to the installer.\n // A candidate has to be visible everywhere the new dataset is, which is\n // the rule every reference answers to (`scopeCovers`, AGL-1044): one\n // pointing at a dataset some of those sites cannot see resolves to nothing\n // there, and nothing says why. That is also what keeps an install from\n // binding its reference fields to an agency's internal dataset of the same\n // name (AGL-1046): the display-name collision AGL-1039 fixed on the render\n // path, arriving here instead.\n const byLabel: Record<string, string> = {}\n for (const entry of datasets.docs) {\n if (!scopeCovers(entry.get('visibleTo'), visibleTo)) continue\n const label = String(entry.get('displayName') ?? '').toLowerCase()\n if (label && !byLabel[label]) byLabel[label] = entry.id\n }\n const { schema, degradedFieldIds } = resolveInstalledDatasetSchema(\n published,\n byLabel,\n )\n const datasetId = createResourceUid()\n const { listing } = request\n\n return {\n ok: true,\n // The RELINKED schema, not the published one, is what the base snapshot\n // records (AGL-1015): relinking rewrites reference fields onto this org's\n // datasets, so a base holding the publisher's ids would report every\n // relinked field as a user edit the moment anything is diffed.\n content: schema,\n /**\n * THE ENFORCEMENT POINT (AGL-3454, the AGL-2371 treatment): the count,\n * the decision and the create in ONE transaction.\n *\n * The count above is taken before the installer awaits the provenance\n * write, and every await is a yield: N installs in flight each read the\n * same pre-count, each find room, and each land, and nothing re-counts\n * afterwards. `tx.get` on the aggregate takes a pessimistic lock on the\n * documents the query matched, so the loser of a race retries, re-reads\n * the higher count and is refused, having written nothing.\n *\n * The org document is read outside, as the console's create path reads\n * it: the plan and the purchased add-ons are not client-writable, so\n * locking it would buy contention rather than correctness.\n */\n commit: async (stamp) => {\n const refused = await firebaseAdmin\n .app()\n .firestore()\n .runTransaction<ArtifactRefusal | null>(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.limit)\n tx.create(datasetsRef.doc(datasetId), {\n displayName: String(listing.displayName ?? 'Dataset').slice(0, 120),\n ...(listing.description ? { description: listing.description } : {}),\n // `fields` is the v1 flat list the older editor still reads; keep it\n // in step with the model so both readers agree (AGL-102).\n fields: schema.order,\n model: schema,\n source: stamp.source,\n installedFrom: stamp.installedFrom,\n // The scope decided above. Stamping it is not optional: a dataset\n // with no `visibleTo` matches no scoped read and would render on no\n // site at all.\n //\n // Through the AGL-1478 gate since AGL-1484, so \"every other dataset\n // creator\" is a fact about the type rather than about four object\n // literals that happen to agree today.\n ...newResourceScopeFields(visibleTo),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n return null\n })\n if (refused) return refused\n return {\n ok: true,\n report: { datasetId, fields: schema.order.length, degradedFieldIds },\n }\n },\n }\n}\n\n/**\n * UPDATING: the dataset a listing installed in the site's organization, and\n * what taking the version on offer would do to its records (AGL-1018).\n *\n * The incoming schema is relinked onto THIS org's datasets exactly as install\n * does. The base holds the relinked shape, so diffing the published one would\n * report every reference field as a user edit.\n *\n * A dataset's update is a merge or nothing. Its \"new copy\" would be a whole\n * new dataset, which consumes org quota and lands empty: exactly what the\n * install already does, with the quota check an update does not have.\n */\nexport async function locateInstalledDatasetSchema(\n request: ArtifactLocateRequest,\n): Promise<InstalledArtifactCopy | ArtifactRefusal> {\n if (!request.orgId) return refuse(404, 'Site has no owning organization')\n const datasets = await datasetsOf(request.orgId).get()\n const doc = datasets.docs.find(\n (entry) =>\n entry.get('source.listingId') === request.listingId && !entry.get('deletedAt'),\n )\n if (!doc) return refuse(404, 'Not installed in this organization')\n const byLabel: Record<string, string> = {}\n for (const entry of datasets.docs) {\n const label = String(entry.get('displayName') ?? '').toLowerCase()\n if (label && !byLabel[label]) byLabel[label] = entry.id\n }\n const { schema } = resolveInstalledDatasetSchema(\n request.published as PublishedDatasetSchema,\n byLabel,\n )\n const current = doc.get('model') ?? { order: doc.get('fields') ?? [], fields: {} }\n const summary = summarizeSchemaChange(current as any, schema as any)\n // The count is read for the preview, not estimated: \"3 fields will be\n // removed\" means nothing without \"from 1,240 records\".\n const records = await doc.ref\n .collection('records')\n .count()\n .get()\n .catch(() => null)\n const recordCount = records?.data().count ?? 0\n return {\n ok: true,\n current,\n incoming: schema,\n installedVersion:\n String(doc.get('installedFrom.version') ?? doc.get('source.version') ?? '') || null,\n baseSha: doc.get('installedFrom.sha256') ?? null,\n // A schema change that removes or retypes a field reinterprets rows that\n // already exist. It is applicable, but never without the caller having\n // been told the count and said yes to it specifically.\n impact: {\n preview: {\n schema: {\n added: summary.added,\n removed: summary.removed,\n retyped: summary.retyped,\n additiveOnly: summary.additiveOnly,\n recordCount,\n },\n },\n destructive: !summary.additiveOnly,\n refusal:\n `This update removes or retypes ${\n summary.removed.length + summary.retyped.length\n } field(s) on a dataset holding ${recordCount} record(s).`,\n },\n apply: async ({ content, stamp }) => {\n await doc.ref.set(\n {\n model: content,\n // The v1 flat list the older editor still reads, kept in step.\n fields: (content as PublishedDatasetSchema | undefined)?.order ?? [],\n installedFrom: stamp.installedFrom,\n source: stamp.source,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n },\n }\n}\n\n/** The four answers, as the owner registers them. */\nexport const datasetSchemaArtifactOwner: PluginArtifactOwner = {\n snapshot: snapshotDatasetSchema,\n admits: admitsDatasetSchema,\n prepare: prepareDatasetSchemaInstall,\n locate: locateInstalledDatasetSchema,\n}\n"],"names":["checkDatasetQuota","checkEntitlement","createResourceUid","defaultScopeForNewResource","newResourceScopeFields","scopeCovers","firebaseAdmin","resolveInstalledDatasetSchema","sanitizeDatasetSchema","summarizeSchemaChange","refuse","status","error","ok","datasetsOf","orgId","app","firestore","collection","doc","overDatasetQuota","limit","snapshotDatasetSchema","request","dataset","datasets","datasetSnapshot","sourceId","get","data","exists","deletedAt","model","fields","Object","fromEntries","Array","isArray","map","name","String","type","order","sanitized","referenced","Set","values","schema","field","reference","datasetId","filter","id","Boolean","size","labels","Map","Promise","all","snapshot","label","set","target","has","datasetLabel","content","facts","fieldCount","length","admitsDatasetSchema","workspace","org","prepareDatasetSchemaInstall","published","datasetsRef","quota","allowed","visibleTo","defaultResourceScope","hostId","byLabel","entry","docs","toLowerCase","degradedFieldIds","listing","commit","stamp","refused","runTransaction","tx","live","count","authoritative","create","displayName","slice","description","source","installedFrom","createdAt","FieldValue","serverTimestamp","report","locateInstalledDatasetSchema","find","listingId","current","summary","records","ref","catch","recordCount","incoming","installedVersion","baseSha","impact","preview","added","removed","retyped","additiveOnly","destructive","refusal","apply","updatedAt","merge","datasetSchemaArtifactOwner","admits","prepare","locate"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,0BAA0B,EAC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O;QACL/E,IAAI;QACJ8F;QACAM,UAAUlE;QACVmE,kBACE1E,QAAOrB,SAAAA,YAAAA,IAAIS,GAAG,CAAC,oCAART,YAAoCA,IAAIS,GAAG,CAAC,6BAA5CT,QAAiE,OAAO;QACjFgG,OAAO,GAAEhG,YAAAA,IAAIS,GAAG,CAAC,mCAART,YAAmC;QAC5C,yEAAyE;QACzE,uEAAuE;QACvE,uDAAuD;QACvDiG,QAAQ;YACNC,SAAS;gBACPtE,QAAQ;oBACNuE,OAAOV,QAAQU,KAAK;oBACpBC,SAASX,QAAQW,OAAO;oBACxBC,SAASZ,QAAQY,OAAO;oBACxBC,cAAcb,QAAQa,YAAY;oBAClCT;gBACF;YACF;YACAU,aAAa,CAACd,QAAQa,YAAY;YAClCE,SACE,CAAC,+BAA+B,EAC9Bf,QAAQW,OAAO,CAACnD,MAAM,GAAGwC,QAAQY,OAAO,CAACpD,MAAM,CAChD,+BAA+B,EAAE4C,YAAY,WAAW,CAAC;QAC9D;QACAY,OAAO,OAAO,EAAE3D,OAAO,EAAEsB,KAAK,EAAE;;YAC9B,MAAMpE,IAAI2F,GAAG,CAACjD,GAAG,CACf;gBACE7B,OAAOiC;gBACP,+DAA+D;gBAC/DhC,MAAM,UAAGgC,2BAAD,AAACA,QAAgDvB,KAAK,mBAAI,EAAE;gBACpEyD,eAAeZ,MAAMY,aAAa;gBAClCD,QAAQX,MAAMW,MAAM;gBACpB2B,WAAWvH,cAAcW,SAAS,CAACoF,UAAU,CAACC,eAAe;YAC/D,GACA;gBAAEwB,OAAO;YAAK;QAElB;IACF;AACF;AAEA,mDAAmD,GACnD,OAAO,MAAMC,6BAAkD;IAC7DpE,UAAUrC;IACV0G,QAAQ3D;IACR4D,SAASzD;IACT0D,QAAQ1B;AACV,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/artifact/dataset-schema-artifact.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 {\n checkDatasetQuota,\n checkEntitlement,\n createResourceUid,\n defaultScopeForNewResource,\n newResourceScopeFields,\n} from '@aglyn/aglyn/server'\nimport { sharingCovers } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type {\n ArtifactInstallRequest,\n ArtifactLocateRequest,\n ArtifactRefusal,\n ArtifactSnapshot,\n ArtifactSnapshotRequest,\n ArtifactWorkspace,\n InstalledArtifactCopy,\n PluginArtifactOwner,\n PreparedArtifactInstall,\n} from '@aglyn/aglyn/plugin-manager/plugin-artifact-types'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n resolveInstalledDatasetSchema,\n sanitizeDatasetSchema,\n summarizeSchemaChange,\n type PublishedDatasetSchema,\n} from './dataset-schema'\n\n/**\n * A dataset's schema as an installable artifact (AGL-657), answered by the\n * plugin that keeps datasets (AGL-3080).\n *\n * The installer (the marketplace) owns the listing, who may act on it, the\n * purchase, the provenance stamp and the tally, and asks these four answers\n * for everything that touches `orgs/{orgId}/datasets`, which it never reads.\n * Registered from `declarations.console-server.ts` and loaded with the first\n * publish, install or update.\n */\n\nconst refuse = (status: number, error: string): ArtifactRefusal => ({\n ok: false,\n status,\n error,\n})\n\nconst datasetsOf = (orgId: string) =>\n firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('datasets')\n\nconst overDatasetQuota = (limit: number): ArtifactRefusal =>\n refuse(403, `Dataset limit reached (${limit}) — see Billing to upgrade.`)\n\n/**\n * PUBLISHING: an org dataset's SCHEMA, reduced to what travels.\n *\n * Datasets live at `orgs/{orgId}/datasets/{id}` and are org-shared (AGL-237),\n * so the source is named by the publishing org and the dataset's id.\n *\n * Records NEVER travel: `sanitizeDatasetSchema` reads the model, and nothing\n * here touches the `records` subcollection. A dataset's rows are the org's\n * customer data; only the shape is publishable.\n */\nexport async function snapshotDatasetSchema(\n request: ArtifactSnapshotRequest,\n): Promise<ArtifactSnapshot | ArtifactRefusal> {\n const datasets = datasetsOf(request.orgId)\n const datasetSnapshot = await datasets.doc(request.sourceId).get()\n const dataset = datasetSnapshot.data() as any\n if (!datasetSnapshot.exists || dataset?.deletedAt) {\n return refuse(404, 'Unknown dataset')\n }\n // v1 datasets carry a flat `fields: string[]` with no model; publish the\n // derived shape so unmigrated datasets are publishable too (AGL-102 shim,\n // inlined rather than importing core's deriveModelFromFields to keep the\n // sanitizer's input one plain shape).\n const model = dataset?.model?.fields\n ? dataset.model\n : {\n fields: Object.fromEntries(\n (Array.isArray(dataset?.fields) ? dataset.fields : []).map(\n (name: unknown) => [String(name), { name: String(name), type: 'text' }],\n ),\n ),\n order: (Array.isArray(dataset?.fields) ? dataset.fields : []).map(String),\n }\n\n const sanitized = sanitizeDatasetSchema(model)\n if (sanitized.ok === false) return refuse(422, sanitized.error)\n\n // Reference fields name a dataset id that means nothing outside this org,\n // so resolve each target's display name now: the installer relinks by that\n // label (see resolveInstalledDatasetSchema).\n const referenced = new Set(\n Object.values(sanitized.schema.fields)\n .map((field) => field.reference?.datasetId)\n .filter((id): id is string => Boolean(id)),\n )\n if (referenced.size) {\n const labels = new Map<string, string>()\n await Promise.all(\n [...referenced].map(async (id) => {\n const snapshot = await datasets.doc(id).get()\n const label = snapshot.get('displayName')\n if (label) labels.set(id, String(label))\n }),\n )\n for (const field of Object.values(sanitized.schema.fields)) {\n const target = field.reference?.datasetId\n if (target && labels.has(target)) {\n field.reference = {\n ...field.reference,\n datasetLabel: labels.get(target),\n }\n }\n }\n }\n return {\n ok: true,\n content: sanitized.schema,\n facts: { fieldCount: sanitized.schema.order.length },\n }\n}\n\n/** INSTALLING, before the listing is read: datasets are a plan feature. */\nexport async function admitsDatasetSchema(\n workspace: ArtifactWorkspace,\n): Promise<ArtifactRefusal | null> {\n if (!checkEntitlement(workspace.org as any, 'dataStore')) {\n return refuse(403, 'Datasets require a Starter plan or higher')\n }\n return null\n}\n\n/**\n * INSTALLING: a NEW, EMPTY dataset made from the published model.\n *\n * Installing never merges into an existing dataset, because a schema change\n * on a dataset that already holds rows would silently reinterpret live data.\n * Re-installing makes another dataset rather than replacing one, for the same\n * reason.\n *\n * Nothing is written until `commit`, which the installer calls once it has\n * recorded the provenance of exactly the content prepared here.\n */\nexport async function prepareDatasetSchemaInstall(\n request: ArtifactInstallRequest,\n): Promise<PreparedArtifactInstall | ArtifactRefusal> {\n const published = request.published as PublishedDatasetSchema | undefined\n if (!published?.order?.length) {\n return refuse(500, 'Dataset schema version missing')\n }\n const org = request.org as any\n const datasetsRef = datasetsOf(request.orgId)\n\n // Creating a dataset consumes org quota exactly like the console's own\n // create path (AGL-473): installing must not be a way around it.\n // Deliberately counts EVERY dataset the org owns, not the visible ones\n // (AGL-1046). Scoping decides who can see a dataset, never who pays for\n // it: the org owns all of them. Counting per scope would also make a\n // collaborator's remaining quota disagree with the admin's.\n //\n // This is the early answer, so a workspace already at its cap is refused\n // before the installer records any provenance. The one that holds is in\n // `commit`, below.\n const datasets = await datasetsRef.get()\n const quota = checkDatasetQuota(org, datasets.size)\n if (!quota.allowed) return overDatasetQuota(quota.limit)\n\n /**\n * Who the new dataset is shared with. Decided before relinking, because\n * it also decides what a reference field may point at.\n *\n * A dataset schema installs at ORGANIZATION scope and nowhere else\n * (`INSTALL_TARGETS.datasetSchema`), from the organization Marketplace, the\n * one surface that installs anything. The site that surface acts THROUGH\n * only finds the org: the org's first site, not a site anyone is working\n * in, and it never reaches here. So no site is in context, and the dataset\n * starts where a create on an organization page starts: All sites, whatever\n * the org's Default sharing says. Honoring the acting site instead would\n * hide the dataset from every other site, under an install dialog that\n * says it lands on \"the whole organization — every site\" (AGL-2891).\n */\n const visibleTo = defaultScopeForNewResource({\n defaultResourceScope: org?.defaultResourceScope,\n hostId: null,\n })\n\n // Relink reference fields onto this org's datasets by display name; what\n // can't be relinked degrades to text and is reported to the installer.\n // A candidate has to be visible everywhere the new dataset is, which is\n // the rule every reference answers to (`sharingCovers`, AGL-1044): one\n // pointing at a dataset some of those sites cannot see resolves to nothing\n // there, and nothing says why. That is also what keeps an install from\n // binding its reference fields to an agency's internal dataset of the same\n // name (AGL-1046): the display-name collision AGL-1039 fixed on the render\n // path, arriving here instead.\n const byLabel: Record<string, string> = {}\n for (const entry of datasets.docs) {\n if (!sharingCovers(entry.data(), { visibleTo })) continue\n const label = String(entry.get('displayName') ?? '').toLowerCase()\n if (label && !byLabel[label]) byLabel[label] = entry.id\n }\n const { schema, degradedFieldIds } = resolveInstalledDatasetSchema(\n published,\n byLabel,\n )\n const datasetId = createResourceUid()\n const { listing } = request\n\n return {\n ok: true,\n // The RELINKED schema, not the published one, is what the base snapshot\n // records (AGL-1015): relinking rewrites reference fields onto this org's\n // datasets, so a base holding the publisher's ids would report every\n // relinked field as a user edit the moment anything is diffed.\n content: schema,\n /**\n * THE ENFORCEMENT POINT (AGL-3454, the AGL-2371 treatment): the count,\n * the decision and the create in ONE transaction.\n *\n * The count above is taken before the installer awaits the provenance\n * write, and every await is a yield: N installs in flight each read the\n * same pre-count, each find room, and each land, and nothing re-counts\n * afterwards. `tx.get` on the aggregate takes a pessimistic lock on the\n * documents the query matched, so the loser of a race retries, re-reads\n * the higher count and is refused, having written nothing.\n *\n * The org document is read outside, as the console's create path reads\n * it: the plan and the purchased add-ons are not client-writable, so\n * locking it would buy contention rather than correctness.\n */\n commit: async (stamp) => {\n const refused = await firebaseAdmin\n .app()\n .firestore()\n .runTransaction<ArtifactRefusal | null>(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.limit)\n tx.create(datasetsRef.doc(datasetId), {\n displayName: String(listing.displayName ?? 'Dataset').slice(0, 120),\n ...(listing.description ? { description: listing.description } : {}),\n // `fields` is the v1 flat list the older editor still reads; keep it\n // in step with the model so both readers agree (AGL-102).\n fields: schema.order,\n model: schema,\n source: stamp.source,\n installedFrom: stamp.installedFrom,\n // The scope decided above. Stamping it is not optional: a dataset\n // with no `visibleTo` matches no scoped read and would render on no\n // site at all.\n //\n // Through the AGL-1478 gate since AGL-1484, so \"every other dataset\n // creator\" is a fact about the type rather than about four object\n // literals that happen to agree today.\n ...newResourceScopeFields(visibleTo),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n return null\n })\n if (refused) return refused\n return {\n ok: true,\n report: { datasetId, fields: schema.order.length, degradedFieldIds },\n }\n },\n }\n}\n\n/**\n * UPDATING: the dataset a listing installed in the site's organization, and\n * what taking the version on offer would do to its records (AGL-1018).\n *\n * The incoming schema is relinked onto THIS org's datasets exactly as install\n * does. The base holds the relinked shape, so diffing the published one would\n * report every reference field as a user edit.\n *\n * A dataset's update is a merge or nothing. Its \"new copy\" would be a whole\n * new dataset, which consumes org quota and lands empty: exactly what the\n * install already does, with the quota check an update does not have.\n */\nexport async function locateInstalledDatasetSchema(\n request: ArtifactLocateRequest,\n): Promise<InstalledArtifactCopy | ArtifactRefusal> {\n if (!request.orgId) return refuse(404, 'Site has no owning organization')\n const datasets = await datasetsOf(request.orgId).get()\n const doc = datasets.docs.find(\n (entry) =>\n entry.get('source.listingId') === request.listingId && !entry.get('deletedAt'),\n )\n if (!doc) return refuse(404, 'Not installed in this organization')\n const byLabel: Record<string, string> = {}\n for (const entry of datasets.docs) {\n const label = String(entry.get('displayName') ?? '').toLowerCase()\n if (label && !byLabel[label]) byLabel[label] = entry.id\n }\n const { schema } = resolveInstalledDatasetSchema(\n request.published as PublishedDatasetSchema,\n byLabel,\n )\n const current = doc.get('model') ?? { order: doc.get('fields') ?? [], fields: {} }\n const summary = summarizeSchemaChange(current as any, schema as any)\n // The count is read for the preview, not estimated: \"3 fields will be\n // removed\" means nothing without \"from 1,240 records\".\n const records = await doc.ref\n .collection('records')\n .count()\n .get()\n .catch(() => null)\n const recordCount = records?.data().count ?? 0\n return {\n ok: true,\n current,\n incoming: schema,\n installedVersion:\n String(doc.get('installedFrom.version') ?? doc.get('source.version') ?? '') || null,\n baseSha: doc.get('installedFrom.sha256') ?? null,\n // A schema change that removes or retypes a field reinterprets rows that\n // already exist. It is applicable, but never without the caller having\n // been told the count and said yes to it specifically.\n impact: {\n preview: {\n schema: {\n added: summary.added,\n removed: summary.removed,\n retyped: summary.retyped,\n additiveOnly: summary.additiveOnly,\n recordCount,\n },\n },\n destructive: !summary.additiveOnly,\n refusal:\n `This update removes or retypes ${\n summary.removed.length + summary.retyped.length\n } field(s) on a dataset holding ${recordCount} record(s).`,\n },\n apply: async ({ content, stamp }) => {\n await doc.ref.set(\n {\n model: content,\n // The v1 flat list the older editor still reads, kept in step.\n fields: (content as PublishedDatasetSchema | undefined)?.order ?? [],\n installedFrom: stamp.installedFrom,\n source: stamp.source,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n },\n }\n}\n\n/** The four answers, as the owner registers them. */\nexport const datasetSchemaArtifactOwner: PluginArtifactOwner = {\n snapshot: snapshotDatasetSchema,\n admits: admitsDatasetSchema,\n prepare: prepareDatasetSchemaInstall,\n locate: locateInstalledDatasetSchema,\n}\n"],"names":["checkDatasetQuota","checkEntitlement","createResourceUid","defaultScopeForNewResource","newResourceScopeFields","sharingCovers","firebaseAdmin","resolveInstalledDatasetSchema","sanitizeDatasetSchema","summarizeSchemaChange","refuse","status","error","ok","datasetsOf","orgId","app","firestore","collection","doc","overDatasetQuota","limit","snapshotDatasetSchema","request","dataset","datasets","datasetSnapshot","sourceId","get","data","exists","deletedAt","model","fields","Object","fromEntries","Array","isArray","map","name","String","type","order","sanitized","referenced","Set","values","schema","field","reference","datasetId","filter","id","Boolean","size","labels","Map","Promise","all","snapshot","label","set","target","has","datasetLabel","content","facts","fieldCount","length","admitsDatasetSchema","workspace","org","prepareDatasetSchemaInstall","published","datasetsRef","quota","allowed","visibleTo","defaultResourceScope","hostId","byLabel","entry","docs","toLowerCase","degradedFieldIds","listing","commit","stamp","refused","runTransaction","tx","live","count","authoritative","create","displayName","slice","description","source","installedFrom","createdAt","FieldValue","serverTimestamp","report","locateInstalledDatasetSchema","find","listingId","current","summary","records","ref","catch","recordCount","incoming","installedVersion","baseSha","impact","preview","added","removed","retyped","additiveOnly","destructive","refusal","apply","updatedAt","merge","datasetSchemaArtifactOwner","admits","prepare","locate"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,0BAA0B,EAC1BC,sBAAsB,QACjB,sBAAqB;AAC5B,SAASC,aAAa,QAAQ,sCAAqC;AAYnE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SACEC,6BAA6B,EAC7BC,qBAAqB,EACrBC,qBAAqB,QAEhB,sBAAkB;AAEzB;;;;;;;;;CASC,GAED,MAAMC,SAAS,CAACC,QAAgBC,QAAoC,CAAA;QAClEC,IAAI;QACJF;QACAC;IACF,CAAA;AAEA,MAAME,aAAa,CAACC,QAClBT,cAAcU,GAAG,GAAGC,SAAS,GAAGC,UAAU,CAAC,QAAQC,GAAG,CAACJ,OAAOG,UAAU,CAAC;AAE3E,MAAME,mBAAmB,CAACC,QACxBX,OAAO,KAAK,CAAC,uBAAuB,EAAEW,MAAM,2BAA2B,CAAC;AAE1E;;;;;;;;;CASC,GACD,OAAO,eAAeC,sBACpBC,OAAgC;QAYlBC;IAVd,MAAMC,WAAWX,WAAWS,QAAQR,KAAK;IACzC,MAAMW,kBAAkB,MAAMD,SAASN,GAAG,CAACI,QAAQI,QAAQ,EAAEC,GAAG;IAChE,MAAMJ,UAAUE,gBAAgBG,IAAI;IACpC,IAAI,CAACH,gBAAgBI,MAAM,KAAIN,2BAAAA,QAASO,SAAS,GAAE;QAC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