@uniweb/build 1.23.8 → 1.23.9
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/package.json +8 -8
- package/src/dev/published-mount.js +132 -0
- package/src/foundation/scope-define.js +9 -1
- package/src/site/config.js +17 -0
- package/src/site/index.js +1 -0
- package/src/site/plugin.js +42 -14
- package/src/site/published.js +162 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uniweb/build",
|
|
3
|
-
"version": "1.23.
|
|
3
|
+
"version": "1.23.9",
|
|
4
4
|
"description": "Build tooling for the Uniweb Component Web Platform",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -57,12 +57,12 @@
|
|
|
57
57
|
"js-yaml": "^4.3.2",
|
|
58
58
|
"sharp": "^0.35.5",
|
|
59
59
|
"yaml": "^2.5.0",
|
|
60
|
-
"@uniweb/content-reader": "~1.5.
|
|
61
|
-
"@uniweb/content-writer": "~1.3.2",
|
|
62
|
-
"@uniweb/schemas": "~1.7.4",
|
|
63
|
-
"@uniweb/semantic-parser": "~1.13.5",
|
|
60
|
+
"@uniweb/content-reader": "~1.5.11",
|
|
64
61
|
"@uniweb/projections": "~1.2.17",
|
|
65
|
-
"@uniweb/
|
|
62
|
+
"@uniweb/semantic-parser": "~1.13.5",
|
|
63
|
+
"@uniweb/schemas": "~1.7.4",
|
|
64
|
+
"@uniweb/theming": "~1.3.2",
|
|
65
|
+
"@uniweb/content-writer": "~1.3.2"
|
|
66
66
|
},
|
|
67
67
|
"optionalDependencies": {
|
|
68
68
|
"@uniweb/runtime": "~1.6.5"
|
|
@@ -74,8 +74,8 @@
|
|
|
74
74
|
"@tailwindcss/vite": "^4.0.0",
|
|
75
75
|
"@vitejs/plugin-react": "^4.0.0 || ^5.0.0",
|
|
76
76
|
"vite-plugin-svgr": "^4.0.0",
|
|
77
|
-
"@uniweb/
|
|
78
|
-
"@uniweb/
|
|
77
|
+
"@uniweb/runtime": "~1.6.5",
|
|
78
|
+
"@uniweb/core": "~1.6.13"
|
|
79
79
|
},
|
|
80
80
|
"peerDependenciesMeta": {
|
|
81
81
|
"vite": {
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { PUBLISHED_MOUNT } from '../site/published.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `uniweb dev --published` — the dev server answers a published site's services at addresses of
|
|
5
|
+
* its own and forwards each request to the published address (`../site/published.js` has the
|
|
6
|
+
* contract and how the addresses are made).
|
|
7
|
+
*
|
|
8
|
+
* ⭐ Same-origin on purpose, as `mountDevApi` is. The page asks the dev server, so a session
|
|
9
|
+
* cookie the published site's backend sets is first-party on the dev server's origin, and nothing
|
|
10
|
+
* exercises CORS or third-party-cookie rules the published site does not have. A cookie is kept
|
|
11
|
+
* on the dev server's origin, for its whole path, and loses `Secure` over plain http, where a
|
|
12
|
+
* browser could drop it — except a `__Host-` or `__Secure-` cookie, whose name requires it.
|
|
13
|
+
*
|
|
14
|
+
* ⭐ The request goes as the published page would send it: its method, body and headers, with the
|
|
15
|
+
* published page's origin as its `Origin`, since that is the page a visitor's request comes from.
|
|
16
|
+
* The dev server's own `Host` and `Referer` stay behind, and so does `Accept-Encoding`, because
|
|
17
|
+
* the answer is read whole and handed on decoded. A redirect is handed to the browser as it came.
|
|
18
|
+
*
|
|
19
|
+
* ⚠️ The answer is read whole before it is sent on, so a streamed one arrives at its end.
|
|
20
|
+
*
|
|
21
|
+
* ⛔ Registered SYNCHRONOUSLY, like `mountDevApi`: Vite runs the middleware registered before
|
|
22
|
+
* `configureServer` returns ahead of its SPA fallback, which would answer every address with
|
|
23
|
+
* `index.html`.
|
|
24
|
+
*
|
|
25
|
+
* @param {import('vite').ViteDevServer} server
|
|
26
|
+
* @param {object} options
|
|
27
|
+
* @param {Record<string, string>} options.targets - service → the origin it forwards to (`localServices`)
|
|
28
|
+
* @param {string} options.site - the published page's address
|
|
29
|
+
* @param {string} [options.base] - the dev site's base path, which a request may still carry
|
|
30
|
+
* @param {typeof fetch} [options.fetch] - injected in tests
|
|
31
|
+
* @param {(line: string) => void} [options.log]
|
|
32
|
+
*/
|
|
33
|
+
export function mountPublished(server, { targets, site, base = '/', fetch: send = globalThis.fetch, log = console.log }) {
|
|
34
|
+
const siteOrigin = new URL(site).origin
|
|
35
|
+
|
|
36
|
+
server.middlewares.use(async (req, res, next) => {
|
|
37
|
+
const url = withoutBase(req.url || '', base)
|
|
38
|
+
if (!url.startsWith(`${PUBLISHED_MOUNT}/`)) return next()
|
|
39
|
+
const after = url.slice(PUBLISHED_MOUNT.length + 1)
|
|
40
|
+
const cut = after.search(/[/?]/)
|
|
41
|
+
const name = cut === -1 ? after : after.slice(0, cut)
|
|
42
|
+
const rest = cut === -1 ? '/' : after[cut] === '?' ? `/${after.slice(cut)}` : after.slice(cut)
|
|
43
|
+
const origin = targets[name]
|
|
44
|
+
if (!origin) {
|
|
45
|
+
return problem(res, 404, 'No Such Service', `The site published at ${siteOrigin} offers no ${name} service.`)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const headers = new Headers()
|
|
49
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
50
|
+
if (value === undefined || NOT_SENT.has(key)) continue
|
|
51
|
+
headers.set(key, Array.isArray(value) ? value.join(', ') : value)
|
|
52
|
+
}
|
|
53
|
+
if (headers.has('origin')) headers.set('origin', siteOrigin)
|
|
54
|
+
const init = { method: req.method, headers, redirect: 'manual' }
|
|
55
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
56
|
+
const chunks = []
|
|
57
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
58
|
+
if (chunks.length) init.body = Buffer.concat(chunks)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let response
|
|
62
|
+
try {
|
|
63
|
+
response = await send(`${origin}${rest}`, init)
|
|
64
|
+
} catch (err) {
|
|
65
|
+
return problem(res, 502, 'Published Site Unreachable', `Could not reach ${origin}: ${err?.cause?.message || err.message}`)
|
|
66
|
+
}
|
|
67
|
+
res.statusCode = response.status
|
|
68
|
+
response.headers.forEach((value, key) => {
|
|
69
|
+
if (key !== 'set-cookie' && !NOT_RETURNED.has(key)) res.setHeader(key, value)
|
|
70
|
+
})
|
|
71
|
+
const cookies = response.headers.getSetCookie?.() ?? []
|
|
72
|
+
if (cookies.length) {
|
|
73
|
+
const secure = Boolean(req.socket?.encrypted)
|
|
74
|
+
res.setHeader('set-cookie', cookies.map((cookie) => firstPartyCookie(cookie, { secure })))
|
|
75
|
+
}
|
|
76
|
+
// Bytes, never text: an answer may be an image or a file.
|
|
77
|
+
const bytes = Buffer.from(await response.arrayBuffer())
|
|
78
|
+
res.end(bytes.length ? bytes : undefined)
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
const names = Object.keys(targets)
|
|
82
|
+
log(
|
|
83
|
+
names.length
|
|
84
|
+
? `[dev-published] ${names.map((n) => `${PUBLISHED_MOUNT}/${n}`).join(', ')} → the site as published at ${siteOrigin}`
|
|
85
|
+
: `[dev-published] the site published at ${siteOrigin} offers no service with an address`
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A cookie the published site set, for the dev server's origin: no `Domain`, the whole path, and,
|
|
91
|
+
* over plain http, no `Secure` — so `SameSite=None`, which needs it, becomes `Lax`, the
|
|
92
|
+
* first-party default — unless its name requires `Secure`.
|
|
93
|
+
*
|
|
94
|
+
* @param {string} cookie - one `Set-Cookie` value
|
|
95
|
+
* @param {{ secure: boolean }} options - whether the dev server is reached over https
|
|
96
|
+
* @returns {string}
|
|
97
|
+
*/
|
|
98
|
+
export function firstPartyCookie(cookie, { secure }) {
|
|
99
|
+
const [pair, ...attributes] = cookie.split(';')
|
|
100
|
+
const name = pair.split('=')[0].trim()
|
|
101
|
+
const keepSecure = secure || /^__(Host|Secure)-/.test(name)
|
|
102
|
+
const kept = []
|
|
103
|
+
for (const raw of attributes) {
|
|
104
|
+
const attribute = raw.trim()
|
|
105
|
+
const key = attribute.split('=')[0].trim().toLowerCase()
|
|
106
|
+
if (!attribute || key === 'domain' || key === 'path') continue
|
|
107
|
+
if (!keepSecure && (key === 'secure' || key === 'partitioned')) continue
|
|
108
|
+
if (!keepSecure && key === 'samesite' && /=\s*none\s*$/i.test(attribute)) {
|
|
109
|
+
kept.push('SameSite=Lax')
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
kept.push(attribute)
|
|
113
|
+
}
|
|
114
|
+
return [pair.trim(), 'Path=/', ...kept].join('; ')
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']
|
|
118
|
+
const NOT_SENT = new Set([...HOP_BY_HOP, 'host', 'referer', 'content-length', 'accept-encoding'])
|
|
119
|
+
// `fetch` hands the body on decoded, so its length and encoding are no longer the answer's.
|
|
120
|
+
const NOT_RETURNED = new Set([...HOP_BY_HOP, 'content-length', 'content-encoding'])
|
|
121
|
+
|
|
122
|
+
function problem(res, status, title, detail) {
|
|
123
|
+
res.statusCode = status
|
|
124
|
+
res.setHeader('content-type', 'application/problem+json')
|
|
125
|
+
res.end(JSON.stringify({ status, title, detail }))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** A request may still carry the site's base path; the address is the dev server's own. */
|
|
129
|
+
function withoutBase(url, base) {
|
|
130
|
+
const prefix = String(base || '/').replace(/\/+$/, '')
|
|
131
|
+
return prefix && (url === prefix || url.startsWith(`${prefix}/`)) ? url.slice(prefix.length) || '/' : url
|
|
132
|
+
}
|
|
@@ -24,6 +24,13 @@
|
|
|
24
24
|
* A dev rebuild never ships: it empties `dist/` and writes no `entry-ssr.js`,
|
|
25
25
|
* so `register` builds again before it uploads (`foundationNeedsBuild`).
|
|
26
26
|
*
|
|
27
|
+
* ⭐ The one working copy that talks to a real backend is one served by
|
|
28
|
+
* `uniweb dev --published` (`../site/published.js`): it is answered by the
|
|
29
|
+
* published site's own services, which hold the types as `register` stored
|
|
30
|
+
* them, so it is stamped as a build is and sends `@acme/x` as the published
|
|
31
|
+
* site does [Diego, 2026-11-15]. It still ships nothing: a dev rebuild stays
|
|
32
|
+
* one.
|
|
33
|
+
*
|
|
27
34
|
* An author's own `define` for the key wins: it is left untouched.
|
|
28
35
|
*/
|
|
29
36
|
|
|
@@ -33,6 +40,7 @@ import { loadFoundationConfig } from '../schema.js'
|
|
|
33
40
|
import { foundationNameOf, splitFoundationName } from '../foundation-name.js'
|
|
34
41
|
import { resolveFoundationSrcDir } from '../utils/foundation-source-root.js'
|
|
35
42
|
import { hasDevRebuildMarker } from './dev-rebuild.js'
|
|
43
|
+
import { PUBLISHED_ENV } from '../site/published.js'
|
|
36
44
|
|
|
37
45
|
export const FOUNDATION_SCOPE_KEY = '__FOUNDATION_SCOPE__'
|
|
38
46
|
|
|
@@ -48,7 +56,7 @@ export function foundationScopeDefine({ foundationDir } = {}) {
|
|
|
48
56
|
name: 'uniweb:foundation-scope',
|
|
49
57
|
async config(config, { command }) {
|
|
50
58
|
if (config.define && FOUNDATION_SCOPE_KEY in config.define) return
|
|
51
|
-
const workingCopy = command === 'serve' || hasDevRebuildMarker(config)
|
|
59
|
+
const workingCopy = (command === 'serve' || hasDevRebuildMarker(config)) && !process.env[PUBLISHED_ENV]
|
|
52
60
|
const scope = workingCopy ? null : await foundationScope(foundationDir ?? config.root ?? process.cwd())
|
|
53
61
|
return { define: { [FOUNDATION_SCOPE_KEY]: JSON.stringify(scope) } }
|
|
54
62
|
},
|
package/src/site/config.js
CHANGED
|
@@ -42,6 +42,7 @@ import { libraryImports } from '../foundation/library-imports.js'
|
|
|
42
42
|
import { copiedLibraries, copiedLibrariesWarning } from '../foundation/libraries.js'
|
|
43
43
|
import { workspaceRootOf } from './workspace-extension.js'
|
|
44
44
|
import { readPreview, PREVIEW_ENV } from './preview.js'
|
|
45
|
+
import { PUBLISHED_ENV } from './published.js'
|
|
45
46
|
import { previewMediaPlugin } from './preview-media.js'
|
|
46
47
|
import { previewDirectoryIndexPlugin } from './preview-directory-index.js'
|
|
47
48
|
import { devServerRecordPlugin, requestedDevPort } from './dev-server.js'
|
|
@@ -439,6 +440,22 @@ export async function defineSiteConfig(options = {}) {
|
|
|
439
440
|
}))
|
|
440
441
|
}
|
|
441
442
|
|
|
443
|
+
if (process.env[PUBLISHED_ENV]) {
|
|
444
|
+
// ⛔ NOR DOES A PUBLISHED SITE'S. `uniweb dev --published` hands its dev server the
|
|
445
|
+
// services a published page carries, for that server alone (`./published.js`).
|
|
446
|
+
plugins.push({
|
|
447
|
+
name: 'uniweb:published-only',
|
|
448
|
+
config(_config, env) {
|
|
449
|
+
if (env.command === 'build') {
|
|
450
|
+
throw new Error(
|
|
451
|
+
`[site] ${PUBLISHED_ENV} is what \`uniweb dev --published\` read from a published ` +
|
|
452
|
+
'site, for one dev server, and a build does not take it. Unset it to build.'
|
|
453
|
+
)
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
})
|
|
457
|
+
}
|
|
458
|
+
|
|
442
459
|
if (preview) {
|
|
443
460
|
// ⛔ A PREVIEW'S ANSWER NEVER REACHES A BUILT ARTIFACT. Where the backend serves a
|
|
444
461
|
// version is decided at publish and read for one preview (`./preview.js`); written into
|
package/src/site/index.js
CHANGED
|
@@ -10,6 +10,7 @@ export { siteContentPlugin } from './plugin.js'
|
|
|
10
10
|
export { defineSiteConfig, readSiteConfig, default } from './config.js'
|
|
11
11
|
// What `uniweb dev` hands the dev server of a site a backend holds (`./preview.js`).
|
|
12
12
|
export { PREVIEW_ENV, encodePreview, readPreview } from './preview.js'
|
|
13
|
+
export { PUBLISHED_ENV, encodePublished, readPublished } from './published.js'
|
|
13
14
|
// Where a site's dev server listens, as it states it, for `uniweb dev` (`./dev-server.js`).
|
|
14
15
|
export { DEV_PORT_ENV, DEV_RECORD_ENV, runningDevServer, stopDevServer } from './dev-server.js'
|
|
15
16
|
// Where a statically built site lives, as its deploy target or author states it (`./site-address.js`).
|
package/src/site/plugin.js
CHANGED
|
@@ -244,6 +244,9 @@ import { dataBlockModels, NO_DATA_MODELS } from '../i18n/data-models.js'
|
|
|
244
244
|
import { refuseSearchOption } from './search-declared.js'
|
|
245
245
|
import { mountDevApi } from '../dev/api-mount.js'
|
|
246
246
|
import { mountDevSubmit } from '../dev/submit-mount.js'
|
|
247
|
+
import { mountPublished } from '../dev/published-mount.js'
|
|
248
|
+
import { readPublished, localServices, queriesInFull } from './published.js'
|
|
249
|
+
import { foundationScope } from '../foundation/scope-define.js'
|
|
247
250
|
|
|
248
251
|
/**
|
|
249
252
|
* A shell carrying the page's look by the runtime's own rule (`@uniweb/runtime/ssr`, which a
|
|
@@ -402,12 +405,24 @@ export function siteContentPlugin(options = {}) {
|
|
|
402
405
|
// never in a build.
|
|
403
406
|
let devApiAddress = null
|
|
404
407
|
let devSubmitAddress = null
|
|
408
|
+
// Under `uniweb dev --published`, the published site's services instead, at the dev server's
|
|
409
|
+
// own addresses (`./published.js`): the host tier, as the published page carries it.
|
|
410
|
+
let publishedServices = null
|
|
411
|
+
// ...and the scope of the foundation's name, which names the site's queries in full there.
|
|
412
|
+
let publishedScope = null
|
|
405
413
|
/**
|
|
406
414
|
* The dev payload names those addresses as the site's `backend` and `submit` services:
|
|
407
415
|
* the site tier, which `resolveService` reads when no host speaks. A build never gets
|
|
408
|
-
* here with one.
|
|
416
|
+
* here with one. Under `--published` the dev server is the host, and its payload carries
|
|
417
|
+
* the host's block, as a published page does, and its queries with their types named in
|
|
418
|
+
* full, as the published page holds them (`queriesInFull`).
|
|
409
419
|
*/
|
|
410
420
|
const withDevServices = (content) => {
|
|
421
|
+
if (publishedServices && content?.config) {
|
|
422
|
+
content.config.services = publishedServices
|
|
423
|
+
content.config.queries = queriesInFull(content.config.queries, publishedScope)
|
|
424
|
+
return content
|
|
425
|
+
}
|
|
411
426
|
if (devApiAddress && content?.config) content.config.backend = devApiAddress
|
|
412
427
|
if (devSubmitAddress && content?.config) content.config.submit = devSubmitAddress
|
|
413
428
|
return content
|
|
@@ -659,6 +674,7 @@ export function siteContentPlugin(options = {}) {
|
|
|
659
674
|
viteRoot = config.root
|
|
660
675
|
isProduction = config.command === 'build'
|
|
661
676
|
basePath = config.base || '/'
|
|
677
|
+
if (!isProduction && foundationPath && readPublished()) publishedScope = await foundationScope(foundationPath)
|
|
662
678
|
|
|
663
679
|
// In dev mode, process collections early so JSON files exist before server starts
|
|
664
680
|
// This runs before configureServer, ensuring data is available immediately
|
|
@@ -756,20 +772,32 @@ export function siteContentPlugin(options = {}) {
|
|
|
756
772
|
// ⚠️ Synchronous on purpose — see mountDevApi. An await here and the
|
|
757
773
|
// middleware lands after Vite's SPA fallback, which answers the API with
|
|
758
774
|
// index.html and says nothing about why.
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
775
|
+
//
|
|
776
|
+
// ⭐ `uniweb dev --published` answers every service the published site has with that
|
|
777
|
+
// site's own, forwarded (`../dev/published-mount.js`), so neither the mock nor the
|
|
778
|
+
// local form handler is mounted: the page talks to what visitors of the published site
|
|
779
|
+
// talk to. A handed value that says nothing usable stops the server here.
|
|
780
|
+
const published = readPublished()
|
|
781
|
+
if (published) {
|
|
782
|
+
const { services, targets } = localServices(published)
|
|
783
|
+
publishedServices = services
|
|
784
|
+
mountPublished(devServer, { targets, site: published.site, base: basePath })
|
|
785
|
+
} else {
|
|
786
|
+
try {
|
|
787
|
+
devApiAddress = mountDevApi(devServer, { root: resolvedSitePath })
|
|
788
|
+
} catch (err) {
|
|
789
|
+
console.error(`[dev-api] ${err.message}`)
|
|
790
|
+
}
|
|
764
791
|
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
792
|
+
// A site's forms, taken locally in development when site.yml asks its host for
|
|
793
|
+
// them (`services: { submit: true }`): the dev server is that host here, so a form
|
|
794
|
+
// shows and can be sent before the site is published. Synchronous for the same
|
|
795
|
+
// reason as the mount above.
|
|
796
|
+
try {
|
|
797
|
+
devSubmitAddress = mountDevSubmit(devServer, { root: resolvedSitePath, base: basePath })
|
|
798
|
+
} catch (err) {
|
|
799
|
+
console.error(`[dev-submit] ${err.message}`)
|
|
800
|
+
}
|
|
773
801
|
}
|
|
774
802
|
|
|
775
803
|
// A site-relative workspace extension (`/effects/entry.js`) is served from
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE SITE AS PUBLISHED — what `uniweb dev --published` read from a published site, handed to the
|
|
3
|
+
* one dev server it starts.
|
|
4
|
+
*
|
|
5
|
+
* A site's services — its own `backend`, its `records`, its forms — are its host's to answer once
|
|
6
|
+
* the site is published, at addresses the host chooses. `uniweb dev --published` serves the working
|
|
7
|
+
* copy, its foundation and pages with live reload, against those services. `uniweb dev` reads the
|
|
8
|
+
* host's answer from the published page itself (`__DATA__`, `content.config.services`) and passes
|
|
9
|
+
* it in `UNIWEB_PUBLISHED`, as JSON:
|
|
10
|
+
*
|
|
11
|
+
* { site: 'https://…/', the published page the services were read from
|
|
12
|
+
* backend: 'https://…', the backend the site is published from
|
|
13
|
+
* base: '/' | null, that page's `config.base`
|
|
14
|
+
* services: { backend: '/_api', … } } the host's block, as the page carries it
|
|
15
|
+
*
|
|
16
|
+
* The dev server then plays the host (`../dev/published-mount.js`): its payload carries that block
|
|
17
|
+
* with each address replaced by one of its own, under `PUBLISHED_MOUNT`, and it forwards a request
|
|
18
|
+
* for one of those to the published address. The page sees one origin, so a sign-in cookie is
|
|
19
|
+
* first-party, as it is on the published site, and a query is answered by the site's records
|
|
20
|
+
* service, the entries its public queries open included, as a visitor's is.
|
|
21
|
+
*
|
|
22
|
+
* ⭐ Read, never composed. A host owns its services' addresses and states them in the page it
|
|
23
|
+
* serves (`@uniweb/core/services`), so one is resolved as the published page's runtime resolves it
|
|
24
|
+
* (`resolveServiceUrl`, with that page's base) and against that page's address, and nothing here
|
|
25
|
+
* knows a route.
|
|
26
|
+
*
|
|
27
|
+
* ⛔ Nothing keeps it. It lives as long as the dev server, as a preview does (`./preview.js`), and a
|
|
28
|
+
* build handed it refuses it (`./config.js`), so a published site's addresses never reach a built
|
|
29
|
+
* artifact.
|
|
30
|
+
*/
|
|
31
|
+
import { readEndpoint, resolveServiceUrl } from '@uniweb/core/services'
|
|
32
|
+
|
|
33
|
+
/** The variable `uniweb dev --published` sets for the dev server it starts. */
|
|
34
|
+
export const PUBLISHED_ENV = 'UNIWEB_PUBLISHED'
|
|
35
|
+
|
|
36
|
+
/** Where the dev server answers the published site's services: `/_published/<service>/…`. */
|
|
37
|
+
export const PUBLISHED_MOUNT = '/_published'
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The variable's value.
|
|
41
|
+
*
|
|
42
|
+
* @param {{ site: string, backend: string, base?: string|null, services: object }} published
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/
|
|
45
|
+
export function encodePublished({ site, backend, base = null, services }) {
|
|
46
|
+
return JSON.stringify({ site, backend, base: typeof base === 'string' ? base : null, services })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* What a dev server was handed, or null when it was handed nothing.
|
|
51
|
+
*
|
|
52
|
+
* @param {Record<string, string|undefined>} [env]
|
|
53
|
+
* @returns {{ site: string, backend: string, base: string|null, services: object }|null}
|
|
54
|
+
* @throws {Error} when the variable is set and says nothing usable: a dev server told to use a
|
|
55
|
+
* published site's services must not start on its own mock instead
|
|
56
|
+
*/
|
|
57
|
+
export function readPublished(env = process.env) {
|
|
58
|
+
const raw = env[PUBLISHED_ENV]
|
|
59
|
+
if (!raw) return null
|
|
60
|
+
let given = null
|
|
61
|
+
try {
|
|
62
|
+
given = JSON.parse(raw)
|
|
63
|
+
} catch {
|
|
64
|
+
// reported below
|
|
65
|
+
}
|
|
66
|
+
if (!isHttpUrl(given?.site) || !isHttpUrl(given?.backend) || !isPlainObject(given?.services)) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`${PUBLISHED_ENV} holds no published site (${JSON.stringify(raw).slice(0, 120)}). ` +
|
|
69
|
+
'It is set by `uniweb dev --published`; run that rather than setting it.'
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
site: new URL(given.site).href,
|
|
74
|
+
backend: new URL(given.backend).origin,
|
|
75
|
+
base: typeof given.base === 'string' ? given.base : null,
|
|
76
|
+
services: given.services,
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The services block the dev payload carries — the host's, each address replaced by one of the dev
|
|
82
|
+
* server's — and the origin each service forwards to.
|
|
83
|
+
*
|
|
84
|
+
* An address keeps everything after its origin as written, a `{locale}` slot included, under
|
|
85
|
+
* `/_published/<service>`: the published `records` at `/_query/{locale}` becomes
|
|
86
|
+
* `/_published/records/_query/{locale}`, and a request for `/_published/records/_query/fr` goes to
|
|
87
|
+
* `<its origin>/_query/fr`. A service the host names with no address is carried as it is: the host
|
|
88
|
+
* answered, and offered none.
|
|
89
|
+
*
|
|
90
|
+
* @param {{ site: string, base?: string|null, services: object }} published - from `readPublished`
|
|
91
|
+
* @returns {{ services: object, targets: Record<string, string> }} targets: service → origin
|
|
92
|
+
*/
|
|
93
|
+
export function localServices({ site, base = null, services }) {
|
|
94
|
+
const local = {}
|
|
95
|
+
const targets = {}
|
|
96
|
+
for (const [name, value] of Object.entries(services)) {
|
|
97
|
+
const endpoint = readEndpoint(value)
|
|
98
|
+
if (!endpoint || !SERVICE_NAME.test(name)) {
|
|
99
|
+
local[name] = value
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
const { origin, rest } = splitAddress(resolveServiceUrl(endpoint, base || ''), site)
|
|
103
|
+
targets[name] = origin
|
|
104
|
+
const address = `${PUBLISHED_MOUNT}/${name}${rest}`
|
|
105
|
+
local[name] = typeof value === 'string' ? address : { ...value, endpoint: address }
|
|
106
|
+
}
|
|
107
|
+
return { services: local, targets }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The site's queries as the published page carries them: each `schema` the copy spells `@/x` named
|
|
112
|
+
* in full, `<scope>/x`, with the scope of the foundation's name. A backend matches a type's name
|
|
113
|
+
* exactly, and a published page holds its queries as the backend registered them, so a records ask
|
|
114
|
+
* for `@/course` finds nothing there. Every other value is left as written, and so is every query
|
|
115
|
+
* when the foundation's name has no scope.
|
|
116
|
+
*
|
|
117
|
+
* @param {object|undefined} queries - the payload's `config.queries`
|
|
118
|
+
* @param {string|null} scope - `@acme` for `@acme/courses`
|
|
119
|
+
* @returns {object|undefined}
|
|
120
|
+
*/
|
|
121
|
+
export function queriesInFull(queries, scope) {
|
|
122
|
+
if (!isPlainObject(queries) || typeof scope !== 'string' || !scope.startsWith('@')) return queries
|
|
123
|
+
const full = {}
|
|
124
|
+
for (const [name, query] of Object.entries(queries)) {
|
|
125
|
+
const schema = query?.schema
|
|
126
|
+
full[name] =
|
|
127
|
+
isPlainObject(query) && typeof schema === 'string' && schema.startsWith('@/')
|
|
128
|
+
? { ...query, schema: `${scope}/${schema.slice(2)}` }
|
|
129
|
+
: query
|
|
130
|
+
}
|
|
131
|
+
return full
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// A segment of the dev server's own address, so only a name that is one.
|
|
135
|
+
const SERVICE_NAME = /^[A-Za-z0-9_-]+$/
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* An address the runtime would ask, split into the origin it goes to and the rest, kept as written
|
|
139
|
+
* so a `{locale}` slot survives: `new URL` would encode the braces.
|
|
140
|
+
*/
|
|
141
|
+
function splitAddress(address, site) {
|
|
142
|
+
const absolute = /^((?:[a-z][a-z0-9+.-]*:)?\/\/[^/?#]*)(.*)$/i.exec(address)
|
|
143
|
+
if (absolute) {
|
|
144
|
+
const [, head, tail] = absolute
|
|
145
|
+
const origin = new URL(head.startsWith('//') ? `${new URL(site).protocol}${head}` : head).origin
|
|
146
|
+
return { origin, rest: tail.startsWith('/') ? tail : `/${tail}` }
|
|
147
|
+
}
|
|
148
|
+
return { origin: new URL(site).origin, rest: address.startsWith('/') ? address : `/${address}` }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ⛔ `new URL('localhost:8080')` parses — as the scheme `localhost:` — so a URL is http(s) or nothing.
|
|
152
|
+
function isHttpUrl(value) {
|
|
153
|
+
try {
|
|
154
|
+
return /^https?:$/.test(new URL(value).protocol)
|
|
155
|
+
} catch {
|
|
156
|
+
return false
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function isPlainObject(value) {
|
|
161
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
162
|
+
}
|