Skip to content

Commit 1f4670d

Browse files
refactor(canvas): establish TypeScript extension foundation (#51)
<!-- Use a conventional commit-style title, such as "fix(hub): retain prototype history". --> ## Why <!-- Explain the problem and why this change matters in a short, plain-English paragraph. Link the issue when applicable. --> The canvas frontend already uses TypeScript, but the extension's Node modules remain JavaScript. This first layer of the migration establishes strict type checking without changing how people install or run the plugin. ## What changes <!-- Describe what becomes different for a first-time reader. Explain necessary terms. Include accurate Mermaid diagrams when they clarify the proposal, using before/after diagrams when helpful. Add screenshots for meaningful UI changes. --> <!-- Omit validation sections, checklists, and routine test/CI summaries such as "CI is green" or "tests passed". Mention only known verification gaps that affect the change, not disclaimers about drafting this description. --> Remote branch lookup now has TypeScript source and committed, generated JavaScript. The existing `extension.mjs` entry point, plugin installation, and browser assets stay unchanged. A declaration describes the command runner until its later conversion. Hub's lint and type-check commands include migrated modules. The extension build compiles them before building browser assets, and the freshness check also detects stale generated Node modules outside the assets directory. The contributor guide explains which source to edit and how to rebuild it. --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9d7306a9-9831-4c78-89e7-3c5b581c895e
1 parent 7945a37 commit 1f4670d

10 files changed

Lines changed: 165 additions & 21 deletions

File tree

‎.github/extensions/replica-prototype/check-assets/index.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { readdir, readFile } from "node:fs/promises"
33
import { fileURLToPath } from "node:url"
44

55
export async function checkAssets({
6-
assets = new URL("../assets/", import.meta.url),
6+
assets = new URL("../", import.meta.url),
77
build = () => execFileSync("npm", ["run", "extension:build"], { stdio: "inherit" }),
88
} = {}) {
99
const before = await snapshot(assets)

‎.github/extensions/replica-prototype/check-assets/index.test.mjs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,11 @@ describe("checkAssets()", () => {
6666
}
6767
})
6868

69-
it("runs the CLI check from a path with spaces without invoking the real build", async () => {
69+
it("checks generated Node modules outside browser assets from a path with spaces", async () => {
7070
const directory = path.join(process.cwd(), "storage/replica-extension-tests", randomUUID())
7171
const extension = path.join(directory, "extension with spaces")
7272
const scriptDirectory = path.join(extension, "check-assets")
73-
const assetFile = path.join(extension, "assets", "renderer.js")
73+
const assetFile = path.join(extension, "read-remote-branch", "index.mjs")
7474
const script = path.join(scriptDirectory, "index.mjs")
7575
await mkdir(scriptDirectory, { recursive: true })
7676
await mkdir(path.dirname(assetFile), { recursive: true })
@@ -94,7 +94,7 @@ describe("checkAssets()", () => {
9494
},
9595
stdio: "pipe",
9696
}),
97-
/Extension assets differ after build.*renderer\.js/s,
97+
/Extension assets differ after build.*read-remote-branch\/index\.mjs/s,
9898
)
9999
} finally {
100100
await rm(directory, { recursive: true, force: true })

‎.github/extensions/replica-prototype/read-remote-branch/index.mjs‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
1+
// Edit index.mts; rebuild index.mjs with Hub's extension:modules:build command.
12
import { runCommand } from "../run-command/index.mjs"
2-
33
// Matching refs returns [] for a missing branch; authorization/HTTP errors stay unknown.
44
export async function readRemoteBranch(
55
{ repository, branch, commitSha, repositoryPath },
66
run = runCommand,
77
) {
88
const identity = { repository, branch, commitSha }
99
if (!branch)
10-
return { ...identity, state: "detached", error: "Open a named branch before publishing." }
10+
return {
11+
...identity,
12+
state: "detached",
13+
error: "Open a named branch before publishing.",
14+
}
1115
if (!repository || !commitSha)
1216
return {
1317
...identity,
@@ -29,20 +33,38 @@ export async function readRemoteBranch(
2933
try {
3034
refs = JSON.parse(result.stdout)
3135
} catch {
32-
return { ...identity, state: "unknown", error: "GitHub returned invalid branch data." }
36+
return {
37+
...identity,
38+
state: "unknown",
39+
error: "GitHub returned invalid branch data.",
40+
}
3341
}
3442
if (
3543
!Array.isArray(refs) ||
36-
refs.some(
44+
!refs.every(
3745
(ref) =>
38-
!ref ||
39-
typeof ref.ref !== "string" ||
40-
!/^refs\/heads\//.test(ref.ref) ||
41-
ref.object?.type !== "commit" ||
42-
!/^[0-9a-f]{40}$/.test(ref.object?.sha || ""),
46+
typeof ref === "object" &&
47+
ref !== null &&
48+
"ref" in ref &&
49+
typeof ref.ref === "string" &&
50+
/^refs\/heads\//.test(ref.ref) &&
51+
"object" in ref &&
52+
typeof ref.object === "object" &&
53+
ref.object !== null &&
54+
"type" in ref.object &&
55+
ref.object.type === "commit" &&
56+
"sha" in ref.object &&
57+
typeof ref.object.sha === "string" &&
58+
/^[0-9a-f]{40}$/.test(ref.object.sha),
4359
)
4460
)
45-
return { ...identity, state: "unknown", error: "GitHub returned invalid branch refs." }
61+
return {
62+
...identity,
63+
state: "unknown",
64+
error: "GitHub returned invalid branch refs.",
65+
}
4666
const exact = refs.find((ref) => ref.ref === `refs/heads/${branch}`)
47-
return { ...identity, state: exact ? "present" : "absent", remoteSha: exact?.object.sha || null }
67+
return exact
68+
? { ...identity, state: "present", remoteSha: exact.object.sha }
69+
: { ...identity, state: "absent", remoteSha: null }
4870
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// Edit index.mts; rebuild index.mjs with Hub's extension:modules:build command.
2+
import { runCommand } from "../run-command/index.mjs"
3+
4+
type BranchIdentity = {
5+
repository: string | null
6+
branch: string | null
7+
commitSha: string | null
8+
}
9+
10+
type RemoteBranchResult = BranchIdentity &
11+
(
12+
| { state: "detached" | "unknown"; error: string }
13+
| { state: "present"; remoteSha: string }
14+
| { state: "absent"; remoteSha: null }
15+
)
16+
17+
type BranchRef = { ref: string; object: { type: "commit"; sha: string } }
18+
19+
// Matching refs returns [] for a missing branch; authorization/HTTP errors stay unknown.
20+
export async function readRemoteBranch(
21+
{ repository, branch, commitSha, repositoryPath }: BranchIdentity & { repositoryPath: string },
22+
run: typeof runCommand = runCommand,
23+
): Promise<RemoteBranchResult> {
24+
const identity = { repository, branch, commitSha }
25+
if (!branch)
26+
return {
27+
...identity,
28+
state: "detached",
29+
error: "Open a named branch before publishing.",
30+
}
31+
if (!repository || !commitSha)
32+
return {
33+
...identity,
34+
state: "unknown",
35+
error: "The GitHub origin or checkout commit could not be verified.",
36+
}
37+
const result = await run(
38+
"gh",
39+
[
40+
"api",
41+
"--hostname",
42+
"github.com",
43+
`repos/${repository}/git/matching-refs/heads/${encodeURIComponent(branch)}`,
44+
],
45+
repositoryPath,
46+
)
47+
if (!result.ok) return { ...identity, state: "unknown", error: result.error }
48+
let refs: unknown
49+
try {
50+
refs = JSON.parse(result.stdout)
51+
} catch {
52+
return {
53+
...identity,
54+
state: "unknown",
55+
error: "GitHub returned invalid branch data.",
56+
}
57+
}
58+
if (
59+
!Array.isArray(refs) ||
60+
!refs.every(
61+
(ref: unknown): ref is BranchRef =>
62+
typeof ref === "object" &&
63+
ref !== null &&
64+
"ref" in ref &&
65+
typeof ref.ref === "string" &&
66+
/^refs\/heads\//.test(ref.ref) &&
67+
"object" in ref &&
68+
typeof ref.object === "object" &&
69+
ref.object !== null &&
70+
"type" in ref.object &&
71+
ref.object.type === "commit" &&
72+
"sha" in ref.object &&
73+
typeof ref.object.sha === "string" &&
74+
/^[0-9a-f]{40}$/.test(ref.object.sha),
75+
)
76+
)
77+
return {
78+
...identity,
79+
state: "unknown",
80+
error: "GitHub returned invalid branch refs.",
81+
}
82+
const exact = refs.find((ref) => ref.ref === `refs/heads/${branch}`)
83+
return exact
84+
? { ...identity, state: "present", remoteSha: exact.object.sha }
85+
: { ...identity, state: "absent", remoteSha: null }
86+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export function runCommand(
2+
command: string,
3+
args: string[],
4+
cwd?: string,
5+
options?: { env?: Record<string, string | undefined> },
6+
): Promise<
7+
| { ok: true; stdout: string }
8+
| {
9+
ok: false
10+
error: string
11+
exitCode?: string | number | null
12+
stdout?: string
13+
stderr?: string
14+
}
15+
>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2023",
4+
"lib": ["ES2023"],
5+
"module": "NodeNext",
6+
"moduleResolution": "NodeNext",
7+
"strict": true,
8+
"noUncheckedIndexedAccess": true,
9+
"isolatedModules": true,
10+
"verbatimModuleSyntax": true,
11+
"noEmit": true,
12+
"noEmitOnError": true,
13+
"skipLibCheck": true,
14+
"types": []
15+
},
16+
"include": ["**/*.mts"]
17+
}

‎eslint.config.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import hubConfig from "./hub/eslint.config.ts"
22

33
export default hubConfig.map((config) =>
4-
config.files?.includes("../.github/extensions/replica-prototype/**/*.mjs")
4+
config.files?.some((pattern) => pattern.startsWith("../.github/extensions/replica-prototype/"))
55
? {
66
...config,
77
files: config.files.map((pattern) =>

‎hub/docs/prototype-canvas.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,8 @@ Plugin releases, the Controls definition format and the Canvas interface are ver
454454

455455
Canvas frontend source follows Hub's normal layers under `hub/app/javascript/`. `application/prototype-canvas/` composes the interface; `application/start-prototype-canvas/` starts it, and `application/prototype-preview-bridge/` owns the injected preview entry point. Workflow panels belong in `features/`, reusable fields and dialogs in `components/`, and stateful browser behavior in `hooks/`. Shared contracts, locale copy, protocols and URL helpers live in `utils/`; the Controls engine and definition schema live in `utils/prototype-controls/`. Extension registration and server operations remain in `.github/extensions/replica-prototype/`.
456456

457+
The canvas frontend already uses TypeScript. Extension Node modules are migrating separately, starting with `read-remote-branch/index.mts`. Edit that source, not its generated `index.mjs`. The extension's `tsconfig.json` checks migrated modules in strict mode; declarations describe dependencies that remain JavaScript. Hub's `typecheck` and `lint` commands include these modules. Run `extension:modules:build` to compile them without rebuilding the browser assets. Commit generated `.mjs` files alongside their TypeScript source so the plugin still runs without installed packages or a TypeScript loader. The host entry point remains `extension.mjs`.
458+
457459
Hub builds renderer files, Brand fonts and browser runtime into the plugin's `assets/`; commit them so installed users need no Node packages. Build configuration lives in `hub/vite.prototype-canvas.config.mjs` and `hub/script/`. Generated assets are excluded from formatting checks; do not edit them manually. There is no Vite/npm distribution or release preparation.
458460

459461
For example, a preview reload must cancel an unconfirmed click without losing a command already dequeued by the agent. Test each hook's public behavior beside its implementation, using fake timers for polling and timeouts. Keep cross-feature checks under `application/prototype-canvas/tests/`, including iframe preservation, focus restoration and explicit publication or sharing actions. Keep `index.test.tsx` beside the application component and test-only orchestration helpers under its `tests/`. Shared publication fixtures stay with the publication utility so lower-layer tests do not import application code. Create fresh fixtures inside each case without suite-level reset hooks. Shared jsdom setup supplies stateless browser shims and restores real timers; Vitest configuration resets mocks and stubbed globals before each case.
@@ -469,4 +471,4 @@ bin/devcontainer exec npm run extension:build
469471
bin/devcontainer exec npm run extension:assets:check
470472
```
471473

472-
`extension:test` runs the root plugin's Node `.mjs` tests, including a real-browser delivery check when `/usr/bin/chromium` is available (as in the devcontainer). It covers cross-origin frames, `script-src 'self'`, HTTPS, runtime replacement, and late registration recovery. Hub's `npm test` discovers runtime and renderer Vitest tests; `npm test -- PATH` selects a test path. `npm run lint` checks authored source with ESLint and Prettier. `extension:assets:check` rebuilds and compares root plugin assets, failing for changed, missing, or unexpected generated files and files over the installer's 1,000,000-byte per-file limit. Run `extension:build` before that check, then include generated files with source changes. Both local `bin/ci` and GitHub CI run the extension checks. See [Development](development.md) and [Testing and operations](testing-and-operations.md).
474+
`extension:test` runs the root plugin's Node `.mjs` tests, including a real-browser delivery check when `/usr/bin/chromium` is available (as in the devcontainer). It covers cross-origin frames, `script-src 'self'`, HTTPS, runtime replacement, and late registration recovery. Hub's `npm test` discovers runtime and renderer Vitest tests; `npm test -- PATH` selects a test path. `npm run lint` checks authored source with ESLint and Prettier. `extension:build` compiles migrated Node modules before building the browser assets. `extension:assets:check` rebuilds and compares the plugin's files, including generated Node modules outside `assets/`, failing for changed, missing, or unexpected generated files and files over the installer's 1,000,000-byte per-file limit. Run `extension:build` before that check, then include generated files with source changes. Both local `bin/ci` and GitHub CI run the extension checks. See [Development](development.md) and [Testing and operations](testing-and-operations.md).

‎hub/eslint.config.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export default defineConfig(
2727
js.configs.recommended,
2828
...tseslint.configs.recommendedTypeChecked,
2929
{
30-
files: ["**/*.{ts,tsx}"],
30+
files: ["**/*.{ts,tsx,mts}", "../.github/extensions/replica-prototype/**/*.mts"],
3131
languageOptions: {
3232
globals: { ...globals.browser, ...globals.node },
3333
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
@@ -103,6 +103,7 @@ export default defineConfig(
103103
"script/**/*.mjs",
104104
"test/**/*.mjs",
105105
"../.github/extensions/replica-prototype/**/*.mjs",
106+
"../.github/extensions/replica-prototype/**/*.d.mts",
106107
"app/javascript/utils/prototype-controls/**/*.mjs",
107108
"app/javascript/utils/prototype-controls/**/*.d.mts",
108109
"../packages/learning/**/*.mjs",

‎hub/package.json‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@
1616
"build": "npm run typecheck && vite build",
1717
"dev": "vite dev",
1818
"extension:assets:check": "node ../.github/extensions/replica-prototype/check-assets/index.mjs",
19-
"extension:build": "vite build --config vite.prototype-canvas.config.mjs && node script/build-prototype-preview-bridge.mjs",
19+
"extension:build": "npm run extension:modules:build && vite build --config vite.prototype-canvas.config.mjs && node script/build-prototype-preview-bridge.mjs",
20+
"extension:modules:build": "tsc --project ../.github/extensions/replica-prototype/tsconfig.json --noEmit false && prettier --write '../.github/extensions/replica-prototype/read-remote-branch/index.mjs' --config .prettierrc.json",
2021
"extension:test": "npm run controls:runtime:test && node --test ../.github/extensions/replica-prototype/**/*.test.mjs",
2122
"format": "prettier --write .",
22-
"lint": "eslint . ../.github/extensions/replica-prototype ../packages/learning && prettier --check . '../eslint.config.mjs' '../.github/extensions/replica-prototype/**/*.mjs' '../.github/extensions/replica-prototype/*.json' '../packages/learning/**/*.{mjs,mts,json}' --config .prettierrc.json",
23+
"lint": "eslint . ../.github/extensions/replica-prototype ../packages/learning && prettier --check . '../eslint.config.mjs' '../.github/extensions/replica-prototype/**/*.{mjs,mts}' '../.github/extensions/replica-prototype/*.json' '../packages/learning/**/*.{mjs,mts,json}' --config .prettierrc.json",
2324
"storybook": "STORYBOOK_DISABLE_TELEMETRY=1 storybook dev --host 0.0.0.0 --port 6006 --initial-path /story/hub-design-overview--taxonomy",
2425
"storybook:build": "STORYBOOK_DISABLE_TELEMETRY=1 storybook build --output-dir storybook-static",
2526
"test": "vitest run",
26-
"typecheck": "tsc --noEmit"
27+
"typecheck": "tsc --noEmit && tsc --project ../.github/extensions/replica-prototype/tsconfig.json"
2728
},
2829
"dependencies": {
2930
"@primer/octicons-react": "19.40.0",

0 commit comments

Comments
 (0)