@nuasite/cms-core 0.64.3 → 0.65.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 (187) hide show
  1. package/dist/asset-paths.d.ts.map +1 -0
  2. package/dist/asset-paths.js +55 -0
  3. package/dist/astro-source-analysis.d.ts.map +1 -0
  4. package/dist/astro-source-analysis.js +503 -0
  5. package/dist/byte-range.d.ts.map +1 -0
  6. package/dist/byte-range.js +31 -0
  7. package/dist/{types/check-entries.d.ts → check-entries.d.ts} +3 -3
  8. package/dist/check-entries.d.ts.map +1 -0
  9. package/dist/check-entries.js +98 -0
  10. package/dist/{types/check-live.d.ts → check-live.d.ts} +4 -4
  11. package/dist/check-live.d.ts.map +1 -0
  12. package/dist/check-live.js +49 -0
  13. package/dist/{types/check-shape.d.ts → check-shape.d.ts} +4 -4
  14. package/dist/check-shape.d.ts.map +1 -0
  15. package/dist/check-shape.js +119 -0
  16. package/dist/{types/check-write.d.ts → check-write.d.ts} +4 -4
  17. package/dist/check-write.d.ts.map +1 -0
  18. package/dist/check-write.js +273 -0
  19. package/dist/{types/check.d.ts → check.d.ts} +2 -2
  20. package/dist/check.d.ts.map +1 -0
  21. package/dist/check.js +366 -0
  22. package/dist/{types/collection-scanner.d.ts → collection-scanner.d.ts} +2 -2
  23. package/dist/collection-scanner.d.ts.map +1 -0
  24. package/dist/collection-scanner.js +1483 -0
  25. package/dist/{types/component-registry.d.ts → component-registry.d.ts} +1 -1
  26. package/dist/component-registry.d.ts.map +1 -0
  27. package/dist/component-registry.js +271 -0
  28. package/dist/{types/content-config-ast.d.ts → content-config-ast.d.ts} +1 -1
  29. package/dist/content-config-ast.d.ts.map +1 -0
  30. package/dist/content-config-ast.js +1614 -0
  31. package/dist/{types/core.d.ts → core.d.ts} +3 -3
  32. package/dist/core.d.ts.map +1 -0
  33. package/dist/core.js +94 -0
  34. package/dist/editor-write-model.d.ts.map +1 -0
  35. package/dist/editor-write-model.js +101 -0
  36. package/dist/fs/glob.d.ts.map +1 -0
  37. package/dist/fs/glob.js +79 -0
  38. package/dist/{types/fs → fs}/node-fs.d.ts +1 -1
  39. package/dist/fs/node-fs.d.ts.map +1 -0
  40. package/dist/fs/node-fs.js +199 -0
  41. package/dist/{types/fs → fs}/staged.d.ts +1 -1
  42. package/dist/fs/staged.d.ts.map +1 -0
  43. package/dist/fs/staged.js +203 -0
  44. package/dist/fs/types.d.ts.map +1 -0
  45. package/dist/fs/types.js +0 -0
  46. package/dist/{types/handlers → handlers}/entry-ops.d.ts +2 -2
  47. package/dist/handlers/entry-ops.d.ts.map +1 -0
  48. package/dist/handlers/entry-ops.js +846 -0
  49. package/dist/{types/handlers → handlers}/page-ops.d.ts +1 -1
  50. package/dist/handlers/page-ops.d.ts.map +1 -0
  51. package/dist/handlers/page-ops.js +165 -0
  52. package/dist/{types/handlers → handlers}/redirect-ops.d.ts +1 -1
  53. package/dist/handlers/redirect-ops.d.ts.map +1 -0
  54. package/dist/handlers/redirect-ops.js +111 -0
  55. package/dist/index.d.ts +5 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +4 -0
  58. package/dist/media/contember.d.ts.map +1 -0
  59. package/dist/media/contember.js +79 -0
  60. package/dist/media/errors.d.ts.map +1 -0
  61. package/dist/media/errors.js +22 -0
  62. package/dist/{types/media → media}/file-system.d.ts +1 -1
  63. package/dist/media/file-system.d.ts.map +1 -0
  64. package/dist/media/file-system.js +124 -0
  65. package/dist/{types/media → media}/index.d.ts +8 -8
  66. package/dist/media/index.d.ts.map +1 -0
  67. package/dist/media/index.js +8 -0
  68. package/dist/media/local.d.ts.map +1 -0
  69. package/dist/media/local.js +209 -0
  70. package/dist/media/mime.d.ts.map +1 -0
  71. package/dist/media/mime.js +21 -0
  72. package/dist/media/names.d.ts.map +1 -0
  73. package/dist/media/names.js +23 -0
  74. package/dist/{types/media → media}/project-images.d.ts +1 -1
  75. package/dist/media/project-images.d.ts.map +1 -0
  76. package/dist/media/project-images.js +99 -0
  77. package/dist/media/s3.d.ts.map +1 -0
  78. package/dist/media/s3.js +160 -0
  79. package/dist/media/type-filter.d.ts.map +1 -0
  80. package/dist/media/type-filter.js +164 -0
  81. package/dist/{types/portable.d.ts → portable.d.ts} +25 -25
  82. package/dist/portable.d.ts.map +1 -0
  83. package/dist/portable.js +27 -0
  84. package/dist/{types/project-config-ast.d.ts → project-config-ast.d.ts} +1 -1
  85. package/dist/project-config-ast.d.ts.map +1 -0
  86. package/dist/project-config-ast.js +324 -0
  87. package/dist/public-static-file.d.ts.map +1 -0
  88. package/dist/public-static-file.js +40 -0
  89. package/dist/redirects.d.ts.map +1 -0
  90. package/dist/redirects.js +185 -0
  91. package/dist/route-scan.d.ts.map +1 -0
  92. package/dist/route-scan.js +23 -0
  93. package/dist/schema-port.d.ts.map +1 -0
  94. package/dist/schema-port.js +30 -0
  95. package/dist/{types/schema-probe.d.ts → schema-probe.d.ts} +2 -2
  96. package/dist/schema-probe.d.ts.map +1 -0
  97. package/dist/schema-probe.js +119 -0
  98. package/dist/shared.d.ts.map +1 -0
  99. package/dist/shared.js +163 -0
  100. package/dist/tsconfig.tsbuildinfo +1 -0
  101. package/package.json +12 -12
  102. package/src/check-entries.ts +4 -4
  103. package/src/check-live.ts +4 -4
  104. package/src/check-shape.ts +5 -5
  105. package/src/check-write.ts +6 -6
  106. package/src/check.ts +15 -9
  107. package/src/collection-scanner.ts +3 -3
  108. package/src/component-registry.ts +1 -1
  109. package/src/content-config-ast.ts +1 -1
  110. package/src/core.ts +8 -8
  111. package/src/editor-write-model.ts +1 -1
  112. package/src/fs/node-fs.ts +2 -2
  113. package/src/fs/staged.ts +6 -3
  114. package/src/handlers/entry-ops.ts +7 -7
  115. package/src/handlers/page-ops.ts +2 -2
  116. package/src/handlers/redirect-ops.ts +2 -2
  117. package/src/index.ts +4 -4
  118. package/src/media/contember.ts +1 -1
  119. package/src/media/file-system.ts +4 -4
  120. package/src/media/index.ts +8 -8
  121. package/src/media/local.ts +3 -3
  122. package/src/media/project-images.ts +2 -2
  123. package/src/media/s3.ts +3 -3
  124. package/src/portable.ts +25 -25
  125. package/src/project-config-ast.ts +1 -1
  126. package/src/route-scan.ts +1 -1
  127. package/src/schema-probe.ts +2 -2
  128. package/src/tsconfig.json +5 -1
  129. package/dist/types/asset-paths.d.ts.map +0 -1
  130. package/dist/types/astro-source-analysis.d.ts.map +0 -1
  131. package/dist/types/byte-range.d.ts.map +0 -1
  132. package/dist/types/check-entries.d.ts.map +0 -1
  133. package/dist/types/check-live.d.ts.map +0 -1
  134. package/dist/types/check-shape.d.ts.map +0 -1
  135. package/dist/types/check-write.d.ts.map +0 -1
  136. package/dist/types/check.d.ts.map +0 -1
  137. package/dist/types/collection-scanner.d.ts.map +0 -1
  138. package/dist/types/component-registry.d.ts.map +0 -1
  139. package/dist/types/content-config-ast.d.ts.map +0 -1
  140. package/dist/types/core.d.ts.map +0 -1
  141. package/dist/types/editor-write-model.d.ts.map +0 -1
  142. package/dist/types/fs/glob.d.ts.map +0 -1
  143. package/dist/types/fs/node-fs.d.ts.map +0 -1
  144. package/dist/types/fs/staged.d.ts.map +0 -1
  145. package/dist/types/fs/types.d.ts.map +0 -1
  146. package/dist/types/handlers/entry-ops.d.ts.map +0 -1
  147. package/dist/types/handlers/page-ops.d.ts.map +0 -1
  148. package/dist/types/handlers/redirect-ops.d.ts.map +0 -1
  149. package/dist/types/index.d.ts +0 -5
  150. package/dist/types/index.d.ts.map +0 -1
  151. package/dist/types/media/contember.d.ts.map +0 -1
  152. package/dist/types/media/errors.d.ts.map +0 -1
  153. package/dist/types/media/file-system.d.ts.map +0 -1
  154. package/dist/types/media/index.d.ts.map +0 -1
  155. package/dist/types/media/local.d.ts.map +0 -1
  156. package/dist/types/media/mime.d.ts.map +0 -1
  157. package/dist/types/media/names.d.ts.map +0 -1
  158. package/dist/types/media/project-images.d.ts.map +0 -1
  159. package/dist/types/media/s3.d.ts.map +0 -1
  160. package/dist/types/media/type-filter.d.ts.map +0 -1
  161. package/dist/types/portable.d.ts.map +0 -1
  162. package/dist/types/project-config-ast.d.ts.map +0 -1
  163. package/dist/types/public-static-file.d.ts.map +0 -1
  164. package/dist/types/redirects.d.ts.map +0 -1
  165. package/dist/types/route-scan.d.ts.map +0 -1
  166. package/dist/types/schema-port.d.ts.map +0 -1
  167. package/dist/types/schema-probe.d.ts.map +0 -1
  168. package/dist/types/shared.d.ts.map +0 -1
  169. package/dist/types/tsconfig.tsbuildinfo +0 -1
  170. /package/dist/{types/asset-paths.d.ts → asset-paths.d.ts} +0 -0
  171. /package/dist/{types/astro-source-analysis.d.ts → astro-source-analysis.d.ts} +0 -0
  172. /package/dist/{types/byte-range.d.ts → byte-range.d.ts} +0 -0
  173. /package/dist/{types/editor-write-model.d.ts → editor-write-model.d.ts} +0 -0
  174. /package/dist/{types/fs → fs}/glob.d.ts +0 -0
  175. /package/dist/{types/fs → fs}/types.d.ts +0 -0
  176. /package/dist/{types/media → media}/contember.d.ts +0 -0
  177. /package/dist/{types/media → media}/errors.d.ts +0 -0
  178. /package/dist/{types/media → media}/local.d.ts +0 -0
  179. /package/dist/{types/media → media}/mime.d.ts +0 -0
  180. /package/dist/{types/media → media}/names.d.ts +0 -0
  181. /package/dist/{types/media → media}/s3.d.ts +0 -0
  182. /package/dist/{types/media → media}/type-filter.d.ts +0 -0
  183. /package/dist/{types/public-static-file.d.ts → public-static-file.d.ts} +0 -0
  184. /package/dist/{types/redirects.d.ts → redirects.d.ts} +0 -0
  185. /package/dist/{types/route-scan.d.ts → route-scan.d.ts} +0 -0
  186. /package/dist/{types/schema-port.d.ts → schema-port.d.ts} +0 -0
  187. /package/dist/{types/shared.d.ts → shared.d.ts} +0 -0
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Merge the `_redirects` rules a site gets from several places into the one file a host reads.
3
+ *
4
+ * A nua site has three: `src/_redirects`, which editors maintain through the CMS, the hand-written
5
+ * `public/_redirects`, and the `redirects` map in the Astro config. Each used to be written into
6
+ * `dist/_redirects` on its own, so a path redirected in two of them was listed twice. Cloudflare
7
+ * Pages rejects a file with a repeated source, and with it the whole deploy.
8
+ *
9
+ * Only what is understood is changed: a line this reader cannot take apart (a Netlify role gate with
10
+ * no destination, a trailing comment) is kept as written, where it was. Merging is idempotent, so it
11
+ * does not matter which build step merges last, or how often.
12
+ */
13
+ /** Where the CMS keeps the redirects editors manage, relative to the project root. */
14
+ export const CMS_REDIRECTS_FILE = 'src/_redirects';
15
+ /**
16
+ * Cloudflare Pages' limits on a `_redirects` file. Netlify has none, so going over them is worth a
17
+ * warning, not a failed build.
18
+ */
19
+ export const CLOUDFLARE_REDIRECT_LIMITS = { exact: 2000, pattern: 100 };
20
+ const HEADER = '# Merged by @nuasite. A host applies the first rule that matches, so each source of rules\n'
21
+ + '# is listed ahead of the ones it takes precedence over.\n';
22
+ const isTarget = (field) => field.startsWith('/') || /^https?:\/\/\S/.test(field);
23
+ const isCondition = (field) => field.includes('=') && !isTarget(field);
24
+ const pathOf = (source) => source.replace(/^https?:\/\/[^/]*/, '');
25
+ /**
26
+ * Read one `_redirects` line: `source [query matches] destination [status] [conditions]`. `undefined`
27
+ * for a line that does not have that shape, such as one with no destination, a source or destination
28
+ * that is not a path or URL, a status that is not a three-digit code, or a stray field.
29
+ */
30
+ export function parseRedirectRule(line) {
31
+ const fields = line.trim().split(/\s+/);
32
+ const source = fields.shift();
33
+ if (!source || !isTarget(source))
34
+ return undefined;
35
+ const conditions = [];
36
+ while (fields[0] !== undefined && isCondition(fields[0]))
37
+ conditions.push(fields.shift());
38
+ const destination = fields.shift();
39
+ if (!destination || !isTarget(destination))
40
+ return undefined;
41
+ const status = fields[0] !== undefined && /^\d{3}!?$/.test(fields[0]) ? fields.shift() : undefined;
42
+ while (fields[0] !== undefined && isCondition(fields[0]))
43
+ conditions.push(fields.shift());
44
+ if (fields.length > 0)
45
+ return undefined;
46
+ return {
47
+ source,
48
+ destination,
49
+ status,
50
+ conditions,
51
+ key: [source, ...conditions.toSorted()].join(' '),
52
+ pattern: /\*|:[A-Za-z_]/.test(pathOf(source)),
53
+ text: line.trim().split(/\s+/).join(' '),
54
+ };
55
+ }
56
+ /**
57
+ * Merge `layers`, earlier layers taking precedence. Each layer's lines are written as a block, in their
58
+ * own order, ahead of every layer they take precedence over: a host applies the first rule that
59
+ * matches, so a higher layer wins for every path it covers, by an exact rule or by a pattern, and the
60
+ * order an author chose within a file is kept. Two rules are the same rule when they share a source
61
+ * and, for Netlify, the same conditions (`Language=cs`) and query matches (`id=:id`); the first wins.
62
+ */
63
+ export function mergeRedirects(layers) {
64
+ const entries = [];
65
+ const kept = new Map();
66
+ const overridden = [];
67
+ const unrecognised = [];
68
+ const refused = [];
69
+ const guards = layers.filter(l => !l.restricted).flatMap(l => guardSources(l.text));
70
+ layers.forEach((layer, layerIndex) => {
71
+ const lines = layer.text.split('\n');
72
+ for (let i = 0; i < lines.length; i++) {
73
+ const line = lines[i].trim();
74
+ if (!line || line.startsWith('#'))
75
+ continue;
76
+ const at = { layer: layer.name, lineNumber: i + 1, line };
77
+ const rule = parseRedirectRule(line);
78
+ if (layer.restricted) {
79
+ const reason = refusal(rule, guards);
80
+ if (reason) {
81
+ refused.push({ rule: at, reason });
82
+ continue;
83
+ }
84
+ }
85
+ if (!rule) {
86
+ unrecognised.push(at);
87
+ entries.push({ kind: 'line', at });
88
+ continue;
89
+ }
90
+ const existing = kept.get(rule.key);
91
+ if (existing) {
92
+ if (existing.rule.text !== rule.text)
93
+ overridden.push({ kept: existing.at, dropped: at });
94
+ continue;
95
+ }
96
+ const entry = { kind: 'rule', at, rule, layer: layerIndex };
97
+ kept.set(rule.key, entry);
98
+ entries.push(entry);
99
+ }
100
+ });
101
+ const lines = entries.map(e => e.kind === 'rule' ? e.rule.text : e.at.line);
102
+ const pattern = entries.filter(e => e.kind === 'rule' && e.rule.pattern).length;
103
+ return {
104
+ text: lines.length ? `${HEADER}${lines.join('\n')}\n` : '',
105
+ lines,
106
+ overridden,
107
+ shadowed: findShadowed(entries),
108
+ unrecognised,
109
+ refused,
110
+ counts: { exact: lines.length - pattern, pattern },
111
+ };
112
+ }
113
+ /** Exact rules a pattern from a layer of higher precedence reaches first. Conditional patterns may not apply, so they shadow nothing. */
114
+ function findShadowed(entries) {
115
+ const patterns = entries.flatMap(e => e.kind === 'rule' && e.rule.pattern && e.rule.conditions.length === 0 ? [{ entry: e, matches: patternMatcher(e.rule.source) }] : []);
116
+ const shadowed = [];
117
+ for (const e of entries) {
118
+ if (e.kind !== 'rule' || e.rule.pattern)
119
+ continue;
120
+ const by = patterns.find(p => p.entry.layer < e.layer && p.matches.test(e.rule.source));
121
+ if (by)
122
+ shadowed.push({ by: by.entry.at, rule: e.at });
123
+ }
124
+ return shadowed;
125
+ }
126
+ function patternMatcher(source) {
127
+ const escaped = source.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
128
+ return new RegExp(`^${escaped.replace(/\*/g, '.*').replace(/:[A-Za-z_]\w*/g, '[^/]+')}$`);
129
+ }
130
+ const isPlainRedirect = (rule) => rule.conditions.length === 0 && (rule.status === undefined || /^30[12378]!?$/.test(rule.status));
131
+ /**
132
+ * The sources of the lines in an unrestricted layer that control access to a path: one with
133
+ * conditions (a role gate), a 4xx status (a refusal), or a line not read as a rule at all, which may
134
+ * be either. A plain rewrite (`200` with no conditions) only serves a path from elsewhere, so an
135
+ * editor may still redirect it, for instance to a replacement file.
136
+ */
137
+ function guardSources(text) {
138
+ return text.split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')).flatMap(line => {
139
+ const rule = parseRedirectRule(line);
140
+ if (rule && rule.conditions.length === 0 && !/^4/.test(rule.status ?? ''))
141
+ return [];
142
+ return [rule?.source ?? line.split(/\s+/)[0]];
143
+ });
144
+ }
145
+ /** Why a restricted layer's line may not be merged, or `undefined` when it may. */
146
+ function refusal(rule, guards) {
147
+ if (!rule)
148
+ return 'not read as a rule';
149
+ if (!isPlainRedirect(rule))
150
+ return 'only a redirect with a 3xx status and no conditions is allowed here';
151
+ const guard = guards.find(g => overlaps(g, rule.source));
152
+ if (guard)
153
+ return `${guard} is guarded in code`;
154
+ return undefined;
155
+ }
156
+ /**
157
+ * Whether some request path could match both sources. Deliberately looser than any host: paths are
158
+ * compared decoded and case-insensitively, without repeated or trailing slashes, a `:param` matches any
159
+ * one segment, and a segment with a `*` matches anything from there on, nothing included (so
160
+ * `/admin/*` covers `/admin`). A guard must not be passed by spelling its path another way.
161
+ */
162
+ function overlaps(a, b) {
163
+ const as = segments(a);
164
+ const bs = segments(b);
165
+ for (let i = 0;; i++) {
166
+ const x = as[i];
167
+ const y = bs[i];
168
+ if (x?.includes('*') || y?.includes('*'))
169
+ return true;
170
+ if (x === undefined || y === undefined)
171
+ return x === y;
172
+ if (x !== y && !x.startsWith(':') && !y.startsWith(':'))
173
+ return false;
174
+ }
175
+ }
176
+ function segments(source) {
177
+ let path = pathOf(source);
178
+ try {
179
+ path = decodeURIComponent(path);
180
+ }
181
+ catch {
182
+ // Malformed escapes: compare as written.
183
+ }
184
+ return path.toLowerCase().split('/').filter(Boolean);
185
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-scan.d.ts","sourceRoot":"","sources":["../src/route-scan.ts"],"names":[],"mappings":"AAEA,6EAA6E;AAC7E,MAAM,WAAW,mBAAmB;IACnC,+EAA+E;IAC/E,WAAW,EAAE,MAAM,EAAE,CAAA;IACrB,+DAA+D;IAC/D,GAAG,EAAE,MAAM,EAAE,CAAA;CACb;AAQD,yEAAyE;AACzE,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,mBAAmB,CAcxE"}
@@ -0,0 +1,23 @@
1
+ import { analyzeAstroSource } from "./astro-source-analysis.js";
2
+ function appendUnique(collections, seen, collectionName) {
3
+ if (seen.has(collectionName))
4
+ return;
5
+ seen.add(collectionName);
6
+ collections.push(collectionName);
7
+ }
8
+ /** Find the content collections read by an Astro route's frontmatter. */
9
+ export function scanRouteCollections(source) {
10
+ const analysis = analyzeAstroSource(source);
11
+ const all = [];
12
+ const allSeen = new Set();
13
+ const staticPaths = [];
14
+ const staticPathsSeen = new Set();
15
+ for (const call of analysis.collectionCalls) {
16
+ if (call.accessor !== 'getCollection' || call.collectionName === null)
17
+ continue;
18
+ appendUnique(all, allSeen, call.collectionName);
19
+ if (call.inExportedGetStaticPaths)
20
+ appendUnique(staticPaths, staticPathsSeen, call.collectionName);
21
+ }
22
+ return { staticPaths, all };
23
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-port.d.ts","sourceRoot":"","sources":["../src/schema-port.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,SAAS;IACzB,+EAA+E;IAC/E,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAA;IACzB,OAAO,EAAE,MAAM,CAAA;CACf;AAED,MAAM,MAAM,eAAe,GAAG;IAAE,OAAO,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,SAAS,EAAE,CAAA;CAAE,CAAA;AAEzF,MAAM,WAAW,UAAU;IAC1B,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,CAAC,CAAA;CACnD;AAED,kGAAkG;AAClG,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;AAEpD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAInF;AAED,mGAAmG;AACnG,wBAAgB,SAAS,CAAC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAE1F"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The port through which a project's real collection schemas reach the checker.
3
+ *
4
+ * `cms-core` deliberately does not load them. Getting a live schema means importing the
5
+ * project's `content.config.ts`, which executes project code, needs an `astro:content`
6
+ * stub installed process-wide, and caches the module for the life of the process — all
7
+ * fine in a one-shot CLI, none of it acceptable inside the long-running dev server and
8
+ * sidecar that also load this package. The CLI does the loading and injects the result.
9
+ *
10
+ * `safeParse` is async because that is how Astro validates content
11
+ * (`astro/dist/content/utils.js` calls `safeParseAsync`), so a schema carrying an async
12
+ * refinement is legal and a synchronous parse would throw on it.
13
+ */
14
+ /**
15
+ * Render an issue as a finding's `field` and `message`.
16
+ *
17
+ * Shared so the two live checkers phrase the same rejection identically — they report
18
+ * different actions but the same schema verdict, and a reader comparing them should not
19
+ * have to wonder whether a wording difference means something.
20
+ */
21
+ export function describeIssue(issue) {
22
+ if (issue.path.length === 0)
23
+ return { message: issue.message };
24
+ const field = issue.path.join('.');
25
+ return { field, message: `${field}: ${issue.message}` };
26
+ }
27
+ /** A collection's live schema, if it has one. Guards against inherited `Object.prototype` keys. */
28
+ export function schemaFor(schemas, collection) {
29
+ return Object.hasOwn(schemas, collection) ? schemas[collection] : undefined;
30
+ }
@@ -15,8 +15,8 @@
15
15
  * Every function here is total. A schema that throws answers "I don't know", which callers read
16
16
  * as "report nothing" — a rule that cannot get evidence has to stay quiet rather than guess.
17
17
  */
18
- import type { LoadedEntry } from './check-entries';
19
- import type { LiveSchema } from './schema-port';
18
+ import type { LoadedEntry } from './check-entries.ts';
19
+ import type { LiveSchema } from './schema-port.ts';
20
20
  /** One field in one record: the accepted entry to start from, and where the field sits in it. */
21
21
  export interface ProbePoint {
22
22
  /** Never mutated — every probe works on a clone. */
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-probe.d.ts","sourceRoot":"","sources":["../src/schema-probe.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AACrD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAElD,iGAAiG;AACjG,MAAM,WAAW,UAAU;IAC1B,oDAAoD;IACpD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAA;CACzB;AAED,gHAAgH;AAChH,eAAO,MAAM,OAAO,GAAI,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,MAAM,KAAG,UAA+C,CAAA;AAwDtH;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAKzF;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAE5F;AAED,0GAA0G;AAC1G,wBAAsB,cAAc,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAE5G;AAED;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC,CAWjI"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Ask a live schema what it thinks of one field, without the rest of the record answering for it.
3
+ *
4
+ * The static rules read the config's source and the live rules read the schema's verdict on a
5
+ * whole entry. Neither can say what the schema believes about a *single* field, which is what the
6
+ * drift rules need: whether it insists on the key, whether it would take text there.
7
+ *
8
+ * The technique is the same for every question. Start from an entry the schema already accepts,
9
+ * change exactly one value, parse again, and look at where the issues land. Starting from an
10
+ * accepted entry is what makes the answer attributable — on a record the schema already rejects,
11
+ * every probe comes back "rejected" and means nothing. Reading the issue's *path* rather than
12
+ * overall success is the other half: a schema with a cross-field refinement can fail for reasons
13
+ * that have nothing to do with the field being probed.
14
+ *
15
+ * Every function here is total. A schema that throws answers "I don't know", which callers read
16
+ * as "report nothing" — a rule that cannot get evidence has to stay quiet rather than guess.
17
+ */
18
+ /** The point for a top-level field of `seed`. The probe sets the key, so the seed need not already carry it. */
19
+ export const pointAt = (seed, field) => ({ record: seed, path: [field] });
20
+ /**
21
+ * Values chosen so that no realistic schema accepts all four.
22
+ *
23
+ * They answer one question: does the schema have an opinion about this path at all? A field the
24
+ * parser invented, or one landing in a `passthrough()`/`catchall()` object, accepts anything and
25
+ * must not be reported — a rule firing on a field the schema never governs is a false positive on
26
+ * a project that is fine.
27
+ */
28
+ const GOVERNANCE_PROBES = [{ __nuaProbe: true }, ['__nua_probe__'], 918_273.456, null];
29
+ const isContainer = (value) => typeof value === 'object' && value !== null;
30
+ /** A copy of the record with one value changed, or `null` when it cannot be built. */
31
+ function mutated(point, mutation) {
32
+ let copy;
33
+ try {
34
+ copy = structuredClone(point.record);
35
+ }
36
+ catch {
37
+ // Frontmatter is plain data, so this should not happen — but an unclonable value must cost
38
+ // this one probe, not the run.
39
+ return null;
40
+ }
41
+ let parent = copy;
42
+ for (const segment of point.path.slice(0, -1)) {
43
+ if (!isContainer(parent))
44
+ return null;
45
+ parent = parent[segment];
46
+ }
47
+ const last = point.path.at(-1);
48
+ if (last === undefined || !isContainer(parent))
49
+ return null;
50
+ if ('remove' in mutation)
51
+ delete parent[last];
52
+ else
53
+ parent[last] = mutation.set;
54
+ return copy;
55
+ }
56
+ async function probe(schema, point, mutation) {
57
+ const value = mutated(point, mutation);
58
+ if (value === null)
59
+ return 'unknown';
60
+ try {
61
+ const result = await schema.safeParse(value);
62
+ if (result.success)
63
+ return 'accepted';
64
+ const here = result.issues.some(issue => point.path.every((segment, index) => issue.path[index] === segment));
65
+ return here ? 'rejected-here' : 'rejected-elsewhere';
66
+ }
67
+ catch {
68
+ return 'unknown';
69
+ }
70
+ }
71
+ /**
72
+ * Whether the schema constrains this path at all.
73
+ *
74
+ * True as soon as one probe value is refused *at the path*. False means either a schema that takes
75
+ * anything here or one that could not be asked; both are reasons to report nothing.
76
+ */
77
+ export async function governsPath(schema, point) {
78
+ for (const value of GOVERNANCE_PROBES) {
79
+ if (await probe(schema, point, { set: value }) === 'rejected-here')
80
+ return true;
81
+ }
82
+ return false;
83
+ }
84
+ /**
85
+ * Whether the schema takes the record with this key removed.
86
+ *
87
+ * Deliberately strict — the whole record has to parse, not merely avoid an issue at this path. The
88
+ * claim built on it is that the editor blocks a save the build would accept, and a record failing
89
+ * elsewhere is not evidence the build would accept anything.
90
+ */
91
+ export async function acceptsMissing(schema, point) {
92
+ return await probe(schema, point, { remove: true }) === 'accepted';
93
+ }
94
+ /** Whether the schema refuses `value` *at this path*, as opposed to failing for some unrelated reason. */
95
+ export async function rejectsValueAt(schema, point, value) {
96
+ return await probe(schema, point, { set: value }) === 'rejected-here';
97
+ }
98
+ /**
99
+ * The first entry the schema accepts, or `undefined` when there is none.
100
+ *
101
+ * Shared with the write check so both mean the same thing by "a record the editor is really
102
+ * sitting on". Seeding from a rejected entry would blame every probe for that entry's own
103
+ * problems, which `check-live.ts` already reports.
104
+ */
105
+ export async function firstAcceptedEntry(schema, entries) {
106
+ for (const entry of entries) {
107
+ if (!entry.frontmatter)
108
+ continue;
109
+ try {
110
+ const result = await schema.safeParse(entry.frontmatter);
111
+ if (result.success)
112
+ return entry.frontmatter;
113
+ }
114
+ catch {
115
+ // A schema that throws on an entry has not accepted it; `check-live.ts` reports the throw.
116
+ }
117
+ }
118
+ return undefined;
119
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,KAAK,YAAY,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAiBjH;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,SAAS,CAe7G;AAED;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CACtC,GAAG,EAAE,IAAI,CAAC,oBAAoB,EAAE,UAAU,CAAC,EAC3C,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,GACvC,MAAM,GAAG,SAAS,CAKpB;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAShD;AAED,mFAAmF;AACnF,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAE9E;AAED;;;GAGG;AACH,OAAO,EAAE,OAAO,EAAE,CAAA;AAElB,gGAAgG;AAChG,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;CACnC;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,gBAAgB,GAAG,SAAS,GAAG,MAAM,CAYpG;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,0BAA0B,CACzC,MAAM,EAAE,SAAS,gBAAgB,EAAE,EACnC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC3B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CASzB;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAO/C;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAa3E"}
package/dist/shared.js ADDED
@@ -0,0 +1,163 @@
1
+ import { slugify } from '@nuasite/cms-types';
2
+ /**
3
+ * Coerce a frontmatter value into a URL path segment. Strings pass through;
4
+ * numbers and booleans are stringified (YAML auto-coerces `year: 2024` → number,
5
+ * `draft: true` → boolean); dates use their ISO calendar day (`2024-01-15`), which
6
+ * is what YAML produces a `Date` from. Anything else — `null`/`undefined` (missing)
7
+ * or objects/arrays (not addressable as a single segment) — yields `undefined`,
8
+ * which voids the whole rule so callers fall through to other pathname sources.
9
+ */
10
+ function pathSegmentValue(raw) {
11
+ if (typeof raw === 'string')
12
+ return raw;
13
+ if (typeof raw === 'number' || typeof raw === 'boolean')
14
+ return String(raw);
15
+ if (raw instanceof Date)
16
+ return raw.toISOString().slice(0, 10);
17
+ return undefined;
18
+ }
19
+ /**
20
+ * Compose a collection entry's page URL from a declarative {@link PathnameSpec}
21
+ * and the entry's frontmatter `data`.
22
+ *
23
+ * Each segment resolves to either a fixed `literal` or the value of `data[field]`
24
+ * (optionally remapped through the segment's `map`). Field values are coerced via
25
+ * {@link pathSegmentValue} — strings, numbers, booleans, and dates all resolve.
26
+ * Resolved segments are joined with `/`, prefixed with a single leading `/`,
27
+ * collapsed of duplicate slashes, and stripped of any trailing slash. If any
28
+ * `{ field }` segment's value is missing or not coercible (null/object/array) the
29
+ * whole rule yields `undefined`, so callers fall through to their existing
30
+ * pathname sources.
31
+ */
32
+ export function computePathnameFromSpec(spec, data) {
33
+ const segments = [];
34
+ for (const seg of spec) {
35
+ if ('literal' in seg) {
36
+ segments.push(seg.literal);
37
+ continue;
38
+ }
39
+ const value = pathSegmentValue(data[seg.field]);
40
+ if (value === undefined)
41
+ return undefined;
42
+ segments.push(seg.map && Object.hasOwn(seg.map, value) ? seg.map[value] : value);
43
+ }
44
+ const path = ('/' + segments.join('/')).replace(/\/{2,}/g, '/').replace(/\/+$/, '');
45
+ return path === '' ? '/' : path;
46
+ }
47
+ /**
48
+ * Resolve a collection entry's declarative `cms.pathname` to a page URL — the
49
+ * single source of spec-driven pathname resolution shared by the dev middleware
50
+ * and the build-time manifest writer, so the two never drift.
51
+ *
52
+ * A declared `pathname` spec is the highest-priority source for an entry's URL
53
+ * (it wins over the rendered-route pathname); this helper returns the spec-derived
54
+ * URL, or `undefined` when no spec is declared or the spec doesn't resolve for
55
+ * this entry, in which case callers fall back to their own route-derived sources.
56
+ */
57
+ export function resolvePathnameFromSpec(def, data) {
58
+ // parseCmsPathname never yields an empty array (it returns undefined instead),
59
+ // so a present `pathname` is always a usable spec.
60
+ if (!def.pathname)
61
+ return undefined;
62
+ return computePathnameFromSpec(def.pathname, data ?? {});
63
+ }
64
+ /**
65
+ * Slugify with diacritics normalization for href paths.
66
+ * "Lidé" → "lide", "Aktuálně z nezisku" → "aktualne-z-nezisku"
67
+ */
68
+ export function slugifyHref(text) {
69
+ return '/' + text
70
+ .normalize('NFD')
71
+ .replace(/[\u0300-\u036f]/g, '')
72
+ .toLowerCase()
73
+ .trim()
74
+ .replace(/[^\w\s-]/g, '')
75
+ .replace(/[\s_]+/g, '-')
76
+ .replace(/^-+|-+$/g, '');
77
+ }
78
+ /** Runtime guard: a non-null, non-array object usable as a string-keyed record. */
79
+ export function isPlainRecord(value) {
80
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
81
+ }
82
+ /**
83
+ * Re-exported from `@nuasite/cms-types` so the server and every client slugify identically —
84
+ * a host deriving a slug locally is predicting this write. See `cms-types/src/slug.ts`.
85
+ */
86
+ export { slugify };
87
+ /**
88
+ * Apply a derived field's named transform to its source value.
89
+ *
90
+ * `slug` reuses `slugify` deliberately, and `slugify` **keeps `/`** — it is written to name
91
+ * files on disk, where a nested entry path has to survive. So `transform: 'slug'` on a value
92
+ * that already contains a slash keeps it (`"news/2024"` → `"news/2024"`). That is a conscious
93
+ * reuse of the existing function, not a bug: the transform is documented as "the `slugifyHref`
94
+ * fold without the leading slash", and every other separator still collapses to `-`.
95
+ */
96
+ export function applyDerivedTransform(value, transform) {
97
+ switch (transform) {
98
+ case 'copy':
99
+ return value;
100
+ case 'slug':
101
+ return slugify(value);
102
+ // `slugifyHref` is the default so a declared `derivedFrom: 'category'` produces exactly
103
+ // what `detectDerivedHrefFields` used to infer — migrating an inferred field to a
104
+ // declared one must not rewrite any data.
105
+ default:
106
+ return slugifyHref(value);
107
+ }
108
+ }
109
+ /**
110
+ * Values every derived field in `fields` should hold given `data`, keyed by field name.
111
+ *
112
+ * The single definition of "recompute derived fields", shared by every write path in
113
+ * `cms-core`. A source field that is missing, not a string, or blank yields no entry at all —
114
+ * the existing value is left alone rather than blanked, because "no source" is not "empty
115
+ * result". An empty source is deliberately in that group: every transform maps `''` to
116
+ * something that looks like a value (`slugifyHref('')` is `'/'`, a link to the site root), and
117
+ * writing that into content is worse than leaving the previous value in place. Whitespace-only
118
+ * counts as empty for the same reason — it slugifies to the same thing.
119
+ *
120
+ * `hidden` is deliberately not consulted: an author who sets `hidden: false` on a declared
121
+ * derived field still gets it computed, they only also get to see it.
122
+ */
123
+ export function computeDerivedFieldUpdates(fields, data) {
124
+ const updates = {};
125
+ for (const field of fields) {
126
+ if (!field.derivedFrom)
127
+ continue;
128
+ const source = data[field.derivedFrom];
129
+ if (typeof source !== 'string' || source.trim() === '')
130
+ continue;
131
+ updates[field.name] = applyDerivedTransform(source, field.derivedTransform);
132
+ }
133
+ return updates;
134
+ }
135
+ /**
136
+ * Escape HTML special characters to prevent injection.
137
+ * Covers &, <, >, ", and ' — the full set needed for both text content and attribute values.
138
+ */
139
+ export function escapeHtml(text) {
140
+ return text
141
+ .replace(/&/g, '&amp;')
142
+ .replace(/</g, '&lt;')
143
+ .replace(/>/g, '&gt;')
144
+ .replace(/"/g, '&quot;')
145
+ .replace(/'/g, '&#39;');
146
+ }
147
+ /**
148
+ * Compute a POSIX-style relative import path from one root-relative file to another.
149
+ * Both paths are forward-slash POSIX paths relative to the project root. Ensures
150
+ * the result starts with `./` or `../`.
151
+ */
152
+ export function relativeImportPath(fromFile, toFile) {
153
+ const fromSegments = fromFile.split('/').slice(0, -1);
154
+ const toSegments = toFile.split('/');
155
+ let common = 0;
156
+ while (common < fromSegments.length && common < toSegments.length - 1 && fromSegments[common] === toSegments[common]) {
157
+ common++;
158
+ }
159
+ const up = fromSegments.slice(common).map(() => '..');
160
+ const down = toSegments.slice(common);
161
+ const joined = [...up, ...down].join('/');
162
+ return joined.startsWith('.') ? joined : `./${joined}`;
163
+ }