@vectoriahq/quac 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +35 -2
  3. package/dist/generate/arcgisStacCatalogue.d.ts +46 -0
  4. package/dist/generate/arcgisStacCatalogue.js +189 -0
  5. package/dist/generate/externalStacCatalogue.d.ts +53 -0
  6. package/dist/generate/externalStacCatalogue.js +143 -0
  7. package/dist/generate/fileLayerCollection.d.ts +44 -0
  8. package/dist/generate/fileLayerCollection.js +72 -0
  9. package/dist/generate/folderStacCatalogue.d.ts +48 -0
  10. package/dist/generate/folderStacCatalogue.js +69 -0
  11. package/dist/generate/normalizedProject.d.ts +452 -0
  12. package/dist/generate/normalizedProject.js +877 -0
  13. package/dist/generate/ogcFeaturesStacCatalogue.d.ts +49 -0
  14. package/dist/generate/ogcFeaturesStacCatalogue.js +207 -0
  15. package/dist/generate/qmlForLayer.d.ts +17 -0
  16. package/dist/generate/qmlForLayer.js +36 -0
  17. package/dist/generate/serverLayerTree.d.ts +44 -0
  18. package/dist/generate/serverLayerTree.js +50 -0
  19. package/dist/generate/serverStacCatalogue.d.ts +84 -0
  20. package/dist/generate/serverStacCatalogue.js +327 -0
  21. package/dist/generate/stacCatalogue.d.ts +110 -0
  22. package/dist/generate/stacCatalogue.js +887 -0
  23. package/dist/generate/wfsStacCatalogue.d.ts +37 -0
  24. package/dist/generate/wfsStacCatalogue.js +127 -0
  25. package/dist/generate/wmsStacCatalogue.d.ts +46 -0
  26. package/dist/generate/wmsStacCatalogue.js +229 -0
  27. package/dist/index.d.ts +77 -0
  28. package/dist/index.js +52 -0
  29. package/dist/model/QgsProject.d.ts +724 -0
  30. package/dist/model/QgsProject.js +15 -0
  31. package/dist/model/Stac.d.ts +322 -0
  32. package/dist/model/Stac.js +16 -0
  33. package/dist/model/WmsProject.d.ts +105 -0
  34. package/dist/model/WmsProject.js +1 -0
  35. package/dist/model/arcgis.d.ts +134 -0
  36. package/dist/model/arcgis.js +1 -0
  37. package/dist/model/delimitedText.d.ts +38 -0
  38. package/dist/model/delimitedText.js +46 -0
  39. package/dist/model/featureFilter.d.ts +41 -0
  40. package/dist/model/featureFilter.js +24 -0
  41. package/dist/model/fieldIconAddress.d.ts +27 -0
  42. package/dist/model/fieldIconAddress.js +93 -0
  43. package/dist/model/ogcFeatures.d.ts +40 -0
  44. package/dist/model/ogcFeatures.js +6 -0
  45. package/dist/model/quacExtension.d.ts +28 -0
  46. package/dist/model/quacExtension.js +75 -0
  47. package/dist/model/stacAssetRoles.d.ts +33 -0
  48. package/dist/model/stacAssetRoles.js +44 -0
  49. package/dist/model/stacCollectionNotes.d.ts +21 -0
  50. package/dist/model/stacCollectionNotes.js +44 -0
  51. package/dist/model/stacHref.d.ts +56 -0
  52. package/dist/model/stacHref.js +93 -0
  53. package/dist/model/stacPmtiles.d.ts +38 -0
  54. package/dist/model/stacPmtiles.js +69 -0
  55. package/dist/model/stacSizeAndCount.d.ts +14 -0
  56. package/dist/model/stacSizeAndCount.js +20 -0
  57. package/dist/model/stacStyles.d.ts +93 -0
  58. package/dist/model/stacStyles.js +87 -0
  59. package/dist/model/stacTreeWalk.d.ts +36 -0
  60. package/dist/model/stacTreeWalk.js +76 -0
  61. package/dist/model/stacWms.d.ts +18 -0
  62. package/dist/model/stacWms.js +73 -0
  63. package/dist/model/stacWmts.d.ts +34 -0
  64. package/dist/model/stacWmts.js +90 -0
  65. package/dist/model/stacXyz.d.ts +24 -0
  66. package/dist/model/stacXyz.js +46 -0
  67. package/dist/model/wfs.d.ts +136 -0
  68. package/dist/model/wfs.js +1 -0
  69. package/dist/parse/collectLayerVisibility.d.ts +10 -0
  70. package/dist/parse/collectLayerVisibility.js +22 -0
  71. package/dist/parse/customProperties.d.ts +18 -0
  72. package/dist/parse/customProperties.js +43 -0
  73. package/dist/parse/geometrySiblings.d.ts +25 -0
  74. package/dist/parse/geometrySiblings.js +83 -0
  75. package/dist/parse/parseBrandColour.d.ts +14 -0
  76. package/dist/parse/parseBrandColour.js +25 -0
  77. package/dist/parse/parseDataDefinedEditable.d.ts +38 -0
  78. package/dist/parse/parseDataDefinedEditable.js +76 -0
  79. package/dist/parse/parseDataSource.d.ts +53 -0
  80. package/dist/parse/parseDataSource.js +484 -0
  81. package/dist/parse/parseExtent.d.ts +17 -0
  82. package/dist/parse/parseExtent.js +49 -0
  83. package/dist/parse/parseFormLayout.d.ts +26 -0
  84. package/dist/parse/parseFormLayout.js +60 -0
  85. package/dist/parse/parseGetProjectSettings.d.ts +15 -0
  86. package/dist/parse/parseGetProjectSettings.js +172 -0
  87. package/dist/parse/parseLayers.d.ts +23 -0
  88. package/dist/parse/parseLayers.js +1125 -0
  89. package/dist/parse/parseLegendTree.d.ts +20 -0
  90. package/dist/parse/parseLegendTree.js +66 -0
  91. package/dist/parse/parseMeasurement.d.ts +20 -0
  92. package/dist/parse/parseMeasurement.js +66 -0
  93. package/dist/parse/parseMergin.d.ts +19 -0
  94. package/dist/parse/parseMergin.js +51 -0
  95. package/dist/parse/parseProjectVariables.d.ts +9 -0
  96. package/dist/parse/parseProjectVariables.js +19 -0
  97. package/dist/parse/parseQfieldSync.d.ts +47 -0
  98. package/dist/parse/parseQfieldSync.js +95 -0
  99. package/dist/parse/parseQgsXml.d.ts +15 -0
  100. package/dist/parse/parseQgsXml.js +100 -0
  101. package/dist/parse/parseRelations.d.ts +19 -0
  102. package/dist/parse/parseRelations.js +64 -0
  103. package/dist/parse/parseStyle.d.ts +33 -0
  104. package/dist/parse/parseStyle.js +128 -0
  105. package/dist/parse/parseWmsPublishing.d.ts +21 -0
  106. package/dist/parse/parseWmsPublishing.js +38 -0
  107. package/dist/parse/projectProperties.d.ts +15 -0
  108. package/dist/parse/projectProperties.js +27 -0
  109. package/dist/parse/qgisExpression.d.ts +194 -0
  110. package/dist/parse/qgisExpression.js +859 -0
  111. package/dist/parse/qtDateFormat.d.ts +74 -0
  112. package/dist/parse/qtDateFormat.js +324 -0
  113. package/dist/parse/qtRegex.d.ts +67 -0
  114. package/dist/parse/qtRegex.js +397 -0
  115. package/dist/parse/readProjectFile.d.ts +7 -0
  116. package/dist/parse/readProjectFile.js +27 -0
  117. package/dist/sources/qgisServerUrl.d.ts +6 -0
  118. package/dist/sources/qgisServerUrl.js +17 -0
  119. package/dist/sources/stacDocuments.d.ts +40 -0
  120. package/dist/sources/stacDocuments.js +85 -0
  121. package/dist/sources/stacItems.d.ts +109 -0
  122. package/dist/sources/stacItems.js +287 -0
  123. package/dist/util/catalogueFileFormats.d.ts +58 -0
  124. package/dist/util/catalogueFileFormats.js +64 -0
  125. package/dist/util/devLog.d.ts +10 -0
  126. package/dist/util/devLog.js +22 -0
  127. package/dist/util/fileName.d.ts +18 -0
  128. package/dist/util/fileName.js +45 -0
  129. package/dist/util/nonBlankText.d.ts +2 -0
  130. package/dist/util/nonBlankText.js +4 -0
  131. package/dist/util/wfsVersions.d.ts +9 -0
  132. package/dist/util/wfsVersions.js +13 -0
  133. package/package.json +55 -4
  134. package/src/schema/quac.schema.json +939 -0
