Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion .github/extensions/replica-prototype/assets/renderer.js

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion actions/build/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ name: Replica build
description: Build a Replica prototype and upload its package, with screenshots inline or in a later job

inputs:
base-path:
description: Path where the compiled app is mounted during screenshot capture; configure the app's build base separately
required: false
default: /
build-only:
description: Build static output without packaging, uploading, or capturing screenshots; publish it with a later actions/build/publish step
required: false
Expand Down Expand Up @@ -110,7 +114,9 @@ runs:

- name: Capture screenshots
if: inputs.build-only != 'true' && inputs.screenshots == 'inline'
run: node "$GITHUB_ACTION_PATH/scripts/capture-screenshots/index.mjs" --root "$RUNNER_TEMP/replica-build-root" --config-root "$GITHUB_WORKSPACE" --screenshots "$RUNNER_TEMP/replica-screenshots"
env:
REPLICA_BASE_PATH: ${{ inputs.base-path }}
run: node "$GITHUB_ACTION_PATH/scripts/capture-screenshots/index.mjs" --root "$RUNNER_TEMP/replica-build-root" --config-root "$GITHUB_WORKSPACE" --screenshots "$RUNNER_TEMP/replica-screenshots" --base-path "$REPLICA_BASE_PATH"
shell: bash

- name: Create Replica package
Expand Down
10 changes: 9 additions & 1 deletion actions/build/screenshots/action.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
name: Replica screenshots
description: Capture screenshots for a replica-build-v1 package uploaded earlier in the same workflow run

inputs:
base-path:
description: Original compiled app base path, including the owning repository and run when using Hub private previews
required: false
default: /

runs:
using: composite
steps:
Expand Down Expand Up @@ -33,7 +39,9 @@ runs:
shell: bash

- name: Capture screenshots
run: node "$GITHUB_ACTION_PATH/../scripts/capture-screenshots/index.mjs" --root "$RUNNER_TEMP/replica-build-v1" --config-root "$RUNNER_TEMP/replica-build-v1" --config-file templates.json --screenshots "$RUNNER_TEMP/replica-screenshots"
env:
REPLICA_BASE_PATH: ${{ inputs.base-path }}
run: node "$GITHUB_ACTION_PATH/../scripts/capture-screenshots/index.mjs" --root "$RUNNER_TEMP/replica-build-v1" --config-root "$RUNNER_TEMP/replica-build-v1" --config-file templates.json --screenshots "$RUNNER_TEMP/replica-screenshots" --base-path "$REPLICA_BASE_PATH"
shell: bash

