@aglyn/plugins-data 1.14.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +12 -10
- package/src/lib/artifact/dataset-schema-artifact.server.js +4 -1
- package/src/lib/artifact/dataset-schema-artifact.server.js.map +1 -1
- package/src/lib/components/data-console-page.js +4 -2
- package/src/lib/components/data-console-page.js.map +1 -1
- package/src/lib/components/dataset-record-dialog.component.d.ts +22 -0
- package/src/lib/components/dataset-record-dialog.component.js +77 -54
- package/src/lib/components/dataset-record-dialog.component.js.map +1 -1
- package/src/lib/components/dataset-schema-dialog.component.js +29 -47
- package/src/lib/components/dataset-schema-dialog.component.js.map +1 -1
- package/src/lib/components/host-datasets-card.component.d.ts +12 -0
- package/src/lib/components/host-datasets-card.component.js +651 -220
- package/src/lib/components/host-datasets-card.component.js.map +1 -1
- package/src/lib/components/use-org-sites.d.ts +27 -0
- package/src/lib/components/use-org-sites.js +68 -0
- package/src/lib/components/use-org-sites.js.map +1 -0
- package/src/lib/model/data-record-routes.js +6 -3
- package/src/lib/model/data-record-routes.js.map +1 -1
- package/src/lib/model/dataset-model-core.d.ts +22 -0
- package/src/lib/model/dataset-model-core.js +34 -0
- package/src/lib/model/dataset-model-core.js.map +1 -1
- package/src/lib/model/dataset-rail.d.ts +88 -0
- package/src/lib/model/dataset-rail.js +123 -0
- package/src/lib/model/dataset-rail.js.map +1 -0
- package/src/lib/model/dataset-record-list.js +17 -2
- package/src/lib/model/dataset-record-list.js.map +1 -1
- package/src/lib/model/datasets.d.ts +14 -0
- package/src/lib/model/datasets.js +10 -0
- package/src/lib/model/datasets.js.map +1 -1
- package/src/lib/plugin.d.ts +5 -1
- package/src/lib/plugin.js +8 -3
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/record-pages/record-template-section.component.js +12 -1
- package/src/lib/record-pages/record-template-section.component.js.map +1 -1
- package/src/lib/server/api-v1/datasets.js +6 -1
- package/src/lib/server/api-v1/datasets.js.map +1 -1
- package/src/lib/server/dataset-drafts.js +2 -0
- package/src/lib/server/dataset-drafts.js.map +1 -1
- package/src/lib/server/datasets-route.js +2 -1
- package/src/lib/server/datasets-route.js.map +1 -1
- package/src/lib/site-bundle/datasets-site-bundle.server.js +8 -1
- package/src/lib/site-bundle/datasets-site-bundle.server.js.map +1 -1
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** A site of the workspace the reader is a member of, as the Data page names it. */
|
|
2
|
+
export interface OrgSite {
|
|
3
|
+
$id: string;
|
|
4
|
+
name?: string;
|
|
5
|
+
subdomain?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The workspace's sites this reader is a member of, for naming who a dataset
|
|
9
|
+
* is shared with (AGL-1145, AGL-4047).
|
|
10
|
+
*
|
|
11
|
+
* Queried here rather than via the console's `useOrgHosts`, because this
|
|
12
|
+
* plugin is a lib and cannot import from an app, so it repeats that hook's
|
|
13
|
+
* membership filter. `/hosts/{hostId}` is gated per document on
|
|
14
|
+
* `memberRoles.{uid}`, and Firestore evaluates a LIST against the QUERY rather
|
|
15
|
+
* than its results: filtering on `orgId` alone is a flat denial for every
|
|
16
|
+
* non-staff reader (cloud/hosts-list-constraint.spec.mjs).
|
|
17
|
+
*
|
|
18
|
+
* ONE query, word for word, for the Data card and its Schema dialog: the SDK
|
|
19
|
+
* serves two listeners of the same query from one target, so naming the
|
|
20
|
+
* sites in the rail costs no read the dialog was not already making.
|
|
21
|
+
*/
|
|
22
|
+
export declare function useOrgSites(orgId: string | null | undefined): {
|
|
23
|
+
sites: OrgSite[];
|
|
24
|
+
/** Site id → the name the console shows for it. */
|
|
25
|
+
hostNames: Readonly<Record<string, string>>;
|
|
26
|
+
ready: boolean;
|
|
27
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ 'use client';
|
|
17
|
+
import { HOST_ACCESS_ROLES } from "@aglyn/aglyn";
|
|
18
|
+
import { useFirestore, useFirestoreCollection, useUser } from "@aglyn/tenant-feature-instance";
|
|
19
|
+
import { collection, limit, query, where } from "firebase/firestore";
|
|
20
|
+
import { useMemo } from "react";
|
|
21
|
+
const NO_SITES = [];
|
|
22
|
+
/**
|
|
23
|
+
* The workspace's sites this reader is a member of, for naming who a dataset
|
|
24
|
+
* is shared with (AGL-1145, AGL-4047).
|
|
25
|
+
*
|
|
26
|
+
* Queried here rather than via the console's `useOrgHosts`, because this
|
|
27
|
+
* plugin is a lib and cannot import from an app, so it repeats that hook's
|
|
28
|
+
* membership filter. `/hosts/{hostId}` is gated per document on
|
|
29
|
+
* `memberRoles.{uid}`, and Firestore evaluates a LIST against the QUERY rather
|
|
30
|
+
* than its results: filtering on `orgId` alone is a flat denial for every
|
|
31
|
+
* non-staff reader (cloud/hosts-list-constraint.spec.mjs).
|
|
32
|
+
*
|
|
33
|
+
* ONE query, word for word, for the Data card and its Schema dialog: the SDK
|
|
34
|
+
* serves two listeners of the same query from one target, so naming the
|
|
35
|
+
* sites in the rail costs no read the dialog was not already making.
|
|
36
|
+
*/ export function useOrgSites(orgId) {
|
|
37
|
+
const firestore = useFirestore();
|
|
38
|
+
const { data: user } = useUser();
|
|
39
|
+
const uid = user == null ? void 0 : user.uid;
|
|
40
|
+
const { data } = useFirestoreCollection(// Held rather than substituted while the uid resolves: a placeholder is
|
|
41
|
+
// still a question asked of the server, and here one that is denied.
|
|
42
|
+
()=>uid && orgId ? query(collection(firestore, 'hosts'), where(`memberRoles.${uid}`, 'in', HOST_ACCESS_ROLES), where('orgId', '==', orgId), limit(200)) : null, [
|
|
43
|
+
firestore,
|
|
44
|
+
orgId,
|
|
45
|
+
uid
|
|
46
|
+
], {
|
|
47
|
+
idField: '$id'
|
|
48
|
+
});
|
|
49
|
+
const sites = useMemo(()=>data != null ? data : NO_SITES, [
|
|
50
|
+
data
|
|
51
|
+
]);
|
|
52
|
+
const hostNames = useMemo(()=>Object.fromEntries(sites.map((site)=>{
|
|
53
|
+
var _ref, _site_name;
|
|
54
|
+
return [
|
|
55
|
+
site.$id,
|
|
56
|
+
(_ref = (_site_name = site.name) != null ? _site_name : site.subdomain) != null ? _ref : site.$id
|
|
57
|
+
];
|
|
58
|
+
})), [
|
|
59
|
+
sites
|
|
60
|
+
]);
|
|
61
|
+
return {
|
|
62
|
+
sites,
|
|
63
|
+
hostNames,
|
|
64
|
+
ready: Array.isArray(data)
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=use-org-sites.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/use-org-sites.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'use client'\n\nimport { HOST_ACCESS_ROLES } from '@aglyn/aglyn'\nimport { useFirestore, useFirestoreCollection, useUser } from '@aglyn/tenant-feature-instance'\nimport { collection, limit, query, where } from 'firebase/firestore'\nimport { useMemo } from 'react'\n\n/** A site of the workspace the reader is a member of, as the Data page names it. */\nexport interface OrgSite {\n $id: string\n name?: string\n subdomain?: string\n}\n\nconst NO_SITES: OrgSite[] = []\n\n/**\n * The workspace's sites this reader is a member of, for naming who a dataset\n * is shared with (AGL-1145, AGL-4047).\n *\n * Queried here rather than via the console's `useOrgHosts`, because this\n * plugin is a lib and cannot import from an app, so it repeats that hook's\n * membership filter. `/hosts/{hostId}` is gated per document on\n * `memberRoles.{uid}`, and Firestore evaluates a LIST against the QUERY rather\n * than its results: filtering on `orgId` alone is a flat denial for every\n * non-staff reader (cloud/hosts-list-constraint.spec.mjs).\n *\n * ONE query, word for word, for the Data card and its Schema dialog: the SDK\n * serves two listeners of the same query from one target, so naming the\n * sites in the rail costs no read the dialog was not already making.\n */\nexport function useOrgSites(orgId: string | null | undefined): {\n sites: OrgSite[]\n /** Site id → the name the console shows for it. */\n hostNames: Readonly<Record<string, string>>\n ready: boolean\n} {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = (user as { uid?: string } | undefined)?.uid\n const { data } = useFirestoreCollection<OrgSite>(\n // Held rather than substituted while the uid resolves: a placeholder is\n // still a question asked of the server, and here one that is denied.\n () =>\n uid && orgId\n ? query(\n collection(firestore, 'hosts'),\n where(`memberRoles.${uid}`, 'in', HOST_ACCESS_ROLES),\n where('orgId', '==', orgId),\n limit(200),\n )\n : null,\n [firestore, orgId, uid],\n { idField: '$id' },\n )\n const sites = useMemo(() => data ?? NO_SITES, [data])\n const hostNames = useMemo(\n () => Object.fromEntries(sites.map((site) => [site.$id, site.name ?? site.subdomain ?? site.$id])),\n [sites],\n )\n return { sites, hostNames, ready: Array.isArray(data) }\n}\n"],"names":["HOST_ACCESS_ROLES","useFirestore","useFirestoreCollection","useUser","collection","limit","query","where","useMemo","NO_SITES","useOrgSites","orgId","firestore","data","user","uid","idField","sites","hostNames","Object","fromEntries","map","site","$id","name","subdomain","ready","Array","isArray"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,iBAAiB,QAAQ,eAAc;AAChD,SAASC,YAAY,EAAEC,sBAAsB,EAAEC,OAAO,QAAQ,iCAAgC;AAC9F,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AACpE,SAASC,OAAO,QAAQ,QAAO;AAS/B,MAAMC,WAAsB,EAAE;AAE9B;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,YAAYC,KAAgC;IAM1D,MAAMC,YAAYX;IAClB,MAAM,EAAEY,MAAMC,IAAI,EAAE,GAAGX;IACvB,MAAMY,MAAOD,wBAAD,AAACA,KAAuCC,GAAG;IACvD,MAAM,EAAEF,IAAI,EAAE,GAAGX,uBACf,wEAAwE;IACxE,qEAAqE;IACrE,IACEa,OAAOJ,QACHL,MACEF,WAAWQ,WAAW,UACtBL,MAAM,CAAC,YAAY,EAAEQ,KAAK,EAAE,MAAMf,oBAClCO,MAAM,SAAS,MAAMI,QACrBN,MAAM,QAER,MACN;QAACO;QAAWD;QAAOI;KAAI,EACvB;QAAEC,SAAS;IAAM;IAEnB,MAAMC,QAAQT,QAAQ,IAAMK,eAAAA,OAAQJ,UAAU;QAACI;KAAK;IACpD,MAAMK,YAAYV,QAChB,IAAMW,OAAOC,WAAW,CAACH,MAAMI,GAAG,CAAC,CAACC;gBAAoBA,MAAAA;mBAAX;gBAACA,KAAKC,GAAG;iBAAED,QAAAA,aAAAA,KAAKE,IAAI,YAATF,aAAaA,KAAKG,SAAS,YAA3BH,OAA+BA,KAAKC,GAAG;aAAC;aAChG;QAACN;KAAM;IAET,OAAO;QAAEA;QAAOC;QAAWQ,OAAOC,MAAMC,OAAO,CAACf;IAAM;AACxD"}
|
|
@@ -24,8 +24,8 @@ import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
|
24
24
|
* for `dataset` rather than spelling this plugin's nav slug, and gets `null`
|
|
25
25
|
* (text instead of a link) where it is not loaded. A dataset belongs to the
|
|
26
26
|
* organization and is shared with sites: a site's Data page lists the ones it
|
|
27
|
-
* can see, and the organization's lists them all.
|
|
28
|
-
*
|
|
27
|
+
* can see, and the organization's lists them all. Each dataset is a tab of
|
|
28
|
+
* those pages at `/data/<datasetId>` (AGL-4047), so a record opens its tab.
|
|
29
29
|
*/ /** The nav slug the shell resolves this plugin's site page by. */ const DATA_SLUG = 'data';
|
|
30
30
|
function list({ orgSlug, host }) {
|
|
31
31
|
if (!orgSlug) return null;
|
|
@@ -44,7 +44,10 @@ function list({ orgSlug, host }) {
|
|
|
44
44
|
*/ export function registerDataRecordRoutes() {
|
|
45
45
|
registerPluginRecordRoute('dataset', {
|
|
46
46
|
list,
|
|
47
|
-
record: (context)=>
|
|
47
|
+
record: (context, id)=>{
|
|
48
|
+
const page = list(context);
|
|
49
|
+
return page && id ? `${page}/${encodeURIComponent(id)}` : page;
|
|
50
|
+
}
|
|
48
51
|
}, {
|
|
49
52
|
pluginId: BUNDLE_ID
|
|
50
53
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/data-record-routes.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport {\n registerPluginRecordRoute,\n type PluginRecordRouteContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * Where a dataset is read, published for every other surface (AGL-3616).\n *\n * An assistant job that made a menu or a team as a dataset opens it on the\n * Data page, which is this plugin's — so it asks the record-route registry\n * for `dataset` rather than spelling this plugin's nav slug, and gets `null`\n * (text instead of a link) where it is not loaded. A dataset belongs to the\n * organization and is shared with sites: a site's Data page lists the ones it\n * can see, and the organization's lists them all.
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/data-record-routes.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport {\n registerPluginRecordRoute,\n type PluginRecordRouteContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * Where a dataset is read, published for every other surface (AGL-3616).\n *\n * An assistant job that made a menu or a team as a dataset opens it on the\n * Data page, which is this plugin's — so it asks the record-route registry\n * for `dataset` rather than spelling this plugin's nav slug, and gets `null`\n * (text instead of a link) where it is not loaded. A dataset belongs to the\n * organization and is shared with sites: a site's Data page lists the ones it\n * can see, and the organization's lists them all. Each dataset is a tab of\n * those pages at `/data/<datasetId>` (AGL-4047), so a record opens its tab.\n */\n\n/** The nav slug the shell resolves this plugin's site page by. */\nconst DATA_SLUG = 'data'\n\nfunction list({ orgSlug, host }: PluginRecordRouteContext): string | null {\n if (!orgSlug) return null\n return host ? buildRoute(Route.HOST_PLUGIN, { orgSlug, host, pluginSlug: DATA_SLUG }) : buildRoute(Route.ORG_DATA, { orgSlug })\n}\n\n/**\n * Called from the console registrar. The owner is named rather than read off\n * the loader's marker, so the route registers the same way under a spec that\n * calls the registrar directly.\n */\nexport function registerDataRecordRoutes(): void {\n registerPluginRecordRoute(\n 'dataset',\n {\n list,\n record: (context, id) => {\n const page = list(context)\n return page && id ? `${page}/${encodeURIComponent(id)}` : page\n },\n },\n { pluginId: BUNDLE_ID },\n )\n}\n"],"names":["buildRoute","Route","registerPluginRecordRoute","BUNDLE_ID","DATA_SLUG","list","orgSlug","host","HOST_PLUGIN","pluginSlug","ORG_DATA","registerDataRecordRoutes","record","context","id","page","encodeURIComponent","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SACEC,yBAAyB,QAEpB,mDAAkD;AACzD,SAASC,SAAS,QAAQ,gCAA4B;AAEtD;;;;;;;;;;CAUC,GAED,gEAAgE,GAChE,MAAMC,YAAY;AAElB,SAASC,KAAK,EAAEC,OAAO,EAAEC,IAAI,EAA4B;IACvD,IAAI,CAACD,SAAS,OAAO;IACrB,OAAOC,OAAOP,WAAWC,MAAMO,WAAW,EAAE;QAAEF;QAASC;QAAME,YAAYL;IAAU,KAAKJ,WAAWC,MAAMS,QAAQ,EAAE;QAAEJ;IAAQ;AAC/H;AAEA;;;;CAIC,GACD,OAAO,SAASK;IACdT,0BACE,WACA;QACEG;QACAO,QAAQ,CAACC,SAASC;YAChB,MAAMC,OAAOV,KAAKQ;YAClB,OAAOE,QAAQD,KAAK,GAAGC,KAAK,CAAC,EAAEC,mBAAmBF,KAAK,GAAGC;QAC5D;IACF,GACA;QAAEE,UAAUd;IAAU;AAE1B"}
|
|
@@ -297,3 +297,25 @@ export declare function datasetDisplayName(dataset: {
|
|
|
297
297
|
displayName?: unknown;
|
|
298
298
|
name?: unknown;
|
|
299
299
|
} | null | undefined): string;
|
|
300
|
+
/** One dataset as a picker offers it: what tells it apart from another of its name. */
|
|
301
|
+
export interface DatasetPickerEntry {
|
|
302
|
+
id: string;
|
|
303
|
+
/** The name the Data page shows. */
|
|
304
|
+
name: string;
|
|
305
|
+
/** Who it is shared with, as the console says it: `Bakery only`, `All sites`. */
|
|
306
|
+
sharing: string;
|
|
307
|
+
/** How many fields its model has. */
|
|
308
|
+
fields: number;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* What each dataset is called in a picker (AGL-4047): its name alone, unless
|
|
312
|
+
* another in the same list has that name too. Then who it is shared with
|
|
313
|
+
* follows (`Services · Bakery only`), and where that still matches another,
|
|
314
|
+
* its field count (`Services · Bakery only · 5 fields`). Names are compared
|
|
315
|
+
* the way the stored search key is: trimmed, spaces collapsed, any case.
|
|
316
|
+
*
|
|
317
|
+
* A site start makes the same names on every site, shared with that site
|
|
318
|
+
* alone, so who it is shared with is what tells most of them apart. No imports,
|
|
319
|
+
* so the native apps can generate from it.
|
|
320
|
+
*/
|
|
321
|
+
export declare function datasetPickerLabels(entries: readonly DatasetPickerEntry[]): Record<string, string>;
|
|
@@ -507,5 +507,39 @@ const textKey = datasetFilterTextKey;
|
|
|
507
507
|
}
|
|
508
508
|
return '';
|
|
509
509
|
}
|
|
510
|
+
/**
|
|
511
|
+
* What each dataset is called in a picker (AGL-4047): its name alone, unless
|
|
512
|
+
* another in the same list has that name too. Then who it is shared with
|
|
513
|
+
* follows (`Services · Bakery only`), and where that still matches another,
|
|
514
|
+
* its field count (`Services · Bakery only · 5 fields`). Names are compared
|
|
515
|
+
* the way the stored search key is: trimmed, spaces collapsed, any case.
|
|
516
|
+
*
|
|
517
|
+
* A site start makes the same names on every site, shared with that site
|
|
518
|
+
* alone, so who it is shared with is what tells most of them apart. No imports,
|
|
519
|
+
* so the native apps can generate from it.
|
|
520
|
+
*/ export function datasetPickerLabels(entries) {
|
|
521
|
+
const key = (text)=>text.trim().replace(/\s+/g, ' ').toLowerCase();
|
|
522
|
+
const count = (keys)=>{
|
|
523
|
+
var _counts_get;
|
|
524
|
+
const counts = new Map();
|
|
525
|
+
for (const each of keys)counts.set(each, ((_counts_get = counts.get(each)) != null ? _counts_get : 0) + 1);
|
|
526
|
+
return counts;
|
|
527
|
+
};
|
|
528
|
+
const names = count(entries.map((entry)=>key(entry.name)));
|
|
529
|
+
const shared = (entry)=>`${key(entry.name)}\u0000${key(entry.sharing)}`;
|
|
530
|
+
const sharings = count(entries.map(shared));
|
|
531
|
+
const labels = {};
|
|
532
|
+
for (const entry of entries){
|
|
533
|
+
var _names_get, _sharings_get;
|
|
534
|
+
if (((_names_get = names.get(key(entry.name))) != null ? _names_get : 0) < 2) {
|
|
535
|
+
labels[entry.id] = entry.name;
|
|
536
|
+
} else if (((_sharings_get = sharings.get(shared(entry))) != null ? _sharings_get : 0) < 2) {
|
|
537
|
+
labels[entry.id] = `${entry.name} · ${entry.sharing}`;
|
|
538
|
+
} else {
|
|
539
|
+
labels[entry.id] = `${entry.name} · ${entry.sharing} · ${entry.fields} ${entry.fields === 1 ? 'field' : 'fields'}`;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return labels;
|
|
543
|
+
}
|
|
510
544
|
|
|
511
545
|
//# sourceMappingURL=dataset-model-core.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-model-core.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The pure half of the dataset model (AGL-3668): the model and field types,\n * the v1 shim, the display and input forms of a stored value, and the\n * records table filter grammar (`filterKeys`/`filterValues` and the tokens a\n * clause or a search word asks for). No imports, so the native apps generate\n * from it (tools/scripts/mobile-pure-modules.json) and replay its answers.\n * `dataset-models.ts` re-exports all of it beside the validation and\n * coercion that reach the plugin registry.\n */\n\n/**\n * A human field entry from the quick creator: the stable id plus the\n * display name shown in table headers and bindings pickers (AGL-558).\n */\nexport interface DatasetFieldEntry {\n id: string\n name: string\n}\n\n/** Display fallback for raw ids: \"roast_preference\" → \"Roast preference\". */\nexport function humanizeDatasetFieldId(id: string): string {\n const words = id.replace(/_/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n\n/** dod.ts `FT.Tag` vocabulary plus `reference` (AGL-180 builds on it). */\nexport type DatasetFieldType =\n | 'bool'\n | 'bytes'\n | 'timestamp'\n | 'float'\n | 'int32'\n | 'int64'\n | 'nil'\n | 'text'\n | 'coordinates'\n | 'map'\n | 'sorted'\n | 'reference'\n\nexport const DATASET_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'int64',\n 'float',\n 'timestamp',\n 'coordinates',\n 'map',\n 'sorted',\n 'bytes',\n 'nil',\n 'reference',\n]\n\n/**\n * The types a person picks for a new field in the Schema dialog; the rest\n * exist for compatibility and stay editable on a field that already has one.\n */\nexport const DATASET_AUTHORABLE_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'float',\n 'timestamp',\n 'coordinates',\n 'sorted',\n 'reference',\n]\n\n/** Display names, mirroring dod.ts `lbl`. */\nexport const DATASET_FIELD_TYPE_LABELS: Record<DatasetFieldType, string> = {\n text: 'Text',\n bool: 'Boolean',\n int32: 'Integer',\n int64: 'Big integer',\n float: 'Number',\n timestamp: 'Date & time',\n coordinates: 'Coordinates',\n map: 'Map',\n sorted: 'List',\n bytes: 'Bytes',\n nil: 'Null',\n reference: 'Reference',\n}\n\n/**\n * Plain-JSON validation vocabulary (the dod.ts `Eval` shape, extended\n * with min/max and options, serialized flat instead of enum-keyed).\n */\nexport interface DatasetFieldValidation {\n required?: boolean\n /** Source of a RegExp applied to text values. */\n regex?: string\n /** Numbers/timestamps: value bound. Text: length bound. */\n min?: number\n max?: number\n /** Enum: value must be one of these (text fields). */\n options?: string[]\n}\n\nexport interface DatasetFieldDefinition {\n /**\n * Human-facing display label only. The stable reference id is the KEY in\n * `DatasetModel.fields` (and `order`), NOT this name — bindings resolve\n * `{{item.<fieldId>}}` against that key. The default id is derived from\n * this name once at creation but is user-overridable (AGL-578); renaming\n * the label afterwards never changes the id.\n */\n name: string\n type: DatasetFieldType\n /**\n * Plugin-declared custom type riding this base type (AGL-434) — see\n * plugin-manager/custom-fields. Unknown names degrade to the base type.\n */\n customType?: string\n /**\n * A page-address field's source (AGL-3475): the field an EMPTY address\n * fills in from, once — see `fillRecordAddresses` in `record-pages`.\n * Meaningful only on a field of the page-address custom type.\n */\n slugFrom?: string\n description?: string\n required?: boolean\n /** Default applied by editors when creating documents; never coerced. */\n default?: unknown\n validation?: DatasetFieldValidation\n /**\n * Reference fields (AGL-180): target collection + display field id.\n * `multiple` stores a `sorted` array of FKeys (small-cardinality\n * many-to-many per the dod.ts guidance); `onDelete` is the referenced-\n * document delete policy (default `setNull` — never cascade in v2).\n */\n reference?: {\n datasetId: string\n displayFieldId?: string\n multiple?: boolean\n onDelete?: 'restrict' | 'setNull'\n }\n}\n\nexport interface DatasetModel {\n fields: Record<string, DatasetFieldDefinition>\n /** Field ids in display order. */\n order: string[]\n}\n\n/**\n * Migration shim (v1 → v2): datasets created before models carry flat\n * `fields: string[]` — derive a model where every column is an optional\n * text field whose id is the column name, so the editor and AGL-103\n * bindings keep working on unmigrated docs during rollout.\n */\nexport function deriveModelFromFields(fields: string[]): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const name of fields) {\n // Raw snake_case ids read as titles in table headers and pickers;\n // the id stays the stable key (AGL-558).\n model.fields[name] = { name: humanizeDatasetFieldId(name), type: 'text' }\n model.order.push(name)\n }\n return model\n}\n\n/**\n * Model from quick-creator entries (AGL-558): stable slug ids with the\n * human display names preserved — \"Roast preference\" → id\n * `roast_preference`, name \"Roast preference\".\n */\nexport function modelFromFieldEntries(\n entries: readonly DatasetFieldEntry[],\n): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const entry of entries) {\n model.fields[entry.id] = { name: entry.name, type: 'text' }\n model.order.push(entry.id)\n }\n return model\n}\n\n/** The dataset's model, deriving one from v1 `fields` when absent. */\nexport function effectiveDatasetModel(dataset: {\n model?: DatasetModel\n fields?: string[]\n}): DatasetModel {\n if (dataset.model?.fields && dataset.model.order?.length) {\n return dataset.model\n }\n return deriveModelFromFields(dataset.fields ?? [])\n}\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value)\n\n\n\n/** Storage value → grid display string (AGL-179). */\nexport function formatDatasetValue(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null || value === '') return ''\n switch (field.type) {\n case 'bool':\n return value === true ? '✓' : value === false ? '—' : String(value)\n case 'timestamp':\n return isFiniteNumber(value)\n ? new Date(value).toISOString().slice(0, 16).replace('T', ' ')\n : String(value)\n case 'coordinates': {\n const coordinates = value as { latitude?: number; longitude?: number }\n return isFiniteNumber(coordinates?.latitude) &&\n isFiniteNumber(coordinates?.longitude)\n ? `${coordinates.latitude}, ${coordinates.longitude}`\n : String(value)\n }\n case 'sorted':\n return Array.isArray(value) ? value.join(', ') : String(value)\n case 'map':\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n default:\n return String(value)\n }\n}\n\n/**\n * Storage value → form-input string (AGL-179): the inverse of\n * `coerceDocumentValues` for populating type-appropriate inputs\n * (timestamps as `datetime-local` values, coordinates as \"lat, lon\").\n */\nexport function datasetValueToInput(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null) return ''\n if (field.type === 'timestamp' && isFiniteNumber(value)) {\n return new Date(value).toISOString().slice(0, 16)\n }\n if (field.type === 'bool') {\n return value === true ? 'true' : value === false ? 'false' : String(value)\n }\n if (field.type === 'coordinates' || field.type === 'sorted') {\n return formatDatasetValue(field, value)\n }\n if (field.type === 'map') return formatDatasetValue(field, value)\n return String(value)\n}\n\n/**\n * A dataset record's FILTER TOKENS: every word-level question the records\n * table can ask of a record, flattened into one array of strings Firestore\n * indexes on its own. Its twin, {@link datasetFilterValues}, holds the\n * equalities.\n *\n * ## Why these fields, and not the values\n *\n * A record's fields live under `values`, a user-defined, unbounded map that\n * the index configuration exempts from indexing — auto-indexing it can exceed\n * Firestore's per-document index-entry limit — so `where('values.<field>', …)`\n * is refused. A composite index per dataset would need an admin call per\n * dataset, runs into the project's composite-index cap, and is deleted by the\n * next `firestore:indexes` deploy of a file that does not list it.\n *\n * `filterKeys` and `filterValues` need none of that. Firestore's AUTOMATIC\n * single-field indexes serve `where('filterKeys', 'array-contains', token)`\n * and `where('filterValues.<field>', '==', value)`, and every automatic index\n * ends in the document name — so any number of those equalities and ONE\n * `array-contains`, under `orderBy(documentId())`, compose by index merging,\n * with no composite index and no index deploy, on any dataset of any project\n * (AGL-3321).\n *\n * ## The token grammar\n *\n * `f:<fieldId>=<value>` a field equals a value. Enum (a text field with\n * `validation.options`) values are kept exactly;\n * plain text is lower-cased, trimmed and clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters;\n * booleans are `true`/`false`; numbers are\n * `String(number)`; a `sorted` list contributes one\n * token per member.\n * `f:<fieldId>^<prefix>` a word of a plain text field starts with this.\n * `s:<prefix>` a word of ANY text value (enums and list members\n * included) starts with this — the quick search.\n *\n * Timestamps, references, maps, bytes, coordinates and nil fields carry no\n * field tokens: a timestamp is asked in ranges, which one token cannot serve,\n * and the rest are not asked about by value.\n *\n * The array is sorted, de-duplicated and capped at\n * {@link DATASET_FILTER_KEYS_MAX}. Past the cap, the `=` tokens are kept\n * first, then the per-field word prefixes, then the search prefixes, so a\n * very long record loses search reach before it loses exact matches.\n */\nexport const DATASET_FILTER_KEYS_MAX = 500\n\n/** Plain text values are clipped to this many characters in an `=` token. */\nexport const DATASET_FILTER_VALUE_MAX = 64\n/** Word prefixes run from 1 to this many characters. */\nexport const DATASET_FILTER_PREFIX_MAX = 12\n/** Only the first this-many words of a value contribute prefixes. */\nexport const DATASET_FILTER_WORDS_MAX = 40\n\n/** One clause of the records table's filter: `{ field, op, value }`. */\nexport interface DatasetFilterClause {\n field: string\n op: string\n value: string\n}\n\n/**\n * The words of a text value: split on anything that is not a letter or a\n * digit, lower-cased, at most {@link DATASET_FILTER_WORDS_MAX} of them.\n */\nexport function datasetFilterWords(text: string): string[] {\n return String(text)\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean)\n .slice(0, DATASET_FILTER_WORDS_MAX)\n}\n\n/** A word's prefixes, 1 to {@link DATASET_FILTER_PREFIX_MAX} characters. */\nfunction prefixes(word: string): string[] {\n const chars = Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX)\n return chars.map((_char, at) => chars.slice(0, at + 1).join(''))\n}\n\n/** A word clipped the way its stored prefixes are. */\nfunction clipWord(word: string): string {\n return Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX).join('')\n}\n\nconst isEnum = (field: DatasetFieldDefinition): boolean =>\n field.type === 'text' && (field.validation?.options?.length ?? 0) > 0\n\nconst isNumeric = (field: DatasetFieldDefinition): boolean =>\n field.type === 'int32' || field.type === 'int64' || field.type === 'float'\n\n/**\n * A stored value as text, or null. Numbers are accepted because a form or an\n * automation stores every value as text and an import may do the reverse.\n */\nfunction asText(value: unknown): string | null {\n if (typeof value === 'string') return value\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n return null\n}\n\n/**\n * Plain text as its stored key — its `=` token's value and its\n * `filterValues` entry: lower-cased, trimmed, clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters. What the records table asks a\n * typed value to equal.\n */\nexport function datasetFilterTextKey(value: string): string {\n return Array.from(value.trim().toLowerCase())\n .slice(0, DATASET_FILTER_VALUE_MAX)\n .join('')\n}\nconst textKey = datasetFilterTextKey\n\n/** A stored number (or its text form) as its `=` token's value. */\nfunction numberKey(value: unknown): string | null {\n const number =\n typeof value === 'number'\n ? value\n : typeof value === 'string' && value.trim() !== ''\n ? Number(value)\n : Number.NaN\n return Number.isFinite(number) ? String(number) : null\n}\n\n/** A stored boolean (or its text form) as its `=` token's value. */\nfunction boolKey(value: unknown): string | null {\n if (typeof value === 'boolean') return String(value)\n if (value === 'true' || value === 'false') return value\n return null\n}\n\n/** Every field a model declares, in display order and then the rest. */\nfunction modelFieldIds(model: DatasetModel): string[] {\n return [...new Set([...(model.order ?? []), ...Object.keys(model.fields ?? {})])]\n}\n\n/** The tokens described in {@link DATASET_FILTER_KEYS_MAX}'s comment. */\nexport function datasetFilterKeys(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): string[] {\n const exact: string[] = []\n const fieldWords: string[] = []\n const search: string[] = []\n const searchable = (text: string) => {\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) search.push(`s:${prefix}`)\n }\n }\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n if (isEnum(field)) {\n exact.push(`f:${fieldId}=${text}`)\n } else {\n exact.push(`f:${fieldId}=${textKey(text)}`)\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) {\n fieldWords.push(`f:${fieldId}^${prefix}`)\n }\n }\n }\n searchable(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (field.type === 'sorted') {\n for (const member of Array.isArray(stored) ? stored : [stored]) {\n const text = asText(member)?.trim()\n if (!text) continue\n exact.push(`f:${fieldId}=${text}`)\n searchable(text)\n }\n }\n }\n const kept = [...new Set([...exact, ...fieldWords, ...search])].slice(\n 0,\n DATASET_FILTER_KEYS_MAX,\n )\n return kept.sort()\n}\n\n/** A record's `filterValues`: field id → the value an equality asks for. */\nexport type DatasetFilterValues = Record<string, string | number | boolean>\n\n/**\n * Field ids a query can name as `filterValues.<id>`. A path string splits on\n * `.`, and the SDKs refuse `~ * / [ ]` in one; the model editor allows only\n * letters, digits and underscores, but a v1 dataset's column names were\n * never checked. Backticks are refused too, as the escape a path would need.\n */\nconst FILTER_VALUE_ID = /^[^.~*/[\\]`]+$/\n\n/**\n * The query path of a field's `filterValues` entry, or null for a field id\n * no path can name — such a field is stamped no entry, and the records table\n * offers it no equality (its `contains`, served by `filterKeys`, stands).\n */\nexport function datasetFilterValuePath(fieldId: string): string | null {\n return FILTER_VALUE_ID.test(fieldId) && !/^__.*__$/.test(fieldId)\n ? `filterValues.${fieldId}`\n : null\n}\n\n/**\n * A dataset record's FILTER VALUES: `{ [fieldId]: value }`, one scalar per\n * field an equality can be asked of, so the records table puts every\n * equality on its query (AGL-3321).\n *\n * enum text (`validation.options`) the value exactly, as its `=` token;\n * plain text {@link datasetFilterTextKey};\n * bool a boolean;\n * int32 / int64 / float a number.\n *\n * A form or an automation stores every value as text, so `'19.50'` is the\n * number 19.5 and `'true'` the boolean, as in {@link datasetFilterKeys}.\n * Fields with no value, and timestamps, lists, references, maps, bytes,\n * coordinates and nil fields, carry no entry: a list is asked by member\n * (`f:<id>=<member>` in `filterKeys`), and the rest are not asked about by\n * value.\n *\n * ## What it costs\n *\n * Unlike `values`, this map is NOT exempt from indexing — that is its whole\n * point. Each entry is a scalar and costs two automatic index entries\n * (ascending, descending), so a record costs at most two per model field —\n * bounded by the model's field count (the `/v1` API caps a model at 100\n * fields), far inside Firestore's 40,000 entries per document, where\n * `values` was unbounded because a `map` or `sorted` value may hold anything.\n */\nexport function datasetFilterValues(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): DatasetFilterValues {\n const out: DatasetFilterValues = {}\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null || !datasetFilterValuePath(fieldId)) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n out[fieldId] = isEnum(field) ? text : textKey(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) out[fieldId] = key === 'true'\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) out[fieldId] = Number(key)\n }\n }\n return out\n}\n\n/**\n * The `filterKeys` token a word-level clause asks for, or null when it is\n * not one:\n *\n * - plain text `contains` → the `^` token of the value's FIRST word, so a\n * `contains` is a word-prefix match, not a mid-string one, and one word\n * of several is asked (the records table says so);\n * - list `contains` (and `equals`) → the member's `=` token;\n * - enum, boolean, number and plain text `equals` → the `=` token of the\n * value. The records table asks these of `filterValues` instead, which\n * composes with a `contains`; the token remains what the quick search and\n * older readers match.\n * - everything else — ranges, dates, `isEmpty`, `isAnyOf`, negations — null.\n *\n * `clause.field` is the field id. The operator names are the grid's: a\n * select's `equals`, a number's `=`, a boolean's `is`, a list's `contains`.\n */\nexport function datasetFilterToken(\n model: DatasetModel,\n clause: DatasetFilterClause,\n): string | null {\n const field = model.fields?.[clause.field]\n if (!field) return null\n const { op } = clause\n const value = String(clause.value ?? '')\n if (!value.trim()) return null\n const equals = op === 'equals' || op === '=' || op === 'is'\n if (field.type === 'text') {\n if (isEnum(field)) return equals ? `f:${clause.field}=${value}` : null\n if (equals) return `f:${clause.field}=${textKey(value)}`\n if (op === 'contains') {\n const [first] = datasetFilterWords(value)\n return first ? `f:${clause.field}^${clipWord(first)}` : null\n }\n return null\n }\n if (field.type === 'bool') {\n const key = boolKey(value.trim())\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (isNumeric(field)) {\n const key = numberKey(value)\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (field.type === 'sorted') {\n return equals || op === 'contains' ? `f:${clause.field}=${value.trim()}` : null\n }\n return null\n}\n\n/**\n * The quick-search token for one typed word, or null for a word with no\n * letters or digits. A word with punctuation inside it is asked by its first\n * run — split the search text with {@link datasetFilterWords} to ask for\n * every run.\n */\nexport function datasetSearchToken(word: string): string | null {\n const [first] = datasetFilterWords(word)\n return first ? `s:${clipWord(first)}` : null\n}\n\n/** Dataset field name: starts with a letter; letters/digits/underscores. */\nexport const DATASET_FIELD_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/\n\n\n/**\n * Stable field id from a human name: \"Roast preference\" → \"roast_preference\".\n * Mirrors DATASET_FIELD_PATTERN; returns '' when nothing salvageable.\n */\nexport function slugifyDatasetFieldId(name: string): string {\n const slug = name\n .trim()\n .toLowerCase()\n .replace(/[\\s-]+/g, '_')\n .replace(/[^a-z0-9_]/g, '')\n .replace(/^[0-9_]+/, '')\n .replace(/_+$/, '')\n return DATASET_FIELD_PATTERN.test(slug) ? slug : ''\n}\n\n/**\n * Default reference id for a new field (AGL-578): the `slugifyDatasetFieldId`\n * slug, suffixed (`_2`, `_3`, …) to stay unique within the dataset. `taken`\n * holds the ids already in use (compared case-insensitively). Returns '' when\n * the name yields nothing valid. The user can override the result.\n */\nexport function defaultDatasetFieldId(\n name: string,\n taken: ReadonlySet<string>,\n): string {\n const base = slugifyDatasetFieldId(name)\n if (!base) return ''\n const used = new Set([...taken].map((id) => id.toLowerCase()))\n let candidate = base\n let suffix = 2\n while (used.has(candidate.toLowerCase())) candidate = `${base}_${suffix++}`\n return candidate\n}\n\n/**\n * Validate a user-entered reference id (AGL-578): non-empty, matches\n * `DATASET_FIELD_PATTERN`, and unique within the dataset (`taken` = ids already\n * used, compared case-insensitively). Returns an error message, or null when\n * the id is usable.\n */\nexport function validateDatasetFieldId(\n id: string,\n taken: ReadonlySet<string>,\n): string | null {\n const trimmed = id.trim()\n if (!trimmed) return 'A reference ID is required'\n if (!DATASET_FIELD_PATTERN.test(trimmed))\n return 'Start with a letter; use only letters, numbers, and underscores'\n const used = new Set([...taken].map((existing) => existing.toLowerCase()))\n if (used.has(trimmed.toLowerCase()))\n return 'Another field already uses this reference ID'\n return null\n}\n\n\n/**\n * Parses a comma/newline separated list of HUMAN field names into\n * {id, name} entries — \"Roast preference\" keeps its pretty name and gets\n * the stable id `roast_preference` (AGL-558). Plain snake_case keys\n * still work and pick up a humanized display name. Duplicate ids and\n * unsalvageable entries are dropped rather than failing the set.\n */\nexport function parseDatasetFieldEntries(input: string): DatasetFieldEntry[] {\n const seen = new Set<string>()\n const entries: DatasetFieldEntry[] = []\n for (const raw of input.split(/[,\\n]/)) {\n const trimmed = raw.trim()\n if (!trimmed) continue\n const id = slugifyDatasetFieldId(trimmed)\n if (!id || seen.has(id)) continue\n seen.add(id)\n entries.push({\n id,\n name: DATASET_FIELD_PATTERN.test(trimmed)\n ? humanizeDatasetFieldId(trimmed)\n : trimmed,\n })\n }\n return entries\n}\n\n/**\n * The name a dataset is shown under: `displayName`, which is what every create\n * path writes (AGL-536), then the pre-migration `name`. Blank when the document\n * carries neither.\n */\nexport function datasetDisplayName(\n dataset: { displayName?: unknown; name?: unknown } | null | undefined,\n): string {\n for (const candidate of [dataset?.displayName, dataset?.name]) {\n if (typeof candidate === 'string' && candidate.trim()) {\n return candidate.trim()\n }\n }\n return ''\n}\n"],"names":["humanizeDatasetFieldId","id","words","replace","trim","charAt","toUpperCase","slice","DATASET_FIELD_TYPES","DATASET_AUTHORABLE_FIELD_TYPES","DATASET_FIELD_TYPE_LABELS","text","bool","int32","int64","float","timestamp","coordinates","map","sorted","bytes","nil","reference","deriveModelFromFields","fields","model","order","name","type","push","modelFromFieldEntries","entries","entry","effectiveDatasetModel","dataset","length","isFiniteNumber","value","Number","isFinite","formatDatasetValue","field","String","Date","toISOString","latitude","longitude","Array","isArray","join","JSON","stringify","datasetValueToInput","DATASET_FILTER_KEYS_MAX","DATASET_FILTER_VALUE_MAX","DATASET_FILTER_PREFIX_MAX","DATASET_FILTER_WORDS_MAX","datasetFilterWords","toLowerCase","split","filter","Boolean","prefixes","word","chars","from","_char","at","clipWord","isEnum","validation","options","isNumeric","asText","datasetFilterTextKey","textKey","numberKey","number","NaN","boolKey","modelFieldIds","Set","Object","keys","datasetFilterKeys","values","exact","fieldWords","search","searchable","prefix","fieldId","stored","key","member","kept","sort","FILTER_VALUE_ID","datasetFilterValuePath","test","datasetFilterValues","out","datasetFilterToken","clause","op","equals","first","datasetSearchToken","DATASET_FIELD_PATTERN","slugifyDatasetFieldId","slug","defaultDatasetFieldId","taken","base","used","candidate","suffix","has","validateDatasetFieldId","trimmed","existing","parseDatasetFieldEntries","input","seen","raw","add","datasetDisplayName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED;;;CAGC,GAMD,2EAA2E,GAC3E,OAAO,SAASA,uBAAuBC,EAAU;IAC/C,MAAMC,QAAQD,GAAGE,OAAO,CAAC,MAAM,KAAKC,IAAI;IACxC,OAAOF,QAAQA,MAAMG,MAAM,CAAC,GAAGC,WAAW,KAAKJ,MAAMK,KAAK,CAAC,KAAKN;AAClE;AAiBA,OAAO,MAAMO,sBAA0C;IACrD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;CAGC,GACD,OAAO,MAAMC,iCAAqD;IAChE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,2CAA2C,GAC3C,OAAO,MAAMC,4BAA8D;IACzEC,MAAM;IACNC,MAAM;IACNC,OAAO;IACPC,OAAO;IACPC,OAAO;IACPC,WAAW;IACXC,aAAa;IACbC,KAAK;IACLC,QAAQ;IACRC,OAAO;IACPC,KAAK;IACLC,WAAW;AACb,EAAC;AA+DD;;;;;CAKC,GACD,OAAO,SAASC,sBAAsBC,MAAgB;IACpD,MAAMC,QAAsB;QAAED,QAAQ,CAAC;QAAGE,OAAO,EAAE;IAAC;IACpD,KAAK,MAAMC,QAAQH,OAAQ;QACzB,kEAAkE;QAClE,yCAAyC;QACzCC,MAAMD,MAAM,CAACG,KAAK,GAAG;YAAEA,MAAM3B,uBAAuB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KAAK4G,sBAAsBU;QACjC,IAAI,CAACtH,MAAM0H,KAAKN,GAAG,CAACpH,KAAK;QACzB0H,KAAKE,GAAG,CAAC5H;QACT8B,QAAQF,IAAI,CAAC;YACX5B;YACA0B,MAAMiF,sBAAsBT,IAAI,CAACoB,WAC7BvH,uBAAuBuH,WACvBA;QACN;IACF;IACA,OAAOxF;AACT;AAEA;;;;CAIC,GACD,OAAO,SAAS+F,mBACd5F,OAAqE;IAErE,KAAK,MAAMiF,aAAa;QAACjF,2BAAAA,QAAS6F,WAAW;QAAE7F,2BAAAA,QAASP,IAAI;KAAC,CAAE;QAC7D,IAAI,OAAOwF,cAAc,YAAYA,UAAU/G,IAAI,IAAI;YACrD,OAAO+G,UAAU/G,IAAI;QACvB;IACF;IACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-model-core.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The pure half of the dataset model (AGL-3668): the model and field types,\n * the v1 shim, the display and input forms of a stored value, and the\n * records table filter grammar (`filterKeys`/`filterValues` and the tokens a\n * clause or a search word asks for). No imports, so the native apps generate\n * from it (tools/scripts/mobile-pure-modules.json) and replay its answers.\n * `dataset-models.ts` re-exports all of it beside the validation and\n * coercion that reach the plugin registry.\n */\n\n/**\n * A human field entry from the quick creator: the stable id plus the\n * display name shown in table headers and bindings pickers (AGL-558).\n */\nexport interface DatasetFieldEntry {\n id: string\n name: string\n}\n\n/** Display fallback for raw ids: \"roast_preference\" → \"Roast preference\". */\nexport function humanizeDatasetFieldId(id: string): string {\n const words = id.replace(/_/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n\n/** dod.ts `FT.Tag` vocabulary plus `reference` (AGL-180 builds on it). */\nexport type DatasetFieldType =\n | 'bool'\n | 'bytes'\n | 'timestamp'\n | 'float'\n | 'int32'\n | 'int64'\n | 'nil'\n | 'text'\n | 'coordinates'\n | 'map'\n | 'sorted'\n | 'reference'\n\nexport const DATASET_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'int64',\n 'float',\n 'timestamp',\n 'coordinates',\n 'map',\n 'sorted',\n 'bytes',\n 'nil',\n 'reference',\n]\n\n/**\n * The types a person picks for a new field in the Schema dialog; the rest\n * exist for compatibility and stay editable on a field that already has one.\n */\nexport const DATASET_AUTHORABLE_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'float',\n 'timestamp',\n 'coordinates',\n 'sorted',\n 'reference',\n]\n\n/** Display names, mirroring dod.ts `lbl`. */\nexport const DATASET_FIELD_TYPE_LABELS: Record<DatasetFieldType, string> = {\n text: 'Text',\n bool: 'Boolean',\n int32: 'Integer',\n int64: 'Big integer',\n float: 'Number',\n timestamp: 'Date & time',\n coordinates: 'Coordinates',\n map: 'Map',\n sorted: 'List',\n bytes: 'Bytes',\n nil: 'Null',\n reference: 'Reference',\n}\n\n/**\n * Plain-JSON validation vocabulary (the dod.ts `Eval` shape, extended\n * with min/max and options, serialized flat instead of enum-keyed).\n */\nexport interface DatasetFieldValidation {\n required?: boolean\n /** Source of a RegExp applied to text values. */\n regex?: string\n /** Numbers/timestamps: value bound. Text: length bound. */\n min?: number\n max?: number\n /** Enum: value must be one of these (text fields). */\n options?: string[]\n}\n\nexport interface DatasetFieldDefinition {\n /**\n * Human-facing display label only. The stable reference id is the KEY in\n * `DatasetModel.fields` (and `order`), NOT this name — bindings resolve\n * `{{item.<fieldId>}}` against that key. The default id is derived from\n * this name once at creation but is user-overridable (AGL-578); renaming\n * the label afterwards never changes the id.\n */\n name: string\n type: DatasetFieldType\n /**\n * Plugin-declared custom type riding this base type (AGL-434) — see\n * plugin-manager/custom-fields. Unknown names degrade to the base type.\n */\n customType?: string\n /**\n * A page-address field's source (AGL-3475): the field an EMPTY address\n * fills in from, once — see `fillRecordAddresses` in `record-pages`.\n * Meaningful only on a field of the page-address custom type.\n */\n slugFrom?: string\n description?: string\n required?: boolean\n /** Default applied by editors when creating documents; never coerced. */\n default?: unknown\n validation?: DatasetFieldValidation\n /**\n * Reference fields (AGL-180): target collection + display field id.\n * `multiple` stores a `sorted` array of FKeys (small-cardinality\n * many-to-many per the dod.ts guidance); `onDelete` is the referenced-\n * document delete policy (default `setNull` — never cascade in v2).\n */\n reference?: {\n datasetId: string\n displayFieldId?: string\n multiple?: boolean\n onDelete?: 'restrict' | 'setNull'\n }\n}\n\nexport interface DatasetModel {\n fields: Record<string, DatasetFieldDefinition>\n /** Field ids in display order. */\n order: string[]\n}\n\n/**\n * Migration shim (v1 → v2): datasets created before models carry flat\n * `fields: string[]` — derive a model where every column is an optional\n * text field whose id is the column name, so the editor and AGL-103\n * bindings keep working on unmigrated docs during rollout.\n */\nexport function deriveModelFromFields(fields: string[]): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const name of fields) {\n // Raw snake_case ids read as titles in table headers and pickers;\n // the id stays the stable key (AGL-558).\n model.fields[name] = { name: humanizeDatasetFieldId(name), type: 'text' }\n model.order.push(name)\n }\n return model\n}\n\n/**\n * Model from quick-creator entries (AGL-558): stable slug ids with the\n * human display names preserved — \"Roast preference\" → id\n * `roast_preference`, name \"Roast preference\".\n */\nexport function modelFromFieldEntries(\n entries: readonly DatasetFieldEntry[],\n): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const entry of entries) {\n model.fields[entry.id] = { name: entry.name, type: 'text' }\n model.order.push(entry.id)\n }\n return model\n}\n\n/** The dataset's model, deriving one from v1 `fields` when absent. */\nexport function effectiveDatasetModel(dataset: {\n model?: DatasetModel\n fields?: string[]\n}): DatasetModel {\n if (dataset.model?.fields && dataset.model.order?.length) {\n return dataset.model\n }\n return deriveModelFromFields(dataset.fields ?? [])\n}\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value)\n\n\n\n/** Storage value → grid display string (AGL-179). */\nexport function formatDatasetValue(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null || value === '') return ''\n switch (field.type) {\n case 'bool':\n return value === true ? '✓' : value === false ? '—' : String(value)\n case 'timestamp':\n return isFiniteNumber(value)\n ? new Date(value).toISOString().slice(0, 16).replace('T', ' ')\n : String(value)\n case 'coordinates': {\n const coordinates = value as { latitude?: number; longitude?: number }\n return isFiniteNumber(coordinates?.latitude) &&\n isFiniteNumber(coordinates?.longitude)\n ? `${coordinates.latitude}, ${coordinates.longitude}`\n : String(value)\n }\n case 'sorted':\n return Array.isArray(value) ? value.join(', ') : String(value)\n case 'map':\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n default:\n return String(value)\n }\n}\n\n/**\n * Storage value → form-input string (AGL-179): the inverse of\n * `coerceDocumentValues` for populating type-appropriate inputs\n * (timestamps as `datetime-local` values, coordinates as \"lat, lon\").\n */\nexport function datasetValueToInput(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null) return ''\n if (field.type === 'timestamp' && isFiniteNumber(value)) {\n return new Date(value).toISOString().slice(0, 16)\n }\n if (field.type === 'bool') {\n return value === true ? 'true' : value === false ? 'false' : String(value)\n }\n if (field.type === 'coordinates' || field.type === 'sorted') {\n return formatDatasetValue(field, value)\n }\n if (field.type === 'map') return formatDatasetValue(field, value)\n return String(value)\n}\n\n/**\n * A dataset record's FILTER TOKENS: every word-level question the records\n * table can ask of a record, flattened into one array of strings Firestore\n * indexes on its own. Its twin, {@link datasetFilterValues}, holds the\n * equalities.\n *\n * ## Why these fields, and not the values\n *\n * A record's fields live under `values`, a user-defined, unbounded map that\n * the index configuration exempts from indexing — auto-indexing it can exceed\n * Firestore's per-document index-entry limit — so `where('values.<field>', …)`\n * is refused. A composite index per dataset would need an admin call per\n * dataset, runs into the project's composite-index cap, and is deleted by the\n * next `firestore:indexes` deploy of a file that does not list it.\n *\n * `filterKeys` and `filterValues` need none of that. Firestore's AUTOMATIC\n * single-field indexes serve `where('filterKeys', 'array-contains', token)`\n * and `where('filterValues.<field>', '==', value)`, and every automatic index\n * ends in the document name — so any number of those equalities and ONE\n * `array-contains`, under `orderBy(documentId())`, compose by index merging,\n * with no composite index and no index deploy, on any dataset of any project\n * (AGL-3321).\n *\n * ## The token grammar\n *\n * `f:<fieldId>=<value>` a field equals a value. Enum (a text field with\n * `validation.options`) values are kept exactly;\n * plain text is lower-cased, trimmed and clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters;\n * booleans are `true`/`false`; numbers are\n * `String(number)`; a `sorted` list contributes one\n * token per member.\n * `f:<fieldId>^<prefix>` a word of a plain text field starts with this.\n * `s:<prefix>` a word of ANY text value (enums and list members\n * included) starts with this — the quick search.\n *\n * Timestamps, references, maps, bytes, coordinates and nil fields carry no\n * field tokens: a timestamp is asked in ranges, which one token cannot serve,\n * and the rest are not asked about by value.\n *\n * The array is sorted, de-duplicated and capped at\n * {@link DATASET_FILTER_KEYS_MAX}. Past the cap, the `=` tokens are kept\n * first, then the per-field word prefixes, then the search prefixes, so a\n * very long record loses search reach before it loses exact matches.\n */\nexport const DATASET_FILTER_KEYS_MAX = 500\n\n/** Plain text values are clipped to this many characters in an `=` token. */\nexport const DATASET_FILTER_VALUE_MAX = 64\n/** Word prefixes run from 1 to this many characters. */\nexport const DATASET_FILTER_PREFIX_MAX = 12\n/** Only the first this-many words of a value contribute prefixes. */\nexport const DATASET_FILTER_WORDS_MAX = 40\n\n/** One clause of the records table's filter: `{ field, op, value }`. */\nexport interface DatasetFilterClause {\n field: string\n op: string\n value: string\n}\n\n/**\n * The words of a text value: split on anything that is not a letter or a\n * digit, lower-cased, at most {@link DATASET_FILTER_WORDS_MAX} of them.\n */\nexport function datasetFilterWords(text: string): string[] {\n return String(text)\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean)\n .slice(0, DATASET_FILTER_WORDS_MAX)\n}\n\n/** A word's prefixes, 1 to {@link DATASET_FILTER_PREFIX_MAX} characters. */\nfunction prefixes(word: string): string[] {\n const chars = Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX)\n return chars.map((_char, at) => chars.slice(0, at + 1).join(''))\n}\n\n/** A word clipped the way its stored prefixes are. */\nfunction clipWord(word: string): string {\n return Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX).join('')\n}\n\nconst isEnum = (field: DatasetFieldDefinition): boolean =>\n field.type === 'text' && (field.validation?.options?.length ?? 0) > 0\n\nconst isNumeric = (field: DatasetFieldDefinition): boolean =>\n field.type === 'int32' || field.type === 'int64' || field.type === 'float'\n\n/**\n * A stored value as text, or null. Numbers are accepted because a form or an\n * automation stores every value as text and an import may do the reverse.\n */\nfunction asText(value: unknown): string | null {\n if (typeof value === 'string') return value\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n return null\n}\n\n/**\n * Plain text as its stored key — its `=` token's value and its\n * `filterValues` entry: lower-cased, trimmed, clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters. What the records table asks a\n * typed value to equal.\n */\nexport function datasetFilterTextKey(value: string): string {\n return Array.from(value.trim().toLowerCase())\n .slice(0, DATASET_FILTER_VALUE_MAX)\n .join('')\n}\nconst textKey = datasetFilterTextKey\n\n/** A stored number (or its text form) as its `=` token's value. */\nfunction numberKey(value: unknown): string | null {\n const number =\n typeof value === 'number'\n ? value\n : typeof value === 'string' && value.trim() !== ''\n ? Number(value)\n : Number.NaN\n return Number.isFinite(number) ? String(number) : null\n}\n\n/** A stored boolean (or its text form) as its `=` token's value. */\nfunction boolKey(value: unknown): string | null {\n if (typeof value === 'boolean') return String(value)\n if (value === 'true' || value === 'false') return value\n return null\n}\n\n/** Every field a model declares, in display order and then the rest. */\nfunction modelFieldIds(model: DatasetModel): string[] {\n return [...new Set([...(model.order ?? []), ...Object.keys(model.fields ?? {})])]\n}\n\n/** The tokens described in {@link DATASET_FILTER_KEYS_MAX}'s comment. */\nexport function datasetFilterKeys(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): string[] {\n const exact: string[] = []\n const fieldWords: string[] = []\n const search: string[] = []\n const searchable = (text: string) => {\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) search.push(`s:${prefix}`)\n }\n }\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n if (isEnum(field)) {\n exact.push(`f:${fieldId}=${text}`)\n } else {\n exact.push(`f:${fieldId}=${textKey(text)}`)\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) {\n fieldWords.push(`f:${fieldId}^${prefix}`)\n }\n }\n }\n searchable(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (field.type === 'sorted') {\n for (const member of Array.isArray(stored) ? stored : [stored]) {\n const text = asText(member)?.trim()\n if (!text) continue\n exact.push(`f:${fieldId}=${text}`)\n searchable(text)\n }\n }\n }\n const kept = [...new Set([...exact, ...fieldWords, ...search])].slice(\n 0,\n DATASET_FILTER_KEYS_MAX,\n )\n return kept.sort()\n}\n\n/** A record's `filterValues`: field id → the value an equality asks for. */\nexport type DatasetFilterValues = Record<string, string | number | boolean>\n\n/**\n * Field ids a query can name as `filterValues.<id>`. A path string splits on\n * `.`, and the SDKs refuse `~ * / [ ]` in one; the model editor allows only\n * letters, digits and underscores, but a v1 dataset's column names were\n * never checked. Backticks are refused too, as the escape a path would need.\n */\nconst FILTER_VALUE_ID = /^[^.~*/[\\]`]+$/\n\n/**\n * The query path of a field's `filterValues` entry, or null for a field id\n * no path can name — such a field is stamped no entry, and the records table\n * offers it no equality (its `contains`, served by `filterKeys`, stands).\n */\nexport function datasetFilterValuePath(fieldId: string): string | null {\n return FILTER_VALUE_ID.test(fieldId) && !/^__.*__$/.test(fieldId)\n ? `filterValues.${fieldId}`\n : null\n}\n\n/**\n * A dataset record's FILTER VALUES: `{ [fieldId]: value }`, one scalar per\n * field an equality can be asked of, so the records table puts every\n * equality on its query (AGL-3321).\n *\n * enum text (`validation.options`) the value exactly, as its `=` token;\n * plain text {@link datasetFilterTextKey};\n * bool a boolean;\n * int32 / int64 / float a number.\n *\n * A form or an automation stores every value as text, so `'19.50'` is the\n * number 19.5 and `'true'` the boolean, as in {@link datasetFilterKeys}.\n * Fields with no value, and timestamps, lists, references, maps, bytes,\n * coordinates and nil fields, carry no entry: a list is asked by member\n * (`f:<id>=<member>` in `filterKeys`), and the rest are not asked about by\n * value.\n *\n * ## What it costs\n *\n * Unlike `values`, this map is NOT exempt from indexing — that is its whole\n * point. Each entry is a scalar and costs two automatic index entries\n * (ascending, descending), so a record costs at most two per model field —\n * bounded by the model's field count (the `/v1` API caps a model at 100\n * fields), far inside Firestore's 40,000 entries per document, where\n * `values` was unbounded because a `map` or `sorted` value may hold anything.\n */\nexport function datasetFilterValues(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): DatasetFilterValues {\n const out: DatasetFilterValues = {}\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null || !datasetFilterValuePath(fieldId)) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n out[fieldId] = isEnum(field) ? text : textKey(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) out[fieldId] = key === 'true'\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) out[fieldId] = Number(key)\n }\n }\n return out\n}\n\n/**\n * The `filterKeys` token a word-level clause asks for, or null when it is\n * not one:\n *\n * - plain text `contains` → the `^` token of the value's FIRST word, so a\n * `contains` is a word-prefix match, not a mid-string one, and one word\n * of several is asked (the records table says so);\n * - list `contains` (and `equals`) → the member's `=` token;\n * - enum, boolean, number and plain text `equals` → the `=` token of the\n * value. The records table asks these of `filterValues` instead, which\n * composes with a `contains`; the token remains what the quick search and\n * older readers match.\n * - everything else — ranges, dates, `isEmpty`, `isAnyOf`, negations — null.\n *\n * `clause.field` is the field id. The operator names are the grid's: a\n * select's `equals`, a number's `=`, a boolean's `is`, a list's `contains`.\n */\nexport function datasetFilterToken(\n model: DatasetModel,\n clause: DatasetFilterClause,\n): string | null {\n const field = model.fields?.[clause.field]\n if (!field) return null\n const { op } = clause\n const value = String(clause.value ?? '')\n if (!value.trim()) return null\n const equals = op === 'equals' || op === '=' || op === 'is'\n if (field.type === 'text') {\n if (isEnum(field)) return equals ? `f:${clause.field}=${value}` : null\n if (equals) return `f:${clause.field}=${textKey(value)}`\n if (op === 'contains') {\n const [first] = datasetFilterWords(value)\n return first ? `f:${clause.field}^${clipWord(first)}` : null\n }\n return null\n }\n if (field.type === 'bool') {\n const key = boolKey(value.trim())\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (isNumeric(field)) {\n const key = numberKey(value)\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (field.type === 'sorted') {\n return equals || op === 'contains' ? `f:${clause.field}=${value.trim()}` : null\n }\n return null\n}\n\n/**\n * The quick-search token for one typed word, or null for a word with no\n * letters or digits. A word with punctuation inside it is asked by its first\n * run — split the search text with {@link datasetFilterWords} to ask for\n * every run.\n */\nexport function datasetSearchToken(word: string): string | null {\n const [first] = datasetFilterWords(word)\n return first ? `s:${clipWord(first)}` : null\n}\n\n/** Dataset field name: starts with a letter; letters/digits/underscores. */\nexport const DATASET_FIELD_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/\n\n\n/**\n * Stable field id from a human name: \"Roast preference\" → \"roast_preference\".\n * Mirrors DATASET_FIELD_PATTERN; returns '' when nothing salvageable.\n */\nexport function slugifyDatasetFieldId(name: string): string {\n const slug = name\n .trim()\n .toLowerCase()\n .replace(/[\\s-]+/g, '_')\n .replace(/[^a-z0-9_]/g, '')\n .replace(/^[0-9_]+/, '')\n .replace(/_+$/, '')\n return DATASET_FIELD_PATTERN.test(slug) ? slug : ''\n}\n\n/**\n * Default reference id for a new field (AGL-578): the `slugifyDatasetFieldId`\n * slug, suffixed (`_2`, `_3`, …) to stay unique within the dataset. `taken`\n * holds the ids already in use (compared case-insensitively). Returns '' when\n * the name yields nothing valid. The user can override the result.\n */\nexport function defaultDatasetFieldId(\n name: string,\n taken: ReadonlySet<string>,\n): string {\n const base = slugifyDatasetFieldId(name)\n if (!base) return ''\n const used = new Set([...taken].map((id) => id.toLowerCase()))\n let candidate = base\n let suffix = 2\n while (used.has(candidate.toLowerCase())) candidate = `${base}_${suffix++}`\n return candidate\n}\n\n/**\n * Validate a user-entered reference id (AGL-578): non-empty, matches\n * `DATASET_FIELD_PATTERN`, and unique within the dataset (`taken` = ids already\n * used, compared case-insensitively). Returns an error message, or null when\n * the id is usable.\n */\nexport function validateDatasetFieldId(\n id: string,\n taken: ReadonlySet<string>,\n): string | null {\n const trimmed = id.trim()\n if (!trimmed) return 'A reference ID is required'\n if (!DATASET_FIELD_PATTERN.test(trimmed))\n return 'Start with a letter; use only letters, numbers, and underscores'\n const used = new Set([...taken].map((existing) => existing.toLowerCase()))\n if (used.has(trimmed.toLowerCase()))\n return 'Another field already uses this reference ID'\n return null\n}\n\n\n/**\n * Parses a comma/newline separated list of HUMAN field names into\n * {id, name} entries — \"Roast preference\" keeps its pretty name and gets\n * the stable id `roast_preference` (AGL-558). Plain snake_case keys\n * still work and pick up a humanized display name. Duplicate ids and\n * unsalvageable entries are dropped rather than failing the set.\n */\nexport function parseDatasetFieldEntries(input: string): DatasetFieldEntry[] {\n const seen = new Set<string>()\n const entries: DatasetFieldEntry[] = []\n for (const raw of input.split(/[,\\n]/)) {\n const trimmed = raw.trim()\n if (!trimmed) continue\n const id = slugifyDatasetFieldId(trimmed)\n if (!id || seen.has(id)) continue\n seen.add(id)\n entries.push({\n id,\n name: DATASET_FIELD_PATTERN.test(trimmed)\n ? humanizeDatasetFieldId(trimmed)\n : trimmed,\n })\n }\n return entries\n}\n\n/**\n * The name a dataset is shown under: `displayName`, which is what every create\n * path writes (AGL-536), then the pre-migration `name`. Blank when the document\n * carries neither.\n */\nexport function datasetDisplayName(\n dataset: { displayName?: unknown; name?: unknown } | null | undefined,\n): string {\n for (const candidate of [dataset?.displayName, dataset?.name]) {\n if (typeof candidate === 'string' && candidate.trim()) {\n return candidate.trim()\n }\n }\n return ''\n}\n\n/** One dataset as a picker offers it: what tells it apart from another of its name. */\nexport interface DatasetPickerEntry {\n id: string\n /** The name the Data page shows. */\n name: string\n /** Who it is shared with, as the console says it: `Bakery only`, `All sites`. */\n sharing: string\n /** How many fields its model has. */\n fields: number\n}\n\n/**\n * What each dataset is called in a picker (AGL-4047): its name alone, unless\n * another in the same list has that name too. Then who it is shared with\n * follows (`Services · Bakery only`), and where that still matches another,\n * its field count (`Services · Bakery only · 5 fields`). Names are compared\n * the way the stored search key is: trimmed, spaces collapsed, any case.\n *\n * A site start makes the same names on every site, shared with that site\n * alone, so who it is shared with is what tells most of them apart. No imports,\n * so the native apps can generate from it.\n */\nexport function datasetPickerLabels(entries: readonly DatasetPickerEntry[]): Record<string, string> {\n const key = (text: string) => text.trim().replace(/\\s+/g, ' ').toLowerCase()\n const count = (keys: readonly string[]) => {\n const counts = new Map<string, number>()\n for (const each of keys) counts.set(each, (counts.get(each) ?? 0) + 1)\n return counts\n }\n const names = count(entries.map((entry) => key(entry.name)))\n const shared = (entry: DatasetPickerEntry) => `${key(entry.name)}\\u0000${key(entry.sharing)}`\n const sharings = count(entries.map(shared))\n const labels: Record<string, string> = {}\n for (const entry of entries) {\n if ((names.get(key(entry.name)) ?? 0) < 2) {\n labels[entry.id] = entry.name\n } else if ((sharings.get(shared(entry)) ?? 0) < 2) {\n labels[entry.id] = `${entry.name} · ${entry.sharing}`\n } else {\n labels[entry.id] = `${entry.name} · ${entry.sharing} · ${entry.fields} ${entry.fields === 1 ? 'field' : 'fields'}`\n }\n }\n return labels\n}\n"],"names":["humanizeDatasetFieldId","id","words","replace","trim","charAt","toUpperCase","slice","DATASET_FIELD_TYPES","DATASET_AUTHORABLE_FIELD_TYPES","DATASET_FIELD_TYPE_LABELS","text","bool","int32","int64","float","timestamp","coordinates","map","sorted","bytes","nil","reference","deriveModelFromFields","fields","model","order","name","type","push","modelFromFieldEntries","entries","entry","effectiveDatasetModel","dataset","length","isFiniteNumber","value","Number","isFinite","formatDatasetValue","field","String","Date","toISOString","latitude","longitude","Array","isArray","join","JSON","stringify","datasetValueToInput","DATASET_FILTER_KEYS_MAX","DATASET_FILTER_VALUE_MAX","DATASET_FILTER_PREFIX_MAX","DATASET_FILTER_WORDS_MAX","datasetFilterWords","toLowerCase","split","filter","Boolean","prefixes","word","chars","from","_char","at","clipWord","isEnum","validation","options","isNumeric","asText","datasetFilterTextKey","textKey","numberKey","number","NaN","boolKey","modelFieldIds","Set","Object","keys","datasetFilterKeys","values","exact","fieldWords","search","searchable","prefix","fieldId","stored","key","member","kept","sort","FILTER_VALUE_ID","datasetFilterValuePath","test","datasetFilterValues","out","datasetFilterToken","clause","op","equals","first","datasetSearchToken","DATASET_FIELD_PATTERN","slugifyDatasetFieldId","slug","defaultDatasetFieldId","taken","base","used","candidate","suffix","has","validateDatasetFieldId","trimmed","existing","parseDatasetFieldEntries","input","seen","raw","add","datasetDisplayName","displayName","datasetPickerLabels","count","counts","Map","each","set","get","names","shared","sharing","sharings","labels"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED;;;CAGC,GAMD,2EAA2E,GAC3E,OAAO,SAASA,uBAAuBC,EAAU;IAC/C,MAAM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MR,MAAM,KAAK,IAAI,UAAU,UAAU;QACpH;IACF;IACA,OAAOmH;AACT"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type DatasetModel } from './dataset-models';
|
|
18
|
+
import { type HostDataset } from './datasets';
|
|
19
|
+
/**
|
|
20
|
+
* The Data page's rail of datasets (AGL-4047): one tab per dataset, a second
|
|
21
|
+
* line that tells same-named ones apart, a search over the names, and groups
|
|
22
|
+
* by sharing once there are many. Pure, so the card and its specs read the
|
|
23
|
+
* same answers.
|
|
24
|
+
*/
|
|
25
|
+
/** A dataset as the rail reads it: its document, with the facts it shows. */
|
|
26
|
+
export type DatasetRailEntry = HostDataset & {
|
|
27
|
+
$id: string;
|
|
28
|
+
name?: unknown;
|
|
29
|
+
source?: {
|
|
30
|
+
listingId?: unknown;
|
|
31
|
+
version?: unknown;
|
|
32
|
+
} | null;
|
|
33
|
+
createdAt?: unknown;
|
|
34
|
+
scopeMode?: unknown;
|
|
35
|
+
scopeExcept?: unknown;
|
|
36
|
+
};
|
|
37
|
+
/** Past this many datasets the rail groups them by who they are shared with, and offers the Shared with filter. */
|
|
38
|
+
export declare const DATASET_RAIL_GROUP_AT = 10;
|
|
39
|
+
/** `1 field`, `5 fields`. */
|
|
40
|
+
export declare function datasetFieldCount(dataset: DatasetRailEntry): string;
|
|
41
|
+
/** Who a dataset is shared with, named where `hostNames` has the site: `Bakery only`, `All sites`, `3 sites`. */
|
|
42
|
+
export declare function datasetSharingLabel(dataset: DatasetRailEntry, hostNames: Readonly<Record<string, string>>): string;
|
|
43
|
+
/**
|
|
44
|
+
* The tab's second line. Ungrouped it says who the dataset is shared with and
|
|
45
|
+
* how many fields it has, which is what tells the same name on two sites
|
|
46
|
+
* apart: `Bakery only · 5 fields`. In a group, whose heading already says who
|
|
47
|
+
* it is shared with, it names the first fields instead:
|
|
48
|
+
* `5 fields · Name, Description, Duration`.
|
|
49
|
+
*/
|
|
50
|
+
export declare function datasetRailSecondary(dataset: DatasetRailEntry, options: {
|
|
51
|
+
hostNames: Readonly<Record<string, string>>;
|
|
52
|
+
grouped: boolean;
|
|
53
|
+
}): string;
|
|
54
|
+
/** A dataset's name for the rail and the page: its display name, or a stand-in when it has none. */
|
|
55
|
+
export declare function datasetRailName(dataset: DatasetRailEntry): string;
|
|
56
|
+
/** Datasets in name order, then id, so two of one name keep their places. */
|
|
57
|
+
export declare function sortDatasetsByName<T extends DatasetRailEntry>(datasets: readonly T[]): T[];
|
|
58
|
+
/**
|
|
59
|
+
* Whether a dataset's name starts with what was typed, normalized the way the
|
|
60
|
+
* stored `nameLower` is, so the loaded-list search and the query that replaces
|
|
61
|
+
* it answer alike.
|
|
62
|
+
*/
|
|
63
|
+
export declare function datasetNameMatches(dataset: DatasetRailEntry, typed: string): boolean;
|
|
64
|
+
/** One group of the rail: its heading, with how many it holds, and its datasets in name order. */
|
|
65
|
+
export interface DatasetRailGroup {
|
|
66
|
+
label: string;
|
|
67
|
+
datasets: DatasetRailEntry[];
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The rail's groups by who each dataset is shared with: `Bakery only (6)`.
|
|
71
|
+
* Groups run in heading order, datasets in name order within each.
|
|
72
|
+
*/
|
|
73
|
+
export declare function groupDatasetsBySharing(datasets: readonly DatasetRailEntry[], hostNames: Readonly<Record<string, string>>): DatasetRailGroup[];
|
|
74
|
+
/** Where a dataset came from: the marketplace listing it was installed from, or `--` for one made here. */
|
|
75
|
+
export declare function datasetSourceLabel(dataset: DatasetRailEntry): string;
|
|
76
|
+
/** When a dataset was created, as a date, or `--` where it was never stamped (a site backup restore stamps none). */
|
|
77
|
+
export declare function datasetCreatedLabel(dataset: DatasetRailEntry, locale?: string): string;
|
|
78
|
+
/**
|
|
79
|
+
* A record's own page's heading (AGL-4047): the first field, in the model's
|
|
80
|
+
* order, that shows a value — a reference names an id, so it is passed over —
|
|
81
|
+
* or a stand-in when none does.
|
|
82
|
+
*/
|
|
83
|
+
export declare function datasetRecordTitle(model: DatasetModel, values: Readonly<Record<string, unknown>> | undefined): string;
|
|
84
|
+
/**
|
|
85
|
+
* The picker labels for a list of datasets (AGL-4047), through the pure
|
|
86
|
+
* `datasetPickerLabels`: the name alone unless it collides in the list.
|
|
87
|
+
*/
|
|
88
|
+
export declare function datasetPickerLabelsOf(datasets: readonly DatasetRailEntry[], hostNames?: Readonly<Record<string, string>>): Record<string, string>;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { nameSearchKey } from "@aglyn/aglyn/app-utils/name-search";
|
|
17
|
+
import { describeSharing } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
18
|
+
import { datasetPickerLabels, effectiveDatasetModel, formatDatasetValue } from "./dataset-models.js";
|
|
19
|
+
import { datasetDisplayName } from "./datasets.js";
|
|
20
|
+
/** Past this many datasets the rail groups them by who they are shared with, and offers the Shared with filter. */ export const DATASET_RAIL_GROUP_AT = 10;
|
|
21
|
+
/** How many field names the second line names, in a grouped rail. */ const RAIL_FIELD_NAMES = 3;
|
|
22
|
+
/** `1 field`, `5 fields`. */ export function datasetFieldCount(dataset) {
|
|
23
|
+
const count = effectiveDatasetModel(dataset).order.length;
|
|
24
|
+
return `${count} ${count === 1 ? 'field' : 'fields'}`;
|
|
25
|
+
}
|
|
26
|
+
/** Who a dataset is shared with, named where `hostNames` has the site: `Bakery only`, `All sites`, `3 sites`. */ export function datasetSharingLabel(dataset, hostNames) {
|
|
27
|
+
return describeSharing(dataset, hostNames);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The tab's second line. Ungrouped it says who the dataset is shared with and
|
|
31
|
+
* how many fields it has, which is what tells the same name on two sites
|
|
32
|
+
* apart: `Bakery only · 5 fields`. In a group, whose heading already says who
|
|
33
|
+
* it is shared with, it names the first fields instead:
|
|
34
|
+
* `5 fields · Name, Description, Duration`.
|
|
35
|
+
*/ export function datasetRailSecondary(dataset, options) {
|
|
36
|
+
const fields = datasetFieldCount(dataset);
|
|
37
|
+
if (!options.grouped) return `${datasetSharingLabel(dataset, options.hostNames)} · ${fields}`;
|
|
38
|
+
const model = effectiveDatasetModel(dataset);
|
|
39
|
+
const names = model.order.slice(0, RAIL_FIELD_NAMES).map((id)=>{
|
|
40
|
+
var _ref;
|
|
41
|
+
var _model_fields_id;
|
|
42
|
+
return (_ref = (_model_fields_id = model.fields[id]) == null ? void 0 : _model_fields_id.name) != null ? _ref : id;
|
|
43
|
+
}).filter(Boolean);
|
|
44
|
+
return names.length ? `${fields} · ${names.join(', ')}` : fields;
|
|
45
|
+
}
|
|
46
|
+
/** A dataset's name for the rail and the page: its display name, or a stand-in when it has none. */ export function datasetRailName(dataset) {
|
|
47
|
+
return datasetDisplayName(dataset) || 'Untitled dataset';
|
|
48
|
+
}
|
|
49
|
+
/** Datasets in name order, then id, so two of one name keep their places. */ export function sortDatasetsByName(datasets) {
|
|
50
|
+
return [
|
|
51
|
+
...datasets
|
|
52
|
+
].sort((a, b)=>nameSearchKey(datasetRailName(a)).localeCompare(nameSearchKey(datasetRailName(b))) || a.$id.localeCompare(b.$id));
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Whether a dataset's name starts with what was typed, normalized the way the
|
|
56
|
+
* stored `nameLower` is, so the loaded-list search and the query that replaces
|
|
57
|
+
* it answer alike.
|
|
58
|
+
*/ export function datasetNameMatches(dataset, typed) {
|
|
59
|
+
const key = nameSearchKey(typed);
|
|
60
|
+
return !key || nameSearchKey(datasetDisplayName(dataset)).startsWith(key);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The rail's groups by who each dataset is shared with: `Bakery only (6)`.
|
|
64
|
+
* Groups run in heading order, datasets in name order within each.
|
|
65
|
+
*/ export function groupDatasetsBySharing(datasets, hostNames) {
|
|
66
|
+
const groups = new Map();
|
|
67
|
+
for (const dataset of datasets){
|
|
68
|
+
var _groups_get;
|
|
69
|
+
const label = datasetSharingLabel(dataset, hostNames);
|
|
70
|
+
groups.set(label, [
|
|
71
|
+
...(_groups_get = groups.get(label)) != null ? _groups_get : [],
|
|
72
|
+
dataset
|
|
73
|
+
]);
|
|
74
|
+
}
|
|
75
|
+
return [
|
|
76
|
+
...groups.entries()
|
|
77
|
+
].sort(([a], [b])=>a.localeCompare(b)).map(([label, members])=>({
|
|
78
|
+
label: `${label} (${members.length})`,
|
|
79
|
+
datasets: sortDatasetsByName(members)
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
/** Where a dataset came from: the marketplace listing it was installed from, or `--` for one made here. */ export function datasetSourceLabel(dataset) {
|
|
83
|
+
var _dataset_source;
|
|
84
|
+
if (!((_dataset_source = dataset.source) == null ? void 0 : _dataset_source.listingId)) return '--';
|
|
85
|
+
const version = Number(dataset.source.version);
|
|
86
|
+
return Number.isFinite(version) && version > 0 ? `Marketplace, version ${version}` : 'Marketplace';
|
|
87
|
+
}
|
|
88
|
+
/** When a dataset was created, as a date, or `--` where it was never stamped (a site backup restore stamps none). */ export function datasetCreatedLabel(dataset, locale) {
|
|
89
|
+
const at = dataset.createdAt;
|
|
90
|
+
const date = typeof (at == null ? void 0 : at.toDate) === 'function' ? at.toDate() : typeof (at == null ? void 0 : at.seconds) === 'number' ? new Date(at.seconds * 1000) : null;
|
|
91
|
+
if (!date || Number.isNaN(date.getTime())) return '--';
|
|
92
|
+
return date.toLocaleDateString(locale, {
|
|
93
|
+
month: 'short',
|
|
94
|
+
day: 'numeric',
|
|
95
|
+
year: 'numeric'
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A record's own page's heading (AGL-4047): the first field, in the model's
|
|
100
|
+
* order, that shows a value — a reference names an id, so it is passed over —
|
|
101
|
+
* or a stand-in when none does.
|
|
102
|
+
*/ export function datasetRecordTitle(model, values) {
|
|
103
|
+
for (const fieldId of model.order){
|
|
104
|
+
const field = model.fields[fieldId];
|
|
105
|
+
if (!field || field.type === 'reference') continue;
|
|
106
|
+
const shown = formatDatasetValue(field, values == null ? void 0 : values[fieldId]).trim();
|
|
107
|
+
if (shown) return shown;
|
|
108
|
+
}
|
|
109
|
+
return 'Untitled record';
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The picker labels for a list of datasets (AGL-4047), through the pure
|
|
113
|
+
* `datasetPickerLabels`: the name alone unless it collides in the list.
|
|
114
|
+
*/ export function datasetPickerLabelsOf(datasets, hostNames = {}) {
|
|
115
|
+
return datasetPickerLabels(datasets.map((dataset)=>({
|
|
116
|
+
id: dataset.$id,
|
|
117
|
+
name: datasetRailName(dataset),
|
|
118
|
+
sharing: datasetSharingLabel(dataset, hostNames),
|
|
119
|
+
fields: effectiveDatasetModel(dataset).order.length
|
|
120
|
+
})));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
//# sourceMappingURL=dataset-rail.js.map
|