@aglyn/plugins-data 1.0.0-beta.291 → 1.0.0-beta.293

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-data",
3
- "version": "1.0.0-beta.291",
3
+ "version": "1.0.0-beta.293",
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.0.0-beta.291",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.291",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.291",
31
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.291",
32
- "@aglyn/shared-util-http": "1.0.0-beta.291",
33
- "@aglyn/shared-util-timestamp": "1.0.0-beta.291",
34
- "@aglyn/tenant-data-admin": "1.0.0-beta.291",
35
- "@aglyn/tenant-feature-instance": "1.0.0-beta.291",
36
- "@aglyn/tenant-runtime": "1.0.0-beta.291",
28
+ "@aglyn/aglyn": "1.0.0-beta.293",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.293",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.293",
31
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.293",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.293",
33
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.293",
34
+ "@aglyn/tenant-data-admin": "1.0.0-beta.293",
35
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.293",
36
+ "@aglyn/tenant-runtime": "1.0.0-beta.293",
37
37
  "@swc/helpers": "0.5.23"
38
38
  },
39
39
  "peerDependencies": {
@@ -25,8 +25,8 @@ import { type DatasetDraftFieldType } from './dataset-drafts';
25
25
  * into a page, so the owner edits one row and every page listing it follows.
26
26
  * Its item is written by this plugin's `dataset` draft writer, so every rule
27
27
  * is the writer's: `dataStore` (Starter and up), `datasetsPerOrg`,
28
- * `release_data_store`, the member's role, and the model every record is
29
- * held to.
28
+ * `release_data_store`, the member's "Manage data" (`data.manage`), and the
29
+ * model every record is held to.
30
30
  *
31
31
  * The arguments are flat, as the contract requires: each field as
32
32
  * `Name:type`, and each record as its values in field order joined by ` | `,
@@ -26,8 +26,8 @@ import { DATASET_DRAFT_FIELD_NAME_MAX, DATASET_DRAFT_FIELD_TYPES, DATASET_DRAFT_
26
26
  * into a page, so the owner edits one row and every page listing it follows.
27
27
  * Its item is written by this plugin's `dataset` draft writer, so every rule
28
28
  * is the writer's: `dataStore` (Starter and up), `datasetsPerOrg`,
29
- * `release_data_store`, the member's role, and the model every record is
30
- * held to.
29
+ * `release_data_store`, the member's "Manage data" (`data.manage`), and the
30
+ * model every record is held to.
31
31
  *
32
32
  * The arguments are flat, as the contract requires: each field as
33
33
  * `Name:type`, and each record as its values in field order joined by ` | `,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-ai-capability.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 registerPluginAiCapability,\n type PluginAiCapability,\n type PluginAiCapabilityArgs,\n} from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n DATASET_DRAFT_FIELD_NAME_MAX,\n DATASET_DRAFT_FIELD_TYPES,\n DATASET_DRAFT_FIELDS_MAX,\n DATASET_DRAFT_NAME_MAX,\n DATASET_DRAFT_RECORDS_MAX,\n DATASET_DRAFT_RESOURCE,\n type DatasetDraftFieldType,\n} from './dataset-drafts'\n\n/**\n * WHAT AN AI BUILD CAN MAKE IN DATA (AGL-3616): a dataset with typed fields\n * and its first records.\n *\n * The capability the AI plugin's build planner offers for \"add a menu page\"\n * or \"list our team\": structured content kept as records rather than written\n * into a page, so the owner edits one row and every page listing it follows.\n * Its item is written by this plugin's `dataset` draft writer, so every rule\n * is the writer's: `dataStore` (Starter and up), `datasetsPerOrg`,\n * `release_data_store`, the member's role, and the model every record is\n * held to.\n *\n * The arguments are flat, as the contract requires: each field as\n * `Name:type`, and each record as its values in field order joined by ` | `,\n * which `draftContent` turns into the writer's records. The planner fills\n * them in, so no model runs (`estimateCredits` 0).\n */\n\n/** The operation's name in a build plan. */\nexport const DATASET_AI_OP = 'dataset'\n\n/** What separates one value of a record from the next in its argument. */\nexport const DATASET_AI_VALUE_SEPARATOR = ' | '\n\n/** What separates the items of a list value inside one record value. */\nconst LIST_SEPARATOR = /\\s*;\\s*/\n\n/** The longest one record's argument may be. */\nconst DATASET_AI_RECORD_MAX = 600\n\nconst TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** `\"Price:number\"` → `{ name: 'Price', type: 'number' }`; a type it does not know reads as text. */\nexport function datasetAiFieldOf(spec: string): { name: string; type: DatasetDraftFieldType } {\n const at = spec.lastIndexOf(':')\n const type = at > 0 ? spec.slice(at + 1).trim().toLowerCase() : ''\n if (at > 0 && (TYPES as readonly string[]).includes(type)) {\n return { name: spec.slice(0, at).trim(), type: type as DatasetDraftFieldType }\n }\n return { name: spec.trim(), type: 'text' }\n}\n\n/** The writer's content for an item. Pure. */\nexport function datasetDraftContentFromArgs(args: PluginAiCapabilityArgs): Readonly<Record<string, unknown>> {\n const specs = Array.isArray(args['fields']) ? (args['fields'] as readonly string[]) : []\n const fields = specs.map(datasetAiFieldOf).filter((field) => field.name)\n const rows = Array.isArray(args['records']) ? (args['records'] as readonly string[]) : []\n const records = rows.map((row) => {\n const values = row.split(DATASET_AI_VALUE_SEPARATOR.trim()).map((value) => value.trim())\n const record: Record<string, unknown> = {}\n fields.forEach((field, index) => {\n const value = values[index] ?? ''\n // A page is picked by the owner from the site's pages (AGL-3763); the\n // planner has no page ids to give, so it never seeds one.\n if (!value || field.type === 'page') return\n record[field.name] = field.type === 'list' ? value.split(LIST_SEPARATOR).filter(Boolean) : value\n })\n return record\n })\n const address = typeof args['pageAddressFrom'] === 'string' ? args['pageAddressFrom'].trim() : ''\n return {\n ...(typeof args['name'] === 'string' ? { name: args['name'] } : {}),\n fields,\n records: records.filter((record) => Object.keys(record).length),\n ...(address ? { pageAddressFrom: address } : {}),\n }\n}\n\nexport const datasetAiCapability: PluginAiCapability = {\n op: DATASET_AI_OP,\n noun: 'dataset',\n where: 'Data, as a dataset with its first records',\n intents: [\n 'a list of like things kept as records the owner edits in one place — a menu, a team, services, portfolio pieces, events, FAQs, locations — with typed fields and its first records from the request',\n ],\n argsSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'What the dataset is called, e.g. \"Menu\" or \"Team\".', maxLength: DATASET_DRAFT_NAME_MAX },\n fields: {\n type: 'array',\n description: `Each field as Name:type, type one of ${TYPES.join('|')}; a date or time is text, written the way a visitor reads it; a page field links each record to one of the site's pages, which the owner picks, so leave its values empty. The first text field names each record.`,\n items: { type: 'string', maxLength: DATASET_DRAFT_FIELD_NAME_MAX + 10 },\n maxItems: DATASET_DRAFT_FIELDS_MAX,\n },\n records: {\n type: 'array',\n description:\n `The first records, each its values in field order joined by \"${DATASET_AI_VALUE_SEPARATOR}\" (a list's items joined by \"; \"), from what the request says. ` +\n 'Leave a value empty rather than invent it: never a review, testimonial, rating, quote, price or person’s name the request does not give.',\n items: { type: 'string', maxLength: DATASET_AI_RECORD_MAX },\n maxItems: DATASET_DRAFT_RECORDS_MAX,\n },\n pageAddressFrom: {\n type: 'string',\n description: 'Only where a page shows each record at its own address: the text field its address is made from, e.g. \"Name\".',\n maxLength: DATASET_DRAFT_FIELD_NAME_MAX,\n },\n },\n required: ['name', 'fields'],\n additionalProperties: false,\n },\n maxPerPlan: 3,\n // Free includes no data store (`datasetsPerOrg: 0`).\n freeAllowed: false,\n feature: 'dataStore',\n quota: 'datasetsPerOrg',\n draftResource: DATASET_DRAFT_RESOURCE,\n // Written without a model: the planner already filled the arguments.\n estimateCredits: () => 0,\n degrade: 'omit',\n draftContent: (item) => datasetDraftContentFromArgs(item.args),\n}\n\n/**\n * Registers the capability; the console surface calls it beside the writer,\n * since only the console runs AI jobs (AGL-3026). Idempotent.\n */\nexport function registerDatasetAiCapability(): void {\n registerPluginAiCapability(datasetAiCapability, { pluginId: BUNDLE_ID })\n}\n"],"names":["registerPluginAiCapability","BUNDLE_ID","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_FIELD_TYPES","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_RESOURCE","DATASET_AI_OP","DATASET_AI_VALUE_SEPARATOR","LIST_SEPARATOR","DATASET_AI_RECORD_MAX","TYPES","Object","keys","datasetAiFieldOf","spec","at","lastIndexOf","type","slice","trim","toLowerCase","includes","name","datasetDraftContentFromArgs","args","specs","Array","isArray","fields","map","filter","field","rows","records","row","values","split","value","record","forEach","index","Boolean","address","length","pageAddressFrom","datasetAiCapability","op","noun","where","intents","argsSchema","properties","description","maxLength","join","items","maxItems","required","additionalProperties","maxPerPlan","freeAllowed","feature","quota","draftResource","estimateCredits","degrade","draftContent","item","registerDatasetAiCapability","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,0BAA0B,QAGrB,qDAAoD;AAC3D,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,4BAA4B,EAC5BC,yBAAyB,EACzBC,wBAAwB,EACxBC,sBAAsB,EACtBC,yBAAyB,EACzBC,sBAAsB,QAEjB,sBAA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BACbC,WAAWrD;YACb;QACF;QACAyD,UAAU;YAAC;YAAQ;SAAS;QAC5BC,sBAAsB;IACxB;IACAC,YAAY;IACZ,qDAAqD;IACrDC,aAAa;IACbC,SAAS;IACTC,OAAO;IACPC,eAAe1D;IACf,qEAAqE;IACrE2D,iBAAiB,IAAM;IACvBC,SAAS;IACTC,cAAc,CAACC,OAAS5C,4BAA4B4C,KAAK3C,IAAI;AAC/D,EAAC;AAED;;;CAGC,GACD,OAAO,SAAS4C;IACdtE,2BAA2B+C,qBAAqB;QAAEwB,UAAUtE;IAAU;AACxE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-ai-capability.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 registerPluginAiCapability,\n type PluginAiCapability,\n type PluginAiCapabilityArgs,\n} from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n DATASET_DRAFT_FIELD_NAME_MAX,\n DATASET_DRAFT_FIELD_TYPES,\n DATASET_DRAFT_FIELDS_MAX,\n DATASET_DRAFT_NAME_MAX,\n DATASET_DRAFT_RECORDS_MAX,\n DATASET_DRAFT_RESOURCE,\n type DatasetDraftFieldType,\n} from './dataset-drafts'\n\n/**\n * WHAT AN AI BUILD CAN MAKE IN DATA (AGL-3616): a dataset with typed fields\n * and its first records.\n *\n * The capability the AI plugin's build planner offers for \"add a menu page\"\n * or \"list our team\": structured content kept as records rather than written\n * into a page, so the owner edits one row and every page listing it follows.\n * Its item is written by this plugin's `dataset` draft writer, so every rule\n * is the writer's: `dataStore` (Starter and up), `datasetsPerOrg`,\n * `release_data_store`, the member's \"Manage data\" (`data.manage`), and the\n * model every record is held to.\n *\n * The arguments are flat, as the contract requires: each field as\n * `Name:type`, and each record as its values in field order joined by ` | `,\n * which `draftContent` turns into the writer's records. The planner fills\n * them in, so no model runs (`estimateCredits` 0).\n */\n\n/** The operation's name in a build plan. */\nexport const DATASET_AI_OP = 'dataset'\n\n/** What separates one value of a record from the next in its argument. */\nexport const DATASET_AI_VALUE_SEPARATOR = ' | '\n\n/** What separates the items of a list value inside one record value. */\nconst LIST_SEPARATOR = /\\s*;\\s*/\n\n/** The longest one record's argument may be. */\nconst DATASET_AI_RECORD_MAX = 600\n\nconst TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** `\"Price:number\"` → `{ name: 'Price', type: 'number' }`; a type it does not know reads as text. */\nexport function datasetAiFieldOf(spec: string): { name: string; type: DatasetDraftFieldType } {\n const at = spec.lastIndexOf(':')\n const type = at > 0 ? spec.slice(at + 1).trim().toLowerCase() : ''\n if (at > 0 && (TYPES as readonly string[]).includes(type)) {\n return { name: spec.slice(0, at).trim(), type: type as DatasetDraftFieldType }\n }\n return { name: spec.trim(), type: 'text' }\n}\n\n/** The writer's content for an item. Pure. */\nexport function datasetDraftContentFromArgs(args: PluginAiCapabilityArgs): Readonly<Record<string, unknown>> {\n const specs = Array.isArray(args['fields']) ? (args['fields'] as readonly string[]) : []\n const fields = specs.map(datasetAiFieldOf).filter((field) => field.name)\n const rows = Array.isArray(args['records']) ? (args['records'] as readonly string[]) : []\n const records = rows.map((row) => {\n const values = row.split(DATASET_AI_VALUE_SEPARATOR.trim()).map((value) => value.trim())\n const record: Record<string, unknown> = {}\n fields.forEach((field, index) => {\n const value = values[index] ?? ''\n // A page is picked by the owner from the site's pages (AGL-3763); the\n // planner has no page ids to give, so it never seeds one.\n if (!value || field.type === 'page') return\n record[field.name] = field.type === 'list' ? value.split(LIST_SEPARATOR).filter(Boolean) : value\n })\n return record\n })\n const address = typeof args['pageAddressFrom'] === 'string' ? args['pageAddressFrom'].trim() : ''\n return {\n ...(typeof args['name'] === 'string' ? { name: args['name'] } : {}),\n fields,\n records: records.filter((record) => Object.keys(record).length),\n ...(address ? { pageAddressFrom: address } : {}),\n }\n}\n\nexport const datasetAiCapability: PluginAiCapability = {\n op: DATASET_AI_OP,\n noun: 'dataset',\n where: 'Data, as a dataset with its first records',\n intents: [\n 'a list of like things kept as records the owner edits in one place — a menu, a team, services, portfolio pieces, events, FAQs, locations — with typed fields and its first records from the request',\n ],\n argsSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'What the dataset is called, e.g. \"Menu\" or \"Team\".', maxLength: DATASET_DRAFT_NAME_MAX },\n fields: {\n type: 'array',\n description: `Each field as Name:type, type one of ${TYPES.join('|')}; a date or time is text, written the way a visitor reads it; a page field links each record to one of the site's pages, which the owner picks, so leave its values empty. The first text field names each record.`,\n items: { type: 'string', maxLength: DATASET_DRAFT_FIELD_NAME_MAX + 10 },\n maxItems: DATASET_DRAFT_FIELDS_MAX,\n },\n records: {\n type: 'array',\n description:\n `The first records, each its values in field order joined by \"${DATASET_AI_VALUE_SEPARATOR}\" (a list's items joined by \"; \"), from what the request says. ` +\n 'Leave a value empty rather than invent it: never a review, testimonial, rating, quote, price or person’s name the request does not give.',\n items: { type: 'string', maxLength: DATASET_AI_RECORD_MAX },\n maxItems: DATASET_DRAFT_RECORDS_MAX,\n },\n pageAddressFrom: {\n type: 'string',\n description: 'Only where a page shows each record at its own address: the text field its address is made from, e.g. \"Name\".',\n maxLength: DATASET_DRAFT_FIELD_NAME_MAX,\n },\n },\n required: ['name', 'fields'],\n additionalProperties: false,\n },\n maxPerPlan: 3,\n // Free includes no data store (`datasetsPerOrg: 0`).\n freeAllowed: false,\n feature: 'dataStore',\n quota: 'datasetsPerOrg',\n draftResource: DATASET_DRAFT_RESOURCE,\n // Written without a model: the planner already filled the arguments.\n estimateCredits: () => 0,\n degrade: 'omit',\n draftContent: (item) => datasetDraftContentFromArgs(item.args),\n}\n\n/**\n * Registers the capability; the console surface calls it beside the writer,\n * since only the console runs AI jobs (AGL-3026). Idempotent.\n */\nexport function registerDatasetAiCapability(): void {\n registerPluginAiCapability(datasetAiCapability, { pluginId: BUNDLE_ID })\n}\n"],"names":["registerPluginAiCapability","BUNDLE_ID","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_FIELD_TYPES","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_RESOURCE","DATASET_AI_OP","DATASET_AI_VALUE_SEPARATOR","LIST_SEPARATOR","DATASET_AI_RECORD_MAX","TYPES","Object","keys","datasetAiFieldOf","spec","at","lastIndexOf","type","slice","trim","toLowerCase","includes","name","datasetDraftContentFromArgs","args","specs","Array","isArray","fields","map","filter","field","rows","records","row","values","split","value","record","forEach","index","Boolean","address","length","pageAddressFrom","datasetAiCapability","op","noun","where","intents","argsSchema","properties","description","maxLength","join","items","maxItems","required","additionalProperties","maxPerPlan","freeAllowed","feature","quota","draftResource","estimateCredits","degrade","draftContent","item","registerDatasetAiCapability","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,0BAA0B,QAGrB,qDAAoD;AAC3D,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,4BAA4B,EAC5BC,yBAAyB,EACzBC,wBAAwB,EACxBC,sBAAsB,EACtBC,yBAAyB,EACzBC,sBAAsB,QAEjB,sBAAkB;AAEzB;;;;;;;;;;;;;;;;CAgBC,GAED,0CAA0C,GAC1C,OAAO,MAAMC,gBAAgB,UAAS;AAEtC,wEAAwE,GACxE,OAAO,MAAMC,6BAA6B,MAAK;AAE/C,sEAAsE,GACtE,MAAMC,iBAAiB;AAEvB,8CAA8C,GAC9C,MAAMC,wBAAwB;AAE9B,MAAMC,QAAQC,OAAO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AA4B4C,KAAK3C,IAAI;AAC/D,EAAC;AAED;;;CAGC,GACD,OAAO,SAAS4C;IACdtE,2BAA2B+C,qBAAqB;QAAEwB,UAAUtE;IAAU;AACxE"}
@@ -38,9 +38,9 @@ import { type DatasetFieldType, type DatasetModel } from '../model/dataset-model
38
38
  * counts it; the records are held to `recordsPerDataset` and the dataset
39
39
  * storage band.
40
40
  * - THE PLAN is `dataStore` (Starter and up), THE FLAG `release_data_store`,
41
- * and THE ROLE an org member who may edit org data (owner, admin or
42
- * editor) with `data.manage`, whose access reaches the site — refused in
43
- * the route's own words.
41
+ * and THE MEMBER an org member holding "Manage data" (`data.manage`,
42
+ * AGL-4047), whose access reaches the site — refused in the route's own
43
+ * words.
44
44
  * - THE CHECK holds every record to the model it is written under
45
45
  * (`validateDocument`), so what is seeded is what a person could type.
46
46
  * - A PHOTO is an `image` field (AGL-3616): text storage riding the
@@ -93,9 +93,8 @@ export declare const DATASET_DRAFT_FIELD_TYPES: {
93
93
  readonly page: "text";
94
94
  };
95
95
  export type DatasetDraftFieldType = keyof typeof DATASET_DRAFT_FIELD_TYPES;
96
- /** The datasets route's refusals, word for word. */
97
- export declare const DATASET_DRAFT_ROLE_REFUSAL = "Editing org data requires the editor role";
98
- export declare const DATASET_DRAFT_PERMISSION_REFUSAL = "Your organization role does not allow editing organization data";
96
+ /** The datasets route's refusals, word for word; the first names the permission, never a role (AGL-4047). */
97
+ export declare const DATASET_DRAFT_PERMISSION_REFUSAL: string;
99
98
  export declare const DATASET_DRAFT_PLAN_REFUSAL = "Datasets require a Starter plan or higher";
100
99
  export declare const DATASET_DRAFT_RELEASE_REFUSAL = "Datasets are not available for this workspace yet";
101
100
  export declare const DATASET_DRAFT_SCOPE_REFUSAL = "Your access to this organization does not reach that site";
@@ -166,9 +165,8 @@ export type DatasetDraftContentRead = {
166
165
  export declare function readDatasetDraftContent(content: Readonly<Record<string, unknown>>): DatasetDraftContentRead;
167
166
  /** Whether content is a dataset this plugin would store, with what it says about it. Pure. */
168
167
  export declare function checkDatasetDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck;
169
- /** Who the member is in the org, as the writer asks: their role, and whether they may manage data. */
168
+ /** Who the member is in the org, as the writer asks: whether they hold "Manage data". */
170
169
  export interface DatasetDraftMember {
171
- role: string;
172
170
  canManageData: boolean;
173
171
  /** The membership itself, for whether their access reaches a site. */
174
172
  member: Readonly<Record<string, unknown>>;
@@ -15,6 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
18
+ import { permissionRefusalText } from "@aglyn/aglyn/app-utils/org-permissions";
18
19
  import { memberCanSee } from "@aglyn/aglyn/app-utils/organizations";
19
20
  import { checkDatasetQuota, checkEntitlement, checkQuota } from "@aglyn/aglyn/app-utils/plan-entitlements";
20
21
  import { hostScopeToken, newResourceScopeFields } from "@aglyn/aglyn/app-utils/scope-tokens";
@@ -53,8 +54,7 @@ export const DATASET_DRAFT_FIELD_NAME_MAX = 60;
53
54
  page: 'text'
54
55
  };
55
56
  const DRAFT_TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES);
56
- /** The datasets route's refusals, word for word. */ export const DATASET_DRAFT_ROLE_REFUSAL = 'Editing org data requires the editor role';
57
- export const DATASET_DRAFT_PERMISSION_REFUSAL = 'Your organization role does not allow editing organization data';
57
+ /** The datasets route's refusals, word for word; the first names the permission, never a role (AGL-4047). */ export const DATASET_DRAFT_PERMISSION_REFUSAL = permissionRefusalText('data.manage');
58
58
  export const DATASET_DRAFT_PLAN_REFUSAL = 'Datasets require a Starter plan or higher';
59
59
  export const DATASET_DRAFT_RELEASE_REFUSAL = 'Datasets are not available for this workspace yet';
60
60
  export const DATASET_DRAFT_SCOPE_REFUSAL = 'Your access to this organization does not reach that site';
@@ -271,18 +271,11 @@ function factsOf(model, records, addressField) {
271
271
  facts: factsOf(read.value.model, read.value.records.length, read.value.addressField)
272
272
  };
273
273
  }
274
- /** Roles allowed to create org data — the datasets route's, mirroring the rules' `canWriteOrgData()`. */ const WRITER_ROLES = new Set([
275
- 'owner',
276
- 'admin',
277
- 'editor'
278
- ]);
279
274
  async function platformMember(uid, orgId) {
280
- var _member_role;
281
275
  const membership = await resolveOrgMembership(uid, orgId);
282
276
  const member = membership == null ? void 0 : membership.member;
283
277
  if (!member) return null;
284
278
  return {
285
- role: String((_member_role = member.role) != null ? _member_role : ''),
286
279
  canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),
287
280
  member: member
288
281
  };
@@ -294,17 +287,13 @@ export function createDatasetDraftWriter(deps = {}) {
294
287
  const memberOf = (_deps_member = deps.member) != null ? _deps_member : platformMember;
295
288
  const released = (_deps_released = deps.released) != null ? _deps_released : (orgId)=>isServerReleaseFlagOnForOrg('release_data_store', orgId);
296
289
  const storageFull = (_deps_storageFull = deps.storageFull) != null ? _deps_storageFull : async (org, orgRef)=>Boolean(await dataStorageRefusal(org, orgRef));
297
- /** Everything but the room: the site is the org's, the member's role, the flag, the plan, the scope. */ const early = async (context)=>{
290
+ /** Everything but the room: the site is the org's, the member's key, the flag, the plan, the scope. */ const early = async (context)=>{
298
291
  if (await orgIdForHost(context.hostId) !== context.orgId) return {
299
292
  status: 404,
300
293
  error: 'Unknown site'
301
294
  };
302
295
  const member = await memberOf(context.uid, context.orgId);
303
- if (!member || !WRITER_ROLES.has(member.role)) return {
304
- status: 403,
305
- error: DATASET_DRAFT_ROLE_REFUSAL
306
- };
307
- if (!member.canManageData) return {
296
+ if (!(member == null ? void 0 : member.canManageData)) return {
308
297
  status: 403,
309
298
  error: DATASET_DRAFT_PERMISSION_REFUSAL
310
299
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-drafts.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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkDatasetQuota, checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRecordsRevise,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { dataStorageRefusal } from '@aglyn/tenant-data-admin/server/data-storage-gate'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n coerceDocumentValues,\n datasetIntegrityFields,\n datasetIntegrityUpdate,\n defaultDatasetFieldId,\n validateDocument,\n type DatasetFieldType,\n type DatasetModel,\n} from '../model/dataset-models'\nimport { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from '../model/dataset-image-field'\nimport { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from '../model/dataset-page-field'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n RECORD_PAGE_ADDRESS_MAX,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * A DATASET ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `dataset` resource on the\n * core's resource-drafts seam. Aglyn AI builds a menu, a team, a list of\n * services or a portfolio as a dataset, the way the docs teach a person to,\n * and asks for the writer by name, so every rule is this plugin's:\n *\n * - THE DOCUMENT is the one the Data card's create makes: a display name,\n * the flat `fields` mirror and a typed model, shared with the site it is\n * made for and no other (AGL-4003), and the\n * seeded records, each with the integrity and filter index every record\n * write carries. Where a record page is wanted the model gains a \"Page\n * address\" field that fills from a text field, and every seeded record a\n * unique address (`uniqueRecordAddresses`), so the member's Record pages\n * save has nothing left to fill.\n * - THE ROOM is `datasetsPerOrg` (add-ons included, `checkDatasetQuota`),\n * counted INSIDE the transaction that creates, as the datasets route\n * counts it; the records are held to `recordsPerDataset` and the dataset\n * storage band.\n * - THE PLAN is `dataStore` (Starter and up), THE FLAG `release_data_store`,\n * and THE ROLE an org member who may edit org data (owner, admin or\n * editor) with `data.manage`, whose access reaches the site — refused in\n * the route's own words.\n * - THE CHECK holds every record to the model it is written under\n * (`validateDocument`), so what is seeded is what a person could type.\n * - A PHOTO is an `image` field (AGL-3616): text storage riding the\n * \"Image\" custom type, each value an address the site's Image element\n * shows (`isDatasetImageValue`), so a portfolio's pieces or a team keep\n * the photo the page that lists them binds.\n * - A PAGE is a `page` field (AGL-3763): text storage riding the \"Page\"\n * custom type, each value one of the site's pages as `screen:{id}`\n * (`isDatasetPageValue`), which a Button or Link binds.\n * - A SAMPLE is a seeded record the caller marks as one (`samples`,\n * AGL-4065): a site start whose brief gave no entries for a list seeds it\n * with complete-looking samples, and the record carries `sample: true`\n * beside its values, which the Data card shows as a sample to replace\n * and a published page never reads. Saving the record in Data makes it\n * the owner's.\n *\n * Nothing is published. The writer touches the one new dataset and its\n * records; a page shows them only where a person (or a job's draft page)\n * places a repeat over it.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const DATASET_DRAFT_RESOURCE = 'dataset'\n\n/** The longest dataset name, as the datasets route keeps it. */\nexport const DATASET_DRAFT_NAME_MAX = 120\n/** The most fields a drafted dataset is made with, and the longest name. */\nexport const DATASET_DRAFT_FIELDS_MAX = 16\nexport const DATASET_DRAFT_FIELD_NAME_MAX = 60\n/** The most records a draft is seeded with. */\nexport const DATASET_DRAFT_RECORDS_MAX = 24\n/** The longest text value a seeded record keeps. */\nexport const DATASET_DRAFT_VALUE_MAX = 2_000\n/** The most entries a seeded list value keeps. */\nexport const DATASET_DRAFT_LIST_MAX = 12\n\n/**\n * The field types a caller names, in words a person reads, and the type\n * each one is stored as. A date or a time is written as text the way a\n * visitor reads it (\"Saturday 8 November, 7 pm\"): a stored timestamp renders\n * as a number in a repeat's `{{item.<field>}}`. An image is text holding a\n * photo's address, under the \"Image\" custom type (AGL-3616), and a page is\n * text holding a page's reference, under the \"Page\" custom type (AGL-3763).\n */\nexport const DATASET_DRAFT_FIELD_TYPES = {\n text: 'text',\n number: 'float',\n integer: 'int32',\n boolean: 'bool',\n list: 'sorted',\n image: 'text',\n page: 'text',\n} as const satisfies Record<string, DatasetFieldType>\n\nexport type DatasetDraftFieldType = keyof typeof DATASET_DRAFT_FIELD_TYPES\n\nconst DRAFT_TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** The datasets route's refusals, word for word. */\nexport const DATASET_DRAFT_ROLE_REFUSAL = 'Editing org data requires the editor role'\nexport const DATASET_DRAFT_PERMISSION_REFUSAL = 'Your organization role does not allow editing organization data'\nexport const DATASET_DRAFT_PLAN_REFUSAL = 'Datasets require a Starter plan or higher'\nexport const DATASET_DRAFT_RELEASE_REFUSAL = 'Datasets are not available for this workspace yet'\nexport const DATASET_DRAFT_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const DATASET_DRAFT_STORAGE_REFUSAL = 'Dataset storage is full on this plan — upgrade in Billing'\n\n/** The route's refusal at the plan's dataset allowance. */\nexport function datasetDraftLimitRefusal(quota: ReturnType<typeof checkDatasetQuota>): string {\n return quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n}\n\n/** The route's refusal at the plan's record allowance. */\nexport function datasetDraftRecordLimitRefusal(limit: number): string {\n return `Record limit reached (${limit}) — upgrade in Billing`\n}\n\n/** One field as a caller names it. */\nexport interface DatasetDraftField {\n name: string\n /** Absent is text. */\n type?: DatasetDraftFieldType\n required?: boolean\n}\n\n/**\n * What a caller sends as `content`. Each record's values are keyed by the\n * field NAME the caller gave, since the caller has no ids yet; the writer\n * mints the ids (`roast_preference` from \"Roast preference\").\n */\nexport interface DatasetDraftContent {\n /** The dataset's name; the request's `name` stands in when absent. */\n name?: string\n fields: DatasetDraftField[]\n records?: Array<Record<string, unknown>>\n /**\n * A text field, by name, a \"Page address\" field fills from (AGL-3475):\n * asked for where a record page will show each record at its own address.\n */\n pageAddressFrom?: string\n /**\n * Which seeded records are samples for the owner to replace, by position\n * as `records` (AGL-4065). Absent, or false, is a record of the owner's.\n */\n samples?: boolean[]\n}\n\n/** What the writer reports about a dataset. */\nexport interface DatasetDraftFacts {\n fields: Array<{ id: string; name: string; type: DatasetFieldType }>\n records: number\n /** The page-address field's id, where the dataset has one. */\n addressField: string | null\n /** The first photo field's id, where the dataset has one (AGL-3616). */\n imageField: string | null\n}\n\n/** The draft as the writer will store it. */\nexport interface DatasetDraftRead {\n name: string\n model: DatasetModel\n /** Each record's values by field id, coerced and addressed. */\n records: Array<Record<string, unknown>>\n addressField: string | null\n /** Which records are samples, by position (AGL-4065); absent where none is. */\n samples?: boolean[]\n}\n\nexport type DatasetDraftContentRead =\n | { ok: true; value: DatasetDraftRead }\n | { ok: false; problems: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** A value as a seeded record keeps it, before the model coerces it. */\nfunction seedValue(value: unknown): unknown {\n if (typeof value === 'string') return value.replace(/\\r\\n?/g, '\\n').trim().slice(0, DATASET_DRAFT_VALUE_MAX)\n if (Array.isArray(value)) {\n return value\n .map((entry) => (typeof entry === 'string' ? line(entry) : entry))\n .filter((entry) => entry !== '' && entry !== null && entry !== undefined)\n .slice(0, DATASET_DRAFT_LIST_MAX)\n }\n return value\n}\n\n/** The content as the writer reads it, or every problem that stops it. Pure. */\nexport function readDatasetDraftContent(content: Readonly<Record<string, unknown>>): DatasetDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The dataset needs a name')\n else if (name.length > DATASET_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${DATASET_DRAFT_NAME_MAX} characters`)\n }\n\n const rawFields = content['fields']\n const model: DatasetModel = { fields: {}, order: [] }\n /** Field name, lowercased → id. */\n const byName = new Map<string, string>()\n if (!Array.isArray(rawFields) || !rawFields.length) {\n problems.push('The dataset needs at least one field')\n } else if (rawFields.length > DATASET_DRAFT_FIELDS_MAX) {\n problems.push(`A dataset is made with at most ${DATASET_DRAFT_FIELDS_MAX} fields`)\n } else {\n for (const raw of rawFields) {\n const fieldName = isRecord(raw) ? line(raw['name']) : ''\n const rawType = (isRecord(raw) ? raw['type'] : undefined) ?? 'text'\n if (!fieldName) {\n problems.push('Each field needs a name')\n continue\n }\n if (fieldName.length > DATASET_DRAFT_FIELD_NAME_MAX) {\n problems.push(`The field \"${fieldName.slice(0, 20)}…\" has a name longer than ${DATASET_DRAFT_FIELD_NAME_MAX} characters`)\n continue\n }\n if (!(DRAFT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push(`The field \"${fieldName}\" is one of ${DRAFT_TYPES.join(', ')}`)\n continue\n }\n if (byName.has(fieldName.toLowerCase())) {\n problems.push(`Two fields are both called \"${fieldName}\"`)\n continue\n }\n const id = defaultDatasetFieldId(fieldName, new Set(model.order))\n if (!id) {\n problems.push(`The field \"${fieldName}\" needs a name with a letter in it`)\n continue\n }\n model.fields[id] = {\n name: fieldName,\n type: DATASET_DRAFT_FIELD_TYPES[rawType as DatasetDraftFieldType],\n ...(rawType === 'image' ? { customType: DATASET_IMAGE_FIELD_TYPE } : {}),\n ...(rawType === 'page' ? { customType: DATASET_PAGE_FIELD_TYPE } : {}),\n ...(isRecord(raw) && raw['required'] === true ? { required: true } : {}),\n }\n model.order.push(id)\n byName.set(fieldName.toLowerCase(), id)\n }\n }\n\n // The page address: a text field the address fills from, once.\n let addressField: string | null = null\n const rawAddress = content['pageAddressFrom']\n if (rawAddress !== undefined && rawAddress !== null && rawAddress !== '') {\n const sourceId = byName.get(line(rawAddress).toLowerCase())\n if (!sourceId || model.fields[sourceId]?.type !== 'text' || model.fields[sourceId]?.customType) {\n problems.push('A page address fills from one of the dataset’s text fields')\n } else {\n addressField = defaultDatasetFieldId('slug', new Set(model.order))\n model.fields[addressField] = {\n name: 'Page address',\n type: 'text',\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceId,\n }\n model.order.push(addressField)\n }\n }\n\n const rawRecords = content['records'] ?? []\n const records: Array<Record<string, unknown>> = []\n if (!Array.isArray(rawRecords)) {\n problems.push('Records are a list of values by field name')\n } else if (rawRecords.length > DATASET_DRAFT_RECORDS_MAX) {\n problems.push(`A dataset is seeded with at most ${DATASET_DRAFT_RECORDS_MAX} records`)\n } else if (!problems.length) {\n rawRecords.forEach((raw, index) => {\n if (!isRecord(raw)) {\n problems.push(`Record ${index + 1} is not a set of values`)\n return\n }\n const input: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(raw)) {\n const id = byName.get(line(key).toLowerCase())\n if (!id) {\n problems.push(`Record ${index + 1} names \"${line(key).slice(0, 40)}\", which is not a field`)\n continue\n }\n input[id] = seedValue(value)\n }\n const values = coerceDocumentValues(model, input)\n // An empty value is no value: it is not stored, as the card stores none.\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) {\n delete values[id]\n }\n }\n const errors = validateDocument(model, values)\n // A photo is an address the site's Image shows, whether or not the\n // \"Image\" type's check is registered in this process (AGL-3616).\n for (const [id, value] of Object.entries(values)) {\n const field = model.fields[id]\n if (field?.customType === DATASET_IMAGE_FIELD_TYPE && !errors[id] && !isDatasetImageValue(value)) {\n errors[id] = `${field.name} is not a photo from the media library or an https link`\n }\n // …and a page is one of the site's pages, by reference (AGL-3763).\n if (field?.customType === DATASET_PAGE_FIELD_TYPE && !errors[id] && !isDatasetPageValue(value)) {\n errors[id] = `${field.name} is not one of the site’s pages`\n }\n }\n for (const error of Object.values(errors)) problems.push(`Record ${index + 1}: ${error}`)\n if (!Object.keys(values).length) problems.push(`Record ${index + 1} has no values`)\n records.push(values)\n })\n }\n // Which records are samples (AGL-4065): true or false, one a record at most.\n const rawSamples = content['samples']\n if (rawSamples !== undefined && (!Array.isArray(rawSamples) || rawSamples.some((entry) => typeof entry !== 'boolean'))) {\n problems.push('Samples are a list of true or false, one a record')\n } else if (Array.isArray(rawSamples) && rawSamples.length > records.length) {\n problems.push('Samples name more records than the dataset is seeded with')\n }\n const samples = Array.isArray(rawSamples) && rawSamples.some((entry) => entry === true) ? records.map((_values, index) => rawSamples[index] === true) : null\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n\n // Every seeded record its own address, unique within the dataset.\n if (addressField) {\n const source = model.fields[addressField]?.slugFrom as string\n const assigned = uniqueRecordAddresses(records.map((values, index) => ({ id: String(index), source: values[source] })))\n records.forEach((values, index) => {\n const address = assigned.get(String(index))\n if (address) values[addressField as string] = address.slice(0, RECORD_PAGE_ADDRESS_MAX)\n })\n }\n return { ok: true, value: { name, model, records, addressField, ...(samples ? { samples } : {}) } }\n}\n\n/** The first photo field of a model, by id. */\nfunction imageFieldOf(model: DatasetModel): string | null {\n return model.order.find((id) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE) ?? null\n}\n\nfunction factsOf(model: DatasetModel, records: number, addressField: string | null): DatasetDraftFacts {\n return {\n fields: model.order.map((id) => ({ id, name: model.fields[id]?.name ?? id, type: model.fields[id]?.type ?? 'text' })),\n records,\n addressField,\n imageField: imageFieldOf(model),\n }\n}\n\n/** Whether content is a dataset this plugin would store, with what it says about it. Pure. */\nexport function checkDatasetDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readDatasetDraftContent(content)\n if (read.ok === false) return read\n return {\n ok: true,\n facts: factsOf(read.value.model, read.value.records.length, read.value.addressField) as unknown as Readonly<\n Record<string, unknown>\n >,\n }\n}\n\n/** Who the member is in the org, as the writer asks: their role, and whether they may manage data. */\nexport interface DatasetDraftMember {\n role: string\n canManageData: boolean\n /** The membership itself, for whether their access reaches a site. */\n member: Readonly<Record<string, unknown>>\n}\n\nexport interface DatasetDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<DatasetDraftMember | null>\n /** Whether the data store is released for the org; the platform's flag otherwise. */\n released?: (orgId: string) => Promise<boolean>\n /** Whether dataset bytes may grow; the platform's band otherwise. */\n storageFull?: (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Promise<boolean>\n}\n\n/** Roles allowed to create org data — the datasets route's, mirroring the rules' `canWriteOrgData()`. */\nconst WRITER_ROLES = new Set(['owner', 'admin', 'editor'])\n\nasync function platformMember(uid: string, orgId: string): Promise<DatasetDraftMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n role: String(member.role ?? ''),\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport function createDatasetDraftWriter(deps: DatasetDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n const released = deps.released ?? ((orgId: string) => isServerReleaseFlagOnForOrg('release_data_store', orgId))\n const storageFull =\n deps.storageFull ?? (async (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Boolean(await dataStorageRefusal(org, orgRef)))\n\n /** Everything but the room: the site is the org's, the member's role, the flag, the plan, the scope. */\n const early = async (context: PluginDraftContext): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n const member = await memberOf(context.uid, context.orgId)\n if (!member || !WRITER_ROLES.has(member.role)) return { status: 403, error: DATASET_DRAFT_ROLE_REFUSAL }\n if (!member.canManageData) return { status: 403, error: DATASET_DRAFT_PERMISSION_REFUSAL }\n if (!(await released(context.orgId))) return { status: 403, error: DATASET_DRAFT_RELEASE_REFUSAL }\n if (!checkEntitlement(context.org as never, 'dataStore')) return { status: 403, error: DATASET_DRAFT_PLAN_REFUSAL }\n // A member scoped to some sites must be able to see what they create.\n if (!memberCanSee(member.member as never, scopeOf(context))) {\n return { status: 403, error: DATASET_DRAFT_SCOPE_REFUSAL }\n }\n return null\n }\n\n return {\n refusal: async (context) => {\n const refused = await early(context)\n if (refused) return refused\n const used = (await firestore().collection('orgs').doc(context.orgId).collection('datasets').count().get()).data().count\n const quota = checkDatasetQuota(context.org as never, Number(used) || 0)\n return quota.allowed ? null : { status: 403, error: datasetDraftLimitRefusal(quota) }\n },\n\n check: (content) => checkDatasetDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n const dataset = await firestore().collection('orgs').doc(orgId).collection('datasets').doc(id).get()\n return dataset.exists ? recordOf(dataset) : null\n },\n\n // The late photo pass of an AI site start (AGL-3988): a list's covers\n // given photos once its pages are built. Only what a person could type\n // in the record's card is stored, under the same member rules as `write`.\n reviseRecords: async (request): Promise<PluginDraftRecordsRevise> => {\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const orders = [...new Set(request.records.map((record) => record.order))]\n .filter((order) => Number.isInteger(order) && order >= 0)\n .slice(0, DATASET_DRAFT_RECORDS_MAX)\n if (!orders.length) return { ok: true, changed: 0 }\n const db = firestore()\n const datasetRef = db.collection('orgs').doc(request.orgId).collection('datasets').doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftRecordsRevise> => {\n const dataset = await tx.get(datasetRef)\n const model = dataset.get('model') as DatasetModel | undefined\n if (!dataset.exists || !model?.order) return { ok: false, status: 404, error: 'The dataset is no longer there' }\n const rows = await tx.get(datasetRef.collection('records').where('order', 'in', orders))\n let changed = 0\n for (const revision of request.records) {\n const row = rows.docs.find((doc) => doc.get('order') === revision.order)\n if (!row) continue\n const stored = (row.get('values') ?? {}) as Record<string, unknown>\n // A member changed it since: theirs stands.\n if (Object.entries(revision.where ?? {}).some(([id, value]) => stored[id] !== value)) continue\n // Only the list's own fields are changed; a revision naming none of them changes nothing.\n const named = Object.entries(revision.values).filter(([id]) => model.fields[id])\n if (!named.length) continue\n const input: Record<string, unknown> = { ...stored }\n for (const [id, value] of named) input[id] = seedValue(value)\n const values = coerceDocumentValues(model, input)\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) delete values[id]\n }\n const errors = validateDocument(model, values)\n const badPhoto = Object.entries(values).some(\n ([id, value]) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE && !isDatasetImageValue(value),\n )\n if (Object.keys(errors).length || badPhoto) continue\n tx.update(row.ref, { values, ...datasetIntegrityUpdate(model, values, FieldValue.delete()), updatedAt: request.now })\n changed += 1\n }\n return { ok: true, changed }\n })\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readDatasetDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const db = firestore()\n const orgRef = db.collection('orgs').doc(request.orgId)\n const datasets = orgRef.collection('datasets')\n const datasetRef = datasets.doc(request.id)\n const { name, model, records, addressField, samples } = read.value\n const recordQuota = checkQuota(request.org as never, 'recordsPerDataset', Math.max(0, records.length - 1))\n if (records.length && !recordQuota.allowed) {\n return { ok: false, status: 403, error: datasetDraftRecordLimitRefusal(recordQuota.limit) }\n }\n if (records.length && (await storageFull(request.org, orgRef))) {\n return { ok: false, status: 403, error: DATASET_DRAFT_STORAGE_REFUSAL }\n }\n const visibleTo = scopeOf(request)\n // Minted before the transaction, so a retried attempt writes the same rows.\n const recordIds = records.map(() => createResourceUid())\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const existing = await tx.get(datasetRef)\n // Asked again under the same id: the dataset it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const live = (await tx.get(datasets.count())).data().count\n const quota = checkDatasetQuota(request.org as never, Number(live) || 0)\n if (!quota.allowed) return { ok: false, status: 403, error: datasetDraftLimitRefusal(quota) }\n tx.create(datasetRef, {\n displayName: name,\n fields: [...model.order],\n model,\n ...newResourceScopeFields(visibleTo),\n createdAt: request.now,\n createdBy: request.uid,\n })\n records.forEach((values, order) => {\n tx.create(datasetRef.collection('records').doc(recordIds[order]), {\n values,\n ...datasetIntegrityFields(model, values),\n // A sample for the owner to replace (AGL-4065), beside its values: no page reads it.\n ...(samples?.[order] ? { sample: true } : {}),\n order,\n createdAt: request.now,\n updatedAt: request.now,\n })\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: factsOf(model, records.length, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n })\n },\n }\n}\n\n/**\n * The scope a dataset drafted for a site takes: that site alone (AGL-4003).\n *\n * A drafted dataset is the site's own content, made for it by Aglyn AI, so it\n * is shared with that site and no other, whatever the workspace's Default\n * sharing says for the datasets a person makes on the Data page. Deleting the\n * site erases it with its records (`eraseHost`), where a dataset shared with\n * every site outlived its site: 53 did in one workspace. A member can share it\n * with more sites on the Data page.\n */\nfunction scopeOf(context: Pick<PluginDraftContext, 'hostId'>) {\n return [hostScopeToken(context.hostId)]\n}\n\nfunction recordOf(dataset: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (dataset.data() ?? {}) as { displayName?: unknown; model?: DatasetModel }\n const model: DatasetModel = data.model?.order ? data.model : { fields: {}, order: [] }\n const addressField = model.order.find((id) => model.fields[id]?.customType === RECORD_PAGE_ADDRESS_FIELD_TYPE) ?? null\n return {\n id: dataset.id,\n name: String(data.displayName ?? ''),\n versionId: null,\n // A replay reports the fields; how many records it was seeded with is the first write's to say.\n facts: factsOf(model, 0, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport const datasetDraftWriter = createDatasetDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerDatasetDraftWriter(): void {\n registerPluginResourceDraftWriter(DATASET_DRAFT_RESOURCE, datasetDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["createResourceUid","memberCanSee","checkDatasetQuota","checkEntitlement","checkQuota","hostScopeToken","newResourceScopeFields","registerPluginResourceDraftWriter","firebaseAdmin","FieldValue","dataStorageRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isServerReleaseFlagOnForOrg","BUNDLE_ID","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","defaultDatasetFieldId","validateDocument","DATASET_IMAGE_FIELD_TYPE","isDatasetImageValue","DATASET_PAGE_FIELD_TYPE","isDatasetPageValue","RECORD_PAGE_ADDRESS_FIELD_TYPE","RECORD_PAGE_ADDRESS_MAX","uniqueRecordAddresses","DATASET_DRAFT_RESOURCE","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_VALUE_MAX","DATASET_DRAFT_LIST_MAX","DATASET_DRAFT_FIELD_TYPES","text","number","integer","boolean","list","image","page","DRAFT_TYPES","Object","keys","DATASET_DRAFT_ROLE_REFUSAL","DATASET_DRAFT_PERMISSION_REFUSAL","DATASET_DRAFT_PLAN_REFUSAL","DATASET_DRAFT_RELEASE_REFUSAL","DATASET_DRAFT_SCOPE_REFUSAL","DATASET_DRAFT_STORAGE_REFUSAL","datasetDraftLimitRefusal","quota","upgradeRequired","limit","addonPriceUsd","datasetDraftRecordLimitRefusal","isRecord","value","Array","isArray","line","replace","trim","seedValue","slice","map","entry","filter","undefined","readDatasetDraftContent","content","problems","name","push","length","rawFields","model","fields","order","byName","Map","raw","fieldName","rawType","includes","join","has","toLowerCase","id","Set","type","customType","required","set","addressField","rawAddress","sourceId","get","slugFrom","rawRecords","records","forEach","index","input","key","entries","values","errors","field","error","rawSamples","some","samples","_values","ok","source","assigned","String","address","imageFieldOf","find","factsOf","imageField","checkDatasetDraftContent","read","facts","WRITER_ROLES","platformMember","uid","orgId","member","membership","role","canManageData","createDatasetDraftWriter","deps","firestore","app","orgIdForHost","hostId","memberOf","released","storageFull","org","orgRef","Boolean","early","context","status","scopeOf","refusal","refused","used","collection","doc","count","data","Number","allowed","check","dataset","exists","recordOf","reviseRecords","request","orders","record","isInteger","changed","db","datasetRef","runTransaction","tx","rows","where","revision","row","docs","stored","named","badPhoto","update","ref","delete","updatedAt","now","write","asked","datasets","recordQuota","Math","max","visibleTo","recordIds","existing","replayed","live","create","displayName","createdAt","createdBy","sample","versionId","datasetDraftWriter","registerDatasetDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC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AOZ;eAAAA,EAAAA,mBAAAA,MAAMC,MAAM,CAACW,GAAG,qBAAhBZ,iBAAkBe,UAAU,MAAKpE;kBAA1DqD,oBAA6F;IAClH,OAAO;QACLY,IAAIwE,QAAQxE,EAAE;QACdhB,MAAM6C,QAAOuC,oBAAAA,KAAK0C,WAAW,YAAhB1C,oBAAoB;QACjC8C,WAAW;QACX,gGAAgG;QAChG7E,OAAOJ,QAAQ7C,OAAO,GAAGkB;IAC3B;AACF;AAEA,OAAO,MAAM6G,qBAAqBrE,2BAA0B;AAE5D;;;CAGC,GACD,OAAO,SAASsE;IACdvM,kCAAkCqB,wBAAwBiL,oBAAoB;QAAEE,UAAUhM;IAAU;AACtG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-drafts.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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { permissionRefusalText } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkDatasetQuota, checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRecordsRevise,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { dataStorageRefusal } from '@aglyn/tenant-data-admin/server/data-storage-gate'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n coerceDocumentValues,\n datasetIntegrityFields,\n datasetIntegrityUpdate,\n defaultDatasetFieldId,\n validateDocument,\n type DatasetFieldType,\n type DatasetModel,\n} from '../model/dataset-models'\nimport { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from '../model/dataset-image-field'\nimport { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from '../model/dataset-page-field'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n RECORD_PAGE_ADDRESS_MAX,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * A DATASET ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `dataset` resource on the\n * core's resource-drafts seam. Aglyn AI builds a menu, a team, a list of\n * services or a portfolio as a dataset, the way the docs teach a person to,\n * and asks for the writer by name, so every rule is this plugin's:\n *\n * - THE DOCUMENT is the one the Data card's create makes: a display name,\n * the flat `fields` mirror and a typed model, shared with the site it is\n * made for and no other (AGL-4003), and the\n * seeded records, each with the integrity and filter index every record\n * write carries. Where a record page is wanted the model gains a \"Page\n * address\" field that fills from a text field, and every seeded record a\n * unique address (`uniqueRecordAddresses`), so the member's Record pages\n * save has nothing left to fill.\n * - THE ROOM is `datasetsPerOrg` (add-ons included, `checkDatasetQuota`),\n * counted INSIDE the transaction that creates, as the datasets route\n * counts it; the records are held to `recordsPerDataset` and the dataset\n * storage band.\n * - THE PLAN is `dataStore` (Starter and up), THE FLAG `release_data_store`,\n * and THE MEMBER an org member holding \"Manage data\" (`data.manage`,\n * AGL-4047), whose access reaches the site — refused in the route's own\n * words.\n * - THE CHECK holds every record to the model it is written under\n * (`validateDocument`), so what is seeded is what a person could type.\n * - A PHOTO is an `image` field (AGL-3616): text storage riding the\n * \"Image\" custom type, each value an address the site's Image element\n * shows (`isDatasetImageValue`), so a portfolio's pieces or a team keep\n * the photo the page that lists them binds.\n * - A PAGE is a `page` field (AGL-3763): text storage riding the \"Page\"\n * custom type, each value one of the site's pages as `screen:{id}`\n * (`isDatasetPageValue`), which a Button or Link binds.\n * - A SAMPLE is a seeded record the caller marks as one (`samples`,\n * AGL-4065): a site start whose brief gave no entries for a list seeds it\n * with complete-looking samples, and the record carries `sample: true`\n * beside its values, which the Data card shows as a sample to replace\n * and a published page never reads. Saving the record in Data makes it\n * the owner's.\n *\n * Nothing is published. The writer touches the one new dataset and its\n * records; a page shows them only where a person (or a job's draft page)\n * places a repeat over it.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const DATASET_DRAFT_RESOURCE = 'dataset'\n\n/** The longest dataset name, as the datasets route keeps it. */\nexport const DATASET_DRAFT_NAME_MAX = 120\n/** The most fields a drafted dataset is made with, and the longest name. */\nexport const DATASET_DRAFT_FIELDS_MAX = 16\nexport const DATASET_DRAFT_FIELD_NAME_MAX = 60\n/** The most records a draft is seeded with. */\nexport const DATASET_DRAFT_RECORDS_MAX = 24\n/** The longest text value a seeded record keeps. */\nexport const DATASET_DRAFT_VALUE_MAX = 2_000\n/** The most entries a seeded list value keeps. */\nexport const DATASET_DRAFT_LIST_MAX = 12\n\n/**\n * The field types a caller names, in words a person reads, and the type\n * each one is stored as. A date or a time is written as text the way a\n * visitor reads it (\"Saturday 8 November, 7 pm\"): a stored timestamp renders\n * as a number in a repeat's `{{item.<field>}}`. An image is text holding a\n * photo's address, under the \"Image\" custom type (AGL-3616), and a page is\n * text holding a page's reference, under the \"Page\" custom type (AGL-3763).\n */\nexport const DATASET_DRAFT_FIELD_TYPES = {\n text: 'text',\n number: 'float',\n integer: 'int32',\n boolean: 'bool',\n list: 'sorted',\n image: 'text',\n page: 'text',\n} as const satisfies Record<string, DatasetFieldType>\n\nexport type DatasetDraftFieldType = keyof typeof DATASET_DRAFT_FIELD_TYPES\n\nconst DRAFT_TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** The datasets route's refusals, word for word; the first names the permission, never a role (AGL-4047). */\nexport const DATASET_DRAFT_PERMISSION_REFUSAL = permissionRefusalText('data.manage')\nexport const DATASET_DRAFT_PLAN_REFUSAL = 'Datasets require a Starter plan or higher'\nexport const DATASET_DRAFT_RELEASE_REFUSAL = 'Datasets are not available for this workspace yet'\nexport const DATASET_DRAFT_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const DATASET_DRAFT_STORAGE_REFUSAL = 'Dataset storage is full on this plan — upgrade in Billing'\n\n/** The route's refusal at the plan's dataset allowance. */\nexport function datasetDraftLimitRefusal(quota: ReturnType<typeof checkDatasetQuota>): string {\n return quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n}\n\n/** The route's refusal at the plan's record allowance. */\nexport function datasetDraftRecordLimitRefusal(limit: number): string {\n return `Record limit reached (${limit}) — upgrade in Billing`\n}\n\n/** One field as a caller names it. */\nexport interface DatasetDraftField {\n name: string\n /** Absent is text. */\n type?: DatasetDraftFieldType\n required?: boolean\n}\n\n/**\n * What a caller sends as `content`. Each record's values are keyed by the\n * field NAME the caller gave, since the caller has no ids yet; the writer\n * mints the ids (`roast_preference` from \"Roast preference\").\n */\nexport interface DatasetDraftContent {\n /** The dataset's name; the request's `name` stands in when absent. */\n name?: string\n fields: DatasetDraftField[]\n records?: Array<Record<string, unknown>>\n /**\n * A text field, by name, a \"Page address\" field fills from (AGL-3475):\n * asked for where a record page will show each record at its own address.\n */\n pageAddressFrom?: string\n /**\n * Which seeded records are samples for the owner to replace, by position\n * as `records` (AGL-4065). Absent, or false, is a record of the owner's.\n */\n samples?: boolean[]\n}\n\n/** What the writer reports about a dataset. */\nexport interface DatasetDraftFacts {\n fields: Array<{ id: string; name: string; type: DatasetFieldType }>\n records: number\n /** The page-address field's id, where the dataset has one. */\n addressField: string | null\n /** The first photo field's id, where the dataset has one (AGL-3616). */\n imageField: string | null\n}\n\n/** The draft as the writer will store it. */\nexport interface DatasetDraftRead {\n name: string\n model: DatasetModel\n /** Each record's values by field id, coerced and addressed. */\n records: Array<Record<string, unknown>>\n addressField: string | null\n /** Which records are samples, by position (AGL-4065); absent where none is. */\n samples?: boolean[]\n}\n\nexport type DatasetDraftContentRead =\n | { ok: true; value: DatasetDraftRead }\n | { ok: false; problems: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** A value as a seeded record keeps it, before the model coerces it. */\nfunction seedValue(value: unknown): unknown {\n if (typeof value === 'string') return value.replace(/\\r\\n?/g, '\\n').trim().slice(0, DATASET_DRAFT_VALUE_MAX)\n if (Array.isArray(value)) {\n return value\n .map((entry) => (typeof entry === 'string' ? line(entry) : entry))\n .filter((entry) => entry !== '' && entry !== null && entry !== undefined)\n .slice(0, DATASET_DRAFT_LIST_MAX)\n }\n return value\n}\n\n/** The content as the writer reads it, or every problem that stops it. Pure. */\nexport function readDatasetDraftContent(content: Readonly<Record<string, unknown>>): DatasetDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The dataset needs a name')\n else if (name.length > DATASET_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${DATASET_DRAFT_NAME_MAX} characters`)\n }\n\n const rawFields = content['fields']\n const model: DatasetModel = { fields: {}, order: [] }\n /** Field name, lowercased → id. */\n const byName = new Map<string, string>()\n if (!Array.isArray(rawFields) || !rawFields.length) {\n problems.push('The dataset needs at least one field')\n } else if (rawFields.length > DATASET_DRAFT_FIELDS_MAX) {\n problems.push(`A dataset is made with at most ${DATASET_DRAFT_FIELDS_MAX} fields`)\n } else {\n for (const raw of rawFields) {\n const fieldName = isRecord(raw) ? line(raw['name']) : ''\n const rawType = (isRecord(raw) ? raw['type'] : undefined) ?? 'text'\n if (!fieldName) {\n problems.push('Each field needs a name')\n continue\n }\n if (fieldName.length > DATASET_DRAFT_FIELD_NAME_MAX) {\n problems.push(`The field \"${fieldName.slice(0, 20)}…\" has a name longer than ${DATASET_DRAFT_FIELD_NAME_MAX} characters`)\n continue\n }\n if (!(DRAFT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push(`The field \"${fieldName}\" is one of ${DRAFT_TYPES.join(', ')}`)\n continue\n }\n if (byName.has(fieldName.toLowerCase())) {\n problems.push(`Two fields are both called \"${fieldName}\"`)\n continue\n }\n const id = defaultDatasetFieldId(fieldName, new Set(model.order))\n if (!id) {\n problems.push(`The field \"${fieldName}\" needs a name with a letter in it`)\n continue\n }\n model.fields[id] = {\n name: fieldName,\n type: DATASET_DRAFT_FIELD_TYPES[rawType as DatasetDraftFieldType],\n ...(rawType === 'image' ? { customType: DATASET_IMAGE_FIELD_TYPE } : {}),\n ...(rawType === 'page' ? { customType: DATASET_PAGE_FIELD_TYPE } : {}),\n ...(isRecord(raw) && raw['required'] === true ? { required: true } : {}),\n }\n model.order.push(id)\n byName.set(fieldName.toLowerCase(), id)\n }\n }\n\n // The page address: a text field the address fills from, once.\n let addressField: string | null = null\n const rawAddress = content['pageAddressFrom']\n if (rawAddress !== undefined && rawAddress !== null && rawAddress !== '') {\n const sourceId = byName.get(line(rawAddress).toLowerCase())\n if (!sourceId || model.fields[sourceId]?.type !== 'text' || model.fields[sourceId]?.customType) {\n problems.push('A page address fills from one of the dataset’s text fields')\n } else {\n addressField = defaultDatasetFieldId('slug', new Set(model.order))\n model.fields[addressField] = {\n name: 'Page address',\n type: 'text',\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceId,\n }\n model.order.push(addressField)\n }\n }\n\n const rawRecords = content['records'] ?? []\n const records: Array<Record<string, unknown>> = []\n if (!Array.isArray(rawRecords)) {\n problems.push('Records are a list of values by field name')\n } else if (rawRecords.length > DATASET_DRAFT_RECORDS_MAX) {\n problems.push(`A dataset is seeded with at most ${DATASET_DRAFT_RECORDS_MAX} records`)\n } else if (!problems.length) {\n rawRecords.forEach((raw, index) => {\n if (!isRecord(raw)) {\n problems.push(`Record ${index + 1} is not a set of values`)\n return\n }\n const input: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(raw)) {\n const id = byName.get(line(key).toLowerCase())\n if (!id) {\n problems.push(`Record ${index + 1} names \"${line(key).slice(0, 40)}\", which is not a field`)\n continue\n }\n input[id] = seedValue(value)\n }\n const values = coerceDocumentValues(model, input)\n // An empty value is no value: it is not stored, as the card stores none.\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) {\n delete values[id]\n }\n }\n const errors = validateDocument(model, values)\n // A photo is an address the site's Image shows, whether or not the\n // \"Image\" type's check is registered in this process (AGL-3616).\n for (const [id, value] of Object.entries(values)) {\n const field = model.fields[id]\n if (field?.customType === DATASET_IMAGE_FIELD_TYPE && !errors[id] && !isDatasetImageValue(value)) {\n errors[id] = `${field.name} is not a photo from the media library or an https link`\n }\n // …and a page is one of the site's pages, by reference (AGL-3763).\n if (field?.customType === DATASET_PAGE_FIELD_TYPE && !errors[id] && !isDatasetPageValue(value)) {\n errors[id] = `${field.name} is not one of the site’s pages`\n }\n }\n for (const error of Object.values(errors)) problems.push(`Record ${index + 1}: ${error}`)\n if (!Object.keys(values).length) problems.push(`Record ${index + 1} has no values`)\n records.push(values)\n })\n }\n // Which records are samples (AGL-4065): true or false, one a record at most.\n const rawSamples = content['samples']\n if (rawSamples !== undefined && (!Array.isArray(rawSamples) || rawSamples.some((entry) => typeof entry !== 'boolean'))) {\n problems.push('Samples are a list of true or false, one a record')\n } else if (Array.isArray(rawSamples) && rawSamples.length > records.length) {\n problems.push('Samples name more records than the dataset is seeded with')\n }\n const samples = Array.isArray(rawSamples) && rawSamples.some((entry) => entry === true) ? records.map((_values, index) => rawSamples[index] === true) : null\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n\n // Every seeded record its own address, unique within the dataset.\n if (addressField) {\n const source = model.fields[addressField]?.slugFrom as string\n const assigned = uniqueRecordAddresses(records.map((values, index) => ({ id: String(index), source: values[source] })))\n records.forEach((values, index) => {\n const address = assigned.get(String(index))\n if (address) values[addressField as string] = address.slice(0, RECORD_PAGE_ADDRESS_MAX)\n })\n }\n return { ok: true, value: { name, model, records, addressField, ...(samples ? { samples } : {}) } }\n}\n\n/** The first photo field of a model, by id. */\nfunction imageFieldOf(model: DatasetModel): string | null {\n return model.order.find((id) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE) ?? null\n}\n\nfunction factsOf(model: DatasetModel, records: number, addressField: string | null): DatasetDraftFacts {\n return {\n fields: model.order.map((id) => ({ id, name: model.fields[id]?.name ?? id, type: model.fields[id]?.type ?? 'text' })),\n records,\n addressField,\n imageField: imageFieldOf(model),\n }\n}\n\n/** Whether content is a dataset this plugin would store, with what it says about it. Pure. */\nexport function checkDatasetDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readDatasetDraftContent(content)\n if (read.ok === false) return read\n return {\n ok: true,\n facts: factsOf(read.value.model, read.value.records.length, read.value.addressField) as unknown as Readonly<\n Record<string, unknown>\n >,\n }\n}\n\n/** Who the member is in the org, as the writer asks: whether they hold \"Manage data\". */\nexport interface DatasetDraftMember {\n canManageData: boolean\n /** The membership itself, for whether their access reaches a site. */\n member: Readonly<Record<string, unknown>>\n}\n\nexport interface DatasetDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<DatasetDraftMember | null>\n /** Whether the data store is released for the org; the platform's flag otherwise. */\n released?: (orgId: string) => Promise<boolean>\n /** Whether dataset bytes may grow; the platform's band otherwise. */\n storageFull?: (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Promise<boolean>\n}\n\nasync function platformMember(uid: string, orgId: string): Promise<DatasetDraftMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport function createDatasetDraftWriter(deps: DatasetDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n const released = deps.released ?? ((orgId: string) => isServerReleaseFlagOnForOrg('release_data_store', orgId))\n const storageFull =\n deps.storageFull ?? (async (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Boolean(await dataStorageRefusal(org, orgRef)))\n\n /** Everything but the room: the site is the org's, the member's key, the flag, the plan, the scope. */\n const early = async (context: PluginDraftContext): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n const member = await memberOf(context.uid, context.orgId)\n if (!member?.canManageData) return { status: 403, error: DATASET_DRAFT_PERMISSION_REFUSAL }\n if (!(await released(context.orgId))) return { status: 403, error: DATASET_DRAFT_RELEASE_REFUSAL }\n if (!checkEntitlement(context.org as never, 'dataStore')) return { status: 403, error: DATASET_DRAFT_PLAN_REFUSAL }\n // A member scoped to some sites must be able to see what they create.\n if (!memberCanSee(member.member as never, scopeOf(context))) {\n return { status: 403, error: DATASET_DRAFT_SCOPE_REFUSAL }\n }\n return null\n }\n\n return {\n refusal: async (context) => {\n const refused = await early(context)\n if (refused) return refused\n const used = (await firestore().collection('orgs').doc(context.orgId).collection('datasets').count().get()).data().count\n const quota = checkDatasetQuota(context.org as never, Number(used) || 0)\n return quota.allowed ? null : { status: 403, error: datasetDraftLimitRefusal(quota) }\n },\n\n check: (content) => checkDatasetDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n const dataset = await firestore().collection('orgs').doc(orgId).collection('datasets').doc(id).get()\n return dataset.exists ? recordOf(dataset) : null\n },\n\n // The late photo pass of an AI site start (AGL-3988): a list's covers\n // given photos once its pages are built. Only what a person could type\n // in the record's card is stored, under the same member rules as `write`.\n reviseRecords: async (request): Promise<PluginDraftRecordsRevise> => {\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const orders = [...new Set(request.records.map((record) => record.order))]\n .filter((order) => Number.isInteger(order) && order >= 0)\n .slice(0, DATASET_DRAFT_RECORDS_MAX)\n if (!orders.length) return { ok: true, changed: 0 }\n const db = firestore()\n const datasetRef = db.collection('orgs').doc(request.orgId).collection('datasets').doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftRecordsRevise> => {\n const dataset = await tx.get(datasetRef)\n const model = dataset.get('model') as DatasetModel | undefined\n if (!dataset.exists || !model?.order) return { ok: false, status: 404, error: 'The dataset is no longer there' }\n const rows = await tx.get(datasetRef.collection('records').where('order', 'in', orders))\n let changed = 0\n for (const revision of request.records) {\n const row = rows.docs.find((doc) => doc.get('order') === revision.order)\n if (!row) continue\n const stored = (row.get('values') ?? {}) as Record<string, unknown>\n // A member changed it since: theirs stands.\n if (Object.entries(revision.where ?? {}).some(([id, value]) => stored[id] !== value)) continue\n // Only the list's own fields are changed; a revision naming none of them changes nothing.\n const named = Object.entries(revision.values).filter(([id]) => model.fields[id])\n if (!named.length) continue\n const input: Record<string, unknown> = { ...stored }\n for (const [id, value] of named) input[id] = seedValue(value)\n const values = coerceDocumentValues(model, input)\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) delete values[id]\n }\n const errors = validateDocument(model, values)\n const badPhoto = Object.entries(values).some(\n ([id, value]) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE && !isDatasetImageValue(value),\n )\n if (Object.keys(errors).length || badPhoto) continue\n tx.update(row.ref, { values, ...datasetIntegrityUpdate(model, values, FieldValue.delete()), updatedAt: request.now })\n changed += 1\n }\n return { ok: true, changed }\n })\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readDatasetDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const db = firestore()\n const orgRef = db.collection('orgs').doc(request.orgId)\n const datasets = orgRef.collection('datasets')\n const datasetRef = datasets.doc(request.id)\n const { name, model, records, addressField, samples } = read.value\n const recordQuota = checkQuota(request.org as never, 'recordsPerDataset', Math.max(0, records.length - 1))\n if (records.length && !recordQuota.allowed) {\n return { ok: false, status: 403, error: datasetDraftRecordLimitRefusal(recordQuota.limit) }\n }\n if (records.length && (await storageFull(request.org, orgRef))) {\n return { ok: false, status: 403, error: DATASET_DRAFT_STORAGE_REFUSAL }\n }\n const visibleTo = scopeOf(request)\n // Minted before the transaction, so a retried attempt writes the same rows.\n const recordIds = records.map(() => createResourceUid())\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const existing = await tx.get(datasetRef)\n // Asked again under the same id: the dataset it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const live = (await tx.get(datasets.count())).data().count\n const quota = checkDatasetQuota(request.org as never, Number(live) || 0)\n if (!quota.allowed) return { ok: false, status: 403, error: datasetDraftLimitRefusal(quota) }\n tx.create(datasetRef, {\n displayName: name,\n fields: [...model.order],\n model,\n ...newResourceScopeFields(visibleTo),\n createdAt: request.now,\n createdBy: request.uid,\n })\n records.forEach((values, order) => {\n tx.create(datasetRef.collection('records').doc(recordIds[order]), {\n values,\n ...datasetIntegrityFields(model, values),\n // A sample for the owner to replace (AGL-4065), beside its values: no page reads it.\n ...(samples?.[order] ? { sample: true } : {}),\n order,\n createdAt: request.now,\n updatedAt: request.now,\n })\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: factsOf(model, records.length, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n })\n },\n }\n}\n\n/**\n * The scope a dataset drafted for a site takes: that site alone (AGL-4003).\n *\n * A drafted dataset is the site's own content, made for it by Aglyn AI, so it\n * is shared with that site and no other, whatever the workspace's Default\n * sharing says for the datasets a person makes on the Data page. Deleting the\n * site erases it with its records (`eraseHost`), where a dataset shared with\n * every site outlived its site: 53 did in one workspace. A member can share it\n * with more sites on the Data page.\n */\nfunction scopeOf(context: Pick<PluginDraftContext, 'hostId'>) {\n return [hostScopeToken(context.hostId)]\n}\n\nfunction recordOf(dataset: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (dataset.data() ?? {}) as { displayName?: unknown; model?: DatasetModel }\n const model: DatasetModel = data.model?.order ? data.model : { fields: {}, order: [] }\n const addressField = model.order.find((id) => model.fields[id]?.customType === RECORD_PAGE_ADDRESS_FIELD_TYPE) ?? null\n return {\n id: dataset.id,\n name: String(data.displayName ?? ''),\n versionId: null,\n // A replay reports the fields; how many records it was seeded with is the first write's to say.\n facts: factsOf(model, 0, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport const datasetDraftWriter = createDatasetDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerDatasetDraftWriter(): void {\n registerPluginResourceDraftWriter(DATASET_DRAFT_RESOURCE, datasetDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["createResourceUid","permissionRefusalText","memberCanSee","checkDatasetQuota","checkEntitlement","checkQuota","hostScopeToken","newResourceScopeFields","registerPluginResourceDraftWriter","firebaseAdmin","FieldValue","dataStorageRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isServerReleaseFlagOnForOrg","BUNDLE_ID","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","defaultDatasetFieldId","validateDocument","DATASET_IMAGE_FIELD_TYPE","isDatasetImageValue","DATASET_PAGE_FIELD_TYPE","isDatasetPageValue","RECORD_PAGE_ADDRESS_FIELD_TYPE","RECORD_PAGE_ADDRESS_MAX","uniqueRecordAddresses","DATASET_DRAFT_RESOURCE","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_VALUE_MAX","DATASET_DRAFT_LIST_MAX","DATASET_DRAFT_FIELD_TYPES","text","number","integer","boolean","list","image","page","DRAFT_TYPES","Object","keys","DATASET_DRAFT_PERMISSION_REFUSAL","DATASET_DRAFT_PLAN_REFUSAL","DATASET_DRAFT_RELEASE_REFUSAL","DATASET_DRAFT_SCOPE_REFUSAL","DATASET_DRAFT_STORAGE_REFUSAL","datasetDraftLimitRefusal","quota","upgradeRequired","limit","addonPriceUsd","datasetDraftRecordLimitRefusal","isRecord","value","Array","isArray","line","replace","trim","seedValue","slice","map","entry","filter","undefined","readDatasetDraftContent","content","problems","name","push","length","rawFields","model","fields","order","byName","Map","raw","fieldName","rawType","includes","join","has","toLowerCase","id","Set","type","customType","required","set","addressField","rawAddress","sourceId","get","slugFrom","rawRecords","records","forEach","index","input","key","entries","values","errors","field","error","rawSamples","some","samples","_values","ok","source","assigned","String","address","imageFieldOf","find","factsOf","imageField","checkDatasetDraftContent","read","facts","platformMember","uid","orgId","membership","member","canManageData","createDatasetDraftWriter","deps","firestore","app","orgIdForHost","hostId","memberOf","released","storageFull","org","orgRef","Boolean","early","context","status","scopeOf","refusal","refused","used","collection","doc","count","data","Number","allowed","check","dataset","exists","recordOf","reviseRecords","request","orders","record","isInteger","changed","db","datasetRef","runTransaction","tx","rows","where","revision","row","docs","stored","named","badPhoto","update","ref","delete","updatedAt","now","write","asked","datasets","recordQuota","Math","max","visibleTo","recordIds","existing","replayed","live","create","displayName","createdAt","createdBy","sample","versionId","datasetDraftWriter","registerDatasetDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,YAAY,QAAQ,uCAAsC;AACnE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AAC1G,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,sCAAqC;AAC5F,SACEC,iCAAiC,QAQ5B,qDAAoD;AAC3D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,kBAAkB,QAAQ,oDAAmD;AACtF,SACEC,sBAAsB,EACtBC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,QAGX,6BAAyB;AAChC,SAASC,wBAAwB,EAAEC,mBAAmB,QAAQ,kCAA8B;AAC5F,SAASC,uBAAuB,EAAEC,kBAAkB,QAAQ,iCAA6B;AACzF,SACEC,8BAA8B,EAC9BC,uBAAuB,EACvBC,qBAAqB,QAChB,kCAA8B;AAiDrC,uDAAuD,GACvD,OAAO,MAAMC,yBAAyB,UAAS;AAE/C,8DAA8D,GAC9D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,KAAK9E,KAAK,GAAG;QAAEC,QAAQ,CAAC;QAAGC,OAAO,EAAE;IAAC;IACrF,MAAMgB,gBAAelB,oBAAAA,MAAME,KAAK,CAAC0C,IAAI,CAAC,CAAChC;YAAOZ;eAAAA,EAAAA,mBAAAA,MAAMC,MAAM,CAACW,GAAG,qBAAhBZ,iBAAkBe,UAAU,MAAKnE;kBAA1DoD,oBAA6F;IAClH,OAAO;QACLY,IAAIsE,QAAQtE,EAAE;QACdhB,MAAM6C,QAAOqC,oBAAAA,KAAK0C,WAAW,YAAhB1C,oBAAoB;QACjC8C,WAAW;QACX,gGAAgG;QAChG3E,OAAOJ,QAAQ7C,OAAO,GAAGkB;IAC3B;AACF;AAEA,OAAO,MAAM2G,qBAAqBrE,2BAA0B;AAE5D;;;CAGC,GACD,OAAO,SAASsE;IACdpM,kCAAkCqB,wBAAwB8K,oBAAoB;QAAEE,UAAU7L;IAAU;AACtG"}
@@ -18,6 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { checkDatasetQuota, checkEntitlement, checkQuota, createResourceUid, ensureDeclaredCustomFieldTypes, memberCanSee } from "@aglyn/aglyn/server";
19
19
  import { emailUnverifiedResponse, firebaseAdmin, dataStorageRefusal, isImpersonationSession, isServerReleaseFlagOnForOrg, lockdownRefusal, memberHasOrgPermission, resolveOrgIdForHost, resolveOrgMembership } from "@aglyn/tenant-data-admin";
20
20
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
21
+ import { permissionRefusalText } from "@aglyn/aglyn/app-utils/org-permissions";
21
22
  import { FieldPath, FieldValue, Timestamp } from "firebase-admin/firestore";
22
23
  import { announceDatasetRecords as announceDatasetChange } from "./announce-dataset-records.js";
23
24
  import { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from "../model/dataset-models.js";
@@ -40,11 +41,19 @@ import { RECORD_PAGE_ADDRESS_FIELD_TYPE, fillRecordAddresses, isRecordAddressFie
40
41
  status: 403
41
42
  });
42
43
  }
43
- /** Roles allowed to create org data — mirrors rules' canWriteOrgData(). */ const WRITER_ROLES = new Set([
44
- 'owner',
45
- 'admin',
46
- 'editor'
47
- ]);
44
+ /**
45
+ * The key every action here asks (AGL-4047): "Manage data", whose default is
46
+ * the owner, admin and editor, as the rules' `canWriteOrgDatasets()` asks it.
47
+ */ const DATASETS_PERMISSION = 'data.manage';
48
+ /** The 403 for a member without it, naming the permission, never a role. */ function datasetsPermissionRefusal() {
49
+ return Response.json({
50
+ error: permissionRefusalText(DATASETS_PERMISSION),
51
+ reason: 'permission',
52
+ permission: DATASETS_PERMISSION
53
+ }, {
54
+ status: 403
55
+ });
56
+ }
48
57
  /**
49
58
  * Rows written per import transaction.
50
59
  *
@@ -113,35 +122,25 @@ import { RECORD_PAGE_ADDRESS_FIELD_TYPE, fillRecordAddresses, isRecordAddressFie
113
122
  }
114
123
  const membership = await resolveOrgMembership(decoded.uid, orgId);
115
124
  const member = membership == null ? void 0 : membership.member;
116
- if (!member || !WRITER_ROLES.has(String(member.role))) {
117
- return Response.json({
118
- error: 'Editing org data requires the editor role'
119
- }, {
120
- status: 403
121
- });
122
- }
125
+ if (!member) return datasetsPermissionRefusal();
123
126
  /*==========================================
124
- * AND the granular permission (AGL-2444).
127
+ * "Manage data" (`data.manage`), and nothing about the role (AGL-2444,
128
+ * AGL-4047).
125
129
  *
126
130
  * `data.manage` had ZERO consumers: an owner could build a custom role
127
131
  * with "Manage data" unticked, assign it, and the member kept creating,
128
132
  * editing and deleting datasets — because this gate read the raw role,
129
133
  * exactly the defect AGL-2350 fixed one route over on `hosts.create`.
130
134
  *
131
- * Identical for the built-in roles — `data.manage` is on for owner,
132
- * admin and editor, which is `WRITER_ROLES` — so nobody's access moves.
133
- * What it adds is that a custom role or a per-member override is now
134
- * honoured, which is the narrowing the docs sell.
135
- *
136
- * The role check is kept ALONGSIDE it rather than replaced. It mirrors
137
- * the rules' `canWriteOrgData()`, and a route that disagreed with the
138
- * rules would let one door open while the other stayed shut.
139
- *=========================================*/ if (decoded['staff'] !== true && !await memberHasOrgPermission(orgId, member, 'data.manage')) {
140
- return Response.json({
141
- error: 'Your organization role does not allow editing organization data'
142
- }, {
143
- status: 403
144
- });
135
+ * It then sat BESIDE a role gate (owner, admin or editor), so the key
136
+ * could narrow but never widen: a viewer granted it was still refused.
137
+ * The key's default is exactly those three roles, so with no custom role
138
+ * or override deciding it nobody's access moves; a grant now opens the
139
+ * route as it opens the rules' `canWriteOrgDatasets()`, and a refusal
140
+ * names the permission. Staff keep their bypass, as the rules' `isStaff()`
141
+ * does, and still need a membership.
142
+ *=========================================*/ if (decoded['staff'] !== true && !await memberHasOrgPermission(orgId, member, DATASETS_PERMISSION)) {
143
+ return datasetsPermissionRefusal();
145
144
  }
146
145
  // Release gate (AGL-1653). `<FeatureGate flag="release_data_store">` on
147
146
  // the org Data page was the only gate, so org-level dataset
@@ -334,8 +333,8 @@ import { RECORD_PAGE_ADDRESS_FIELD_TYPE, fillRecordAddresses, isRecordAddressFie
334
333
  /**
335
334
  * The caller has to be able to SEE the dataset they add rows to.
336
335
  *
337
- * The role and `data.manage` gates above are about the org, and a member
338
- * scoped to one site passes both. The rules hold every record update and
336
+ * The `data.manage` gate above is about the org, and a member scoped
337
+ * to one site can pass it. The rules hold every record update and
339
338
  * delete to the parent dataset being visible (`parentDatasetVisible()`),
340
339
  * and refuse client record creates outright, so this route is the one
341
340
  * place a member's create can be held to the same condition. Without it,
@@ -476,7 +475,7 @@ import { RECORD_PAGE_ADDRESS_FIELD_TYPE, fillRecordAddresses, isRecordAddressFie
476
475
  * Firestore — it consumes no quota — with the values coerced, filled
477
476
  * and validated against the model and the integrity and filter index
478
477
  * moved with them; the native apps reach the same write here, under
479
- * the same role, `data.manage` and visibility gates as a create.
478
+ * the same `data.manage` and visibility gates as a create.
480
479
  * `values` is replaced whole, so a removed field's value strips here,
481
480
  * as it does on the card (the AGL-178 policy).
482
481
  */ if (action === 'update-record') {
@@ -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 { 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/** Roles allowed to create org data — mirrors rules' canWriteOrgData(). */\nconst WRITER_ROLES = new Set(['owner', 'admin', 'editor'])\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 || !WRITER_ROLES.has(String(member.role))) {\n return Response.json({ error: 'Editing org data requires the editor role' }, { status: 403 })\n }\n /*==========================================\n * AND the granular permission (AGL-2444).\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 * Identical for the built-in roles — `data.manage` is on for owner,\n * admin and editor, which is `WRITER_ROLES` — so nobody's access moves.\n * What it adds is that a custom role or a per-member override is now\n * honoured, which is the narrowing the docs sell.\n *\n * The role check is kept ALONGSIDE it rather than replaced. It mirrors\n * the rules' `canWriteOrgData()`, and a route that disagreed with the\n * rules would let one door open while the other stayed shut.\n *=========================================*/\n if (\n decoded['staff'] !== true &&\n !(await memberHasOrgPermission(orgId, member, 'data.manage'))\n ) {\n return Response.json({\n error: 'Your organization role does not allow editing organization data',\n }, { status: 403 })\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 role and `data.manage` gates above are about the org, and a member\n * scoped to one site passes both. 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 role, `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","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","WRITER_ROLES","Set","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","has","role","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","order","nextModel","name","customType","slugFrom","update","updatedAt","snapshot","orderBy","documentId","docs","valuesOf","taken","filter","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","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,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,iBAAiB,EACjBC,8BAA8B,EAC9BC,YAAY,QACP,sBAAqB;AAC5B,SACEC,uBAAuB,EACvBC,aAAa,EACbC,kBAAkB,EAClBC,sBAAsB,EACtBC,2BAA2B,EAC3BC,eAAe,EACfC,sBAAsB,EACtBC,mBAAmB,EACnBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,EAAEC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAC3E,SAASC,0BAA0BC,qBAAqB,QAAQ,gCAA4B;AAC5F,SAASC,oBAAoB,EAAEC,sBAAsB,EAAEC,sBAAsB,EAAEC,qBAAqB,EAAEC,gBAAgB,QAAQ,6BAAyB;AACvJ,SAASC,qBAAqB,QAAQ,uBAAmB;AACzD,SAASC,mBAAmB,EAAEC,mBAAmB,EAAEC,uBAAuB,QAAQ,yCAAqC;AACvH,SACEC,8BAA8B,EAC9BC,mBAAmB,EACn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f,QAAQ;gBAAI;YAElB;YACA,OAAOL,SAASC,IAAI,CAAC;gBAAEyE,IAAI;gBAAMwE;gBAAKM,SAASN,IAAI9H,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,IAAI3B,iBAAiB2B,QAAQ;YAC3B,OAAOF,SAASC,IAAI,CAAC;gBAAEC,OAAO;YAAkB,GAAG;gBAAEG,QAAQ;YAAI;QACnE;QACAoJ,QAAQvJ,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 {\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;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