- name: Create Replica screenshot package
Expand Down
3 changes: 3 additions & 0 deletions actions/build/scripts/action-contract/index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ appendFileSync(process.env.TRACE, JSON.stringify({ command: process.argv[1].spli
REPLICA_BUILD_ONLY: inputs.buildOnly ?? "false",
REPLICA_OUTPUT_DIRECTORY: inputs.outputDirectory,
REPLICA_SCREENSHOTS: inputs.screenshots,
REPLICA_BASE_PATH: inputs.basePath ?? "/",
},
})
}
Expand Down Expand Up @@ -168,6 +169,8 @@ describe("Replica composite action", () => {
workspace,
"--screenshots",
path.join(runner, "replica-screenshots"),
"--base-path",
"/",
])
assert.deepEqual(called("create-package").args.slice(1), [
"--root",
Expand Down
16 changes: 13 additions & 3 deletions actions/build/scripts/capture-screenshots/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { listenOnLoopback } from "../listen-on-loopback/index.mjs"
import { readTemplates } from "../read-templates/index.mjs"
import { requiredPathArgument } from "../required-path-argument/index.mjs"
import { validateBuildOutput } from "../validate-build-output/index.mjs"
import { normalizeBasePath } from "../normalize-base-path/index.mjs"

async function createCaptureProxy(allowedOrigin) {
const proxy = createServer((incoming, response) => {
Expand Down Expand Up @@ -49,7 +50,9 @@ export async function captureScreenshots(
screenshots,
configRoot = root,
configFile = ".github/replica.json",
basePath = "/",
) {
const base = normalizeBasePath(basePath)
await validateBuildOutput(root)
const manifest = await readTemplates(configRoot, configFile)
const controlsAdapter = await readFile(
Expand All @@ -62,6 +65,7 @@ export async function captureScreenshots(
const server = createStaticServer(
path.join(root, "dist"),
manifest?.templates.map((template) => template.path),
base,
)
const port = await listenOnLoopback(server)
const allowedOrigin = `http://127.0.0.1:${port}`
Expand All @@ -74,7 +78,7 @@ export async function captureScreenshots(
proxy: { server: captureProxy.address },
args: ["--proxy-bypass-list=<-loopback>"],
})
const adapterUrl = `${allowedOrigin}/__replica/capture-controls.js`
const adapterUrl = `${allowedOrigin}${base}__replica/capture-controls.js`

const destinations = [
{ path: START_ROUTE, directory: "" },
Expand Down Expand Up @@ -113,7 +117,7 @@ export async function captureScreenshots(
}
})

let address = `${allowedOrigin}${destination.path}`
let address = `${allowedOrigin}${base}${destination.path.slice(1)}`
for (let attempt = 0; ; attempt++) {
if (attempt === 4)
throw new Error("Controls URL defaults did not settle after navigation.")
Expand All @@ -132,7 +136,10 @@ export async function captureScreenshots(
return bindings?.takeNavigation()
})
if (!navigation) break
if (new URL(navigation).origin !== allowedOrigin)
if (
new URL(navigation).origin !== allowedOrigin ||
!new URL(navigation).pathname.startsWith(base)
)
throw new Error("Controls URL defaults cannot leave the retained Build.")
address = navigation
}
Expand Down Expand Up @@ -176,6 +183,9 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
process.argv.includes("--config-file")
? requiredPathArgument("config-file", { resolve: false })
: undefined,
process.argv.includes("--base-path")
? requiredPathArgument("base-path", { resolve: false })
: undefined,
)
console.log(
"Captured light and dark desktop and narrow screenshots for the root page and declared templates.",
Expand Down
60 changes: 60 additions & 0 deletions actions/build/scripts/capture-screenshots/index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,66 @@ import { MAX_SCREENSHOT_HEIGHT } from "../constants.mjs"
import { captureScreenshots } from "./index.mjs"

describe("captureScreenshots()", () => {
it("boots a fixed-base app and its lazy module with Controls at root and a deep template", async () => {
const root = await temporaryDirectory()
const screenshots = await temporaryDirectory()
const base = "/previews/github/123/456/"
await mkdir(path.join(root, "dist"))
await mkdir(path.join(root, ".github"))
await writeFile(
path.join(root, "dist/index.html"),
`<!doctype html><body style="margin:0;background:blue"><input id="accent" type="color" value="#0000ff"><script type="module" src="${base}app.js"></script></body>`,
)
await writeFile(
path.join(root, "dist/app.js"),
`const base=${JSON.stringify(base)};
const { ready } = await import(base+"lazy.js");
const route = location.pathname.slice(base.length-1);
if (ready && (route === "/" || (route === "/build/agents/v2.0" && location.search === "?q=a%20b&q=second" && location.hash === "#details")))
document.querySelector("input").addEventListener("input", event => document.body.style.background=event.target.value);`,
)
await writeFile(path.join(root, "dist/lazy.js"), "export const ready=true")
await writeFile(
path.join(root, "dist/controls.replica.json"),
JSON.stringify({
version: 1,
scope: "page",
controls: [
{
id: "accent",
label: "Accent",
type: "color",
default: "#ff0000",
binding: { type: "field", selector: "#accent" },
},
],
}),
)
await writeFile(
path.join(root, ".github/replica.json"),
JSON.stringify({
version: 1,
templates: [
{
id: "agents",
name: "Agents",
category: "Build",
description: "Agent details.",
path: "/build/agents/v2.0?q=a%20b&q=second#details",
},
],
}),
)
await captureScreenshots(root, screenshots, root, ".github/replica.json", base)
for (const directory of ["", "templates/agents"]) {
const image = pngjs.PNG.sync.read(
await readFile(path.join(screenshots, directory, "desktop.png")),
)
const bottom = (image.height - 1) * image.width * 4
assert.deepEqual([...image.data.subarray(bottom, bottom + 3)], [255, 0, 0], directory)
}
})

it("blocks prototype WebSocket connections during capture", async () => {
let connected = false
const socketServer = createServer((socket) => {
Expand Down
35 changes: 33 additions & 2 deletions actions/build/scripts/create-static-server/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,36 @@ import { createServer } from "node:http"
import path from "node:path"

import { CONTENT_TYPES } from "../constants.mjs"
import { normalizeBasePath } from "../normalize-base-path/index.mjs"

/** Serves checked dist files and falls back to the app entry for browser routes. */
export function createStaticServer(dist, templatePaths = []) {
export function createStaticServer(dist, templatePaths = [], basePath = "/") {
const base = normalizeBasePath(basePath)
const templatePathnames = new Set(
templatePaths.map((route) => decodeURIComponent(new URL(route, "http://localhost").pathname)),
)

return createServer(async (request, response) => {
try {
const requestPath = decodeURIComponent(new URL(request.url, "http://localhost").pathname)
const rawPath = request.url.split("?")[0]
const decoded = decodeURIComponent(rawPath)
if (
/%2f|%5c/i.test(rawPath) ||
/[\\\p{Cc}]/u.test(decoded) ||
decoded.split("/").some((part) => part === "." || part === "..")
) {
response.writeHead(400).end()
return
}
if (base !== "/" && decoded === base.slice(0, -1)) {
response.writeHead(308, { Location: `${base}${request.url.slice(rawPath.length)}` }).end()
return
}
if (!decoded.startsWith(base)) {
response.writeHead(404).end()
return
}
const requestPath = `/${decoded.slice(base.length)}`
const templateNavigation = templatePathnames.has(requestPath)
const acceptsHtml = request.headers.accept?.includes("text/html")

Expand All @@ -33,6 +53,17 @@ export function createStaticServer(dist, templatePaths = []) {
let details
try {
details = await lstat(filePath)
if (details.isDirectory() && requestPath.endsWith("/")) {
const index = path.join(filePath, "index.html")
const indexDetails = await lstat(index).catch((error) => {
if (!["ENOENT", "ENOTDIR"].includes(error.code)) throw error
return undefined
})
if (indexDetails?.isFile()) {
filePath = index
details = indexDetails
}
}
} catch (error) {
if (!["ENOENT", "ENOTDIR", "ENAMETOOLONG"].includes(error.code)) {
throw error
Expand Down
Loading
Loading