@@ -0,0 +1,887 @@
1
+ import { arcgisQueryAsset } from "./arcgisStacCatalogue.js";
2
+ import { QUAC_MEASUREMENT_FIELD, slugify, generateStacFromNormalized, unionBboxes, withSelfLink } from "./normalizedProject.js";
3
+ import { wfsGetFeatureAsset } from "./wfsStacCatalogue.js";
4
+ import { delimitedTextField, QUAC_DELIMITED_TEXT } from "../model/delimitedText.js";
5
+ import { featureFilterField, QUAC_FEATURE_FILTER } from "../model/featureFilter.js";
6
+ import { readDataAsset } from "../model/stacAssetRoles.js";
7
+ import { decodeAssetPath, encodeAssetPath } from "../model/stacHref.js";
8
+ import { DEFAULT_STYLE_ROLE, styleAssetKey } from "../model/stacStyles.js";
9
+ import { buildWmsLink, WEB_MAP_LINKS_EXTENSION } from "../model/stacWms.js";
10
+ import { buildWmtsLink } from "../model/stacWmts.js";
11
+ import { buildXyzLink } from "../model/stacXyz.js";
12
+ import { findGeometrySiblings, readSiblingShapes, siblingCollectionId } from "../parse/geometrySiblings.js";
13
+ import { declaredMediaTypeForFile, isLayerFileOfFormat, PROJECT_DATA_ROLES, QML_STYLE_MEDIA_TYPE } from "../util/catalogueFileFormats.js";
14
+ /**
15
+ * Generates a STAC Catalog tree from a parsed QgsProject.
16
+ *
17
+ * Mapping:
18
+ * QgsProject → top-level Catalog
19
+ * QgsProject.layerTree → nested Catalogs (groups) + Collection links
20
+ * LayerEntry → Collection
21
+ * LayerEntry.dataSource → Asset within the Collection
22
+ * GeoJSON properties → table:columns extension on the Collection
23
+ *
24
+ * Pure function — no side effects, no I/O. Companion GeoJSONs are passed
25
+ * in by the caller; if absent for a given layer, the Collection is still
26
+ * emitted but `table:columns` is omitted.
27
+ *
28
+ * This is a thin wrapper: `qgsProjectToNormalized` resolves the QGS-specific
29
+ * wording, assets and columns into the shared `NormalizedProject`, and
30
+ * `generateStacFromNormalized` (see normalizedProject.ts) builds the catalogue.
31
+ */
32
+ export function generateStacCatalogue(project, companions = [], options = {}) {
33
+ // `selfHref` is the folder the project was published from, for a project
34
+ // loaded out of cloud storage. A dragged-in project has no address to record.
35
+ //
36
+ // `projectPath` is the project document's own path inside that folder, which
37
+ // the layers' style assets address into — a path, not an href, so the
38
+ // generator is the one place that escapes it. A caller that doesn't know
39
+ // where the project file sits leaves it off, and the style assets fall back
40
+ // to a bare fragment — see `buildStyleAssets`.
41
+ //
42
+ // `projectFileName` is the project file's name for each layer's `via` link
43
+ // alone, where the caller knows it but leaves `projectPath` off, as the drop
44
+ // route does. `projectPath` gives the link where it is set.
45
+ //
46
+ // `initialView` is the project's saved map canvas extent **already in
47
+ // WGS84**, which is what `quac:initial_view` publishes. The canvas has
48
+ // its own CRS and this package holds no reprojection — it must not import
49
+ // OpenLayers or proj4 (see `packages/quac/src/index.ts`) — so the caller converts and
50
+ // passes the result, or leaves it off.
51
+ //
52
+ // `layerWgs84Extents` is the same conversion, per layer, for a layer whose
53
+ // `<wgs84extent>` QGIS didn't write: `layer.extent` is in the layer's own
54
+ // CRS, and this package cannot reproject it for the same reason it cannot
55
+ // reproject the canvas. `resolveLayerWgs84Extents` in the same file builds
56
+ // this map; a layer left out of it (or a caller that leaves the option off
57
+ // entirely) has no box of its own.
58
+ return withSelfLink(generateStacFromNormalized(qgsProjectToNormalized(project, companions, options.projectPath, options.projectPath ?? options.projectFileName, options.initialView ?? null, options.layerWgs84Extents)), options.selfHref);
59
+ }
60
+ /**
61
+ * The key a style asset takes for the field its renderer classifies by, when
62
+ * that renderer is a categorised one. The project author's declaration.
63
+ */
64
+ export const QUAC_CATEGORISED_FIELD = 'quac:categorised_field';
65
+ /**
66
+ * The key a data asset takes for the shapes of feature its Collection holds,
67
+ * from QGIS file sources' `|geometrytype=`: a list of `Point`, `LineString` and
68
+ * `Polygon`, a `Multi*` geometry counting as its single-part shape.
69
+ */
70
+ export const QUAC_GEOMETRY_FILTER = 'quac:geometry_filter';
71
+ /**
72
+ * The shapes a Collection's data asset keeps, or null where it names none, or
73
+ * names anything this does not read, so a data file is read whole.
74
+ */
75
+ export function readCollectionGeometryFilter(collection) {
76
+ const value = readDataAsset(collection)?.[QUAC_GEOMETRY_FILTER];
77
+ if (!Array.isArray(value) || value.length === 0)
78
+ return null;
79
+ const isShape = (entry) => entry === 'Point' || entry === 'LineString' || entry === 'Polygon';
80
+ return value.every(isShape) ? value : null;
81
+ }
82
+ /**
83
+ * The key a data asset takes for the table of a GeoPackage its Collection
84
+ * reads, from a QGIS file source's `|layername=`.
85
+ */
86
+ export const QUAC_LAYER_NAME = 'quac:layer_name';
87
+ /** The table a Collection's data asset names, or null where it names none. */
88
+ export function readCollectionLayerName(collection) {
89
+ const value = readDataAsset(collection)?.[QUAC_LAYER_NAME];
90
+ return typeof value === 'string' && value.trim() !== '' ? value : null;
91
+ }
92
+ /** Projects a parsed QgsProject into the source-agnostic normalized model. */
93
+ function qgsProjectToNormalized(project, companions, projectPath, projectFileName, initialView, layerWgs84Extents) {
94
+ const companionByLayerId = new Map();
95
+ for (const c of companions) {
96
+ if (c.geojson)
97
+ companionByLayerId.set(c.layerId, c.geojson);
98
+ }
99
+ const layersById = new Map();
100
+ for (const layer of project.layers)
101
+ layersById.set(layer.id, layer);
102
+ // Layers QGIS split out of one file by shape are one Collection, under the
103
+ // first sibling's id, so whatever names a later sibling names that Collection.
104
+ const siblingsById = findGeometrySiblings(project);
105
+ const collectionIdOf = (layerId) => siblingCollectionId(siblingsById, layerId);
106
+ const context = {
107
+ companionByLayerId,
108
+ projectPath,
109
+ projectFileName,
110
+ layerWgs84Extents,
111
+ relationsByChildLayerId: collectRelationsByChildLayerId(project.relations ?? [], layersById, collectionIdOf),
112
+ valueRelationsByLayerId: collectValueRelationsByLayerId(project.layers, layersById, collectionIdOf),
113
+ siblingsById,
114
+ measurement: project.measurement ?? null,
115
+ wfsTransactionLayers: project.wfsTransactionLayers ?? null,
116
+ wmsPublishing: project.wmsPublishing ?? null,
117
+ filtersByCollectionId: collectFiltersByCollectionId(project.merginFilters ?? [], layersById, collectionIdOf)
118
+ };
119
+ const nodes = walkQgsGroup(project.layerTree, layersById, context);
120
+ // A layer the layers panel does not list comes after every listed one, in the
121
+ // order the project file holds it.
122
+ const listedLayerIds = new Set();
123
+ const collectListedLayerIds = (group) => {
124
+ for (const child of group.children) {
125
+ if (child.kind === 'layer')
126
+ listedLayerIds.add(child.layerId);
127
+ else
128
+ collectListedLayerIds(child);
129
+ }
130
+ };
131
+ collectListedLayerIds(project.layerTree);
132
+ for (const layer of project.layers) {
133
+ if (listedLayerIds.has(layer.id))
134
+ continue;
135
+ const node = layerToNormalized(layer, context);
136
+ if (node)
137
+ nodes.push(node);
138
+ }
139
+ // The Catalog's extent is what the project's data covers — the union of its
140
+ // layers' boxes, the same thing every other source's Catalog extent means.
141
+ // Where the map *opens* is a different fact, and is only true of a project
142
+ // whose author saved a canvas position, so it goes in its own field below
143
+ // and is absent from a project that declares none.
144
+ return {
145
+ id: slugify(project.title || 'qgs-project') || 'qgs-project',
146
+ title: project.title,
147
+ description: project.metadata.abstract ?? (project.title
148
+ ? `STAC catalogue generated from QGIS project "${project.title}".`
149
+ : 'STAC catalogue generated from a QGIS project.'),
150
+ bbox: unionExtent(project.layers, layerWgs84Extents),
151
+ providers: project.metadata.author ? [{ name: project.metadata.author, roles: ['producer'] }] : undefined,
152
+ initialView,
153
+ activeCollectionId: project.initialActiveLayerId && layersById.has(project.initialActiveLayerId)
154
+ ? collectionIdOf(project.initialActiveLayerId)
155
+ : null,
156
+ nodes
157
+ };
158
+ }
159
+ /**
160
+ * Sorts a project's filters by the Collection each goes onto: its layer's, the
161
+ * first sibling's for a layer QGIS split by shape. A filter whose layer is not
162
+ * in the project, or does not have its field, goes nowhere.
163
+ */
164
+ function collectFiltersByCollectionId(filters, layersById, collectionIdOf) {
165
+ const byCollectionId = new Map();
166
+ for (const { layerId, field, name } of filters) {
167
+ if (!layersById.get(layerId)?.fieldNames.includes(field))
168
+ continue;
169
+ const collectionId = collectionIdOf(layerId);
170
+ byCollectionId.set(collectionId, [...(byCollectionId.get(collectionId) ?? []), { field, name }]);
171
+ }
172
+ return byCollectionId;
173
+ }
174
+ /**
175
+ * Groups the project's relations under the child layer each one hangs off a
176
+ * parent, which is the layer whose Collection has them.
177
+ *
178
+ * A `.qgs` Collection's id is the QGIS layer id (`packages/quac/spec/README.md`
179
+ * § Collection ids), so a relation's layer ids are already Collection ids. One
180
+ * pointing to a layer the project does not hold is dropped — it would point at a
181
+ * Collection this catalogue has no entry for.
182
+ */
183
+ function collectRelationsByChildLayerId(relations, layersById, collectionIdOf) {
184
+ const byChildLayerId = new Map();
185
+ for (const relation of relations) {
186
+ if (!layersById.has(relation.parentLayerId) || !layersById.has(relation.childLayerId))
187
+ continue;
188
+ const childCollectionId = collectionIdOf(relation.childLayerId);
189
+ const forChild = byChildLayerId.get(childCollectionId) ?? [];
190
+ forChild.push({
191
+ id: relation.id,
192
+ name: relation.name,
193
+ parentCollectionId: collectionIdOf(relation.parentLayerId),
194
+ fields: relation.fieldPairs.map((pair) => ({ parent: pair.parentField, child: pair.childField }))
195
+ });
196
+ byChildLayerId.set(childCollectionId, forChild);
197
+ }
198
+ return byChildLayerId;
199
+ }
200
+ /**
201
+ * Each layer's Value Relation widgets as `quac:value_relation` writes
202
+ * them, keyed by layer id and then field name. The lookup is found by layer id
203
+ * and then by layer name, as QGIS finds it
204
+ * (`QgsVectorLayerRef::resolveByIdOrNameOnly`, `src/core/qgsvectorlayerref.cpp`,
205
+ * `qgis/QGIS@master`); its Collection id is its layer id. A widget naming a
206
+ * layer the project does not hold writes nothing, since it would point at a
207
+ * Collection this catalogue has no entry for.
208
+ */
209
+ function collectValueRelationsByLayerId(layers, layersById, collectionIdOf) {
210
+ const byLayerId = new Map();
211
+ for (const layer of layers) {
212
+ const relations = {};
213
+ for (const [field, widget] of Object.entries(layer.fieldValueRelations)) {
214
+ const lookup = layersById.get(widget.layerId) ?? layers.find((candidate) => candidate.name === widget.layerName);
215
+ if (lookup)
216
+ relations[field] = valueRelationToJson(collectionIdOf(lookup.id), widget);
217
+ }
218
+ if (Object.keys(relations).length > 0)
219
+ byLayerId.set(layer.id, relations);
220
+ }
221
+ return byLayerId;
222
+ }
223
+ /** A Value Relation widget as `quac:value_relation` stores it: a member at its default is left off. */
224
+ function valueRelationToJson(collectionId, widget) {
225
+ return {
226
+ collection: collectionId,
227
+ key: widget.keyField,
228
+ value: widget.valueField,
229
+ ...(widget.filterExpression ? { filter: widget.filterExpression } : {}),
230
+ ...(widget.allowNull ? { allow_null: true } : {}),
231
+ ...(widget.allowMulti ? { allow_multi: true } : {}),
232
+ ...(widget.orderBy !== 'key' ? { order_by: widget.orderBy } : {}),
233
+ ...(widget.orderBy === 'field' && widget.orderField ? { order_field: widget.orderField } : {}),
234
+ ...(widget.descending ? { descending: true } : {})
235
+ };
236
+ }
237
+ /**
238
+ * Walks a QGIS layer tree group and returns its children as normalized nodes,
239
+ * resolving each leaf's LayerEntry (leaves whose layer id isn't in the
240
+ * project are skipped, as before). A group holding nothing but one set of
241
+ * geometry siblings is that set's layer, titled with the group's name.
242
+ */
243
+ function walkQgsGroup(group, layersById, context) {
244
+ const nodes = [];
245
+ for (const node of group.children) {
246
+ if (node.kind === 'layer') {
247
+ const layer = layersById.get(node.layerId);
248
+ if (!layer)
249
+ continue;
250
+ const normalized = layerToNormalized(layer, context);
251
+ if (normalized)
252
+ nodes.push(normalized);
253
+ }
254
+ else if (node.kind === 'group') {
255
+ const siblings = wholeGroupSiblings(node, context.siblingsById);
256
+ if (siblings) {
257
+ nodes.push(siblingsToNormalized(siblings, node.name, context));
258
+ continue;
259
+ }
260
+ nodes.push({
261
+ kind: 'group',
262
+ id: slugify(node.name) || 'group',
263
+ title: node.name,
264
+ description: qgisPlaceholderDescription('group', node.name),
265
+ ...(node.mutuallyExclusive ? { mutuallyExclusive: true } : {}),
266
+ children: walkQgsGroup(node, layersById, context)
267
+ });
268
+ }
269
+ }
270
+ return nodes;
271
+ }
272
+ /** The set of geometry siblings that is the whole of `group`'s contents, or null. */
273
+ function wholeGroupSiblings(group, siblingsById) {
274
+ const first = group.children[0];
275
+ const siblings = first?.kind === 'layer' ? siblingsById.get(first.layerId) : undefined;
276
+ if (!siblings || group.children.length !== siblings.length)
277
+ return null;
278
+ const isWholeGroup = group.children.every((child) => (child.kind === 'layer' && siblings.some((sibling) => sibling.id === child.layerId)));
279
+ return isWholeGroup ? siblings : null;
280
+ }
281
+ /**
282
+ * A layer's Collection: its own, or for a geometry sibling, the set's, which
283
+ * its first sibling stands for, so a later sibling has none and gives null.
284
+ */
285
+ function layerToNormalized(layer, context) {
286
+ const siblings = context.siblingsById.get(layer.id);
287
+ if (!siblings)
288
+ return qgsLayerToNormalized(layer, context);
289
+ return siblings[0] === layer ? siblingsToNormalized(siblings, layer.name, context) : null;
290
+ }
291
+ /**
292
+ * One Collection for layers QGIS split out of one file by shape: the first
293
+ * sibling's settings,
294
+ * every sibling's extent, and a data asset keeping the siblings' shapes. With
295
+ * all three shapes it keeps none, so the layer reads the whole file, features
296
+ * with no shape included.
297
+ */
298
+ function siblingsToNormalized(siblings, title, context) {
299
+ const first = siblings[0];
300
+ const shapes = readSiblingShapes(siblings);
301
+ const wkbTypes = siblings.flatMap((layer) => layer.wkbType ? [layer.wkbType] : []);
302
+ return {
303
+ ...qgsLayerToNormalized(first, context, shapes.length === 3 ? null : shapes),
304
+ title,
305
+ description: first.resourceMetadata.abstract ?? qgisPlaceholderDescription('layer', title),
306
+ bbox: unionExtent([...siblings], context.layerWgs84Extents),
307
+ // A sibling that names no WKB type leaves the list unknown, so none is written.
308
+ wkbTypes: wkbTypes.length === siblings.length ? wkbTypes : [],
309
+ // QGIS Server names each sibling separately, so the one Collection has no name of its own.
310
+ qgisServerNames: null
311
+ };
312
+ }
313
+ /**
314
+ * The names QGIS Server would give the layer if it served the project
315
+ * (`QgsWmsLayerInfos::buildWmsLayerInfos`, `src/server/services/wms/qgswmslayerinfos.cpp`,
316
+ * and `QgsMapLayerServerProperties::wfsTypeName`, `src/core/qgsmaplayerserverproperties.cpp`,
317
+ * `qgis/QGIS@master`, read 2026-11-03). Its WMS name is its layer id where the
318
+ * project ticks **Use layer ids as names**, else its short name, else its name,
319
+ * and none where the project leaves it out of WMS. Its WFS type name, given
320
+ * only where the project publishes it for WFS, is its short name or else its
321
+ * name, with each space made `_` and each `:` and em dash made `-`.
322
+ */
323
+ export function qgisServerNamesOf(layer, context) {
324
+ const publishing = context.wmsPublishing;
325
+ const ownName = layer.shortName || layer.name;
326
+ const wmsName = publishing?.restrictedLayers.includes(layer.name)
327
+ ? null
328
+ : publishing?.useLayerIds ? layer.id : ownName;
329
+ const wfsPublished = context.wfsTransactionLayers?.published.includes(layer.id) ?? false;
330
+ const wfsTypeName = wfsPublished ? ownName.replace(/ /g, '_').replace(/[:\u2014]/g, '-') : null;
331
+ return { wmsName: wmsName || null, wfsTypeName: wfsTypeName || null };
332
+ }
333
+ /** The shape a file layer's own `|geometrytype=` keeps, as the list `quac:geometry_filter` holds. */
334
+ function geometryFilterOf(layer) {
335
+ const shapes = readSiblingShapes([layer]);
336
+ return shapes.length > 0 ? shapes : null;
337
+ }
338
+ function qgsLayerToNormalized(layer, context, geometryFilter = geometryFilterOf(layer)) {
339
+ const geojson = context.companionByLayerId.get(layer.id) ?? null;
340
+ const { projectPath, layerWgs84Extents } = context;
341
+ const relatedTo = context.relationsByChildLayerId.get(layer.id);
342
+ const valueRelations = context.valueRelationsByLayerId.get(layer.id);
343
+ const bbox = effectiveWgs84Bbox(layer, layerWgs84Extents);
344
+ const metadata = layer.resourceMetadata;
345
+ const ds = layer.dataSource;
346
+ const webMapLink = ds.kind === 'wms' ? buildWmsLink(ds) : ds.kind === 'wmts' ? buildWmtsLink(ds) : ds.kind === 'xyz' ? buildXyzLink(ds.url, ds.tiles) : null;
347
+ return {
348
+ kind: 'layer',
349
+ id: layer.id,
350
+ title: layer.name,
351
+ // Text written into the catalogue document, which carries the project's own name.
352
+ description: metadata.abstract ?? qgisPlaceholderDescription('layer', layer.name),
353
+ bbox,
354
+ geometryType: layer.geometryType,
355
+ wkbTypes: layer.wkbType ? [layer.wkbType] : [],
356
+ qgisServerNames: qgisServerNamesOf(layer, context),
357
+ tableColumns: deriveTableColumns(geojson, layer.fieldNames, layer.fieldAliases, layer.fieldValueMaps, layer.fieldAttachments, layer.fieldEditRules, valueRelations, layer.formLayout ?? null, layer.fieldIcons, layer.fieldControls),
358
+ formOrder: layer.formLayout?.fields.map((field) => field.name),
359
+ assets: buildLayerAssets(layer, projectPath, geometryFilter),
360
+ keywords: metadata.keywords.length > 0 ? metadata.keywords : undefined,
361
+ license: metadata.license,
362
+ providers: buildLayerProviders(layer),
363
+ temporalInterval: metadata.temporalInterval,
364
+ displayField: layer.displayField,
365
+ visibilityChecked: layer.isVisible,
366
+ // An image layer has no features to edit. An ArcGIS layer keeps the
367
+ // project's own Read-only tick: whether edits are written back to the
368
+ // service is left to the application reading the catalogue.
369
+ editable: ds.kind === 'wms' || ds.kind === 'wmts' || ds.kind === 'xyz' ? false : layer.editable,
370
+ identifiable: layer.queryable,
371
+ scaleRange: layer.scaleRange,
372
+ opacity: layer.opacity,
373
+ relatedTo,
374
+ isPrivate: layer.isPrivate,
375
+ legendImage: layer.legendImage,
376
+ icon: layer.icon,
377
+ locks: combineLocks(layer.locks ?? {}, wfsTransactionLocks(layer.id, context.wfsTransactionLayers)),
378
+ filters: context.filtersByCollectionId.get(layer.id),
379
+ vendorFields: buildVendorFields(layer, context.measurement),
380
+ ...(webMapLink || context.projectFileName ? {
381
+ links: [
382
+ ...(webMapLink ? [webMapLink] : []),
383
+ ...(context.projectFileName ? [projectLink(context.projectFileName)] : [])
384
+ ]
385
+ } : {}),
386
+ ...(webMapLink ? { extensions: [WEB_MAP_LINKS_EXTENSION] } : {})
387
+ };
388
+ }
389
+ /** The title of the `via` link to the QGIS project a layer's Collection was written from. */
390
+ export const QGIS_PROJECT_LINK_TITLE = 'QGIS project';
391
+ /** A `via` link to the project file, beside the Collection: where its details came from. */
392
+ function projectLink(projectFileName) {
393
+ return { rel: 'via', href: `./${encodeAssetPath(projectFileName)}`, title: QGIS_PROJECT_LINK_TITLE };
394
+ }
395
+ const PLACEHOLDER_DESCRIPTION = /^Layer (group )?"[\s\S]*" from the QGIS project\.$/;
396
+ /**
397
+ * The description a Collection takes where its QGIS layer or group has no
398
+ * abstract of its own, since STAC requires one. `isQgisPlaceholderDescription`
399
+ * tells it apart from one the project wrote.
400
+ */
401
+ export function qgisPlaceholderDescription(kind, name) {
402
+ return `${kind === 'group' ? 'Layer group' : 'Layer'} "${name}" from the QGIS project.`;
403
+ }
404
+ /** Whether a description is the one `qgisPlaceholderDescription` writes. */
405
+ export function isQgisPlaceholderDescription(description) {
406
+ return description !== undefined && PLACEHOLDER_DESCRIPTION.test(description);
407
+ }
408
+ /**
409
+ * The edits a layer published for WFS does not take: an unticked **Insert**
410
+ * locks adding, **Update** both attributes and geometry, which WFS-T updates
411
+ * together, and **Delete** deleting. A layer the project does not publish
412
+ * locks nothing, so a project that publishes nothing is unchanged.
413
+ */
414
+ function wfsTransactionLocks(layerId, layers) {
415
+ if (!layers?.published.includes(layerId))
416
+ return {};
417
+ const locks = {};
418
+ if (!layers.insert.includes(layerId))
419
+ locks.add = true;
420
+ if (!layers.update.includes(layerId)) {
421
+ locks.attributes = true;
422
+ locks.geometry = true;
423
+ }
424
+ if (!layers.delete.includes(layerId))
425
+ locks.delete = true;
426
+ return locks;
427
+ }
428
+ /** Either source's locks, where `true` from either wins over the other's expression. */
429
+ function combineLocks(first, second) {
430
+ const locks = { ...first };
431
+ for (const [edit, lock] of Object.entries(second)) {
432
+ if (lock === true || !locks[edit])
433
+ locks[edit] = lock;
434
+ }
435
+ return locks;
436
+ }
437
+ /**
438
+ * A layer's own providers: its `<attribution>` credit line as a `licensor`,
439
+ * and each `<resourceMetadata><contact>` identifying an organisation or a person as
440
+ * a `producer`. Neither is the project-wide author, which
441
+ * `qgsProjectToNormalized` puts on the Catalog and `buildCollection` merges
442
+ * onto every layer's providers separately.
443
+ */
444
+ function buildLayerProviders(layer) {
445
+ const providers = [];
446
+ if (layer.attribution) {
447
+ providers.push({
448
+ name: layer.attribution.text,
449
+ roles: ['licensor'],
450
+ ...(layer.attribution.href ? { url: layer.attribution.href } : {})
451
+ });
452
+ }
453
+ for (const contact of layer.resourceMetadata.contacts) {
454
+ const name = contact.organization || contact.name;
455
+ if (!name)
456
+ continue;
457
+ providers.push({
458
+ name,
459
+ roles: ['producer'],
460
+ ...(contact.email ? { url: `mailto:${contact.email}` } : {})
461
+ });
462
+ }
463
+ return providers.length > 0 ? providers : undefined;
464
+ }
465
+ /**
466
+ * Declares the project's measurement units, an XYZ layer's deepest zoom
467
+ * level as `quac:max_zoom`, a WFS-backed layer's service and feature
468
+ * type as `quac:wfs_*` fields, and an ArcGIS layer's address and filter as
469
+ * `quac:arcgis_*` fields, so a consumer reads them directly instead of taking
470
+ * them back apart out of the asset href.
471
+ */
472
+ function buildVendorFields(layer, measurement) {
473
+ const ds = layer.dataSource;
474
+ const shared = measurement
475
+ ? { [QUAC_MEASUREMENT_FIELD]: { area_unit: measurement.areaUnit, distance_unit: measurement.distanceUnit } }
476
+ : {};
477
+ if (ds.kind === 'xyz')
478
+ return ds.maxZoom === null ? shared : { ...shared, 'quac:max_zoom': ds.maxZoom };
479
+ // The same fields an ArcGIS Online layer's Collection carries, so one reader loads both.
480
+ if (ds.kind === 'arcgis') {
481
+ return { ...shared, 'quac:arcgis_layer_url': ds.url, ...(ds.where ? { 'quac:arcgis_where': ds.where } : {}) };
482
+ }
483
+ if (ds.kind !== 'wfs')
484
+ return shared;
485
+ const fields = {
486
+ ...shared,
487
+ 'quac:wfs_endpoint': ds.url,
488
+ 'quac:wfs_type_name': ds.typeName
489
+ };
490
+ if (ds.srsName)
491
+ fields['quac:wfs_srs_name'] = ds.srsName;
492
+ return fields;
493
+ }
494
+ /** The layer's data asset and its style set, in one namespace with no clashes. */
495
+ function buildLayerAssets(layer, projectPath, geometryFilter) {
496
+ const dataAssets = buildAssets(layer, geometryFilter);
497
+ return { ...dataAssets, ...buildStyleAssets(layer, projectPath, dataAssets) };
498
+ }
499
+ function buildAssets(layer, geometryFilter) {
500
+ const ds = layer.dataSource;
501
+ if (ds.kind === 'wms' || ds.kind === 'wmts')
502
+ return {};
503
+ if (ds.kind === 'xyz') {
504
+ // A `{quadkey}` template has no `rel: "xyz"` link to go in, so it goes in
505
+ // the data asset (`packages/quac/spec/README.md` § "A layer's data,
506
+ // and the ways to reach it").
507
+ if (buildXyzLink(ds.url))
508
+ return {};
509
+ return {
510
+ data: {
511
+ href: ds.url,
512
+ title: 'XYZ tile template',
513
+ roles: ['data']
514
+ }
515
+ };
516
+ }
517
+ if (ds.kind === 'file') {
518
+ return {
519
+ data: {
520
+ // The path the project gives, not just the file's name: a project
521
+ // referencing `data/roads.geojson` publishes an href that finds it.
522
+ // Relative to the Catalog's `self` link, which for a cloud project is
523
+ // the folder it was published from.
524
+ // An online file's own address; it is not beside the project.
525
+ href: ds.url ?? `./${encodeAssetPath(ds.relPath)}`,
526
+ type: declaredMediaTypeForFile(ds.filename, PROJECT_DATA_ROLES),
527
+ title: ds.filename,
528
+ roles: ['data'],
529
+ ...(geometryFilter ? { [QUAC_GEOMETRY_FILTER]: geometryFilter } : {}),
530
+ // Only a GeoPackage's: QGIS also writes `|layername=` for a GeoJSON
531
+ // file, which holds one layer.
532
+ ...(ds.layerName && isLayerFileOfFormat(ds.filename, 'geopackage') ? { [QUAC_LAYER_NAME]: ds.layerName } : {}),
533
+ ...(ds.delimitedText ? { [QUAC_DELIMITED_TEXT]: delimitedTextField(ds.delimitedText) } : {}),
534
+ ...(ds.featureFilter ? { [QUAC_FEATURE_FILTER]: featureFilterField(ds.featureFilter) } : {})
535
+ }
536
+ };
537
+ }
538
+ if (ds.kind === 'arcgis') {
539
+ return { data: arcgisQueryAsset({ layerUrl: ds.url, where: ds.where }, layer.name) };
540
+ }
541
+ if (ds.kind === 'wfs') {
542
+ return {
543
+ data: {
544
+ ...wfsGetFeatureAsset(ds.url, ds.typeName, ds.typeName),
545
+ ...(ds.featureFilter ? { [QUAC_FEATURE_FILTER]: featureFilterField(ds.featureFilter) } : {})
546
+ }
547
+ };
548
+ }
549
+ // Unsupported source: a placeholder asset naming the provider. The data
550
+ // source itself is not written, because a database connection string can
551
+ // hold a user name and password.
552
+ return {
553
+ data: {
554
+ href: '',
555
+ title: `Unsupported source: ${ds.hint ?? 'unknown'}`,
556
+ roles: ['data']
557
+ }
558
+ };
559
+ }
560
+ /**
561
+ * Declares a layer's named styles as `style` assets, one per style the project
562
+ * defines (`packages/quac/spec/README.md` § Styles). QGIS keeps them in its style
563
+ * manager — "Asset Owner" and "Priority" on the graffiti sample — and they are
564
+ * declared here rather than embedded, like every other style in the profile.
565
+ *
566
+ * **The active style is emitted first and has the `default` role**, because
567
+ * QGIS records which style is current independently of the order they appear in
568
+ * the file — emitting file order and leaving the default unmarked would hand a
569
+ * consumer a different style from the one QGIS draws.
570
+ *
571
+ * A style QGIS defined but wrote no renderer for is skipped — there would be
572
+ * nothing at the address to fetch.
573
+ *
574
+ * The address is a fragment into the project document, since that is where the
575
+ * style is; there is no per-style file to point at. `projectPath` identifies that
576
+ * document when the caller knows where it sits, and is omitted otherwise,
577
+ * leaving a bare fragment — see the known gaps in the profile. The path and
578
+ * both halves of the fragment are escaped, so a project or style whose name
579
+ * holds a `#` still gives an address that can be taken back apart.
580
+ *
581
+ * `existing` is the assets already built for the layer, so a style named after
582
+ * one of them takes a disambiguated key instead of replacing it.
583
+ */
584
+ function buildStyleAssets(layer, projectPath, existing) {
585
+ const assets = {};
586
+ // The first style with a renderer is the default — the active one, unless
587
+ // QGIS wrote no renderer for it. Marked rather than left to its position,
588
+ // because a style named `2024` takes an asset key JavaScript enumerates
589
+ // ahead of every other, whenever it was written.
590
+ let defaultMarked = false;
591
+ for (const style of orderActiveStyleFirst(layer.styles, layer.activeStyleIndex)) {
592
+ if (!style.rendererV2RawXml && !style.vectorTileRendererRawXml)
593
+ continue;
594
+ const fragment = `${encodeURIComponent(layer.id)}/${encodeURIComponent(style.name)}`;
595
+ assets[styleAssetKey({ ...existing, ...assets }, style.name)] = {
596
+ href: `${projectPath ? `./${encodeAssetPath(projectPath)}` : ''}#${fragment}`,
597
+ type: QML_STYLE_MEDIA_TYPE,
598
+ title: style.name,
599
+ roles: defaultMarked ? ['style'] : ['style', DEFAULT_STYLE_ROLE],
600
+ // Written only for a categorised style, so a reader can tell which field
601
+ // a style classifies by without fetching and converting the style itself.
602
+ ...(style.categorisedField ? { [QUAC_CATEGORISED_FIELD]: style.categorisedField } : {})
603
+ };
604
+ defaultMarked = true;
605
+ }
606
+ return assets;
607
+ }
608
+ /**
609
+ * A QGIS style asset's address, taken back apart — the counterpart of the href
610
+ * `buildStyleAssets` writes, kept beside it so the two cannot drift.
611
+ *
612
+ * The address is `./project.qgs#<layer-id>/<style-name>`, with the document
613
+ * path and both halves of the fragment percent-encoded, and the document absent
614
+ * for a caller that did not know where the project file sat. Because the
615
+ * document path is escaped, the first `#` is always the one starting the
616
+ * fragment — a project named `Assets #2.qgs` has its `#` as `%23`, where
617
+ * unescaped it would cut the address in half and leave every layer in that
618
+ * project unstyled.
619
+ *
620
+ * Returns null for an href with no such fragment — a style file sitting
621
+ * beside the data, which is the folder catalogue's shape and is dereferenced by
622
+ * fetching it rather than by reading the project.
623
+ */
624
+ export function parseQgisStyleAssetHref(href) {
625
+ const hash = href.indexOf('#');
626
+ if (hash < 0)
627
+ return null;
628
+ const fragment = href.slice(hash + 1);
629
+ const slash = fragment.indexOf('/');
630
+ if (slash <= 0 || slash === fragment.length - 1)
631
+ return null;
632
+ try {
633
+ const document = href.slice(0, hash);
634
+ return {
635
+ documentPath: document ? decodeAssetPath(document) : null,
636
+ layerId: decodeURIComponent(fragment.slice(0, slash)),
637
+ styleName: decodeURIComponent(fragment.slice(slash + 1))
638
+ };
639
+ }
640
+ catch {
641
+ // A malformed escape sequence — not an address this wrote.
642
+ return null;
643
+ }
644
+ }
645
+ /** The active style, then the rest in the order the project lists them. */
646
+ function orderActiveStyleFirst(styles, activeIndex) {
647
+ const active = styles[activeIndex];
648
+ if (!active)
649
+ return styles;
650
+ return [active, ...styles.filter((style) => style !== active)];
651
+ }
652
+ /**
653
+ * A layer's bbox in WGS84: QGIS's own `<wgs84extent>` when it wrote one,
654
+ * otherwise the caller-supplied reprojection of `layer.extent` keyed by
655
+ * layer id, otherwise null. `layer.extent` itself is in the layer's CRS and
656
+ * is never published as it stands.
657
+ */
658
+ function effectiveWgs84Bbox(layer, layerWgs84Extents) {
659
+ return layer.wgs84Extent ?? layerWgs84Extents?.get(layer.id) ?? null;
660
+ }
661
+ /**
662
+ * Returns the union of all layers' bboxes (preferring wgs84Extent, then a
663
+ * caller-supplied reprojection), or null if no layer has any extent.
664
+ */
665
+ function unionExtent(layers, layerWgs84Extents) {
666
+ return unionBboxes(layers.map((layer) => effectiveWgs84Bbox(layer, layerWgs84Extents)));
667
+ }
668
+ /**
669
+ * Emits a `table:columns` array seeded by the canonical list of fields
670
+ * QGIS declares in <fieldConfiguration>, enriched with whatever extra
671
+ * metadata is available:
672
+ *
673
+ * - **name** always — from `fieldNames` (or as a fallback, from
674
+ * GeoJSON properties or alias keys, so callers that
675
+ * haven't parsed fieldConfiguration still get something)
676
+ * - **title** from QGIS field aliases when set (non-empty)
677
+ * - **type** inferred from every GeoJSON property value when data
678
+ * is available; omitted otherwise (QGIS doesn't declare
679
+ * field types in the .qgs for WFS layers — the type
680
+ * fills in once the WFS fetch resolves and the STAC
681
+ * catalogue regenerates)
682
+ * - **values** a field's ValueMap picklist, when QGIS's edit widget
683
+ * config declares one
684
+ * - **quac:value_relation**
685
+ * the Collection a field's choices are read from, when
686
+ * QGIS's Value Relation edit widget names one the project holds
687
+ * - **quac:attachment**
688
+ * that the field holds a file's path, when QGIS's
689
+ * Attachment edit widget declares one
690
+ * - **quac:editable** / **quac:default** /
691
+ * **quac:constraints** / **quac:hidden** /
692
+ * **quac:reuse_last_value**
693
+ * that the field cannot be changed, a value it is filled
694
+ * with, that it must not be blank, that the form never
695
+ * shows it, and that a new feature is offered its last
696
+ * value, from QGIS's Attributes Form
697
+ * - **quac:searchable**
698
+ * that a search of the layer's features skips the field,
699
+ * from QGIS's Not searchable in the Fields tab
700
+ * - **quac:color** that the field holds a colour, when QGIS's Color edit
701
+ * widget declares one
702
+ * - **quac:visible_when** / **quac:in_form** / **quac:editable_when**
703
+ * the expressions that decide whether the form shows the
704
+ * field, that the form layout does not place it, and the
705
+ * expression that locks it while false, from
706
+ * QGIS's Drag and Drop Designer
707
+ * - **quac:icon** the address of the icon drawn beside the field's name,
708
+ * from the layer's `quac_icon_<field>` variable
709
+ * - **quac:control** the control the edit form draws the field's choices
710
+ * with, from the layer's `quac_control_<field>` variable
711
+ *
712
+ * The QGS fieldConfiguration is the source of truth for "what fields
713
+ * exist": this means a hidden WFS layer's schema is fully visible to the
714
+ * dev panel and to STAC clients before any data is fetched.
715
+ */
716
+ function deriveTableColumns(geojson, fieldNames, fieldAliases, fieldValueMaps = {}, fieldAttachments = {}, fieldEditRules = {}, fieldValueRelations = {}, formLayout = null, fieldIcons = {}, fieldControls = {}) {
717
+ const observedTypes = new Map();
718
+ const orderedFieldNames = [];
719
+ const seen = new Set();
720
+ const addFieldName = (name) => {
721
+ if (seen.has(name))
722
+ return;
723
+ seen.add(name);
724
+ orderedFieldNames.push(name);
725
+ };
726
+ // Canonical order from QGIS fieldConfiguration.
727
+ for (const name of fieldNames)
728
+ addFieldName(name);
729
+ // Pick up alias-only fields (rare) and GeoJSON-only fields (e.g. if QGIS
730
+ // didn't write fieldConfiguration) so nothing is silently dropped.
731
+ for (const name of Object.keys(fieldAliases))
732
+ addFieldName(name);
733
+ if (geojson) {
734
+ for (const feature of geojson.features) {
735
+ const props = feature.properties;
736
+ if (!props)
737
+ continue;
738
+ for (const [key, value] of Object.entries(props)) {
739
+ addFieldName(key);
740
+ if (value === null || value === undefined)
741
+ continue;
742
+ const type = inferTableType(value);
743
+ const observed = observedTypes.get(key);
744
+ observedTypes.set(key, observed ? widenTableType(observed, type) : type);
745
+ }
746
+ }
747
+ }
748
+ const placedFields = new Map(formLayout?.fields.map((field) => [field.name, field]));
749
+ return orderedFieldNames.map((name) => {
750
+ const column = { name };
751
+ const type = observedTypes.get(name);
752
+ if (type)
753
+ column.type = type;
754
+ const alias = fieldAliases[name];
755
+ if (alias)
756
+ column.title = alias;
757
+ const values = fieldValueMaps[name];
758
+ if (values)
759
+ column.values = values;
760
+ const valueRelation = fieldValueRelations[name];
761
+ if (valueRelation)
762
+ column['quac:value_relation'] = valueRelation;
763
+ const attachment = fieldAttachments[name];
764
+ if (attachment)
765
+ column['quac:attachment'] = attachmentToJson(attachment);
766
+ const editRule = fieldEditRules[name];
767
+ if (editRule?.readOnly)
768
+ column['quac:editable'] = false;
769
+ if (editRule?.defaultValue)
770
+ column['quac:default'] = defaultToJson(editRule.defaultValue);
771
+ else if (editRule?.defaultExpression) {
772
+ column['quac:default'] = { kind: 'expression', expression: editRule.defaultExpression.expression, on_update: editRule.defaultExpression.onUpdate };
773
+ }
774
+ if (editRule?.notNull || editRule?.unique || editRule?.constraintExpression) {
775
+ const { constraintExpression } = editRule;
776
+ column['quac:constraints'] = {
777
+ ...(editRule.notNull ? { not_null: editRule.notNull } : {}),
778
+ ...(editRule.unique ? { unique: editRule.unique } : {}),
779
+ ...(constraintExpression ? { expression: constraintExpressionToJson(constraintExpression) } : {})
780
+ };
781
+ }
782
+ if (editRule?.hidden)
783
+ column['quac:hidden'] = true;
784
+ if (editRule?.notSearchable)
785
+ column['quac:searchable'] = false;
786
+ if (editRule?.reuseLastValue)
787
+ column['quac:reuse_last_value'] = true;
788
+ if (editRule?.duplicatePolicy)
789
+ column['quac:duplicate_policy'] = editRule.duplicatePolicy;
790
+ if (editRule?.checkbox) {
791
+ const { checkedValue, uncheckedValue, showStoredValue, allowNull } = editRule.checkbox;
792
+ column['quac:checkbox'] = {
793
+ ...(checkedValue ? { checked: checkedValue } : {}),
794
+ ...(uncheckedValue ? { unchecked: uncheckedValue } : {}),
795
+ ...(showStoredValue ? { show_stored: true } : {}),
796
+ ...(allowNull ? { allow_null: true } : {})
797
+ };
798
+ }
799
+ if (editRule?.range)
800
+ column['quac:range'] = { ...editRule.range };
801
+ if (editRule?.dateFormat)
802
+ column['quac:date_format'] = editRule.dateFormat;
803
+ if (editRule?.colour)
804
+ column['quac:color'] = true;
805
+ const icon = fieldIcons[name];
806
+ if (icon)
807
+ column['quac:icon'] = icon;
808
+ const control = fieldControls[name];
809
+ if (control)
810
+ column['quac:control'] = control;
811
+ if (formLayout) {
812
+ const placed = placedFields.get(name);
813
+ if (!placed)
814
+ column['quac:in_form'] = false;
815
+ else if (placed.visibleWhen.length > 0)
816
+ column['quac:visible_when'] = [...placed.visibleWhen];
817
+ if (placed?.editableWhen)
818
+ column['quac:editable_when'] = placed.editableWhen;
819
+ }
820
+ return column;
821
+ });
822
+ }
823
+ /** A field's constraint expression as `quac:constraints` stores it: a description the source left blank is left off. */
824
+ function constraintExpressionToJson(constraint) {
825
+ return {
826
+ expression: constraint.expression,
827
+ ...(constraint.description ? { description: constraint.description } : {}),
828
+ strength: constraint.strength
829
+ };
830
+ }
831
+ /** A field's default value as `quac:default` stores it. */
832
+ function defaultToJson(defaultValue) {
833
+ switch (defaultValue.kind) {
834
+ case 'now': return { kind: 'now', on_update: defaultValue.onUpdate };
835
+ case 'uuid': return { kind: 'uuid', format: defaultValue.format, on_update: defaultValue.onUpdate };
836
+ case 'fixed': return { kind: 'fixed', value: defaultValue.value, on_update: defaultValue.onUpdate };
837
+ }
838
+ }
839
+ /**
840
+ * A field's Attachment widget as `quac:attachment` stores it. A member
841
+ * the source said nothing about is left off rather than written null.
842
+ */
843
+ function attachmentToJson(attachment) {
844
+ return {
845
+ ...(attachment.viewer ? { viewer: attachment.viewer } : {}),
846
+ ...(attachment.filter ? { filter: attachment.filter } : {}),
847
+ ...(attachment.defaultRoot ? { default_root: attachment.defaultRoot } : {}),
848
+ relative_storage: attachment.relativeStorage
849
+ };
850
+ }
851
+ /**
852
+ * The narrowest type holding values of both types: `int` and `long` make
853
+ * `long`, a whole number and a fraction make `double`, a date and a timestamp
854
+ * make `timestamp`, and any other pair makes `string`.
855
+ */
856
+ function widenTableType(a, b) {
857
+ if (a === b)
858
+ return a;
859
+ const pair = new Set([a, b]);
860
+ if (pair.has('double') && (pair.has('int') || pair.has('long')))
861
+ return 'double';
862
+ if (pair.has('int') && pair.has('long'))
863
+ return 'long';
864
+ if (pair.has('date') && pair.has('timestamp'))
865
+ return 'timestamp';
866
+ return 'string';
867
+ }
868
+ /** The range of a 32-bit integer, the values an `int` column holds. */
869
+ const INT32_MIN = -(2 ** 31);
870
+ const INT32_MAX = 2 ** 31 - 1;
871
+ function inferTableType(value) {
872
+ if (typeof value === 'boolean')
873
+ return 'boolean';
874
+ if (typeof value === 'number') {
875
+ if (!Number.isInteger(value))
876
+ return 'double';
877
+ return value >= INT32_MIN && value <= INT32_MAX ? 'int' : 'long';
878
+ }
879
+ if (typeof value === 'string') {
880
+ // ISO-8601 date or datetime sniffing — strict to avoid false positives.
881
+ if (/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/.test(value)) {
882
+ return value.length > 10 ? 'timestamp' : 'date';
883
+ }
884
+ return 'string';
885
+ }
886
+ return 'string';
887
+ }