@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,1125 @@
1
+ import { readCustomPropertyList } from "./customProperties.js";
2
+ import { parseDataSource } from "./parseDataSource.js";
3
+ import { parseFormLayout } from "./parseFormLayout.js";
4
+ import { parseQfieldSyncLocks } from "./parseQfieldSync.js";
5
+ import { parseLayerStyles } from "./parseStyle.js";
6
+ import { readQgisExpression, unescapeStringLiteral } from "./qgisExpression.js";
7
+ import { resolveFieldIconAddress } from "../model/fieldIconAddress.js";
8
+ import { devLog } from "../util/devLog.js";
9
+ /**
10
+ * Parses the <projectlayers> block into a list of LayerEntry. Annotation
11
+ * layers (<main-annotation-layer>) are filtered out — they're QGIS's drawing
12
+ * layer, not real data.
13
+ *
14
+ * Each <maplayer> has the shape:
15
+ * <maplayer type="vector" geometry="Point" hasScaleBasedVisibilityFlag="0"
16
+ * minScale="..." maxScale="..." ...>
17
+ * <id>...</id>
18
+ * <datasource>...</datasource>
19
+ * <layername>...</layername>
20
+ * <provider>ogr</provider> ← optional, used as a hint
21
+ * <srs><spatialrefsys><authid>EPSG:4326</authid>...
22
+ * <extent><xmin>...</xmin>...</extent>
23
+ * ...
24
+ * <renderer-v2 ...> ← inline symbology, captured by parseStyle
25
+ * </maplayer>
26
+ *
27
+ * On any per-layer failure the layer is skipped (logged via devLog) so a
28
+ * single bad layer doesn't take down the whole project.
29
+ */
30
+ export function parseProjectLayers(qgisRoot) {
31
+ const projectLayers = qgisRoot.querySelector('projectlayers');
32
+ if (!projectLayers)
33
+ return [];
34
+ const layers = [];
35
+ for (const node of Array.from(projectLayers.children)) {
36
+ if (node.tagName !== 'maplayer')
37
+ continue;
38
+ try {
39
+ const layer = parseMapLayer(node);
40
+ if (layer)
41
+ layers.push(layer);
42
+ }
43
+ catch (err) {
44
+ devLog('qgs/parseLayers', 'failed to parse a maplayer; skipping', {
45
+ error: String(err),
46
+ id: node.querySelector('id')?.textContent ?? '<unknown>'
47
+ });
48
+ }
49
+ }
50
+ return layers;
51
+ }
52
+ function parseMapLayer(maplayer) {
53
+ const id = maplayer.querySelector('id')?.textContent?.trim();
54
+ const name = maplayer.querySelector('layername')?.textContent?.trim() ?? '';
55
+ if (!id)
56
+ return null;
57
+ const type = maplayer.getAttribute('type') ?? '';
58
+ const geometryType = maplayer.getAttribute('geometry') || null;
59
+ const wkbType = maplayer.getAttribute('wkbType') || null;
60
+ const crs = maplayer.querySelector('srs spatialrefsys authid')?.textContent?.trim() || null;
61
+ const extent = parseBoundingBox(maplayer, 'extent');
62
+ const wgs84Extent = parseBoundingBox(maplayer, 'wgs84extent');
63
+ const datasourceText = directChildText(maplayer, 'datasource') ?? '';
64
+ const providerHint = directChildText(maplayer, 'provider') ?? null;
65
+ const dataSource = parseDataSource(datasourceText, providerHint);
66
+ const fieldNames = parseFieldNames(maplayer);
67
+ const fieldAliases = parseFieldAliases(maplayer);
68
+ const { styles, activeIndex } = parseLayerStyles(maplayer);
69
+ return {
70
+ id,
71
+ name,
72
+ type,
73
+ geometryType,
74
+ wkbType,
75
+ shortName: directChildText(maplayer, 'shortname') || null,
76
+ crs,
77
+ extent,
78
+ wgs84Extent,
79
+ dataSource,
80
+ displayField: parseDisplayField(maplayer),
81
+ // isVisible is set later by parseQgsXml after the layer tree is parsed,
82
+ // since visibility flows from the layer-tree-layer's `checked` attribute
83
+ // (and parent groups), not from the maplayer itself.
84
+ isVisible: true,
85
+ queryable: parseQueryable(maplayer),
86
+ opacity: parseOpacity(maplayer),
87
+ editable: maplayer.getAttribute('readOnly') !== '1',
88
+ fieldNames,
89
+ fieldAliases,
90
+ ...serverHiddenFieldsOf(maplayer),
91
+ styles,
92
+ activeStyleIndex: activeIndex,
93
+ resourceMetadata: parseLayerResourceMetadata(maplayer),
94
+ attribution: parseLayerAttribution(maplayer),
95
+ fieldValueMaps: parseFieldValueMaps(maplayer),
96
+ isPrivate: parsePrivate(maplayer),
97
+ legendImage: parseLegendImage(maplayer),
98
+ fieldValueRelations: parseFieldValueRelations(maplayer),
99
+ fieldAttachments: parseFieldAttachments(maplayer),
100
+ fieldEditRules: parseFieldEditRules(maplayer),
101
+ icon: parseLayerIcon(maplayer),
102
+ fieldIcons: parseFieldIcons(maplayer),
103
+ fieldControls: parseFieldControls(maplayer),
104
+ formLayout: parseFormLayout(maplayer),
105
+ scaleRange: parseScaleRange(maplayer),
106
+ locks: parseQfieldSyncLocks(maplayer),
107
+ rawXml: new XMLSerializer().serializeToString(maplayer)
108
+ };
109
+ }
110
+ /**
111
+ * The fields QGIS Server hides from WMS and from WFS. QGIS saves each field's
112
+ * choice as `configurationFlags` on its `<fieldConfiguration><field>`, holding
113
+ * `HideFromWms` and `HideFromWfs` joined by `|`, and a project saved by QGIS
114
+ * 3.14 or older as the lists `<excludeAttributesWMS>` and
115
+ * `<excludeAttributesWFS>` of `<attribute>` names, which QGIS still reads and
116
+ * adds to the flags (`QgsVectorLayer::readSymbology`,
117
+ * `src/core/vector/qgsvectorlayer.cpp`, `qgis/QGIS@master` at `ec40788`, read
118
+ * 2026-11-06). Only the layer's own blocks are read, never a saved style's.
119
+ */
120
+ function serverHiddenFieldsOf(maplayer) {
121
+ const wms = new Set();
122
+ const wfs = new Set();
123
+ for (const [name, field] of layerFields(maplayer)) {
124
+ const flags = configurationFlagsOf(field);
125
+ if (flags.includes('HideFromWms'))
126
+ wms.add(name);
127
+ if (flags.includes('HideFromWfs'))
128
+ wfs.add(name);
129
+ }
130
+ for (const [element, into] of [['excludeAttributesWMS', wms], ['excludeAttributesWFS', wfs]]) {
131
+ for (const attribute of directChild(maplayer, element)?.querySelectorAll(':scope > attribute') ?? []) {
132
+ const name = attribute.textContent?.trim();
133
+ if (name)
134
+ into.add(name);
135
+ }
136
+ }
137
+ if (wms.size === 0 && wfs.size === 0)
138
+ return {};
139
+ return { serverHiddenFields: { wms: [...wms], wfs: [...wfs] } };
140
+ }
141
+ /**
142
+ * Reads a `<resourceMetadata>` block — a direct child of `<maplayer>`, sibling
143
+ * to `<srs>`. Both `<maplayer>` elements in
144
+ * `packages/quac/src/tests/fixtures/qgis/graffiti/graffiti.qgs` have one, empty fields and
145
+ * all; an absent block (a layer saved by something other than QGIS) reads the
146
+ * same as one with nothing filled in.
147
+ *
148
+ * `license` reads the first non-blank `<license>` element: QGIS writes each
149
+ * licence as its own sibling element under `<resourceMetadata>` rather than a
150
+ * wrapper holding several (`QgsLayerMetadata::writeMetadataXml`,
151
+ * `src/core/metadata/qgslayermetadata.cpp`, `qgis/QGIS@master`, read
152
+ * 2026-08-12) — this repo's fixtures never populate one, so the element name
153
+ * is checked against that source rather than a sample file.
154
+ */
155
+ function parseLayerResourceMetadata(maplayer) {
156
+ const block = directChild(maplayer, 'resourceMetadata');
157
+ if (!block) {
158
+ return { abstract: null, license: null, keywords: [], contacts: [], temporalInterval: null };
159
+ }
160
+ const abstractText = directChildText(block, 'abstract');
161
+ const license = Array.from(block.querySelectorAll(':scope > license'))
162
+ .map((node) => node.textContent?.trim() ?? '')
163
+ .find((text) => text.length > 0) ?? null;
164
+ const keywords = [];
165
+ const seenKeywords = new Set();
166
+ for (const keyword of block.querySelectorAll(':scope > keywords > keyword')) {
167
+ const text = keyword.textContent?.trim();
168
+ if (!text || seenKeywords.has(text))
169
+ continue;
170
+ seenKeywords.add(text);
171
+ keywords.push(text);
172
+ }
173
+ const contacts = [];
174
+ for (const contact of block.querySelectorAll(':scope > contact')) {
175
+ const contactName = directChildText(contact, 'name') ?? '';
176
+ const organization = directChildText(contact, 'organization') ?? '';
177
+ const email = directChildText(contact, 'email') ?? '';
178
+ if (!contactName && !organization)
179
+ continue;
180
+ contacts.push({ name: contactName, organization, email });
181
+ }
182
+ return {
183
+ abstract: abstractText && abstractText.length > 0 ? abstractText : null,
184
+ license,
185
+ keywords,
186
+ contacts,
187
+ temporalInterval: parseResourceMetadataTemporal(block)
188
+ };
189
+ }
190
+ /**
191
+ * Reads `<resourceMetadata><extent><temporal>`'s declared range: a
192
+ * `<period><start>`/`<end>` — the shape `graffiti.qgs` writes, empty — or a
193
+ * single `<instant>` read as both ends of the interval. No fixture in this
194
+ * repo has an `<instant>`, so that alternative is checked instead against
195
+ * `QgsLayerMetadata::writeMetadataXml` (`src/core/metadata/qgslayermetadata.cpp`,
196
+ * `qgis/QGIS@master`, read 2026-08-12), which writes one or the other. Null
197
+ * when the block declares neither, or declares them blank.
198
+ */
199
+ function parseResourceMetadataTemporal(block) {
200
+ const temporal = block.querySelector(':scope > extent > temporal');
201
+ if (!temporal)
202
+ return null;
203
+ const period = directChild(temporal, 'period');
204
+ if (period) {
205
+ const start = directChildText(period, 'start');
206
+ const end = directChildText(period, 'end');
207
+ if (!start && !end)
208
+ return null;
209
+ return [start || null, end || null];
210
+ }
211
+ const instant = directChildText(temporal, 'instant');
212
+ return instant ? [instant, instant] : null;
213
+ }
214
+ /**
215
+ * Reads `<attribution href="...">text</attribution>` — a direct child of
216
+ * `<maplayer>`, separate from `<resourceMetadata>` (verified against
217
+ * a saved QGIS project, where it sits alongside
218
+ * `<resourceMetadata>` and `<provider>`). Null when the layer declares none.
219
+ */
220
+ function parseLayerAttribution(maplayer) {
221
+ const node = directChild(maplayer, 'attribution');
222
+ const text = node?.textContent?.trim();
223
+ if (!text)
224
+ return null;
225
+ const href = node?.getAttribute('href')?.trim();
226
+ return { text, href: href && href.length > 0 ? href : null };
227
+ }
228
+ /** `QgsValueMapFieldFormatter::NULL_VALUE`: the stored value of a value map's blank entry. */
229
+ const VALUE_MAP_NULL_CODE = '{2839923C-8B7D-419E-B84B-CA2FE9B80EC7}';
230
+ /**
231
+ * Reads every field's ValueMap edit widget into its picklist, keyed by field
232
+ * name. QGIS 3.x writes a widget's config as a generic `<Option>` tree
233
+ * (verified in this project's own fixtures, e.g.
234
+ * a saved QGIS project's `TextEdit`/`CheckBox` field
235
+ * configs); for `ValueMap` specifically, each entry is a nested
236
+ * `<Option type="Map">` holding one `<Option>` whose `name` is the display
237
+ * label and `value` is what QGIS stores
238
+ * (`QgsValueMapConfigDlg`, `src/gui/editorwidgets/qgsvaluemapconfigdlg.cpp`,
239
+ * `qgis/QGIS@master`, read 2026-08-12 — no fixture in this repo has a
240
+ * ValueMap widget to check the shape against directly):
241
+ *
242
+ * <editWidget type="ValueMap">
243
+ * <config>
244
+ * <Option type="Map">
245
+ * <Option type="List" name="map">
246
+ * <Option type="Map">
247
+ * <Option type="QString" name="Waiting" value="waiting"/>
248
+ * </Option>
249
+ * </Option>
250
+ * </Option>
251
+ * </config>
252
+ * </editWidget>
253
+ *
254
+ * Older projects write the map flat instead, as one `<Option type="Map"
255
+ * name="map">` whose children are the entries; QGIS reads both
256
+ * (`QgsValueMapFieldFormatter::representValue`,
257
+ * `src/core/fieldformatter/qgsvaluemapfieldformatter.cpp`, read 2026-10-23).
258
+ *
259
+ * QGIS writes the blank entry's value as the fixed code
260
+ * `QgsValueMapFieldFormatter::NULL_VALUE` (same file); it is read as an empty
261
+ * string, the blank choice's label.
262
+ *
263
+ * A field with no ValueMap widget, or one with no entries, is absent from the
264
+ * returned map.
265
+ */
266
+ function parseFieldValueMaps(maplayer) {
267
+ const result = {};
268
+ for (const [name, editWidget] of layerEditWidgets(maplayer)) {
269
+ if (result[name])
270
+ continue;
271
+ if (editWidget?.getAttribute('type') !== 'ValueMap')
272
+ continue;
273
+ const mapList = editWidget.querySelector(':scope > config > Option[type="Map"] > Option[type="List"][name="map"]');
274
+ const flatMap = editWidget.querySelector(':scope > config > Option[type="Map"] > Option[type="Map"][name="map"]');
275
+ const options = mapList
276
+ ? mapList.querySelectorAll(':scope > Option[type="Map"] > Option')
277
+ : flatMap?.querySelectorAll(':scope > Option') ?? [];
278
+ const entries = [];
279
+ for (const entry of options) {
280
+ const label = entry.getAttribute('name');
281
+ const value = entry.getAttribute('value');
282
+ if (label && value !== null)
283
+ entries.push({ value: value === VALUE_MAP_NULL_CODE ? '' : value, label });
284
+ }
285
+ if (entries.length > 0)
286
+ result[name] = entries;
287
+ }
288
+ return result;
289
+ }
290
+ /**
291
+ * Reads every field's Value Relation edit widget, keyed by field name. QGIS
292
+ * writes the widget's config as the same flat `<Option>` map the `TextEdit`
293
+ * and `CheckBox` widgets use (`QgsValueRelationConfigDlg::config`,
294
+ * `src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp`, `qgis/QGIS@master`,
295
+ * read 2026-10-24):
296
+ *
297
+ * <editWidget type="ValueRelation">
298
+ * <config>
299
+ * <Option type="Map">
300
+ * <Option type="QString" value="asset_types_1" name="Layer"/>
301
+ * <Option type="QString" value="Asset types" name="LayerName"/>
302
+ * <Option type="QString" value="name" name="Key"/>
303
+ * <Option type="QString" value="name" name="Value"/>
304
+ * <Option type="bool" value="false" name="AllowNull"/>
305
+ * <Option type="bool" value="true" name="OrderByValue"/>
306
+ * </Option>
307
+ * </config>
308
+ * </editWidget>
309
+ *
310
+ * The lookup is named by `Layer` (its id) and `LayerName`; a widget naming
311
+ * neither, or with no `Key` or no `Value`, is skipped, since no list can come
312
+ * from it. The order follows the formatter's: `OrderByValue` first, then
313
+ * `OrderByField` where it names a field, and the key otherwise
314
+ * (`QgsValueRelationFieldFormatter::createCache`,
315
+ * `src/core/fieldformatter/qgsvaluerelationfieldformatter.cpp`, same commit).
316
+ * `Group`, `DisplayGroupName`, `Description`, `NofColumns`, `UseCompleter` and
317
+ * `CompleterMatchFlags` are not read.
318
+ *
319
+ * A field with no ValueRelation widget is absent from the returned map.
320
+ */
321
+ function parseFieldValueRelations(maplayer) {
322
+ const result = {};
323
+ for (const [name, editWidget] of layerEditWidgets(maplayer)) {
324
+ if (result[name])
325
+ continue;
326
+ if (editWidget?.getAttribute('type') !== 'ValueRelation')
327
+ continue;
328
+ const options = readOptionMap(editWidget);
329
+ const layerId = readTrimmedOption(options, 'Layer') ?? '';
330
+ const layerName = readTrimmedOption(options, 'LayerName') ?? '';
331
+ const keyField = readTrimmedOption(options, 'Key');
332
+ const valueField = readTrimmedOption(options, 'Value');
333
+ if ((!layerId && !layerName) || !keyField || !valueField)
334
+ continue;
335
+ const orderField = readFlag(options, 'OrderByField') ? readTrimmedOption(options, 'OrderByFieldName') : null;
336
+ result[name] = {
337
+ layerId,
338
+ layerName,
339
+ keyField,
340
+ valueField,
341
+ filterExpression: readTrimmedOption(options, 'FilterExpression') ?? '',
342
+ allowNull: readFlag(options, 'AllowNull'),
343
+ allowMulti: readFlag(options, 'AllowMulti'),
344
+ orderBy: readFlag(options, 'OrderByValue') ? 'value' : orderField ? 'field' : 'key',
345
+ orderField: readFlag(options, 'OrderByValue') ? null : orderField,
346
+ descending: readFlag(options, 'OrderByDescending')
347
+ };
348
+ }
349
+ return result;
350
+ }
351
+ /**
352
+ * QGIS's `DocumentViewerContent`, by its own order from zero
353
+ * (`src/gui/qgsexternalresourcewidget.h`, `qgis/QGIS@master`, read
354
+ * 2026-08-29). `NoContent` is index 0 and reads as null.
355
+ */
356
+ const DOCUMENT_VIEWERS = [null, 'image', 'web', 'audio', 'video'];
357
+ /**
358
+ * QGIS's `QgsFileWidget::RelativeStorage`, by its own order from zero
359
+ * (`src/gui/qgsfilewidget.h`, same commit).
360
+ */
361
+ const RELATIVE_STORAGE = ['absolute', 'project', 'default-root'];
362
+ /**
363
+ * The `QgsFileWidget::StorageMode` values that pick one file — `GetFile` and
364
+ * `SaveFile`, indices 0 and 3 of `GetFile, GetDirectory, GetMultipleFiles,
365
+ * SaveFile` (`src/gui/qgsfilewidget.h`, same commit). A widget set to either
366
+ * of the other two stores a directory or a list, neither of which is the
367
+ * single path `quac:attachment` declares.
368
+ */
369
+ const SINGLE_FILE_STORAGE_MODES = new Set([0, 3]);
370
+ /**
371
+ * Reads every field's Attachment edit widget into what the catalogue records,
372
+ * keyed by field name. QGIS registers the widget as `ExternalResource`
373
+ * (`QgsEditorWidgetRegistry::initEditors`,
374
+ * `src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp`, `qgis/QGIS@master`,
375
+ * read 2026-08-29) and writes its config as the same flat `<Option>` map the
376
+ * `TextEdit` and `CheckBox` widgets use in
377
+ * `packages/quac/src/tests/fixtures/qgis/graffiti/graffiti.qgs`:
378
+ *
379
+ * <editWidget type="ExternalResource">
380
+ * <config>
381
+ * <Option type="Map">
382
+ * <Option type="QString" value="photos" name="DefaultRoot"/>
383
+ * <Option type="int" value="1" name="DocumentViewer"/>
384
+ * <Option type="int" value="1" name="RelativeStorage"/>
385
+ * </Option>
386
+ * </config>
387
+ * </editWidget>
388
+ *
389
+ * The widget writes more keys than these four; the rest are left behind
390
+ * and the catalogue does not carry them. A value-less `<Option type="invalid">`,
391
+ * which QGIS writes for an unset key, is skipped rather than read as blank.
392
+ * A widget whose `StorageMode` picks a directory or several files is not an
393
+ * attachment here.
394
+ *
395
+ * A field with no ExternalResource widget is absent from the returned map.
396
+ */
397
+ function parseFieldAttachments(maplayer) {
398
+ const result = {};
399
+ for (const [name, editWidget] of layerEditWidgets(maplayer)) {
400
+ if (result[name])
401
+ continue;
402
+ if (editWidget?.getAttribute('type') !== 'ExternalResource')
403
+ continue;
404
+ const options = readOptionMap(editWidget);
405
+ const storageMode = options.get('StorageMode');
406
+ if (storageMode !== undefined && !SINGLE_FILE_STORAGE_MODES.has(Number(storageMode)))
407
+ continue;
408
+ result[name] = {
409
+ viewer: DOCUMENT_VIEWERS[Number(options.get('DocumentViewer'))] ?? null,
410
+ filter: readTrimmedOption(options, 'FileWidgetFilter'),
411
+ defaultRoot: readTrimmedOption(options, 'DefaultRoot'),
412
+ relativeStorage: RELATIVE_STORAGE[Number(options.get('RelativeStorage'))] ?? 'absolute'
413
+ };
414
+ }
415
+ return result;
416
+ }
417
+ /**
418
+ * The default-value expressions read as `now`, compared with spaces removed
419
+ * and in lower case. `$now` is QGIS's older spelling of `now()`.
420
+ */
421
+ const NOW_EXPRESSIONS = new Set(['now()', '$now', 'to_date(now())', 'to_datetime(now())']);
422
+ /**
423
+ * Reads the Attributes Form settings the catalogue records for every field, keyed
424
+ * by field name. QGIS writes them as blocks of the layer's own, shown here as
425
+ * `packages/quac/src/tests/fixtures/qgis/graffiti/graffiti.qgs` writes them:
426
+ *
427
+ * <fieldConfiguration>
428
+ * <field name="date_report"><editWidget type="Hidden">…</editWidget></field>
429
+ * </fieldConfiguration>
430
+ * <defaults>
431
+ * <default field="date_report" expression="" applyOnUpdate="0"/>
432
+ * </defaults>
433
+ * <constraints>
434
+ * <constraint field="date_report" constraints="0" notnull_strength="0" unique_strength="0" exp_strength="0"/>
435
+ * </constraints>
436
+ * <editable>
437
+ * <field editable="1" name="date_report"/>
438
+ * </editable>
439
+ * <reuseLastValuePolicy>
440
+ * <field name="date_report" reuseLastValuePolicy="AllowedDefaultOn"/>
441
+ * </reuseLastValuePolicy>
442
+ * <duplicatePolicies>
443
+ * <policy field="date_report" policy="DefaultValue"/>
444
+ * </duplicatePolicies>
445
+ * <constraintExpressions>
446
+ * <constraint field="date_report" exp="" desc=""/>
447
+ * </constraintExpressions>
448
+ *
449
+ * A default is kept as a `defaultValue` where `parseDefaultExpression` reads it,
450
+ * as a `defaultExpression` where only `readQgisExpression` does, and otherwise
451
+ * left out. A constraint expression follows the same rule. A field the
452
+ * `<editable>` block does not list is editable. A field with none of these
453
+ * settings is absent from the returned map.
454
+ */
455
+ function parseFieldEditRules(maplayer) {
456
+ const result = {};
457
+ const ruleFor = (name) => {
458
+ result[name] ??= { readOnly: false, defaultValue: null, notNull: null, unique: null, hidden: false, reuseLastValue: false, duplicatePolicy: null };
459
+ return result[name];
460
+ };
461
+ // Scoped to the layer's own blocks, as the field configuration is above: a
462
+ // saved alternate style embeds its own copies.
463
+ const fieldsWithExpression = new Set();
464
+ for (const node of directChild(maplayer, 'defaults')?.querySelectorAll(':scope > default') ?? []) {
465
+ const name = node.getAttribute('field');
466
+ const expression = node.getAttribute('expression') ?? '';
467
+ if (!name || !expression.trim())
468
+ continue;
469
+ fieldsWithExpression.add(name);
470
+ const onUpdate = node.getAttribute('applyOnUpdate') === '1';
471
+ const defaultValue = parseDefaultExpression(expression, onUpdate);
472
+ if (defaultValue)
473
+ ruleFor(name).defaultValue = defaultValue;
474
+ else if (readQgisExpression(expression, { geometry: true, aggregates: true, lookups: true }))
475
+ ruleFor(name).defaultExpression = { expression: expression.trim(), onUpdate };
476
+ }
477
+ // The UUID Generator widget disables its line edit and fills a null field
478
+ // with `QUuid::createUuid().toString()`, which has braces
479
+ // (`QgsUuidWidgetWrapper`, `src/gui/editorwidgets/qgsuuidwidgetwrapper.cpp`,
480
+ // `qgis/QGIS@master`, read 2026-10-23). A default expression fills the field
481
+ // first, so the widget's identifier stands only where there is none. The
482
+ // widget's shortening to a string field's declared length is not followed:
483
+ // a `.qgs` file does not carry a WFS field's length.
484
+ const seenWidgets = new Set();
485
+ const allowNullOff = new Set();
486
+ for (const [name, field] of layerFields(maplayer)) {
487
+ if (seenWidgets.has(name))
488
+ continue;
489
+ seenWidgets.add(name);
490
+ const widgetType = directChild(field, 'editWidget')?.getAttribute('type');
491
+ if (widgetType === 'Hidden')
492
+ ruleFor(name).hidden = true;
493
+ // The Fields tab's Not searchable, which QGIS's search of the active
494
+ // layer's features skips (`QgsActiveLayerFeaturesLocatorFilter`,
495
+ // `src/app/locator/qgsactivelayerfeatureslocatorfilter.cpp`,
496
+ // `qgis/QGIS@master`, read 2026-11-11).
497
+ if (configurationFlagsOf(field).includes('NotSearchable'))
498
+ ruleFor(name).notSearchable = true;
499
+ // The widget has no settings of its own (`QgsColorWidgetFactory::configWidget`,
500
+ // `src/gui/editorwidgets/qgscolorwidgetfactory.cpp`, `qgis/QGIS@master`,
501
+ // read 2026-10-25).
502
+ if (widgetType === 'Color')
503
+ ruleFor(name).colour = true;
504
+ if (widgetType === 'CheckBox' || widgetType === 'Range' || widgetType === 'DateTime') {
505
+ readWidgetOptions(field, name, widgetType, ruleFor, allowNullOff);
506
+ }
507
+ if (widgetType === 'UuidGenerator') {
508
+ const rule = ruleFor(name);
509
+ rule.readOnly = true;
510
+ if (!fieldsWithExpression.has(name))
511
+ rule.defaultValue = { kind: 'uuid', format: 'with_braces', onUpdate: false };
512
+ }
513
+ }
514
+ // `constraints` is a bit mask with Not null as 1, Unique as 2 and Expression
515
+ // as 4, and a missing strength reads as 1, hard; 2 is soft and 0 not set
516
+ // (`QgsVectorLayer::readSymbology`, `src/core/vector/qgsvectorlayer.cpp`, and
517
+ // `QgsFieldConstraints`, `src/core/qgsfieldconstraints.h`, `qgis/QGIS@master`,
518
+ // read 2026-10-23). An expression is kept only where `readQgisExpression`
519
+ // reads it.
520
+ const constraintExpressions = new Map();
521
+ for (const node of directChild(maplayer, 'constraintExpressions')?.querySelectorAll(':scope > constraint') ?? []) {
522
+ const name = node.getAttribute('field');
523
+ const expression = (node.getAttribute('exp') ?? '').trim();
524
+ if (name && expression)
525
+ constraintExpressions.set(name, { expression, description: (node.getAttribute('desc') ?? '').trim() });
526
+ }
527
+ for (const node of directChild(maplayer, 'constraints')?.querySelectorAll(':scope > constraint') ?? []) {
528
+ const name = node.getAttribute('field');
529
+ const constraints = Number(node.getAttribute('constraints') ?? '0');
530
+ if (!name || !Number.isInteger(constraints))
531
+ continue;
532
+ if (constraints & 1) {
533
+ const notNull = constraintStrength(node.getAttribute('notnull_strength'));
534
+ if (notNull)
535
+ ruleFor(name).notNull = notNull;
536
+ }
537
+ if (constraints & 2) {
538
+ const unique = constraintStrength(node.getAttribute('unique_strength'));
539
+ if (unique)
540
+ ruleFor(name).unique = unique;
541
+ }
542
+ const written = constraintExpressions.get(name);
543
+ if (constraints & 4 && written && readQgisExpression(written.expression, { geometry: true })) {
544
+ const strength = constraintStrength(node.getAttribute('exp_strength'));
545
+ if (strength) {
546
+ const expression = { expression: written.expression, strength };
547
+ if (written.description)
548
+ expression.description = written.description;
549
+ ruleFor(name).constraintExpression = expression;
550
+ }
551
+ }
552
+ }
553
+ // A Range with Allow NULL off, or a Date/Time with it off, is a required
554
+ // field.
555
+ // It also raises a Not null that only warns.
556
+ for (const name of allowNullOff)
557
+ ruleFor(name).notNull = 'enforced';
558
+ // A field absent from `<duplicatePolicies>`, or holding a key QGIS does not
559
+ // know, reads as `Duplicate` (`QgsVectorLayer::readSymbology`,
560
+ // `src/core/vector/qgsvectorlayer.cpp`, `qgis/QGIS@master`, read 2026-10-23).
561
+ for (const node of directChild(maplayer, 'duplicatePolicies')?.querySelectorAll(':scope > policy') ?? []) {
562
+ const name = node.getAttribute('field');
563
+ const policy = node.getAttribute('policy');
564
+ if (name && (policy === 'DefaultValue' || policy === 'UnsetField')) {
565
+ ruleFor(name).duplicatePolicy = policy === 'DefaultValue' ? 'default' : 'unset';
566
+ }
567
+ }
568
+ for (const node of directChild(maplayer, 'editable')?.querySelectorAll(':scope > field') ?? []) {
569
+ const name = node.getAttribute('name');
570
+ if (name && node.getAttribute('editable') === '0')
571
+ ruleFor(name).readOnly = true;
572
+ }
573
+ for (const [name, reuse] of parseReuseLastValue(maplayer)) {
574
+ if (reuse)
575
+ ruleFor(name).reuseLastValue = true;
576
+ }
577
+ return result;
578
+ }
579
+ /**
580
+ * Reads a Checkbox, Range or Date/Time widget's config into the field's rule.
581
+ * QGIS writes the config as a flat `<Option type="Map">` and an untouched
582
+ * widget writes an empty `<Option/>`, which reads as every default
583
+ * (`QgsCheckboxConfigDlg`, `QgsRangeConfigDlg` and `QgsDateTimeEditConfig`,
584
+ * `src/gui/editorwidgets/`, `qgis/QGIS@master`, read 2026-10-23). A value-less
585
+ * `<Option type="invalid">` reads as unset. Range's `AllowNull` and Date/Time's
586
+ * `allow_null` both default to true; a field with either off goes in `allowNullOff`.
587
+ */
588
+ function readWidgetOptions(field, name, widgetType, ruleFor, allowNullOff) {
589
+ const options = readOptionMap(directChild(field, 'editWidget'));
590
+ const number = (key) => {
591
+ const text = options.get(key)?.trim();
592
+ if (!text)
593
+ return undefined;
594
+ const value = Number(text);
595
+ return Number.isFinite(value) ? value : undefined;
596
+ };
597
+ switch (widgetType) {
598
+ case 'CheckBox':
599
+ ruleFor(name).checkbox = {
600
+ checkedValue: readTrimmedOption(options, 'CheckedState'),
601
+ uncheckedValue: readTrimmedOption(options, 'UncheckedState'),
602
+ showStoredValue: options.get('TextDisplayMethod') === '1',
603
+ allowNull: readFlag(options, 'AllowNullState', false)
604
+ };
605
+ return;
606
+ case 'Range': {
607
+ const range = {};
608
+ const min = number('Min');
609
+ const max = number('Max');
610
+ const step = number('Step');
611
+ const precision = number('Precision');
612
+ const suffix = options.get('Suffix');
613
+ if (min !== undefined)
614
+ range.min = min;
615
+ if (max !== undefined)
616
+ range.max = max;
617
+ if (step !== undefined)
618
+ range.step = step;
619
+ if (precision !== undefined && Number.isInteger(precision) && precision >= 0)
620
+ range.precision = precision;
621
+ if (suffix)
622
+ range.suffix = suffix;
623
+ if (Object.keys(range).length > 0)
624
+ ruleFor(name).range = range;
625
+ if (!readFlag(options, 'AllowNull', true))
626
+ allowNullOff.add(name);
627
+ return;
628
+ }
629
+ case 'DateTime': {
630
+ // A date or date-time field ignores `field_format`, which this parser
631
+ // cannot tell here. ISO 8601 and the default for a date are what an
632
+ // application already reads, so they write nothing.
633
+ const format = options.get('field_format')?.trim();
634
+ if (format && format !== 'yyyy-MM-dd' && !readFlag(options, 'field_iso_format', false))
635
+ ruleFor(name).dateFormat = format;
636
+ if (!readFlag(options, 'allow_null', true))
637
+ allowNullOff.add(name);
638
+ }
639
+ }
640
+ }
641
+ /** A constraint's strength: 1, or absent, is hard; 2 is soft; 0 or anything else is not set. */
642
+ function constraintStrength(strength) {
643
+ switch (strength ?? '1') {
644
+ case '1': return 'enforced';
645
+ case '2': return 'warn';
646
+ default: return null;
647
+ }
648
+ }
649
+ /**
650
+ * Which fields offer a new feature the value last entered, from either of
651
+ * QGIS's two forms. An older project writes
652
+ * `<reuseLastValue><field name reuseLastValue="1"/></reuseLastValue>`; QGIS now
653
+ * writes `<reuseLastValuePolicy><field name reuseLastValuePolicy="AllowedDefaultOn"/></reuseLastValuePolicy>`,
654
+ * and reads the older block first so the newer one wins
655
+ * (`QgsEditFormConfig::readXml`, `src/core/editform/qgseditformconfig.cpp`,
656
+ * `qgis/QGIS@master`, read 2026-10-23). `AllowedDefaultOff` reads as not
657
+ * reused: it is off until someone ticks it in QGIS's own form, which a
658
+ * reading application's form may have no tick for.
659
+ */
660
+ function parseReuseLastValue(maplayer) {
661
+ const reuse = new Map();
662
+ for (const node of directChild(maplayer, 'reuseLastValue')?.querySelectorAll(':scope > field') ?? []) {
663
+ const name = node.getAttribute('name');
664
+ const flag = Number(node.getAttribute('reuseLastValue'));
665
+ if (name)
666
+ reuse.set(name, Number.isInteger(flag) && flag !== 0);
667
+ }
668
+ for (const node of directChild(maplayer, 'reuseLastValuePolicy')?.querySelectorAll(':scope > field') ?? []) {
669
+ const name = node.getAttribute('name');
670
+ if (name)
671
+ reuse.set(name, node.getAttribute('reuseLastValuePolicy') === 'AllowedDefaultOn');
672
+ }
673
+ return reuse;
674
+ }
675
+ /**
676
+ * Reads a default-value expression an application can fill: one of
677
+ * `NOW_EXPRESSIONS`, `uuid()` or `$uuid` with an optional format, or a lone
678
+ * literal. Anything else, such as a field reference, a variable or a
679
+ * calculation, is null.
680
+ *
681
+ * `uuid()` takes `format` (`WithBraces` by default, `WithoutBraces`, `Id128`,
682
+ * compared ignoring case, with any other text read as `WithBraces`) and
683
+ * `version` (4 by default, or 7), by position or by name (`format:='Id128'`)
684
+ * (`fcnUuid` and its registration, `src/core/expression/qgsexpressionfunction.cpp`,
685
+ * `qgis/QGIS@master`, read 2026-10-23). A version other than 4 is null: the
686
+ * app makes version 4 identifiers only.
687
+ */
688
+ function parseDefaultExpression(expression, onUpdate) {
689
+ if (NOW_EXPRESSIONS.has(expression.replace(/\s+/g, '').toLowerCase()))
690
+ return { kind: 'now', onUpdate };
691
+ const tokens = tokenizeExpression(expression);
692
+ if (!tokens)
693
+ return null;
694
+ const literal = readLiteral(tokens, 0);
695
+ if (literal && literal.next === tokens.length)
696
+ return { kind: 'fixed', value: literal.value, onUpdate };
697
+ const format = readUuidCall(tokens);
698
+ return format ? { kind: 'uuid', format, onUpdate } : null;
699
+ }
700
+ /**
701
+ * Splits an expression into the tokens a literal or a `uuid()` call is made
702
+ * of, following QGIS's lexer (`src/core/qgsexpressionlexer.ll`,
703
+ * `qgis/QGIS@master`, read 2026-10-23), which ignores case. Null where the
704
+ * expression holds anything else, such as an operator, a quoted field name or
705
+ * a comment.
706
+ */
707
+ function tokenizeExpression(expression) {
708
+ const pattern = /\s+|'((?:''|\\.|[^'\\])*)'|(\d*(?:\.\d+(?:[eE][-+]?\d+)?|[eE][-+]?\d+)|\d+)|([A-Za-z_\x80-\uFFFF$][A-Za-z0-9_\x80-\uFFFF]*)(\s*:=\s*)?|([(),-])/y;
709
+ const tokens = [];
710
+ pattern.lastIndex = 0;
711
+ while (pattern.lastIndex < expression.length) {
712
+ const match = pattern.exec(expression);
713
+ if (!match)
714
+ return null;
715
+ const [, text, number, name, named, punct] = match;
716
+ if (text !== undefined)
717
+ tokens.push({ type: 'string', value: unescapeStringLiteral(text) });
718
+ else if (number !== undefined)
719
+ tokens.push({ type: 'number', value: Number(number) });
720
+ else if (name !== undefined)
721
+ tokens.push({ type: named ? 'named' : 'name', value: name.toLowerCase() });
722
+ else if (punct !== undefined)
723
+ tokens.push({ type: 'punct', value: punct });
724
+ }
725
+ return tokens;
726
+ }
727
+ /** The literal starting at `index` — a string, a number with or without a minus, `TRUE`, `FALSE` or `NULL` — and the index after it. */
728
+ function readLiteral(tokens, index) {
729
+ const token = tokens[index];
730
+ const after = tokens[index + 1];
731
+ if (token?.type === 'punct' && token.value === '-' && after?.type === 'number')
732
+ return { value: -after.value, next: index + 2 };
733
+ if (token?.type === 'string' || token?.type === 'number')
734
+ return { value: token.value, next: index + 1 };
735
+ if (token?.type !== 'name')
736
+ return null;
737
+ if (token.value === 'true')
738
+ return { value: true, next: index + 1 };
739
+ if (token.value === 'false')
740
+ return { value: false, next: index + 1 };
741
+ if (token.value === 'null')
742
+ return { value: null, next: index + 1 };
743
+ return null;
744
+ }
745
+ /** The format of a whole-expression `uuid()` or `$uuid`, or null where the expression is not one. */
746
+ function readUuidCall(tokens) {
747
+ const [head, open] = tokens;
748
+ if (head?.type !== 'name')
749
+ return null;
750
+ if (head.value === '$uuid')
751
+ return tokens.length === 1 ? 'with_braces' : null;
752
+ if (head.value !== 'uuid' || open?.type !== 'punct' || open.value !== '(')
753
+ return null;
754
+ const close = tokens[tokens.length - 1];
755
+ if (close?.type !== 'punct' || close.value !== ')')
756
+ return null;
757
+ const args = {};
758
+ const positions = ['format', 'version'];
759
+ let index = 2;
760
+ let position = 0;
761
+ while (index < tokens.length - 1) {
762
+ if (position > 0) {
763
+ const comma = tokens[index];
764
+ if (comma?.type !== 'punct' || comma.value !== ',')
765
+ return null;
766
+ index += 1;
767
+ }
768
+ const token = tokens[index];
769
+ let parameter = positions[position];
770
+ if (token?.type === 'named') {
771
+ if (token.value !== 'format' && token.value !== 'version')
772
+ return null;
773
+ parameter = token.value;
774
+ index += 1;
775
+ }
776
+ const literal = readLiteral(tokens, index);
777
+ if (!parameter || !literal || parameter in args)
778
+ return null;
779
+ args[parameter] = literal.value;
780
+ index = literal.next;
781
+ position += 1;
782
+ }
783
+ if (args.version !== undefined && args.version !== 4)
784
+ return null;
785
+ if (args.format === undefined)
786
+ return 'with_braces';
787
+ if (typeof args.format !== 'string')
788
+ return null;
789
+ const format = args.format.toLowerCase();
790
+ return format === 'withoutbraces' ? 'without_braces' : format === 'id128' ? 'id128' : 'with_braces';
791
+ }
792
+ function readTrimmedOption(options, key) {
793
+ const value = options.get(key)?.trim();
794
+ return value ? value : null;
795
+ }
796
+ function parseBoundingBox(maplayer, tag) {
797
+ const node = directChild(maplayer, tag);
798
+ if (!node)
799
+ return null;
800
+ const xmin = readNumber(node, 'xmin');
801
+ const ymin = readNumber(node, 'ymin');
802
+ const xmax = readNumber(node, 'xmax');
803
+ const ymax = readNumber(node, 'ymax');
804
+ if (xmin === null || ymin === null || xmax === null || ymax === null)
805
+ return null;
806
+ return { xmin, ymin, xmax, ymax };
807
+ }
808
+ /**
809
+ * Parses <fieldConfiguration> into the canonical list of field names.
810
+ *
811
+ * <fieldConfiguration>
812
+ * <field name="objectid" configurationFlags="...">
813
+ * <editWidget type="...">...</editWidget>
814
+ * </field>
815
+ * ...
816
+ * </fieldConfiguration>
817
+ *
818
+ * Modern QGIS may write fieldConfiguration both at the maplayer level and
819
+ * inside the active <map-layer-style> block — we collect from anywhere
820
+ * inside the maplayer and dedupe, preserving first-seen order.
821
+ *
822
+ * QGIS does not declare field types here for WFS layers (those come from
823
+ * DescribeFeatureType at runtime), so this function only returns names.
824
+ */
825
+ function parseFieldNames(maplayer) {
826
+ const seen = new Set();
827
+ const ordered = [];
828
+ const fields = maplayer.querySelectorAll('fieldConfiguration > field');
829
+ for (const node of Array.from(fields)) {
830
+ const name = node.getAttribute('name');
831
+ if (!name)
832
+ continue;
833
+ if (seen.has(name))
834
+ continue;
835
+ seen.add(name);
836
+ ordered.push(name);
837
+ }
838
+ return ordered;
839
+ }
840
+ /**
841
+ * Parses <aliases> into a { fieldName: aliasText } map.
842
+ *
843
+ * <aliases>
844
+ * <alias field="incident_uid" name="Incident UID" index="0"/>
845
+ * ...
846
+ * </aliases>
847
+ *
848
+ * Modern QGIS supports per-style aliases — they live inside the active
849
+ * <map-layer-style> block under the style manager. Legacy QGIS put them
850
+ * at the maplayer level. Same project can have both, and the maplayer-
851
+ * level copy may have empty `name=""` placeholders. We collect every
852
+ * <alias> anywhere inside the maplayer and keep the last non-empty value
853
+ * per field, which is the active-style block's when both are present.
854
+ */
855
+ function parseFieldAliases(maplayer) {
856
+ const out = {};
857
+ const nodes = maplayer.querySelectorAll('aliases > alias');
858
+ for (const node of Array.from(nodes)) {
859
+ const field = node.getAttribute('field');
860
+ const name = node.getAttribute('name');
861
+ if (!field || !name)
862
+ continue;
863
+ out[field] = name;
864
+ }
865
+ return out;
866
+ }
867
+ /** The start of the name of a layer variable that sets a field's icon: `quac_icon_species`. */
868
+ const FIELD_ICON_VARIABLE_PREFIX = 'quac_icon_';
869
+ /**
870
+ * Reads the field icons the layer's variables set, as an address for each
871
+ * field (`resolveFieldIconAddress`). A variable whose value names no icon is
872
+ * left out; whether the layer has the field is for the reader of the result.
873
+ *
874
+ * QGIS keeps a layer's variables as two lists of the same length in its custom
875
+ * properties, `variableNames` and `variableValues`
876
+ * (`QgsExpressionContextUtils::setLayerVariable`,
877
+ * `src/core/expression/qgsexpressioncontextutils.cpp`), saved as a direct
878
+ * child of `<maplayer>`:
879
+ *
880
+ * <customproperties>
881
+ * <Option type="Map">
882
+ * <Option name="variableNames" type="StringList">
883
+ * <Option type="QString" value="quac_icon_species"/>
884
+ * </Option>
885
+ * <Option name="variableValues" type="StringList">
886
+ * <Option type="QString" value="tabler:tree"/>
887
+ * </Option>
888
+ * </Option>
889
+ * </customproperties>
890
+ *
891
+ * A project saved before QGIS 3.20 holds `<property key="variableNames">`
892
+ * with a `<value>` per entry, or a `value` attribute for a single one, which
893
+ * QGIS still reads (`QgsObjectCustomProperties::readXml`,
894
+ * `src/core/qgsobjectcustomproperties.cpp`, `qgis/QGIS@master`, read
895
+ * 2026-10-25).
896
+ */
897
+ function parseFieldIcons(maplayer) {
898
+ const icons = {};
899
+ for (const [field, value] of readFieldVariables(maplayer, FIELD_ICON_VARIABLE_PREFIX)) {
900
+ const address = resolveFieldIconAddress(value);
901
+ if (address)
902
+ icons[field] = address;
903
+ }
904
+ return icons;
905
+ }
906
+ /** The name of the layer variable that sets the layer's own icon. */
907
+ const LAYER_ICON_VARIABLE = 'quac_icon';
908
+ /**
909
+ * Reads the icon the layer's `quac_icon` variable sets, as an address
910
+ * (`resolveFieldIconAddress`), held in the same lists as the field icons.
911
+ * Null where the layer has no such variable or its value names no icon.
912
+ */
913
+ function parseLayerIcon(maplayer) {
914
+ const properties = directChild(maplayer, 'customproperties');
915
+ if (!properties)
916
+ return null;
917
+ const names = readCustomPropertyList(properties, 'variableNames');
918
+ const values = readCustomPropertyList(properties, 'variableValues');
919
+ const index = names.indexOf(LAYER_ICON_VARIABLE);
920
+ return index === -1 || index >= values.length ? null : resolveFieldIconAddress(values[index]);
921
+ }
922
+ /** The start of the name of a layer variable that chooses a field's control: `quac_control_condition`. */
923
+ const FIELD_CONTROL_VARIABLE_PREFIX = 'quac_control_';
924
+ /**
925
+ * Reads the control each field's `quac_control_<field>` variable asks for,
926
+ * held in the same lists as the field icons. The value is compared without
927
+ * regard to case or surrounding spaces, and one that names no control is left
928
+ * out.
929
+ */
930
+ function parseFieldControls(maplayer) {
931
+ const controls = {};
932
+ for (const [field, value] of readFieldVariables(maplayer, FIELD_CONTROL_VARIABLE_PREFIX)) {
933
+ const control = value.trim().toLowerCase();
934
+ if (control === 'buttons' || control === 'dropdown')
935
+ controls[field] = control;
936
+ }
937
+ return controls;
938
+ }
939
+ /** Each of the layer's variables named `prefix` and a field's name, as that field's name and the variable's value. */
940
+ function readFieldVariables(maplayer, prefix) {
941
+ const properties = directChild(maplayer, 'customproperties');
942
+ if (!properties)
943
+ return [];
944
+ const names = readCustomPropertyList(properties, 'variableNames');
945
+ const values = readCustomPropertyList(properties, 'variableValues');
946
+ return names.flatMap((variable, index) => {
947
+ if (!variable.startsWith(prefix) || index >= values.length)
948
+ return [];
949
+ const field = variable.slice(prefix.length);
950
+ return field ? [[field, values[index]]] : [];
951
+ });
952
+ }
953
+ /**
954
+ * Reads the layer's preview/display field from `<previewExpression>`. QGIS
955
+ * writes the value as a quoted field reference, e.g.
956
+ * `<previewExpression>"location_description"</previewExpression>`. We strip
957
+ * the surrounding quotes to recover the field name. More complex expressions
958
+ * (concatenations, conditionals) are not a single field reference, so they
959
+ * return null.
960
+ */
961
+ function parseDisplayField(maplayer) {
962
+ const node = directChild(maplayer, 'previewExpression');
963
+ const text = node?.textContent?.trim();
964
+ if (!text)
965
+ return null;
966
+ const match = /^"([^"]+)"$/.exec(text);
967
+ return match ? match[1] : null;
968
+ }
969
+ /**
970
+ * Reads the layer's queryable flag from `<flags><Identifiable>1</Identifiable></flags>`.
971
+ * "1" means queryable; "0" means not. Defaults to true when the flags
972
+ * element is absent (matches QGIS's default behaviour).
973
+ */
974
+ function parseQueryable(maplayer) {
975
+ const flags = directChild(maplayer, 'flags');
976
+ if (!flags)
977
+ return true;
978
+ const identifiable = directChild(flags, 'Identifiable');
979
+ if (!identifiable)
980
+ return true;
981
+ return identifiable.textContent?.trim() === '1';
982
+ }
983
+ /** The image types an embedded legend image is read as, by the bytes it opens with. */
984
+ const IMAGE_SIGNATURES = [
985
+ ['image/png', (bytes) => bytes.startsWith('\x89PNG')],
986
+ ['image/jpeg', (bytes) => bytes.startsWith('\xff\xd8\xff')],
987
+ ['image/gif', (bytes) => bytes.startsWith('GIF8')],
988
+ ['image/webp', (bytes) => bytes.startsWith('RIFF') && bytes.slice(8, 12) === 'WEBP'],
989
+ ['image/svg+xml', (bytes) => /^\s*(?:<\?xml|<svg)/.test(bytes)]
990
+ ];
991
+ /**
992
+ * Reads the layer's legend placeholder image where QGIS embeds it. **Embed
993
+ * File…** saves the file as `base64:` and its contents, with no type
994
+ * (`QgsFileContentSourceLineEdit`, `src/gui/qgsfilecontentsourcelineedit.cpp`),
995
+ * so the type is read from the bytes the image opens with. QGIS's image cache
996
+ * also reads a `data:` URL (`QgsAbstractContentCacheBase::parseBase64DataUrl`,
997
+ * `src/core/qgsabstractcontentcache.cpp`), so one is kept as written. Both
998
+ * read at qgis/QGIS@master, 2026-10-25. A file path or web address is not
999
+ * read: it names a file rather than holding one.
1000
+ */
1001
+ function parseLegendImage(maplayer) {
1002
+ const source = maplayer.getAttribute('legendPlaceholderImage')?.trim() ?? '';
1003
+ if (/^data:image\/[\w+.-]+;base64,[A-Za-z0-9+/=\s]+$/.test(source))
1004
+ return source;
1005
+ const match = /^base64:([A-Za-z0-9+/=\s]+)$/i.exec(source);
1006
+ if (!match)
1007
+ return null;
1008
+ const data = match[1].replace(/\s/g, '');
1009
+ let opening;
1010
+ try {
1011
+ opening = atob(data.slice(0, 24));
1012
+ }
1013
+ catch {
1014
+ return null;
1015
+ }
1016
+ const type = IMAGE_SIGNATURES.find(([, matches]) => matches(opening))?.[0];
1017
+ return type ? `data:${type};base64,${data}` : null;
1018
+ }
1019
+ /**
1020
+ * Reads the layer's Private flag from `<flags><Private>1</Private></flags>`,
1021
+ * the **Private** column of QGIS's Project Properties → Data Sources
1022
+ * (`QgsMapLayer::writeCommonStyle`, `src/core/qgsmaplayer.cpp`,
1023
+ * `qgis/QGIS@master`, read 2026-10-24). QGIS writes every flag, each as 0 or 1.
1024
+ * A layer with no flags, or no Private flag, is not private.
1025
+ */
1026
+ function parsePrivate(maplayer) {
1027
+ const flags = directChild(maplayer, 'flags');
1028
+ if (!flags)
1029
+ return false;
1030
+ return directChild(flags, 'Private')?.textContent?.trim() === '1';
1031
+ }
1032
+ /**
1033
+ * Reads scale-dependent visibility from the `<maplayer>` attributes. QGIS
1034
+ * writes `minScale` and `maxScale` whether or not the flag is on, so both are
1035
+ * ignored unless `hasScaleBasedVisibilityFlag` is "1". A value of 0 means no
1036
+ * limit on that side.
1037
+ */
1038
+ function parseScaleRange(maplayer) {
1039
+ if (maplayer.getAttribute('hasScaleBasedVisibilityFlag') !== '1')
1040
+ return null;
1041
+ const minScale = parseScaleDenominator(maplayer.getAttribute('minScale'));
1042
+ const maxScale = parseScaleDenominator(maplayer.getAttribute('maxScale'));
1043
+ if (minScale === null && maxScale === null)
1044
+ return null;
1045
+ return { minScale, maxScale };
1046
+ }
1047
+ function parseScaleDenominator(text) {
1048
+ const value = Number(text);
1049
+ return text && Number.isFinite(value) && value > 0 ? value : null;
1050
+ }
1051
+ /**
1052
+ * Reads the layer's opacity from `<layerOpacity>`. Defaults to 1 when the
1053
+ * element is absent or unparseable.
1054
+ */
1055
+ function parseOpacity(maplayer) {
1056
+ const text = directChildText(maplayer, 'layerOpacity')
1057
+ ?? maplayer.querySelector('pipe > rasterrenderer')?.getAttribute('opacity');
1058
+ if (!text)
1059
+ return 1;
1060
+ const value = Number(text);
1061
+ return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 1;
1062
+ }
1063
+ /**
1064
+ * The layer's own `<fieldConfiguration>` fields that have a name, as
1065
+ * `[name, <field>]`, in document order. A saved alternate style embeds its
1066
+ * own `<fieldConfiguration>`, which can disagree with the layer's own, so only
1067
+ * the direct child of `<maplayer>` is read (see docs/gotchas.md).
1068
+ */
1069
+ function* layerFields(maplayer) {
1070
+ for (const field of directChild(maplayer, 'fieldConfiguration')?.querySelectorAll(':scope > field') ?? []) {
1071
+ const name = field.getAttribute('name');
1072
+ if (name)
1073
+ yield [name, field];
1074
+ }
1075
+ }
1076
+ /**
1077
+ * A `<fieldConfiguration><field>`'s `configurationFlags`: the Fields tab's
1078
+ * Configuration column, saved as `Qgis::FieldConfigurationFlag` names joined
1079
+ * by `|`, such as `NotSearchable|HideFromWms`, and `NoFlag` where none is set.
1080
+ */
1081
+ function configurationFlagsOf(field) {
1082
+ return (field.getAttribute('configurationFlags') ?? '').split('|').map((flag) => flag.trim());
1083
+ }
1084
+ /** The named fields' `<editWidget>`, as `[name, <editWidget>]`; null where a field has none. */
1085
+ function* layerEditWidgets(maplayer) {
1086
+ for (const [name, field] of layerFields(maplayer))
1087
+ yield [name, directChild(field, 'editWidget')];
1088
+ }
1089
+ /**
1090
+ * A flat widget config as key and value: the widget's `<Option type="Map">`
1091
+ * members that have a name and a `value`. An `<Option type="invalid">` that
1092
+ * QGIS writes for an unset key has no `value` and is left out.
1093
+ */
1094
+ function readOptionMap(editWidget) {
1095
+ const options = new Map();
1096
+ for (const option of editWidget?.querySelectorAll(':scope > config > Option[type="Map"] > Option') ?? []) {
1097
+ const key = option.getAttribute('name');
1098
+ const value = option.getAttribute('value');
1099
+ if (key && value !== null)
1100
+ options.set(key, value);
1101
+ }
1102
+ return options;
1103
+ }
1104
+ /** A Boolean widget option: `true` or `1` is on, any other value off, and an absent key `fallback`. */
1105
+ function readFlag(options, key, fallback = false) {
1106
+ const value = options.get(key);
1107
+ return value === undefined ? fallback : value === 'true' || value === '1';
1108
+ }
1109
+ function directChild(parent, tag) {
1110
+ for (const child of Array.from(parent.children)) {
1111
+ if (child.tagName === tag)
1112
+ return child;
1113
+ }
1114
+ return null;
1115
+ }
1116
+ function directChildText(parent, tag) {
1117
+ return directChild(parent, tag)?.textContent?.trim() ?? null;
1118
+ }
1119
+ function readNumber(parent, tag) {
1120
+ const text = parent.querySelector(tag)?.textContent?.trim();
1121
+ if (!text)
1122
+ return null;
1123
+ const value = Number(text);
1124
+ return Number.isFinite(value) ? value : null;
1125
+ }