@vectoriahq/quac 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,6 +61,18 @@ const catalogue = generateStacCatalogue(project, [], {
61
61
 
62
62
  `selfHref` is the address of the folder the project is published in, and `projectPath` is the project file's path inside that folder. A layer's data files and styles are addressed relative to them, so a catalogue to be published or saved apart from the project needs both. Without `projectPath`, each style's address names no file, and only an application already holding the project can read it; without `selfHref`, the catalogue's relative addresses have no folder to start from.
63
63
 
64
+ `generateStacCatalogue` returns one document, with each Catalog carrying its Collections and nested Catalogs inline. `splitCatalogue` gives the same catalogue as separate documents, each with the path to save it at, for a STAC client that follows `child` links:
65
+
66
+ ```js
67
+ import { splitCatalogue } from '@vectoriahq/quac'
68
+
69
+ for (const { path, document } of splitCatalogue(catalogue, { rootFileName: 'survey.json', childrenFolder: 'survey' })) {
70
+ // path: 'survey.json', 'survey/collections/roads_3f2a….json', …
71
+ }
72
+ ```
73
+
74
+ Each path is relative to the folder the root document is saved in, and every relative address inside a document is rewritten from that document's own path, so a layer's data file keeps its place. Without options, the root is `catalog.json` and the other documents sit beside it. The field reference's [§ The document](https://github.com/vectoriahq/quac/tree/main/packages/quac/spec#the-document) says how the documents are named.
75
+
64
76
  `project.notes` lists the project's settings that the catalogue does not carry, such as a widget it does not read or an expression it cannot read. Each note gives the layer, the field where there is one, a reason code and the setting's own text where it helps; the `ProjectNoteReason` type lists the codes and what each means. The notes are not written into the catalogue.
65
77
 
66
78
  The JSON Schema that checks a catalogue's `quac:` fields is exported as `@vectoriahq/quac/schema`.
@@ -1,4 +1,4 @@
1
- import type { LayerLocks, FieldAttachment, FieldEditRule, LayerFormLayout, LayerScaleRange, ProjectMeasurement } from '../model/QgsProject.ts';
1
+ import type { LayerLocks, PrintLayoutTemplate, FieldAttachment, FieldEditRule, LayerFormLayout, LayerScaleRange, ProjectMeasurement } from '../model/QgsProject.ts';
2
2
  import type { StacAsset, StacCatalog, StacCollection, StacExtent, StacLink, StacProvider, TableColumn, TableColumnValue, TableColumnValueRelation } from '../model/Stac.ts';
3
3
  /**
4
4
  * Source-agnostic intermediate model + the single STAC generator that
@@ -80,6 +80,8 @@ export declare const QUAC_MUTUALLY_EXCLUSIVE_FIELD = "quac:mutually_exclusive";
80
80
  * names as the one the map opens with as the active layer.
81
81
  */
82
82
  export declare const QUAC_ACTIVE_COLLECTION_FIELD = "quac:active_collection";
83
+ /** The project's print layouts, on the top-level Catalog: each as its name and its QGIS layout template. */
84
+ export declare const QUAC_PRINT_LAYOUTS_FIELD = "quac:print_layouts";
83
85
  /**
84
86
  * One relation a Collection declares in `quac:related_to`: the parent
85
87
  * Collection its records hang off, the field pair(s) joining them, and the name
@@ -297,6 +299,12 @@ export declare function readCatalogueActiveCollection(catalog: StacCatalog): str
297
299
  * about where to open", so a caller frames the map its own way rather than
298
300
  * reading a missing field as an instruction.
299
301
  */
302
+ /**
303
+ * Reads `quac:print_layouts` back off a Catalog: each print layout's name and
304
+ * template, in its order. An entry without a string name, or whose template is
305
+ * not a `<Layout>` element, is not read. Empty where the Catalog lists none.
306
+ */
307
+ export declare function readCataloguePrintLayouts(catalog: StacCatalog): PrintLayoutTemplate[];
300
308
  export declare function readCatalogueInitialView(catalog: StacCatalog): NormalizedBbox | null;
301
309
  /**
302
310
  * Reads shared source declarations back off a Collection.
@@ -4,6 +4,7 @@ import { STAC_VERSION } from "../model/Stac.js";
4
4
  import { PROJ_CODE, PROJECTION_EXTENSION } from "../model/stacProjection.js";
5
5
  import { collectCatalogueCollections } from "../model/stacTreeWalk.js";
6
6
  import { readNonBlank } from "../util/nonBlankText.js";
7
+ import { nameRecord } from "../util/nameRecord.js";
7
8
  /**
8
9
  * Source-agnostic intermediate model + the single STAC generator that
9
10
  * consumes it.
@@ -89,6 +90,8 @@ const INITIAL_VIEW_FIELD = 'quac:initial_view';
89
90
  * names as the one the map opens with as the active layer.
90
91
  */
91
92
  export const QUAC_ACTIVE_COLLECTION_FIELD = 'quac:active_collection';
93
+ /** The project's print layouts, on the top-level Catalog: each as its name and its QGIS layout template. */
94
+ export const QUAC_PRINT_LAYOUTS_FIELD = 'quac:print_layouts';
92
95
  /**
93
96
  * Records where a catalogue came from as the Catalog's `self` link, so the
94
97
  * document says it rather than a reader holding it alongside. Sources with no
@@ -352,6 +355,22 @@ export function readCatalogueActiveCollection(catalog) {
352
355
  * about where to open", so a caller frames the map its own way rather than
353
356
  * reading a missing field as an instruction.
354
357
  */
358
+ /**
359
+ * Reads `quac:print_layouts` back off a Catalog: each print layout's name and
360
+ * template, in its order. An entry without a string name, or whose template is
361
+ * not a `<Layout>` element, is not read. Empty where the Catalog lists none.
362
+ */
363
+ export function readCataloguePrintLayouts(catalog) {
364
+ const value = catalog[QUAC_PRINT_LAYOUTS_FIELD];
365
+ if (!Array.isArray(value))
366
+ return [];
367
+ return value.flatMap((entry) => {
368
+ if (!entry || typeof entry !== 'object')
369
+ return [];
370
+ const { name, template } = entry;
371
+ return typeof name === 'string' && typeof template === 'string' && /^<Layout[\s/>]/.test(template) ? [{ name, template }] : [];
372
+ });
373
+ }
355
374
  export function readCatalogueInitialView(catalog) {
356
375
  const value = catalog[INITIAL_VIEW_FIELD];
357
376
  if (!Array.isArray(value) || value.length !== 4)
@@ -396,7 +415,7 @@ export function* declaredColumns(collection) {
396
415
  }
397
416
  /** Each field's alias, its column's `title`. A column with a blank or no `title` is absent. */
398
417
  export function readCollectionFieldAliases(collection) {
399
- const aliases = {};
418
+ const aliases = nameRecord();
400
419
  for (const [name, column] of declaredColumns(collection)) {
401
420
  const alias = readNonBlank(column.title);
402
421
  if (alias)
@@ -406,7 +425,7 @@ export function readCollectionFieldAliases(collection) {
406
425
  }
407
426
  /** Each field's comment, its column's `description`, trimmed. A column with a blank or no `description` is absent. */
408
427
  export function readCollectionFieldComments(collection) {
409
- const comments = {};
428
+ const comments = nameRecord();
410
429
  for (const [name, column] of declaredColumns(collection)) {
411
430
  const comment = readNonBlank(column.description);
412
431
  if (comment)
@@ -425,7 +444,7 @@ export function readCollectionFieldNames(collection) {
425
444
  }
426
445
  /** Each declared column `type`, keyed by field name. A column with no `type` is absent. */
427
446
  export function readCollectionFieldTypes(collection) {
428
- const types = {};
447
+ const types = nameRecord();
429
448
  for (const [name, column] of declaredColumns(collection)) {
430
449
  const type = readNonBlank(column.type);
431
450
  if (type)
@@ -439,7 +458,7 @@ export function readCollectionFieldTypes(collection) {
439
458
  * other kind, is dropped, and a column left with no entries is absent.
440
459
  */
441
460
  export function readCollectionFieldValues(collection) {
442
- const picklists = {};
461
+ const picklists = nameRecord();
443
462
  for (const [name, column] of declaredColumns(collection)) {
444
463
  const declared = column['quac:values'];
445
464
  if (!Array.isArray(declared))
@@ -468,7 +487,7 @@ export function readCollectionFieldValues(collection) {
468
487
  * `order_field`, reads as ordered by key.
469
488
  */
470
489
  export function readCollectionFieldValueRelations(collection) {
471
- const relations = {};
490
+ const relations = nameRecord();
472
491
  for (const [name, column] of declaredColumns(collection)) {
473
492
  const declared = column['quac:value_relation'];
474
493
  if (!declared || typeof declared !== 'object')
@@ -585,7 +604,7 @@ export function readCollectionPrivate(collection) {
585
604
  * omitted or unrecognised `relative_storage` as absolute.
586
605
  */
587
606
  export function readCollectionFieldAttachments(collection) {
588
- const attachments = {};
607
+ const attachments = nameRecord();
589
608
  for (const [name, column] of declaredColumns(collection)) {
590
609
  const declared = column['quac:attachment'];
591
610
  if (!declared || typeof declared !== 'object' || Array.isArray(declared))
@@ -623,7 +642,7 @@ export function readCollectionFieldAttachments(collection) {
623
642
  */
624
643
  export function readCollectionFieldEditRules(collection) {
625
644
  const relations = readCollectionFieldValueRelations(collection);
626
- const rules = {};
645
+ const rules = nameRecord();
627
646
  for (const [name, candidate] of declaredColumns(collection)) {
628
647
  const readOnly = candidate['quac:editable'] === false;
629
648
  const defaultValue = readColumnDefault(candidate['quac:default']);
@@ -0,0 +1,54 @@
1
+ import type { StacCatalog, StacCollection } from '../model/Stac.ts';
2
+ /**
3
+ * Writes a catalogue as separate documents: the root Catalog, each nested
4
+ * Catalog and each Collection in a document of its own, linked by `child`,
5
+ * `parent` and `root` links, with no `collections` or `catalogs` arrays
6
+ * (`packages/quac/spec/README.md` § "The document").
7
+ */
8
+ /** Where the documents go. */
9
+ export interface SplitCatalogueOptions {
10
+ /**
11
+ * The root Catalog's file name: one file name ending in `.json`, such as
12
+ * `catalog.json` or `Parks.json`. `catalog.json` where it is left off.
13
+ */
14
+ rootFileName?: string;
15
+ /**
16
+ * The folder every other document goes in, relative to the root document's
17
+ * folder, such as `Parks`. Empty, the default, puts them beside the root
18
+ * document.
19
+ */
20
+ childrenFolder?: string;
21
+ }
22
+ /** One document of a catalogue written as separate documents. */
23
+ export interface CatalogueDocument {
24
+ /**
25
+ * Where the document is saved, relative to the root document's folder: file
26
+ * and folder names joined by `/`, not escaped. Always inside that folder.
27
+ */
28
+ path: string;
29
+ document: StacCatalog | StacCollection;
30
+ }
31
+ /**
32
+ * The catalogue `catalogue` holds, one document holding the whole tree, as
33
+ * separate documents, the root first and then each child after its parent, in
34
+ * the order the parent's `child` links list them.
35
+ *
36
+ * A Catalog's Collections go in a `collections` folder beside it and its
37
+ * nested Catalogs in a `catalogs` folder, each in a folder of its own holding
38
+ * its `catalog.json`. The root's go in `childrenFolder`. A document's file or
39
+ * folder name is its id, made safe as a file name on any system (`safeName`),
40
+ * and where two in one folder would take the same name, in any case, the later
41
+ * one is given `-2`, `-3` and so on.
42
+ *
43
+ * Every relative href, in each link and asset, is rewritten from the
44
+ * document's own path. A `self`, `root` or `parent` link names that document's
45
+ * new path, and a `child` link whose href is a child's own `self` href names
46
+ * the child's. Every other relative href is resolved against the root
47
+ * document's folder, as the one document's hrefs are, so a data file keeps its
48
+ * place, even one outside that folder. An absolute href, one starting with `/`,
49
+ * and one holding only a query or a fragment are left as they are. A child that
50
+ * no `child` link names is given one.
51
+ *
52
+ * Throws where `rootFileName` or `childrenFolder` is not a safe relative path.
53
+ */
54
+ export declare function splitCatalogue(catalogue: StacCatalog, options?: SplitCatalogueOptions): CatalogueDocument[];
@@ -0,0 +1,202 @@
1
+ const DEFAULT_ROOT_FILE_NAME = 'catalog.json';
2
+ /**
3
+ * The catalogue `catalogue` holds, one document holding the whole tree, as
4
+ * separate documents, the root first and then each child after its parent, in
5
+ * the order the parent's `child` links list them.
6
+ *
7
+ * A Catalog's Collections go in a `collections` folder beside it and its
8
+ * nested Catalogs in a `catalogs` folder, each in a folder of its own holding
9
+ * its `catalog.json`. The root's go in `childrenFolder`. A document's file or
10
+ * folder name is its id, made safe as a file name on any system (`safeName`),
11
+ * and where two in one folder would take the same name, in any case, the later
12
+ * one is given `-2`, `-3` and so on.
13
+ *
14
+ * Every relative href, in each link and asset, is rewritten from the
15
+ * document's own path. A `self`, `root` or `parent` link names that document's
16
+ * new path, and a `child` link whose href is a child's own `self` href names
17
+ * the child's. Every other relative href is resolved against the root
18
+ * document's folder, as the one document's hrefs are, so a data file keeps its
19
+ * place, even one outside that folder. An absolute href, one starting with `/`,
20
+ * and one holding only a query or a fragment are left as they are. A child that
21
+ * no `child` link names is given one.
22
+ *
23
+ * Throws where `rootFileName` or `childrenFolder` is not a safe relative path.
24
+ */
25
+ export function splitCatalogue(catalogue, options = {}) {
26
+ const rootFileName = options.rootFileName ?? DEFAULT_ROOT_FILE_NAME;
27
+ if (!isSafeName(rootFileName) || !/\.json$/i.test(rootFileName)) {
28
+ throw new Error(`The root document's file name must be one safe file name ending in .json: ${JSON.stringify(rootFileName)}`);
29
+ }
30
+ const childrenFolder = (options.childrenFolder ?? '').replace(/\/$/, '');
31
+ const folderNames = childrenFolder ? childrenFolder.split('/') : [];
32
+ if (!folderNames.every(isSafeName) || folderNames[0]?.toLowerCase() === rootFileName.toLowerCase()) {
33
+ throw new Error(`The children's folder must be a relative path of safe folder names, apart from the root document: ${JSON.stringify(options.childrenFolder)}`);
34
+ }
35
+ const root = placeCatalog(catalogue, rootFileName, folderNames);
36
+ const documents = [];
37
+ writeDocuments(root, null, root, documents);
38
+ return documents;
39
+ }
40
+ /**
41
+ * Places a Catalog at `path` and its children in `folder`, so every path is
42
+ * known before any href is written.
43
+ */
44
+ function placeCatalog(catalog, path, folder) {
45
+ const candidates = [...(catalog.collections ?? []), ...(catalog.catalogs ?? [])];
46
+ const claimed = new Set();
47
+ const ordered = [];
48
+ catalog.links.forEach((link, linkIndex) => {
49
+ if (link.rel !== 'child')
50
+ return;
51
+ const node = candidates.find((candidate) => !claimed.has(candidate) && selfHrefOf(candidate) === link.href);
52
+ if (!node)
53
+ return;
54
+ claimed.add(node);
55
+ ordered.push({ node, linkIndex });
56
+ });
57
+ for (const node of candidates) {
58
+ if (!claimed.has(node))
59
+ ordered.push({ node, linkIndex: -1 });
60
+ }
61
+ const fileNames = new Set();
62
+ const folderNames = new Set();
63
+ const children = ordered.map(({ node, linkIndex }) => {
64
+ if (node.type === 'Collection') {
65
+ const fileName = unclaimedName(safeName(node.id), '.json', fileNames);
66
+ return { placed: { node, path: [...folder, 'collections', fileName].join('/'), children: [] }, linkIndex };
67
+ }
68
+ const childFolder = [...folder, 'catalogs', unclaimedName(safeName(node.id), '', folderNames)];
69
+ return { placed: placeCatalog(node, [...childFolder, 'catalog.json'].join('/'), childFolder), linkIndex };
70
+ });
71
+ return { node: catalog, path, children };
72
+ }
73
+ function writeDocuments(placed, parent, root, into) {
74
+ const folder = placed.path.split('/').slice(0, -1).map(encodeURIComponent);
75
+ const hrefTo = (other) => relativeHref(folder, { ups: 0, segments: other.path.split('/').map(encodeURIComponent) });
76
+ const childAt = new Map(placed.children.filter((child) => child.linkIndex >= 0).map((child) => [child.linkIndex, child.placed]));
77
+ const links = placed.node.links.map((link, index) => {
78
+ if (!isPathHref(link.href))
79
+ return { ...link };
80
+ const child = childAt.get(index);
81
+ if (child)
82
+ return { ...link, href: hrefTo(child) };
83
+ if (link.rel === 'self')
84
+ return { ...link, href: hrefTo(placed) };
85
+ if (link.rel === 'root')
86
+ return { ...link, href: hrefTo(root) };
87
+ if (link.rel === 'parent' && parent)
88
+ return { ...link, href: hrefTo(parent) };
89
+ return { ...link, href: rewriteHref(link.href, folder) };
90
+ });
91
+ for (const child of placed.children) {
92
+ if (child.linkIndex >= 0)
93
+ continue;
94
+ const title = child.placed.node.title;
95
+ links.push({ rel: 'child', href: hrefTo(child.placed), type: 'application/json', ...(title === undefined ? {} : { title }) });
96
+ }
97
+ const document = {};
98
+ for (const [key, value] of Object.entries(placed.node)) {
99
+ if (key === 'collections' || key === 'catalogs')
100
+ continue;
101
+ if (key === 'links')
102
+ document[key] = links;
103
+ else if (key === 'assets' && value && typeof value === 'object')
104
+ document[key] = rewriteAssets(value, folder);
105
+ else
106
+ document[key] = value;
107
+ }
108
+ into.push({ path: placed.path, document: document });
109
+ for (const child of placed.children)
110
+ writeDocuments(child.placed, placed, root, into);
111
+ }
112
+ function rewriteAssets(assets, folder) {
113
+ return Object.fromEntries(Object.entries(assets).map(([key, asset]) => ([key, typeof asset?.href === 'string' ? { ...asset, href: rewriteHref(asset.href, folder) } : asset])));
114
+ }
115
+ function selfHrefOf(node) {
116
+ return node.links.find((link) => link.rel === 'self')?.href;
117
+ }
118
+ /**
119
+ * Whether an href is a relative path, which moves with the document holding
120
+ * it: not an absolute address, not one starting with `/`, and not one holding
121
+ * only a query or a fragment, which names the document it is in.
122
+ */
123
+ function isPathHref(href) {
124
+ return typeof href === 'string' && href !== '' && !/^[a-z][a-z0-9+.-]*:/i.test(href) && !/^[/?#]/.test(href);
125
+ }
126
+ /** A relative href, which resolves against the root document's folder, rewritten from `folder`, a folder inside it. */
127
+ function rewriteHref(href, folder) {
128
+ if (!isPathHref(href))
129
+ return href;
130
+ const cut = href.search(/[?#]/);
131
+ const path = cut < 0 ? href : href.slice(0, cut);
132
+ const rest = cut < 0 ? '' : href.slice(cut);
133
+ return relativeHref(folder, resolvePath(path)) + rest;
134
+ }
135
+ /** A relative path resolved against the root document's folder, its `.` and `..` segments taken out. */
136
+ function resolvePath(path) {
137
+ const segments = [];
138
+ let ups = 0;
139
+ const parts = path.split('/');
140
+ parts.forEach((part, index) => {
141
+ const last = index === parts.length - 1;
142
+ if (part === '.' || part === '..') {
143
+ if (part === '..') {
144
+ if (segments.length > 0)
145
+ segments.pop();
146
+ else
147
+ ups += 1;
148
+ }
149
+ // A path ending in `.` or `..` names a folder.
150
+ if (last)
151
+ segments.push('');
152
+ return;
153
+ }
154
+ segments.push(part);
155
+ });
156
+ return { ups, segments };
157
+ }
158
+ /** The href naming `target` from `folder`, both from the root document's folder. */
159
+ function relativeHref(folder, target) {
160
+ if (target.ups > 0)
161
+ return '../'.repeat(folder.length + target.ups) + target.segments.join('/');
162
+ const targetFolder = target.segments.slice(0, -1);
163
+ let shared = 0;
164
+ while (shared < folder.length && shared < targetFolder.length && folder[shared] === targetFolder[shared])
165
+ shared += 1;
166
+ const rest = target.segments.slice(shared).join('/');
167
+ const ups = folder.length - shared;
168
+ return ups > 0 ? '../'.repeat(ups) + rest : `./${rest}`;
169
+ }
170
+ /** Characters no file name may hold on Windows, macOS or Linux: controls, `/`, and those Windows refuses. */
171
+ const UNSAFE_CHARACTERS = /[\u0000-\u001f\u007f"*/:<>?\\|]/g;
172
+ /** The names Windows keeps for devices, with or without an extension. */
173
+ const RESERVED_NAME = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\.|$)/i;
174
+ /**
175
+ * An id made a file or folder name that is safe on any system: each character
176
+ * a name may not hold, `/` among them, becomes `_`, as does each `.` or space
177
+ * at its end, which Windows drops; an empty name is `_`; and a name Windows
178
+ * keeps for a device, such as `con`, is given a leading `_`. So no name is
179
+ * empty, `.` or `..`.
180
+ */
181
+ function safeName(id) {
182
+ let name = id.replace(UNSAFE_CHARACTERS, '_');
183
+ // Counted from the end, not matched with /[. ]+$/, which takes time growing with the square of a run of spaces that does not end the id.
184
+ let kept = name.length;
185
+ while (kept > 0 && (name[kept - 1] === '.' || name[kept - 1] === ' '))
186
+ kept -= 1;
187
+ name = name.slice(0, kept) + '_'.repeat(name.length - kept);
188
+ if (name === '')
189
+ name = '_';
190
+ return RESERVED_NAME.test(name) ? `_${name}` : name;
191
+ }
192
+ function isSafeName(name) {
193
+ return safeName(name) === name;
194
+ }
195
+ /** `name` and `suffix`, or with `-2`, `-3` and so on before the suffix, whichever is first not in `taken`, compared in lower case. */
196
+ function unclaimedName(name, suffix, taken) {
197
+ let candidate = `${name}${suffix}`;
198
+ for (let count = 2; taken.has(candidate.toLowerCase()); count += 1)
199
+ candidate = `${name}-${count}${suffix}`;
200
+ taken.add(candidate.toLowerCase());
201
+ return candidate;
202
+ }
@@ -119,4 +119,12 @@ export declare function parseQgisStyleAssetHref(href: string): {
119
119
  layerId: string;
120
120
  styleName: string;
121
121
  } | null;
122
+ /**
123
+ * Whether an Attachment widget's default folder is a path relative to the
124
+ * project, and not a path on the computer that saved it, such as
125
+ * `/srv/photos`, `C:\\Survey` or `~/photos`, a network share or an address.
126
+ * QGIS's folder picker saves an absolute path, which would publish the
127
+ * computer's folder names.
128
+ */
129
+ export declare function isProjectRelativeFolder(folder: string): boolean;
122
130
  export {};
@@ -1,5 +1,5 @@
1
1
  import { arcgisQueryAsset } from "./arcgisStacCatalogue.js";
2
- import { QUAC_MEASUREMENT_FIELD, slugify, generateStacFromNormalized, unionBboxes, withSelfLink } from "./normalizedProject.js";
2
+ import { QUAC_MEASUREMENT_FIELD, QUAC_PRINT_LAYOUTS_FIELD, slugify, generateStacFromNormalized, unionBboxes, withSelfLink } from "./normalizedProject.js";
3
3
  import { wfsGetFeatureAsset } from "./wfsStacCatalogue.js";
4
4
  import { delimitedTextField, QUAC_DELIMITED_TEXT } from "../model/delimitedText.js";
5
5
  import { featureFilterField, QUAC_FEATURE_FILTER } from "../model/featureFilter.js";
@@ -13,6 +13,7 @@ import { buildXyzLink } from "../model/stacXyz.js";
13
13
  import { findGeometrySiblings, readSiblingShapes, siblingCollectionId } from "../parse/geometrySiblings.js";
14
14
  import { findValueRelationLookup, isFilterInProject, isRelationInProject } from "../parse/projectNotes.js";
15
15
  import { declaredMediaTypeForFile, isLayerFileOfFormat, PROJECT_DATA_ROLES, QML_STYLE_MEDIA_TYPE } from "../util/catalogueFileFormats.js";
16
+ import { nameRecord } from "../util/nameRecord.js";
16
17
  /**
17
18
  * Generates a STAC Catalog tree from a parsed QgsProject.
18
19
  *
@@ -162,6 +163,9 @@ function qgsProjectToNormalized(project, companions, projectPath, projectFileNam
162
163
  activeCollectionId: project.initialActiveLayerId && layersById.has(project.initialActiveLayerId)
163
164
  ? collectionIdOf(project.initialActiveLayerId)
164
165
  : null,
166
+ vendorFields: project.printLayouts && project.printLayouts.length > 0
167
+ ? { [QUAC_PRINT_LAYOUTS_FIELD]: project.printLayouts.map(({ name, template }) => ({ name, template })) }
168
+ : undefined,
165
169
  nodes
166
170
  };
167
171
  }
@@ -217,7 +221,7 @@ function collectRelationsByChildLayerId(relations, layersById, collectionIdOf) {
217
221
  function collectValueRelationsByLayerId(layers, layersById, collectionIdOf) {
218
222
  const byLayerId = new Map();
219
223
  for (const layer of layers) {
220
- const relations = {};
224
+ const relations = nameRecord();
221
225
  for (const [field, widget] of Object.entries(layer.fieldValueRelations)) {
222
226
  const lookup = findValueRelationLookup(widget, layers, layersById);
223
227
  if (lookup)
@@ -639,7 +643,7 @@ function buildAssets(layer, geometryFilter) {
639
643
  * one of them takes a disambiguated key instead of replacing it.
640
644
  */
641
645
  function buildStyleAssets(layer, projectPath, existing) {
642
- const assets = {};
646
+ const assets = nameRecord();
643
647
  // The first style with a renderer is the default — the active one, unless
644
648
  // QGIS wrote no renderer for it. Marked rather than left to its position,
645
649
  // because a style named `2024` takes an asset key JavaScript enumerates
@@ -774,7 +778,7 @@ function unionExtent(layers, layerWgs84Extents) {
774
778
  * exist": this means a hidden WFS layer's schema is fully visible to the
775
779
  * dev panel and to STAC clients before any data is fetched.
776
780
  */
777
- function deriveTableColumns(geojson, fieldNames, fieldAliases, fieldValueMaps = {}, fieldAttachments = {}, fieldEditRules = {}, fieldValueRelations = {}, formLayout = null, fieldIcons = {}, fieldControls = {}, fieldComments = {}) {
781
+ function deriveTableColumns(geojson, fieldNames, fieldAliases, fieldValueMaps = nameRecord(), fieldAttachments = nameRecord(), fieldEditRules = nameRecord(), fieldValueRelations = nameRecord(), formLayout = null, fieldIcons = nameRecord(), fieldControls = nameRecord(), fieldComments = nameRecord()) {
778
782
  const observedTypes = new Map();
779
783
  const orderedFieldNames = [];
780
784
  const seen = new Set();
@@ -902,15 +906,26 @@ function defaultToJson(defaultValue) {
902
906
  case 'fixed': return { kind: 'fixed', value: defaultValue.value, on_update: defaultValue.onUpdate };
903
907
  }
904
908
  }
909
+ /**
910
+ * Whether an Attachment widget's default folder is a path relative to the
911
+ * project, and not a path on the computer that saved it, such as
912
+ * `/srv/photos`, `C:\\Survey` or `~/photos`, a network share or an address.
913
+ * QGIS's folder picker saves an absolute path, which would publish the
914
+ * computer's folder names.
915
+ */
916
+ export function isProjectRelativeFolder(folder) {
917
+ return !/^(?:[/\\~]|[A-Za-z][A-Za-z0-9+.-]*:)/.test(folder.trim());
918
+ }
905
919
  /**
906
920
  * A field's Attachment widget as `quac:attachment` stores it. A member
907
- * the source said nothing about is left off rather than written null.
921
+ * the source said nothing about is left off rather than written null, and a
922
+ * default folder that is not relative to the project is left off.
908
923
  */
909
924
  function attachmentToJson(attachment) {
910
925
  return {
911
926
  ...(attachment.viewer ? { viewer: attachment.viewer } : {}),
912
927
  ...(attachment.filter ? { filter: attachment.filter } : {}),
913
- ...(attachment.defaultRoot ? { default_root: attachment.defaultRoot } : {}),
928
+ ...(attachment.defaultRoot && isProjectRelativeFolder(attachment.defaultRoot) ? { default_root: attachment.defaultRoot } : {}),
914
929
  relative_storage: attachment.relativeStorage
915
930
  };
916
931
  }
package/dist/index.d.ts CHANGED
@@ -34,7 +34,7 @@ export { FILE_EXTENSION, FILE_SIZE_FIELD, TABLE_ROW_COUNT_FIELD, readCollectionR
34
34
  export { PMTILES_MEDIA_TYPE, VISUAL_ROLE, readCollectionPmtiles } from './model/stacPmtiles.ts';
35
35
  export type { StacPmtilesSource } from './model/stacPmtiles.ts';
36
36
  export type { StacCompanionData } from './generate/stacCatalogue.ts';
37
- export { QUAC_ACTIVE_COLLECTION_FIELD, QUAC_FILTERS_FIELD, QUAC_FORM_ORDER_FIELD, QUAC_LOCKS_FIELD, QUAC_MUTUALLY_EXCLUSIVE_FIELD, QUAC_PRIVATE_FIELD, readCatalogueActiveCollection, readCatalogueInitialView, readCollectionDisplayField, readCollectionEditable, readCollectionFieldAliases, readCollectionFieldComments, readCollectionFieldAttachments, readCollectionFieldEditRules, readCollectionFieldNames, readCollectionFieldTypes, readCollectionFieldValueRelations, readCollectionFieldValues, readCollectionFormLayout, readCollectionGeometryType, readCollectionIdentifiable, readCollectionMeasurement, readCollectionOpacity, readCollectionIcon, readCollectionAddedMessage, readCollectionLegendImage, readCollectionFilters, readCollectionLocks, readCollectionPrivate, readCollectionRelatedTo, readCollectionScaleRange, readCollectionVisibility, statedOpacity } from './generate/normalizedProject.ts';
37
+ export { QUAC_ACTIVE_COLLECTION_FIELD, QUAC_FILTERS_FIELD, QUAC_FORM_ORDER_FIELD, QUAC_LOCKS_FIELD, QUAC_MUTUALLY_EXCLUSIVE_FIELD, QUAC_PRIVATE_FIELD, readCatalogueActiveCollection, readCatalogueInitialView, readCataloguePrintLayouts, readCollectionDisplayField, readCollectionEditable, readCollectionFieldAliases, readCollectionFieldComments, readCollectionFieldAttachments, readCollectionFieldEditRules, readCollectionFieldNames, readCollectionFieldTypes, readCollectionFieldValueRelations, readCollectionFieldValues, readCollectionFormLayout, readCollectionGeometryType, readCollectionIdentifiable, readCollectionMeasurement, readCollectionOpacity, readCollectionIcon, readCollectionAddedMessage, readCollectionLegendImage, readCollectionFilters, readCollectionLocks, readCollectionPrivate, readCollectionRelatedTo, readCollectionScaleRange, readCollectionVisibility, statedOpacity } from './generate/normalizedProject.ts';
38
38
  export type { CollectionFilter, CollectionFormLayout, CollectionRelation, CollectionRelationField } from './generate/normalizedProject.ts';
39
39
  export { generateStacCatalogueFromWfsCapabilities } from './generate/wfsStacCatalogue.ts';
40
40
  export type { WfsStacCatalogueOptions } from './generate/wfsStacCatalogue.ts';
@@ -49,7 +49,8 @@ export type { ArcgisStacCatalogueOptions } from './generate/arcgisStacCatalogue.
49
49
  export { normalizeExternalStacCatalogue, parseWfsGetFeatureUrl, resolveWfsCollectionSource } from './generate/externalStacCatalogue.ts';
50
50
  export { decodeItemRowId, describeItem, encodeItemRowId, itemAsCollection, ITEMS_PAGE_SIZE, readItemsHref, readItemTimestamp, sortItemsNewestFirst } from './sources/stacItems.ts';
51
51
  export { stripQgisServerQuery } from './sources/qgisServerUrl.ts';
52
- export type { WmsProject, WmsLayerTreeNode, WmsLayer, WmsLayerGroup, WmsBoundingBox, WmsStyle, WmsAttribute } from './model/WmsProject.ts';
52
+ export type { PrintLayoutTemplate } from './model/QgsProject.ts';
53
+ export type { WmsProject, WmsLayerTreeNode, WmsLayer, WmsLayerGroup, WmsBoundingBox, WmsStyle, WmsAttribute, WmsPrintLayout, WmsPrintLayoutMap } from './model/WmsProject.ts';
53
54
  export { parseGetProjectSettings } from './parse/parseGetProjectSettings.ts';
54
55
  export { generateStacCatalogueFromWms } from './generate/wmsStacCatalogue.ts';
55
56
  export type { WmsStacCatalogueOptions } from './generate/wmsStacCatalogue.ts';
@@ -82,4 +83,6 @@ export { generateServerStacCatalogue, withoutHiddenFields } from './generate/ser
82
83
  export type { HiddenFieldContext } from './generate/serverStacCatalogue.ts';
83
84
  export { serverLayerTree } from './generate/serverLayerTree.ts';
84
85
  export type { ServerLayerTree, ServerLayerTreeGroup, ServerLayerTreeLayer, ServerLayerTreeNode } from './generate/serverLayerTree.ts';
86
+ export { splitCatalogue } from './generate/splitCatalogue.ts';
87
+ export type { CatalogueDocument, SplitCatalogueOptions } from './generate/splitCatalogue.ts';
85
88
  export { PROJ_CODE, PROJECTION_EXTENSION, readCollectionCrs } from './model/stacProjection.ts';
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@ export { DATA_ROLE, findAssetByRole, readDataAsset } from "./model/stacAssetRole
23
23
  export { THUMBNAIL_ROLE, readCollectionAttribution, readCollectionDeprecation, readCollectionSelfHref, readCollectionThumbnail } from "./model/stacCollectionNotes.js";
24
24
  export { FILE_EXTENSION, FILE_SIZE_FIELD, TABLE_ROW_COUNT_FIELD, readCollectionRowCount, readDataAssetFileSize } from "./model/stacSizeAndCount.js";
25
25
  export { PMTILES_MEDIA_TYPE, VISUAL_ROLE, readCollectionPmtiles } from "./model/stacPmtiles.js";
26
- export { QUAC_ACTIVE_COLLECTION_FIELD, QUAC_FILTERS_FIELD, QUAC_FORM_ORDER_FIELD, QUAC_LOCKS_FIELD, QUAC_MUTUALLY_EXCLUSIVE_FIELD, QUAC_PRIVATE_FIELD, readCatalogueActiveCollection, readCatalogueInitialView, readCollectionDisplayField, readCollectionEditable, readCollectionFieldAliases, readCollectionFieldComments, readCollectionFieldAttachments, readCollectionFieldEditRules, readCollectionFieldNames, readCollectionFieldTypes, readCollectionFieldValueRelations, readCollectionFieldValues, readCollectionFormLayout, readCollectionGeometryType, readCollectionIdentifiable, readCollectionMeasurement, readCollectionOpacity, readCollectionIcon, readCollectionAddedMessage, readCollectionLegendImage, readCollectionFilters, readCollectionLocks, readCollectionPrivate, readCollectionRelatedTo, readCollectionScaleRange, readCollectionVisibility, statedOpacity } from "./generate/normalizedProject.js";
26
+ export { QUAC_ACTIVE_COLLECTION_FIELD, QUAC_FILTERS_FIELD, QUAC_FORM_ORDER_FIELD, QUAC_LOCKS_FIELD, QUAC_MUTUALLY_EXCLUSIVE_FIELD, QUAC_PRIVATE_FIELD, readCatalogueActiveCollection, readCatalogueInitialView, readCataloguePrintLayouts, readCollectionDisplayField, readCollectionEditable, readCollectionFieldAliases, readCollectionFieldComments, readCollectionFieldAttachments, readCollectionFieldEditRules, readCollectionFieldNames, readCollectionFieldTypes, readCollectionFieldValueRelations, readCollectionFieldValues, readCollectionFormLayout, readCollectionGeometryType, readCollectionIdentifiable, readCollectionMeasurement, readCollectionOpacity, readCollectionIcon, readCollectionAddedMessage, readCollectionLegendImage, readCollectionFilters, readCollectionLocks, readCollectionPrivate, readCollectionRelatedTo, readCollectionScaleRange, readCollectionVisibility, statedOpacity } from "./generate/normalizedProject.js";
27
27
  export { generateStacCatalogueFromWfsCapabilities } from "./generate/wfsStacCatalogue.js";
28
28
  export { generateStacCatalogueFromFolder } from "./generate/folderStacCatalogue.js";
29
29
  export { generateCollectionForDroppedFile, generateCollectionForLinkedFile } from "./generate/fileLayerCollection.js";
@@ -53,4 +53,5 @@ export { DEFAULT_WFS_VERSION, SPOKEN_WFS_VERSIONS, WFS_CAPABILITIES_VERSION, WFS
53
53
  export { QUAC_SCHEMA_URL, declareQuacExtension, isNewerQuacMajor, listQuacExtension, readQuacVersion } from "./model/quacExtension.js";
54
54
  export { generateServerStacCatalogue, withoutHiddenFields } from "./generate/serverStacCatalogue.js";
55
55
  export { serverLayerTree } from "./generate/serverLayerTree.js";
56
+ export { splitCatalogue } from "./generate/splitCatalogue.js";
56
57
  export { PROJ_CODE, PROJECTION_EXTENSION, readCollectionCrs } from "./model/stacProjection.js";
@@ -66,9 +66,19 @@ export interface QgsProject {
66
66
  * notes are not written into the catalogue.
67
67
  */
68
68
  notes?: ProjectNote[];
69
+ /**
70
+ * The project's print layouts, in its order (`parsePrintLayouts`); absent or
71
+ * empty where it has none.
72
+ */
73
+ printLayouts?: PrintLayoutTemplate[];
69
74
  /** Original full QGS XML, retained so future parsers can re-mine without re-loading. */
70
75
  rawXml: string | null;
71
76
  }
77
+ /** A print layout as its name and its `<Layout>` element, which is a QGIS layout template. */
78
+ export interface PrintLayoutTemplate {
79
+ name: string;
80
+ template: string;
81
+ }
72
82
  /**
73
83
  * Why a project's setting is not in its catalogue:
74
84
  *
@@ -22,9 +22,40 @@ export interface WmsProject {
22
22
  layerTree: WmsLayerTreeNode[];
23
23
  /** Names of layers exposed via WFS (subset of the layer tree). */
24
24
  wfsLayerNames: string[];
25
+ /** The print layouts the server can print with GetPrint, in the order it lists them. */
26
+ printLayouts: WmsPrintLayout[];
25
27
  /** Full source XML, retained so future enhancements can re-mine. */
26
28
  rawXml: string | null;
27
29
  }
30
+ /**
31
+ * A print layout as GetProjectSettings lists it, in `<ComposerTemplates>`
32
+ * (`getComposerTemplatesElement`, `src/server/services/wms/qgswmsgetcapabilities.cpp`,
33
+ * `qgis/QGIS@master`, read 2026-11-25). Sizes are in millimetres.
34
+ */
35
+ export interface WmsPrintLayout {
36
+ /** The layout's name: GetPrint's `TEMPLATE`. */
37
+ name: string;
38
+ /** The first page's width. */
39
+ width: number;
40
+ /** The first page's height. */
41
+ height: number;
42
+ /** Whether the layout's atlas is on: GetPrint's `ATLAS_PK` then prints chosen features. */
43
+ isAtlasEnabled: boolean;
44
+ /** The atlas's coverage layer, by the name GetPrint's `LAYERS` uses; null when none is listed. */
45
+ atlasCoverageLayer: string | null;
46
+ /** The layout's map items. */
47
+ maps: WmsPrintLayoutMap[];
48
+ /** The IDs of the layout's labels; a label with no ID is not listed. */
49
+ labelIds: string[];
50
+ }
51
+ export interface WmsPrintLayoutMap {
52
+ /** The map item's name in GetPrint parameters, such as `map0` in `map0:EXTENT`. */
53
+ name: string;
54
+ /** The map item's name in the layout, as QGIS shows it. */
55
+ itemName: string;
56
+ width: number;
57
+ height: number;
58
+ }
28
59
  export interface WmsBoundingBox {
29
60
  westBoundLongitude: number;
30
61
  eastBoundLongitude: number;
@@ -23,5 +23,9 @@ export declare function resolveFieldIconAddress(value: string): string | null;
23
23
  * name `@latest` or an exact release.
24
24
  */
25
25
  export declare function isIconLibraryAddress(url: string): boolean;
26
- /** The address as the URL parser writes it, or null where it is not an `https://` address. */
26
+ /**
27
+ * The address as the URL parser writes it, or null where it is not an
28
+ * `https://` address or holds a user name or password, which a catalogue
29
+ * would otherwise publish.
30
+ */
27
31
  export declare function readHttpsAddress(value: unknown): string | null;
@@ -79,13 +79,17 @@ export function isIconLibraryAddress(url) {
79
79
  const rest = url.slice(JSDELIVR_NPM.length);
80
80
  return Object.values(ICON_LIBRARIES).some((library) => rest.startsWith(`${library.packageName}@`) || rest.startsWith(`${library.packageName}/`));
81
81
  }
82
- /** The address as the URL parser writes it, or null where it is not an `https://` address. */
82
+ /**
83
+ * The address as the URL parser writes it, or null where it is not an
84
+ * `https://` address or holds a user name or password, which a catalogue
85
+ * would otherwise publish.
86
+ */
83
87
  export function readHttpsAddress(value) {
84
88
  if (typeof value !== 'string')
85
89
  return null;
86
90
  try {
87
91
  const url = new URL(value.trim());
88
- return url.protocol === 'https:' ? url.href : null;
92
+ return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
89
93
  }
90
94
  catch {
91
95
  return null;
@@ -5,8 +5,9 @@ import type { WmsProject } from '../model/WmsProject.ts';
5
5
  *
6
6
  * The response is a WMS_Capabilities document with QGIS-specific extensions
7
7
  * for `displayField`, `geometryType`, `visibilityChecked`, `<Attributes>`
8
- * and `<WFSLayers>`. We capture what's useful for STAC + app-config
9
- * generation and ignore what isn't (e.g. GetMap / GetPrint format lists).
8
+ * `<WFSLayers>` and `<ComposerTemplates>`. We capture what's useful for STAC +
9
+ * app-config generation and for printing a layout, and ignore what isn't (e.g.
10
+ * GetMap / GetPrint format lists).
10
11
  *
11
12
  * Throws when the XML is unparseable or has the wrong root element.
12
13
  * Sub-elements that fail to parse log via devLog and yield null/empty
@@ -5,8 +5,9 @@ import { devLog } from "../util/devLog.js";
5
5
  *
6
6
  * The response is a WMS_Capabilities document with QGIS-specific extensions
7
7
  * for `displayField`, `geometryType`, `visibilityChecked`, `<Attributes>`
8
- * and `<WFSLayers>`. We capture what's useful for STAC + app-config
9
- * generation and ignore what isn't (e.g. GetMap / GetPrint format lists).
8
+ * `<WFSLayers>` and `<ComposerTemplates>`. We capture what's useful for STAC +
9
+ * app-config generation and for printing a layout, and ignore what isn't (e.g.
10
+ * GetMap / GetPrint format lists).
10
11
  *
11
12
  * Throws when the XML is unparseable or has the wrong root element.
12
13
  * Sub-elements that fail to parse log via devLog and yield null/empty
@@ -38,10 +39,13 @@ export function parseGetProjectSettings(xmlText) {
38
39
  const wfsLayerNames = Array.from(capability?.querySelectorAll(':scope > WFSLayers > WFSLayer') ?? [])
39
40
  .map((node) => node.getAttribute('name'))
40
41
  .filter((name) => Boolean(name));
42
+ const printLayouts = Array.from(capability?.querySelectorAll(':scope > ComposerTemplates > ComposerTemplate') ?? [])
43
+ .map(parsePrintLayout);
41
44
  devLog('qgs/parseGetProjectSettings', 'parsed WMS project', {
42
45
  title,
43
46
  rootLayerCount: layerTree.length,
44
- wfsLayerCount: wfsLayerNames.length
47
+ wfsLayerCount: wfsLayerNames.length,
48
+ printLayoutCount: printLayouts.length
45
49
  });
46
50
  return {
47
51
  title,
@@ -49,9 +53,29 @@ export function parseGetProjectSettings(xmlText) {
49
53
  bbox: projectBbox,
50
54
  layerTree,
51
55
  wfsLayerNames,
56
+ printLayouts,
52
57
  rawXml: xmlText
53
58
  };
54
59
  }
60
+ function parsePrintLayout(element) {
61
+ const maps = Array.from(element.querySelectorAll(':scope > ComposerMap')).map((map) => ({
62
+ name: map.getAttribute('name') ?? '',
63
+ itemName: map.getAttribute('itemName') ?? '',
64
+ width: Number(map.getAttribute('width')) || 0,
65
+ height: Number(map.getAttribute('height')) || 0
66
+ }));
67
+ return {
68
+ name: element.getAttribute('name') ?? '',
69
+ width: Number(element.getAttribute('width')) || 0,
70
+ height: Number(element.getAttribute('height')) || 0,
71
+ isAtlasEnabled: element.getAttribute('atlasEnabled') === '1',
72
+ atlasCoverageLayer: element.getAttribute('atlasCoverageLayer') || null,
73
+ maps,
74
+ labelIds: Array.from(element.querySelectorAll(':scope > ComposerLabel'))
75
+ .map((label) => label.getAttribute('name') ?? '')
76
+ .filter(Boolean)
77
+ };
78
+ }
55
79
  function bboxOf(node) {
56
80
  return node.kind === 'layer' ? node.bbox : node.bbox;
57
81
  }
@@ -6,6 +6,7 @@ import { parseLayerStyles } from "./parseStyle.js";
6
6
  import { readQgisExpression, unescapeStringLiteral } from "./qgisExpression.js";
7
7
  import { resolveFieldIconAddress } from "../model/fieldIconAddress.js";
8
8
  import { devLog } from "../util/devLog.js";
9
+ import { nameRecord } from "../util/nameRecord.js";
9
10
  /**
10
11
  * Parses the <projectlayers> block into a list of LayerEntry. Annotation
11
12
  * layers (<main-annotation-layer>) are filtered out — they're QGIS's drawing
@@ -310,7 +311,7 @@ const VALUE_MAP_NULL_CODE = '{2839923C-8B7D-419E-B84B-CA2FE9B80EC7}';
310
311
  * returned map.
311
312
  */
312
313
  function parseFieldValueMaps(maplayer) {
313
- const result = {};
314
+ const result = nameRecord();
314
315
  for (const [name, editWidget] of layerEditWidgets(maplayer)) {
315
316
  if (result[name])
316
317
  continue;
@@ -365,7 +366,7 @@ function parseFieldValueMaps(maplayer) {
365
366
  * A field with no ValueRelation widget is absent from the returned map.
366
367
  */
367
368
  function parseFieldValueRelations(maplayer) {
368
- const result = {};
369
+ const result = nameRecord();
369
370
  for (const [name, editWidget] of layerEditWidgets(maplayer)) {
370
371
  if (result[name])
371
372
  continue;
@@ -441,7 +442,7 @@ const SINGLE_FILE_STORAGE_MODES = new Set([0, 3]);
441
442
  * A field with no ExternalResource widget is absent from the returned map.
442
443
  */
443
444
  function parseFieldAttachments(maplayer) {
444
- const result = {};
445
+ const result = nameRecord();
445
446
  for (const [name, editWidget] of layerEditWidgets(maplayer)) {
446
447
  if (result[name])
447
448
  continue;
@@ -499,7 +500,7 @@ const NOW_EXPRESSIONS = new Set(['now()', '$now', 'to_date(now())', 'to_datetime
499
500
  * settings is absent from the returned map.
500
501
  */
501
502
  function parseFieldEditRules(maplayer, note) {
502
- const result = {};
503
+ const result = nameRecord();
503
504
  const ruleFor = (name) => {
504
505
  result[name] ??= { readOnly: false, defaultValue: null, notNull: null, unique: null, hidden: false, reuseLastValue: false, duplicatePolicy: null };
505
506
  return result[name];
@@ -912,7 +913,7 @@ function parseFieldNames(maplayer) {
912
913
  * per field, which is the active-style block's when both are present.
913
914
  */
914
915
  function parseFieldAliases(maplayer) {
915
- const out = {};
916
+ const out = nameRecord();
916
917
  const nodes = maplayer.querySelectorAll('aliases > alias');
917
918
  for (const node of Array.from(nodes)) {
918
919
  const field = node.getAttribute('field');
@@ -938,7 +939,7 @@ function parseFieldAliases(maplayer) {
938
939
  * entries name a field, the later stands, as QGIS's map of them keeps it.
939
940
  */
940
941
  function parseFieldComments(maplayer) {
941
- const out = {};
942
+ const out = nameRecord();
942
943
  for (const node of directChild(maplayer, 'customComments')?.querySelectorAll(':scope > customComment') ?? []) {
943
944
  const field = node.getAttribute('field');
944
945
  if (!field)
@@ -982,7 +983,7 @@ const FIELD_ICON_VARIABLE_PREFIX = 'quac_icon_';
982
983
  * 2026-10-25).
983
984
  */
984
985
  function parseFieldIcons(maplayer) {
985
- const icons = {};
986
+ const icons = nameRecord();
986
987
  for (const [field, value] of readFieldVariables(maplayer, FIELD_ICON_VARIABLE_PREFIX)) {
987
988
  const address = resolveFieldIconAddress(value);
988
989
  if (address)
@@ -1034,7 +1035,7 @@ const FIELD_CONTROL_VARIABLE_PREFIX = 'quac_control_';
1034
1035
  * out.
1035
1036
  */
1036
1037
  function parseFieldControls(maplayer) {
1037
- const controls = {};
1038
+ const controls = nameRecord();
1038
1039
  for (const [field, value] of readFieldVariables(maplayer, FIELD_CONTROL_VARIABLE_PREFIX)) {
1039
1040
  const control = value.trim().toLowerCase();
1040
1041
  if (control === 'buttons' || control === 'dropdown')
@@ -0,0 +1,28 @@
1
+ import type { PrintLayoutTemplate } from '../model/QgsProject.ts';
2
+ /**
3
+ * The project's print layouts, from `<qgis><Layouts>`, each as its name and its
4
+ * `<Layout>` element written out by `writeLayoutTemplate`. That element is what
5
+ * QGIS saves as a layout template (`.qpt`): `QgsLayout::saveAsTemplate` writes
6
+ * the same `writeXml` element as the only element of the file
7
+ * (`src/core/layout/qgslayout.cpp`, `qgis/QGIS@master`, read 2026-11-25).
8
+ *
9
+ * A layout whose name the project leaves out of WMS, under Project Properties →
10
+ * QGIS Server → WMS capabilities → **Exclude layouts**, saved as
11
+ * `WMSRestrictedComposers` (`QgsServerProjectUtils::wmsRestrictedComposers`,
12
+ * `src/server/qgsserverprojectutils.cpp`, same revision), is left out, as its
13
+ * excluded layers are. Reports are not read.
14
+ */
15
+ export declare function parsePrintLayouts(qgisRoot: Element): PrintLayoutTemplate[];
16
+ /**
17
+ * A layout element as XML text, written by one fixed rule so that the
18
+ * plugin's Python writes the same text: attributes in the order the document
19
+ * holds them, an element with no children closed as `<name/>`, text that is
20
+ * only white space left out, comments and processing instructions left out,
21
+ * and `&`, `<`, `>` escaped everywhere, with `"`, tab, line feed and carriage
22
+ * return escaped in attribute values too.
23
+ *
24
+ * It holds no layer's data source and no absolute path: each `SOURCE_ATTRIBUTE`
25
+ * is left out, and an attribute whose value is an `ABSOLUTE_PATH` is written
26
+ * empty.
27
+ */
28
+ export declare function writeLayoutTemplate(element: Element): string;
@@ -0,0 +1,79 @@
1
+ import { propertyList } from "./projectProperties.js";
2
+ /**
3
+ * The project's print layouts, from `<qgis><Layouts>`, each as its name and its
4
+ * `<Layout>` element written out by `writeLayoutTemplate`. That element is what
5
+ * QGIS saves as a layout template (`.qpt`): `QgsLayout::saveAsTemplate` writes
6
+ * the same `writeXml` element as the only element of the file
7
+ * (`src/core/layout/qgslayout.cpp`, `qgis/QGIS@master`, read 2026-11-25).
8
+ *
9
+ * A layout whose name the project leaves out of WMS, under Project Properties →
10
+ * QGIS Server → WMS capabilities → **Exclude layouts**, saved as
11
+ * `WMSRestrictedComposers` (`QgsServerProjectUtils::wmsRestrictedComposers`,
12
+ * `src/server/qgsserverprojectutils.cpp`, same revision), is left out, as its
13
+ * excluded layers are. Reports are not read.
14
+ */
15
+ export function parsePrintLayouts(qgisRoot) {
16
+ const properties = qgisRoot.querySelector(':scope > properties');
17
+ const restricted = new Set(properties ? propertyList(properties, 'WMSRestrictedComposers') : []);
18
+ return Array.from(qgisRoot.querySelectorAll(':scope > Layouts > Layout'))
19
+ .map((layout) => ({ name: layout.getAttribute('name') ?? '', template: writeLayoutTemplate(layout) }))
20
+ .filter((layout) => !restricted.has(layout.name));
21
+ }
22
+ /**
23
+ * An attribute QGIS writes a layer's data source or provider in: `source` and
24
+ * `provider` on a map item's `<Layer>`, and `coverageLayerSource`,
25
+ * `vectorLayerSource` and the like, which a data source's password or file
26
+ * path can be in.
27
+ */
28
+ const SOURCE_ATTRIBUTE = /^(source|provider)$|(Source|Provider)$/;
29
+ /**
30
+ * A value that is a path on the computer that saved the project: from the
31
+ * root of a disk or a home folder (`~/`), a drive, a network share, or a
32
+ * `file:` address. It is narrower than `isProjectRelativeFolder`'s test of an
33
+ * Attachment folder, because it reads every attribute of a layout, label text
34
+ * included, so a value such as `Address: 12 Main St` is not taken for an
35
+ * address.
36
+ */
37
+ const ABSOLUTE_PATH = /^\s*(\/|\\|~[\\/]|[A-Za-z]:([\\/]|$)|file:)/i;
38
+ /**
39
+ * A layout element as XML text, written by one fixed rule so that the
40
+ * plugin's Python writes the same text: attributes in the order the document
41
+ * holds them, an element with no children closed as `<name/>`, text that is
42
+ * only white space left out, comments and processing instructions left out,
43
+ * and `&`, `<`, `>` escaped everywhere, with `"`, tab, line feed and carriage
44
+ * return escaped in attribute values too.
45
+ *
46
+ * It holds no layer's data source and no absolute path: each `SOURCE_ATTRIBUTE`
47
+ * is left out, and an attribute whose value is an `ABSOLUTE_PATH` is written
48
+ * empty.
49
+ */
50
+ export function writeLayoutTemplate(element) {
51
+ const attributes = Array.from(element.attributes)
52
+ .filter((attribute) => !SOURCE_ATTRIBUTE.test(attribute.name))
53
+ .map((attribute) => ` ${attribute.name}="${ABSOLUTE_PATH.test(attribute.value) ? '' : escapeAttribute(attribute.value)}"`)
54
+ .join('');
55
+ const children = Array.from(element.childNodes)
56
+ .map((child) => {
57
+ if (child.nodeType === 1)
58
+ return writeLayoutTemplate(child);
59
+ if (child.nodeType === 3 || child.nodeType === 4) {
60
+ const text = child.nodeValue ?? '';
61
+ return text.trim() === '' ? '' : escapeText(text);
62
+ }
63
+ return '';
64
+ })
65
+ .join('');
66
+ return children === ''
67
+ ? `<${element.tagName}${attributes}/>`
68
+ : `<${element.tagName}${attributes}>${children}</${element.tagName}>`;
69
+ }
70
+ function escapeText(text) {
71
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
72
+ }
73
+ function escapeAttribute(value) {
74
+ return escapeText(value)
75
+ .replace(/"/g, '&quot;')
76
+ .replace(/\t/g, '&#9;')
77
+ .replace(/\n/g, '&#10;')
78
+ .replace(/\r/g, '&#13;');
79
+ }
@@ -5,6 +5,7 @@ import { parseProjectLayers } from "./parseLayers.js";
5
5
  import { parseLegendTree } from "./parseLegendTree.js";
6
6
  import { parseProjectMeasurement } from "./parseMeasurement.js";
7
7
  import { parseMerginFilters } from "./parseMergin.js";
8
+ import { parsePrintLayouts } from "./parsePrintLayouts.js";
8
9
  import { parseProjectVariables } from "./parseProjectVariables.js";
9
10
  import { parseInitialActiveLayerId, parseWfsTransactionLayers } from "./parseQfieldSync.js";
10
11
  import { parseProjectRelations } from "./parseRelations.js";
@@ -88,6 +89,7 @@ export function parseQgsXml(xmlText) {
88
89
  wmsCrsList: parseWmsCrsList(qgisRoot),
89
90
  merginFilters,
90
91
  notes,
92
+ printLayouts: parsePrintLayouts(qgisRoot),
91
93
  rawXml: xmlText
92
94
  };
93
95
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * An empty record to file values by a name a project gives, such as a field's
3
+ * or a style's, with no properties of its own to inherit: a field named
4
+ * `__proto__` is then a key like any other rather than the record's
5
+ * prototype, and one named `constructor` reads as absent until it is set.
6
+ */
7
+ export declare function nameRecord<T>(): Record<string, T>;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * An empty record to file values by a name a project gives, such as a field's
3
+ * or a style's, with no properties of its own to inherit: a field named
4
+ * `__proto__` is then a key like any other rather than the record's
5
+ * prototype, and one named `constructor` reads as absent until it is set.
6
+ */
7
+ export function nameRecord() {
8
+ return Object.create(null);
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectoriahq/quac",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Writes and reads QUAC, which adds map layer settings to STAC catalogues.",
@@ -79,6 +79,20 @@
79
79
  "maxItems": 4,
80
80
  "items": { "type": "number" }
81
81
  },
82
+ "quac:print_layouts": {
83
+ "description": "On the top-level Catalog: the source's print layouts, in its order, each as its name and its QGIS layout template, the <Layout> element that QGIS saves in a .qpt file. Written from a QGIS project's Layout Manager, less any layout that its QGIS Server settings exclude.",
84
+ "type": "array",
85
+ "minItems": 1,
86
+ "items": {
87
+ "type": "object",
88
+ "required": ["name", "template"],
89
+ "properties": {
90
+ "name": { "type": "string" },
91
+ "template": { "type": "string", "pattern": "^<Layout[ />]" }
92
+ },
93
+ "additionalProperties": false
94
+ }
95
+ },
82
96
  "quac:visibility_checked": {
83
97
  "description": "On a group: whether the group opens switched on. In a catalogue of basemaps, true marks the basemap that is shown first, and false keeps a group hidden.",
84
98
  "type": "boolean"