@nuasite/cms-core 0.64.3 → 0.65.1

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,164 @@
1
+ import { matchesMediaType, } from '@nuasite/cms-types';
2
+ /** The value of a `?type=` parameter, or `null` when it names no tab we know. */
3
+ export function parseMediaTypeFilter(raw) {
4
+ if (raw === null || raw === undefined || raw === '')
5
+ return 'all';
6
+ return raw === 'all' || raw === 'photo' || raw === 'graphic' || raw === 'video' || raw === 'document' ? raw : null;
7
+ }
8
+ /**
9
+ * A cursor `listFilteredMedia` refused: not one it minted, or minted under a different tab. A host
10
+ * answers it with a 400 and the message, never by listing from the start.
11
+ */
12
+ export class MediaCursorError extends Error {
13
+ name = 'MediaCursorError';
14
+ }
15
+ export const MEDIA_INVALID_CURSOR = 'Invalid media cursor';
16
+ export const MEDIA_CURSOR_TYPE_MISMATCH = 'This cursor continues a listing filtered by a different ?type=. Start the listing again when the filter changes';
17
+ const FILTERED_CURSOR_VERSION = 1;
18
+ function toBase64Url(text) {
19
+ let binary = '';
20
+ for (const byte of new TextEncoder().encode(text))
21
+ binary += String.fromCharCode(byte);
22
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
23
+ }
24
+ function fromBase64Url(raw) {
25
+ const binary = atob(raw.replace(/-/g, '+').replace(/_/g, '/'));
26
+ return new TextDecoder().decode(Uint8Array.from(binary, char => char.charCodeAt(0)));
27
+ }
28
+ function encodeFilteredCursor(position, type) {
29
+ const { source, skip, size } = position;
30
+ return toBase64Url(JSON.stringify({ fv: FILTERED_CURSOR_VERSION, type, source, skip, size }));
31
+ }
32
+ /**
33
+ * The tab and position a filtered cursor carries, or `null` when `raw` is not one `listFilteredMedia`
34
+ * minted. A host that also serves unfiltered listings uses it to refuse one followed without its
35
+ * `?type=`, which the adapter would otherwise read as its own cursor.
36
+ */
37
+ export function decodeFilteredMediaCursor(raw) {
38
+ let parsed;
39
+ try {
40
+ parsed = JSON.parse(fromBase64Url(raw));
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ if (typeof parsed !== 'object' || parsed === null || !('fv' in parsed) || parsed.fv !== FILTERED_CURSOR_VERSION)
46
+ return null;
47
+ const type = 'type' in parsed && typeof parsed.type === 'string' ? parseMediaTypeFilter(parsed.type) : null;
48
+ if (type === null || type === 'all')
49
+ return null;
50
+ const source = 'source' in parsed ? parsed.source : undefined;
51
+ if (source !== undefined && typeof source !== 'string')
52
+ return null;
53
+ const skip = 'skip' in parsed ? parsed.skip : undefined;
54
+ const size = 'size' in parsed ? parsed.size : undefined;
55
+ if (typeof skip !== 'number' || !Number.isSafeInteger(skip) || skip < 0)
56
+ return null;
57
+ // The cursor travels through the client, so its size is held to what this module would mint:
58
+ // otherwise a forged one asks the source for any number of items, past every `limit` clamp.
59
+ if (typeof size !== 'number' || !Number.isSafeInteger(size) || size < MIN_SOURCE_PAGE || size > MAX_FILTERED_MEDIA_LIMIT)
60
+ return null;
61
+ if (skip > size)
62
+ return null;
63
+ return { type, source, skip, size };
64
+ }
65
+ /**
66
+ * The smallest source page a filtered listing reads. A tab that matches one item in ten would
67
+ * otherwise spend a source round trip per handful of matches, and against the local adapter each
68
+ * round trip re-reads the whole folder.
69
+ */
70
+ const MIN_SOURCE_PAGE = 200;
71
+ /**
72
+ * The largest filtered page, and so the largest source page. The same bound both HTTP layers put on
73
+ * an unfiltered `limit`, applied here again so a caller that forgets to clamp cannot widen the scan.
74
+ */
75
+ export const MAX_FILTERED_MEDIA_LIMIT = 1000;
76
+ /**
77
+ * Source items one filtered page may ask for, all pages together: twenty pages at the smallest
78
+ * source page. A "Documents" tab over a library of photos matches nothing, and without a bound
79
+ * that is a walk of the whole library in a single request.
80
+ */
81
+ const MAX_SCANNED = 20 * MIN_SOURCE_PAGE;
82
+ /** `limit` held to `[1, MAX_FILTERED_MEDIA_LIMIT]`; one that is not a finite number sets no target. */
83
+ function clampLimit(limit) {
84
+ if (limit === undefined || !Number.isFinite(limit))
85
+ return undefined;
86
+ return Math.min(Math.max(Math.floor(limit), 1), MAX_FILTERED_MEDIA_LIMIT);
87
+ }
88
+ /**
89
+ * One page of a cursor-paged listing, filtered to `type`.
90
+ *
91
+ * A filter cannot be pushed into the adapters: they page over a filesystem, a bucket or a remote
92
+ * API, each with its own cursor. So it is applied here, above whichever one answered, by pulling
93
+ * further pages until this one is full. That keeps the cost of a filter inside a single request:
94
+ * without it the client is the one that drains, one round trip per page, and every round trip that
95
+ * reaches the sidecar's project scan makes it re-walk the project.
96
+ *
97
+ * A filtered page holds at most `limit` items. The source is read at `max(limit, 200)` items a
98
+ * page, so a page usually fills halfway through a source page; the cursor it hands back is one of
99
+ * ours, bound to `type`, and resumes by re-reading that source page and skipping what was already
100
+ * listed. That relies on a source answering the same cursor and size with the same page, which an
101
+ * offset or continuation-token listing does as long as nothing is written in between: the same
102
+ * caveat any offset pager carries. An unfiltered listing is passed straight through, the source's
103
+ * own cursor included.
104
+ *
105
+ * A cursor this did not mint, or minted under another tab, throws `MediaCursorError`.
106
+ * `hasMore` can be true on a page short of `limit`: that is what the scan bound below leaves behind.
107
+ */
108
+ export async function listFilteredMedia(list, options,
109
+ /**
110
+ * How many source items one filtered page may ask for, counted as the larger of what each source
111
+ * page was asked for and what it returned. Reaching it just ends the page early. `hasMore` still
112
+ * says there is more, so the caller can ask again. The first source page is always read.
113
+ */
114
+ maxScanned = MAX_SCANNED) {
115
+ const type = options.type ?? 'all';
116
+ if (type === 'all')
117
+ return await list(options);
118
+ const limit = clampLimit(options.limit);
119
+ let position = { source: undefined, skip: 0, size: Math.max(limit ?? 0, MIN_SOURCE_PAGE) };
120
+ if (options.cursor !== undefined) {
121
+ const decoded = decodeFilteredMediaCursor(options.cursor);
122
+ if (decoded === null)
123
+ throw new MediaCursorError(MEDIA_INVALID_CURSOR);
124
+ if (decoded.type !== type)
125
+ throw new MediaCursorError(MEDIA_CURSOR_TYPE_MISMATCH);
126
+ position = decoded;
127
+ }
128
+ const items = [];
129
+ let folders;
130
+ const done = (hasMore, next) => ({
131
+ items,
132
+ folders: folders ?? [],
133
+ hasMore,
134
+ cursor: next === undefined ? undefined : encodeFilteredCursor(next, type),
135
+ appliedType: type,
136
+ });
137
+ for (let scanned = 0;;) {
138
+ const page = await list({ ...options, cursor: position.source, limit: position.size });
139
+ folders ??= page.folders;
140
+ const pageItems = page.items;
141
+ scanned += Math.max(position.size, pageItems.length);
142
+ for (let index = position.skip; index < pageItems.length; index++) {
143
+ const item = pageItems[index];
144
+ if (item === undefined || !matchesMediaType(item.contentType, type))
145
+ continue;
146
+ items.push(item);
147
+ if (limit === undefined || items.length < limit)
148
+ continue;
149
+ // Full. Stop at this item when the source page still holds a match after it; otherwise
150
+ // the page is spent and the listing continues the way the source does.
151
+ const matchesLeft = pageItems.slice(index + 1).some(later => matchesMediaType(later.contentType, type));
152
+ if (matchesLeft)
153
+ return done(true, { ...position, skip: index + 1 });
154
+ break;
155
+ }
156
+ const next = page.hasMore && page.cursor !== undefined ? { source: page.cursor, skip: 0, size: position.size } : undefined;
157
+ const full = limit !== undefined && items.length >= limit;
158
+ // An adapter that reports more but hands back no cursor cannot be advanced: say there is more
159
+ // anyway, with no cursor, rather than claim the listing ended.
160
+ if (full || next === undefined || scanned >= maxScanned)
161
+ return done(page.hasMore, next);
162
+ position = next;
163
+ }
164
+ }
@@ -2,29 +2,29 @@
2
2
  * Everything cms-core offers that runs without `node:fs`. The package root resolves here under the
3
3
  * `workerd` condition; the default root adds the Node filesystem and the local media adapter.
4
4
  */
5
- export { resolveAssetCandidates } from './asset-paths';
6
- export { analyzeAstroScript, analyzeAstroSource, type AstroCollectionBinding, type AstroContentAccessor, type AstroContentCall, type AstroSourceAnalysis, type AstroSourceImport, } from './astro-source-analysis';
7
- export { type ByteRange, resolveByteRange } from './byte-range';
8
- export { checkContent, type CheckContentOptions, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check';
9
- export { collectionKind, entryStem, loadCollections, type LoadedCollection, type LoadedCollections, type LoadedEntry, normalizeBase, parseEntry, } from './check-entries';
10
- export { checkAgainstSchemas, type LiveCheckInput } from './check-live';
11
- export { checkFieldShapes, type ShapeCheckInput } from './check-shape';
12
- export { checkEditorWrites, type WriteCheckInput } from './check-write';
13
- export { collectionScanReport, scanCollections } from './collection-scanner';
14
- export { scanComponentDefinitions } from './component-registry';
15
- export { classifyEmptyContentConfig, CONTENT_CONFIG_PATHS, type ContentConfigRead, type DeclaredCollection, type EmptyContentConfigReason, type ParseCache, parseConfigSource, parseContentConfig, type ParsedCollection, type ParsedConfig, type ParsedField, type ParsedReference, readContentConfig, UNREAD_CONTENT_CONFIG_PATHS, } from './content-config-ast';
16
- export { createCmsCore } from './core';
17
- export type { CmsCore, CmsCoreOptions } from './core';
18
- export { applyCreateRouteFields, blankFieldValue, blankRequiredFields, type CollectionKind, type CreateWriteField, isBlankFieldValue, newEntryFrontmatter, newRepeaterItem, normalizeCreateWrite, omitEmptyOnCreate, type RepeaterItemField, type RequiredGuardField, seedValueForRequiredField, withoutBlankArrayItems, type WriteModelField, } from './editor-write-model';
19
- export { globMayMatchUnder, globToRegExp, UnreadableDirectoryError } from './fs/glob';
20
- export { type CmsChangeset, type CmsCommit, CmsCommitConflictError, type CmsFileVersion, type CmsStagedChange, commitChangeset, createStagedFileSystem, digestBytes, type StagedFileSystem, versionMatches, versionOf, } from './fs/staged';
21
- export type { CmsFileSystem, GlobOptions } from './fs/types';
22
- export { type AddArrayItemInput, type CreateEntryInput, ensureMdxImports, type EntryAsset, type EntryOpsDeps, type GetEntryResult, parseFrontmatter, type RemoveArrayItemInput, serializeFrontmatter, type UpdateEntryInput, } from './handlers/entry-ops';
23
- export { type ContemberStorageOptions, createContemberStorageAdapter, createFileSystemStorageAdapter, createS3StorageAdapter, decodeFilteredMediaCursor, type FileSystemStorageOptions, getFileExtension, isUnsafeFolder, listFilteredMedia, listProjectImages, type ListProjectImagesOptions, MEDIA_CURSOR_TYPE_MISMATCH, MEDIA_INVALID_CURSOR, MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND, MediaCursorError, mediaErrorStatus, MIME_BY_EXT, mimeFromExt, parseMediaTypeFilter, type S3StorageOptions, uploadsDirRelativeToRoot, } from './media/index';
24
- export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast';
25
- export { CLOUDFLARE_REDIRECT_LIMITS, CMS_REDIRECTS_FILE, type MergedRedirects, mergeRedirects, parseRedirectRule, type RedirectLayer, type RedirectLine, type RedirectRuleLine, } from './redirects';
26
- export { type RouteCollectionScan, scanRouteCollections } from './route-scan';
27
- export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port';
28
- export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe';
29
- export { applyDerivedTransform, computeDerivedFieldUpdates, computePathnameFromSpec, type DerivedFieldSpec, escapeHtml, relativeImportPath, resolvePathnameFromSpec, slugify, slugifyHref, } from './shared';
5
+ export { resolveAssetCandidates } from './asset-paths.ts';
6
+ export { analyzeAstroScript, analyzeAstroSource, type AstroCollectionBinding, type AstroContentAccessor, type AstroContentCall, type AstroSourceAnalysis, type AstroSourceImport, } from './astro-source-analysis.ts';
7
+ export { type ByteRange, resolveByteRange } from './byte-range.ts';
8
+ export { collectionKind, entryStem, loadCollections, type LoadedCollection, type LoadedCollections, type LoadedEntry, normalizeBase, parseEntry, } from './check-entries.ts';
9
+ export { checkAgainstSchemas, type LiveCheckInput } from './check-live.ts';
10
+ export { checkFieldShapes, type ShapeCheckInput } from './check-shape.ts';
11
+ export { checkEditorWrites, type WriteCheckInput } from './check-write.ts';
12
+ export { checkContent, type CheckContentOptions, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check.ts';
13
+ export { collectionScanReport, scanCollections } from './collection-scanner.ts';
14
+ export { scanComponentDefinitions } from './component-registry.ts';
15
+ export { classifyEmptyContentConfig, CONTENT_CONFIG_PATHS, type ContentConfigRead, type DeclaredCollection, type EmptyContentConfigReason, type ParseCache, parseConfigSource, parseContentConfig, type ParsedCollection, type ParsedConfig, type ParsedField, type ParsedReference, readContentConfig, UNREAD_CONTENT_CONFIG_PATHS, } from './content-config-ast.ts';
16
+ export { createCmsCore } from './core.ts';
17
+ export type { CmsCore, CmsCoreOptions } from './core.ts';
18
+ export { applyCreateRouteFields, blankFieldValue, blankRequiredFields, type CollectionKind, type CreateWriteField, isBlankFieldValue, newEntryFrontmatter, newRepeaterItem, normalizeCreateWrite, omitEmptyOnCreate, type RepeaterItemField, type RequiredGuardField, seedValueForRequiredField, withoutBlankArrayItems, type WriteModelField, } from './editor-write-model.ts';
19
+ export { globMayMatchUnder, globToRegExp, UnreadableDirectoryError } from './fs/glob.ts';
20
+ export { type CmsChangeset, type CmsCommit, CmsCommitConflictError, type CmsFileVersion, type CmsStagedChange, commitChangeset, createStagedFileSystem, digestBytes, type StagedFileSystem, versionMatches, versionOf, } from './fs/staged.ts';
21
+ export type { CmsFileSystem, GlobOptions } from './fs/types.ts';
22
+ export { type AddArrayItemInput, type CreateEntryInput, ensureMdxImports, type EntryAsset, type EntryOpsDeps, type GetEntryResult, parseFrontmatter, type RemoveArrayItemInput, serializeFrontmatter, type UpdateEntryInput, } from './handlers/entry-ops.ts';
23
+ export { type ContemberStorageOptions, createContemberStorageAdapter, createFileSystemStorageAdapter, createS3StorageAdapter, decodeFilteredMediaCursor, type FileSystemStorageOptions, getFileExtension, isUnsafeFolder, listFilteredMedia, listProjectImages, type ListProjectImagesOptions, MEDIA_CURSOR_TYPE_MISMATCH, MEDIA_INVALID_CURSOR, MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND, MediaCursorError, mediaErrorStatus, MIME_BY_EXT, mimeFromExt, parseMediaTypeFilter, type S3StorageOptions, uploadsDirRelativeToRoot, } from './media/index.ts';
24
+ export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast.ts';
25
+ export { CLOUDFLARE_REDIRECT_LIMITS, CMS_REDIRECTS_FILE, type MergedRedirects, mergeRedirects, parseRedirectRule, type RedirectLayer, type RedirectLine, type RedirectRuleLine, } from './redirects.ts';
26
+ export { type RouteCollectionScan, scanRouteCollections } from './route-scan.ts';
27
+ export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port.ts';
28
+ export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe.ts';
29
+ export { applyDerivedTransform, computeDerivedFieldUpdates, computePathnameFromSpec, type DerivedFieldSpec, escapeHtml, relativeImportPath, resolvePathnameFromSpec, slugify, slugifyHref, } from './shared.ts';
30
30
  //# sourceMappingURL=portable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portable.d.ts","sourceRoot":"","sources":["../src/portable.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Everything cms-core offers that runs without `node:fs`. The package root resolves here under the
3
+ * `workerd` condition; the default root adds the Node filesystem and the local media adapter.
4
+ */
5
+ export { resolveAssetCandidates } from "./asset-paths.js";
6
+ export { analyzeAstroScript, analyzeAstroSource, } from "./astro-source-analysis.js";
7
+ export { resolveByteRange } from "./byte-range.js";
8
+ export { collectionKind, entryStem, loadCollections, normalizeBase, parseEntry, } from "./check-entries.js";
9
+ export { checkAgainstSchemas } from "./check-live.js";
10
+ export { checkFieldShapes } from "./check-shape.js";
11
+ export { checkEditorWrites } from "./check-write.js";
12
+ export { checkContent, formatCheckReport } from "./check.js";
13
+ export { collectionScanReport, scanCollections } from "./collection-scanner.js";
14
+ export { scanComponentDefinitions } from "./component-registry.js";
15
+ export { classifyEmptyContentConfig, CONTENT_CONFIG_PATHS, parseConfigSource, parseContentConfig, readContentConfig, UNREAD_CONTENT_CONFIG_PATHS, } from "./content-config-ast.js";
16
+ export { createCmsCore } from "./core.js";
17
+ export { applyCreateRouteFields, blankFieldValue, blankRequiredFields, isBlankFieldValue, newEntryFrontmatter, newRepeaterItem, normalizeCreateWrite, omitEmptyOnCreate, seedValueForRequiredField, withoutBlankArrayItems, } from "./editor-write-model.js";
18
+ export { globMayMatchUnder, globToRegExp, UnreadableDirectoryError } from "./fs/glob.js";
19
+ export { CmsCommitConflictError, commitChangeset, createStagedFileSystem, digestBytes, versionMatches, versionOf, } from "./fs/staged.js";
20
+ export { ensureMdxImports, parseFrontmatter, serializeFrontmatter, } from "./handlers/entry-ops.js";
21
+ export { createContemberStorageAdapter, createFileSystemStorageAdapter, createS3StorageAdapter, decodeFilteredMediaCursor, getFileExtension, isUnsafeFolder, listFilteredMedia, listProjectImages, MEDIA_CURSOR_TYPE_MISMATCH, MEDIA_INVALID_CURSOR, MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND, MediaCursorError, mediaErrorStatus, MIME_BY_EXT, mimeFromExt, parseMediaTypeFilter, uploadsDirRelativeToRoot, } from "./media/index.js";
22
+ export { parseProjectCmsConfig, parseProjectCmsConfigSource } from "./project-config-ast.js";
23
+ export { CLOUDFLARE_REDIRECT_LIMITS, CMS_REDIRECTS_FILE, mergeRedirects, parseRedirectRule, } from "./redirects.js";
24
+ export { scanRouteCollections } from "./route-scan.js";
25
+ export { describeIssue, schemaFor } from "./schema-port.js";
26
+ export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, rejectsValueAt } from "./schema-probe.js";
27
+ export { applyDerivedTransform, computeDerivedFieldUpdates, computePathnameFromSpec, escapeHtml, relativeImportPath, resolvePathnameFromSpec, slugify, slugifyHref, } from "./shared.js";
@@ -1,5 +1,5 @@
1
1
  import type { CmsConfig } from '@nuasite/cms-types';
2
- import type { CmsFileSystem } from './fs/types';
2
+ import type { CmsFileSystem } from './fs/types.ts';
3
3
  /**
4
4
  * Parse the project-level CMS config from an Astro config source string: `listStyles` and
5
5
  * the project's language (see {@link parseLocale}), from wherever the config hands the
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-config-ast.d.ts","sourceRoot":"","sources":["../src/project-config-ast.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAgB,MAAM,oBAAoB,CAAA;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAqSlD;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAWrE;AAID,mGAAmG;AACnG,wBAAsB,qBAAqB,CAAC,EAAE,EAAE,aAAa,GAAG,OAAO,CAAC,SAAS,CAAC,CAWjF"}
@@ -0,0 +1,324 @@
1
+ import { parse } from '@babel/parser';
2
+ const EMPTY_CONFIG = { listStyles: [] };
3
+ function parseSource(source) {
4
+ try {
5
+ return parse(source, {
6
+ sourceType: 'module',
7
+ plugins: ['typescript'],
8
+ errorRecovery: true,
9
+ });
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ function collectBindings(ast) {
16
+ const bindings = new Map();
17
+ for (const stmt of ast.program.body) {
18
+ const varDecl = stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'VariableDeclaration'
19
+ ? stmt.declaration
20
+ : stmt.type === 'VariableDeclaration'
21
+ ? stmt
22
+ : null;
23
+ if (!varDecl)
24
+ continue;
25
+ for (const decl of varDecl.declarations) {
26
+ if (decl.id.type === 'Identifier' && decl.init)
27
+ bindings.set(decl.id.name, decl.init);
28
+ }
29
+ }
30
+ return bindings;
31
+ }
32
+ /**
33
+ * The expression under the wrappers that exist for the type checker only — `x as T`,
34
+ * `x satisfies T`, `x!`, `<T>x`. They are gone at runtime, so a config that works there must
35
+ * read the same here: `const LOCALE = 'cs' as const`, `defineConfig({ … } satisfies NuaConfig)`.
36
+ */
37
+ function withoutTypeWrappers(node) {
38
+ let current = node;
39
+ while (current.type === 'TSAsExpression' || current.type === 'TSSatisfiesExpression' || current.type === 'TSNonNullExpression'
40
+ || current.type === 'TSTypeAssertion') {
41
+ current = current.expression;
42
+ }
43
+ return current;
44
+ }
45
+ function resolveExpression(node, bindings, visited = new Set()) {
46
+ let current = withoutTypeWrappers(node);
47
+ while (current.type === 'Identifier') {
48
+ if (visited.has(current.name))
49
+ return current;
50
+ visited.add(current.name);
51
+ const next = bindings.get(current.name);
52
+ if (!next)
53
+ return current;
54
+ current = withoutTypeWrappers(next);
55
+ }
56
+ return current;
57
+ }
58
+ function propertyKeyName(key) {
59
+ if (key.type === 'Identifier')
60
+ return key.name;
61
+ if (key.type === 'StringLiteral')
62
+ return key.value;
63
+ return null;
64
+ }
65
+ function objectPropertyValue(node, keyName, bindings) {
66
+ for (const prop of node.properties) {
67
+ if (prop.type !== 'ObjectProperty')
68
+ continue;
69
+ if (propertyKeyName(prop.key) !== keyName)
70
+ continue;
71
+ return resolveExpression(prop.value, bindings);
72
+ }
73
+ return null;
74
+ }
75
+ function objectAtPath(root, keys, bindings) {
76
+ let current = root;
77
+ for (const key of keys) {
78
+ const value = objectPropertyValue(current, key, bindings);
79
+ if (!value || value.type !== 'ObjectExpression')
80
+ return null;
81
+ current = value;
82
+ }
83
+ return current;
84
+ }
85
+ function staticString(node, bindings) {
86
+ const resolved = resolveExpression(node, bindings);
87
+ if (resolved.type === 'StringLiteral')
88
+ return resolved.value;
89
+ if (resolved.type === 'TemplateLiteral' && resolved.expressions.length === 0) {
90
+ return resolved.quasis[0]?.value.cooked ?? resolved.quasis[0]?.value.raw;
91
+ }
92
+ return undefined;
93
+ }
94
+ function parseListStyle(node, bindings) {
95
+ const resolved = resolveExpression(node, bindings);
96
+ if (resolved.type !== 'ObjectExpression')
97
+ return null;
98
+ const labelNode = objectPropertyValue(resolved, 'label', bindings);
99
+ const classNode = objectPropertyValue(resolved, 'class', bindings);
100
+ if (!labelNode || !classNode)
101
+ return null;
102
+ const label = staticString(labelNode, bindings);
103
+ const className = staticString(classNode, bindings);
104
+ if (label === undefined || className === undefined)
105
+ return null;
106
+ return { label, class: className };
107
+ }
108
+ function parseListStyles(node, bindings) {
109
+ const styles = [];
110
+ for (const element of node.elements) {
111
+ if (!element || element.type === 'SpreadElement')
112
+ continue;
113
+ const style = parseListStyle(element, bindings);
114
+ if (style)
115
+ styles.push(style);
116
+ }
117
+ return styles;
118
+ }
119
+ function configObjectFromDefaultExport(ast, bindings) {
120
+ for (const stmt of ast.program.body) {
121
+ if (stmt.type !== 'ExportDefaultDeclaration')
122
+ continue;
123
+ const declaration = resolveExpression(stmt.declaration, bindings);
124
+ if (declaration.type === 'ObjectExpression')
125
+ return declaration;
126
+ if (declaration.type === 'CallExpression') {
127
+ const firstArg = declaration.arguments[0];
128
+ if (!firstArg || firstArg.type === 'SpreadElement')
129
+ return null;
130
+ const resolvedArg = resolveExpression(firstArg, bindings);
131
+ if (resolvedArg.type === 'ObjectExpression')
132
+ return resolvedArg;
133
+ }
134
+ }
135
+ return null;
136
+ }
137
+ /**
138
+ * The integrations that take the CMS options as a call argument, by the module their default
139
+ * export comes from, with the path to those options inside the first argument:
140
+ * `nuaCms(options)` and `nua({ cms: options })`.
141
+ */
142
+ const CMS_INTEGRATION_OPTIONS_PATH = {
143
+ '@nuasite/cms': [],
144
+ '@nuasite/nua': ['cms'],
145
+ '@nuasite/nua/integration': ['cms'],
146
+ };
147
+ /** Local names the file imports a CMS-carrying integration under, mapped to its options path. */
148
+ function collectCmsIntegrationImports(ast) {
149
+ const imports = new Map();
150
+ for (const stmt of ast.program.body) {
151
+ if (stmt.type !== 'ImportDeclaration')
152
+ continue;
153
+ const optionsPath = CMS_INTEGRATION_OPTIONS_PATH[stmt.source.value];
154
+ if (!optionsPath)
155
+ continue;
156
+ for (const specifier of stmt.specifiers) {
157
+ // `import nuaCms from …` and `import { default as nuaCms } from …`. `@nuasite/nua` also
158
+ // exports its integration by name, as `nua`.
159
+ const importedName = specifier.type === 'ImportDefaultSpecifier'
160
+ ? 'default'
161
+ : specifier.type === 'ImportSpecifier'
162
+ ? propertyKeyName(specifier.imported)
163
+ : null;
164
+ if (importedName === 'default' || (importedName === 'nua' && optionsPath.length > 0))
165
+ imports.set(specifier.local.name, optionsPath);
166
+ }
167
+ }
168
+ return imports;
169
+ }
170
+ /**
171
+ * What the default export's config goes through before Astro sees it: the `defineConfig` of
172
+ * `@nuasite/nua/config`, which adds the nua integration on its own; Astro's, or no call at
173
+ * all, where a `nua` key means nothing; or a function this reader does not know.
174
+ */
175
+ function defaultExportWrapper(ast, bindings) {
176
+ const exported = ast.program.body.find(stmt => stmt.type === 'ExportDefaultDeclaration');
177
+ const declaration = exported?.type === 'ExportDefaultDeclaration' ? resolveExpression(exported.declaration, bindings) : null;
178
+ if (declaration?.type !== 'CallExpression')
179
+ return 'astro';
180
+ // `(defineConfig as any)(…)` and `defineConfig!(…)` call the same function.
181
+ const callee = withoutTypeWrappers(declaration.callee);
182
+ if (callee.type !== 'Identifier')
183
+ return 'unknown';
184
+ for (const stmt of ast.program.body) {
185
+ if (stmt.type !== 'ImportDeclaration' || !stmt.specifiers.some(specifier => specifier.local.name === callee.name))
186
+ continue;
187
+ if (stmt.source.value === '@nuasite/nua/config')
188
+ return 'nua';
189
+ if (stmt.source.value === 'astro/config')
190
+ return 'astro';
191
+ }
192
+ return 'unknown';
193
+ }
194
+ /**
195
+ * The CMS instance a nua integration runs, given the value of its `cms` option (`null` when
196
+ * the option is not set). nua runs a CMS unless told `cms: false`; `true`, nothing, or a
197
+ * value that cannot be read are all an instance — only an object can carry a `cmsConfig`.
198
+ */
199
+ function nuaCmsInstance(cms, bindings) {
200
+ if (cms?.type === 'BooleanLiteral' && !cms.value)
201
+ return undefined;
202
+ return cms?.type === 'ObjectExpression' ? objectAtPath(cms, ['cmsConfig'], bindings) : null;
203
+ }
204
+ /** The CMS instance the config's own `nua` key stands for, if anything reads that key. */
205
+ function wrapperCmsInstance(ast, configObject, bindings) {
206
+ const wrapper = defaultExportWrapper(ast, bindings);
207
+ if (wrapper === 'astro')
208
+ return undefined;
209
+ const nua = objectPropertyValue(configObject, 'nua', bindings);
210
+ const cms = nua?.type === 'ObjectExpression' ? objectPropertyValue(nua, 'cms', bindings) : null;
211
+ if (wrapper === 'unknown') {
212
+ // Somebody's own wrapper: whether it adds nua cannot be known from here. A `nua.cms`
213
+ // block is taken as a sign that it does; without one, nothing is assumed.
214
+ return cms?.type === 'ObjectExpression' ? nuaCmsInstance(cms, bindings) : undefined;
215
+ }
216
+ // The nua wrapper adds the integration whether or not the config mentions `nua` — only
217
+ // `nua: false` stops it — so the instance is there even with nothing to read from.
218
+ if (nua?.type === 'BooleanLiteral' && !nua.value)
219
+ return undefined;
220
+ return nuaCmsInstance(cms, bindings);
221
+ }
222
+ /**
223
+ * The `cmsConfig` object of the CMS instance whose configuration the page ends up with, or
224
+ * null when that instance declares none (or none can be read).
225
+ *
226
+ * The CMS options reach the integration three ways: the `nua` key of `defineConfig` from
227
+ * `@nuasite/nua/config`, or the integration called directly in `integrations` —
228
+ * `nuaCms({ … })`, `nua({ cms: { … } })`. A call is recognised by where its callee is
229
+ * imported from, not by its name.
230
+ *
231
+ * A site picks one. A config that uses several runs several CMS instances, every one of them
232
+ * assigns `window.NuaCmsConfig`, and the page keeps the last assignment. Which one that is was
233
+ * established by running such configs through Astro's own dev setup, not by reading hook
234
+ * code: nua registers its CMS behind everything listed in `integrations`, so
235
+ *
236
+ * - nua's CMS — the wrapper's, or a listed `nua()` call's — beats every `nuaCms()` call,
237
+ * wherever it stands and whether or not it carries a `cmsConfig`;
238
+ * - without one, the last `nuaCms()` call is it.
239
+ *
240
+ * Exactly one object is the answer; `listStyles` from one instance and `locale` from another
241
+ * would describe a configuration no page ever has. Two nua integrations in one config (the
242
+ * wrapper plus a listed `nua()`, or `nua()` twice) is not a working setup — their page
243
+ * scripts collide — so nothing is promised for it beyond an answer.
244
+ */
245
+ function effectiveCmsConfig(ast, configObject, bindings) {
246
+ let fromNua = wrapperCmsInstance(ast, configObject, bindings);
247
+ let fromCms;
248
+ const integrations = objectPropertyValue(configObject, 'integrations', bindings);
249
+ const integrationImports = collectCmsIntegrationImports(ast);
250
+ for (const element of integrations?.type === 'ArrayExpression' ? integrations.elements : []) {
251
+ if (!element || element.type === 'SpreadElement')
252
+ continue;
253
+ const call = resolveExpression(element, bindings);
254
+ // The callee as it is at runtime: `(nuaCms as any)(…)` is a `nuaCms` call like any other.
255
+ const callee = call.type === 'CallExpression' ? withoutTypeWrappers(call.callee) : null;
256
+ if (call.type !== 'CallExpression' || callee?.type !== 'Identifier')
257
+ continue;
258
+ const optionsPath = integrationImports.get(callee.name);
259
+ if (!optionsPath)
260
+ continue;
261
+ const firstArg = call.arguments[0];
262
+ const options = firstArg && firstArg.type !== 'SpreadElement' ? resolveExpression(firstArg, bindings) : null;
263
+ const optionsObject = options?.type === 'ObjectExpression' ? options : null;
264
+ if (optionsPath.length === 0) {
265
+ fromCms = optionsObject && objectAtPath(optionsObject, ['cmsConfig'], bindings);
266
+ }
267
+ else if (fromNua === undefined) {
268
+ fromNua = nuaCmsInstance(optionsObject && objectPropertyValue(optionsObject, 'cms', bindings), bindings);
269
+ }
270
+ }
271
+ return fromNua !== undefined ? fromNua : fromCms ?? null;
272
+ }
273
+ /** `listStyles` of the `cmsConfig` object; empty when absent or not an array. */
274
+ function parseConfigListStyles(cmsConfig, bindings) {
275
+ const listStylesNode = cmsConfig ? objectPropertyValue(cmsConfig, 'listStyles', bindings) : null;
276
+ return listStylesNode?.type === 'ArrayExpression' ? parseListStyles(listStylesNode, bindings) : [];
277
+ }
278
+ /** The value of `key` in `object`, when it is a non-empty static string. */
279
+ function staticStringOf(object, key, bindings) {
280
+ const node = object ? objectPropertyValue(object, key, bindings) : null;
281
+ return (node && staticString(node, bindings)) || undefined;
282
+ }
283
+ /**
284
+ * The project's language: `cmsConfig.locale` when declared, otherwise Astro's
285
+ * `i18n.defaultLocale`. The explicit key comes first because most sites are single-language
286
+ * and have no `i18n` block — adding one changes how Astro routes, which is not a lever to
287
+ * pull for the sake of sorting labels. A value that cannot be read statically counts as
288
+ * absent, so an unreadable explicit locale falls through to `i18n.defaultLocale`.
289
+ */
290
+ function parseLocale(cmsConfig, configObject, bindings) {
291
+ return staticStringOf(cmsConfig, 'locale', bindings) ?? staticStringOf(objectAtPath(configObject, ['i18n'], bindings), 'defaultLocale', bindings);
292
+ }
293
+ /**
294
+ * Parse the project-level CMS config from an Astro config source string: `listStyles` and
295
+ * the project's language (see {@link parseLocale}), from wherever the config hands the
296
+ * integration its `cmsConfig` (see {@link effectiveCmsConfig}).
297
+ */
298
+ export function parseProjectCmsConfigSource(source) {
299
+ const ast = parseSource(source);
300
+ if (!ast)
301
+ return EMPTY_CONFIG;
302
+ const bindings = collectBindings(ast);
303
+ const configObject = configObjectFromDefaultExport(ast, bindings);
304
+ if (!configObject)
305
+ return EMPTY_CONFIG;
306
+ const cmsConfig = effectiveCmsConfig(ast, configObject, bindings);
307
+ const locale = parseLocale(cmsConfig, configObject, bindings);
308
+ return { listStyles: parseConfigListStyles(cmsConfig, bindings), ...(locale ? { locale } : {}) };
309
+ }
310
+ const ASTRO_CONFIG_FILES = ['astro.config.ts', 'astro.config.mts', 'astro.config.mjs', 'astro.config.js'];
311
+ /** Read and parse the consuming project's Astro config, tolerating absence or malformed config. */
312
+ export async function parseProjectCmsConfig(fs) {
313
+ for (const file of ASTRO_CONFIG_FILES) {
314
+ let source;
315
+ try {
316
+ source = await fs.readFile(file);
317
+ }
318
+ catch {
319
+ continue;
320
+ }
321
+ return parseProjectCmsConfigSource(source);
322
+ }
323
+ return EMPTY_CONFIG;
324
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public-static-file.d.ts","sourceRoot":"","sources":["../src/public-static-file.ts"],"names":[],"mappings":"AAGA;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CA6BzG"}
@@ -0,0 +1,40 @@
1
+ import { statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ /**
4
+ * Build a checker that decides whether a request URL maps to an existing file
5
+ * under Astro's `publicDir`. Used to bypass HTML rewriting for vendor pages
6
+ * whose inline scripts can be corrupted by injected markers or content-length
7
+ * mismatches.
8
+ *
9
+ * Cache lives for the dev server's lifetime; vendor HTML is essentially static,
10
+ * and the cache is cleared on restart.
11
+ */
12
+ export function createPublicStaticFileChecker(publicDir) {
13
+ if (!publicDir)
14
+ return () => false;
15
+ const cache = new Map();
16
+ return (urlPath) => {
17
+ const cleaned = urlPath.split('?')[0] || '';
18
+ if (!cleaned.startsWith('/') || cleaned.includes('..'))
19
+ return false;
20
+ const cached = cache.get(cleaned);
21
+ if (cached !== undefined)
22
+ return cached;
23
+ const candidates = [path.join(publicDir, cleaned)];
24
+ if (cleaned.endsWith('/')) {
25
+ candidates.push(path.join(publicDir, cleaned, 'index.html'));
26
+ }
27
+ let exists = false;
28
+ for (const p of candidates) {
29
+ try {
30
+ if (statSync(p).isFile()) {
31
+ exists = true;
32
+ break;
33
+ }
34
+ }
35
+ catch { }
36
+ }
37
+ cache.set(cleaned, exists);
38
+ return exists;
39
+ };
40
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redirects.d.ts","sourceRoot":"","sources":["../src/redirects.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,sFAAsF;AACtF,eAAO,MAAM,kBAAkB,mBAAmB,CAAA;AAElD,2FAA2F;AAC3F,MAAM,WAAW,aAAa;IAC7B,sFAAsF;IACtF,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACpB;AAED,MAAM,WAAW,YAAY;IAC5B,KAAK,EAAE,MAAM,CAAA;IACb,mDAAmD;IACnD,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,MAAM,CAAA;CACZ;AAED,MAAM,WAAW,eAAe;IAC/B,2DAA2D;IAC3D,IAAI,EAAE,MAAM,CAAA;IACZ,4GAA4G;IAC5G,KAAK,EAAE,MAAM,EAAE,CAAA;IACf,4FAA4F;IAC5F,UAAU,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,YAAY,CAAC;QAAC,OAAO,EAAE,YAAY,CAAA;KAAE,CAAC,CAAA;IAChE,4GAA4G;IAC5G,QAAQ,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,YAAY,CAAC;QAAC,IAAI,EAAE,YAAY,CAAA;KAAE,CAAC,CAAA;IACzD,iDAAiD;IACjD,YAAY,EAAE,YAAY,EAAE,CAAA;IAC5B,+GAA+G;IAC/G,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,YAAY,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IACtD,iFAAiF;IACjF,MAAM,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAC1C;AAED;;;GAGG;AACH,eAAO,MAAM,0BAA0B;;;CAAyC,CAAA;AAKhF,2DAA2D;AAC3D,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,WAAW,EAAE,MAAM,CAAA;IACnB,oFAAoF;IACpF,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,uEAAuE;IACvE,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,6EAA6E;IAC7E,GAAG,EAAE,MAAM,CAAA;IACX,oDAAoD;IACpD,OAAO,EAAE,OAAO,CAAA;IAChB,0CAA0C;IAC1C,IAAI,EAAE,MAAM,CAAA;CACZ;AAMD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAsB5E;AAMD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,eAAe,CAkDvE"}