@risinghq/lienzo 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +82 -2
  2. package/dist/shell/assets/index-Cna8wlzF.js +4 -0
  3. package/dist/shell/assets/index-CoJSASvW.css +2 -0
  4. package/dist/shell/index.html +13 -0
  5. package/package.json +76 -4
  6. package/src/bench/bench.ts +132 -0
  7. package/src/bridge/page.ts +443 -0
  8. package/src/bridge/protocol.ts +124 -0
  9. package/src/bridge/record.ts +75 -0
  10. package/src/bridge/script.ts +24 -0
  11. package/src/bridge/state.ts +143 -0
  12. package/src/capture/capture.ts +125 -0
  13. package/src/capture/compare.ts +46 -0
  14. package/src/capture/diff.ts +16 -0
  15. package/src/capture/manifest.ts +60 -0
  16. package/src/capture/refs.ts +20 -0
  17. package/src/capture/replay.ts +25 -0
  18. package/src/capture/review.ts +78 -0
  19. package/src/capture/serve.ts +32 -0
  20. package/src/capture/snap.ts +62 -0
  21. package/src/capture/store.ts +28 -0
  22. package/src/cli.ts +287 -0
  23. package/src/cloud/checkout.ts +33 -0
  24. package/src/cloud/credentials.ts +25 -0
  25. package/src/cloud/link.ts +60 -0
  26. package/src/cloud/login.ts +85 -0
  27. package/src/commands/canvas.ts +46 -0
  28. package/src/commands/change.ts +218 -0
  29. package/src/commands/class.ts +66 -0
  30. package/src/commands/command.ts +27 -0
  31. package/src/commands/create.ts +95 -0
  32. package/src/commands/element.ts +118 -0
  33. package/src/commands/file.ts +96 -0
  34. package/src/commands/frame.ts +58 -0
  35. package/src/commands/override.ts +38 -0
  36. package/src/commands/prop.ts +18 -0
  37. package/src/commands/registry.ts +76 -0
  38. package/src/commands/rule.ts +131 -0
  39. package/src/commands/stage.ts +52 -0
  40. package/src/commands/story.ts +112 -0
  41. package/src/commands/style.ts +123 -0
  42. package/src/commands/text.ts +17 -0
  43. package/src/commands/token.ts +60 -0
  44. package/src/commands/transaction.ts +66 -0
  45. package/src/job/docker.ts +109 -0
  46. package/src/job/job.ts +125 -0
  47. package/src/job/server.ts +62 -0
  48. package/src/mirror/apply.ts +121 -0
  49. package/src/mirror/entry.ts +7 -0
  50. package/src/mirror/host.ts +68 -0
  51. package/src/mirror/observe.ts +271 -0
  52. package/src/mirror/script.ts +18 -0
  53. package/src/mirror/transport.ts +7 -0
  54. package/src/mirror/wire.ts +25 -0
  55. package/src/project/config.ts +98 -0
  56. package/src/project/design.ts +59 -0
  57. package/src/project/detect.ts +184 -0
  58. package/src/project/files.ts +30 -0
  59. package/src/project/git.ts +68 -0
  60. package/src/project/github.ts +42 -0
  61. package/src/project/history.ts +89 -0
  62. package/src/project/project.ts +106 -0
  63. package/src/project/spawn.ts +23 -0
  64. package/src/project/step.ts +15 -0
  65. package/src/protocol.ts +125 -0
  66. package/src/sandbox/forward.ts +73 -0
  67. package/src/sandbox/install.ts +44 -0
  68. package/src/sandbox/sandbox.ts +57 -0
  69. package/src/serve/build.ts +49 -0
  70. package/src/serve/canvases.ts +65 -0
  71. package/src/serve/dev.ts +296 -0
  72. package/src/serve/env.ts +16 -0
  73. package/src/serve/mcp.ts +65 -0
  74. package/src/serve/middleware.ts +172 -0
  75. package/src/serve/next/config.ts +68 -0
  76. package/src/serve/next/hook.ts +74 -0
  77. package/src/serve/next/loader.ts +37 -0
  78. package/src/serve/nuxt.ts +14 -0
  79. package/src/serve/plugin.ts +95 -0
  80. package/src/serve/preload.ts +167 -0
  81. package/src/serve/resend.ts +29 -0
  82. package/src/serve/running.ts +115 -0
  83. package/src/serve/screenshot.ts +26 -0
  84. package/src/serve/sources.ts +46 -0
  85. package/src/serve/uncached.ts +25 -0
  86. package/src/serve/vite-build.ts +15 -0
  87. package/src/serve/vite.ts +19 -0
  88. package/src/session/session.ts +96 -0
  89. package/src/share/ask.ts +24 -0
  90. package/src/share/client.ts +140 -0
  91. package/src/share/consent.ts +39 -0
  92. package/src/share/frame.ts +26 -0
  93. package/src/source/astro/astro.ts +10 -0
  94. package/src/source/astro/elements.ts +60 -0
  95. package/src/source/blocks.ts +42 -0
  96. package/src/source/css.ts +48 -0
  97. package/src/source/estree.ts +55 -0
  98. package/src/source/extract.ts +68 -0
  99. package/src/source/insert.ts +189 -0
  100. package/src/source/jsx/elements.ts +136 -0
  101. package/src/source/jsx/jsx.ts +5 -0
  102. package/src/source/language.ts +176 -0
  103. package/src/source/location.ts +34 -0
  104. package/src/source/modules.ts +41 -0
  105. package/src/source/overrides.ts +35 -0
  106. package/src/source/page.ts +69 -0
  107. package/src/source/patch.ts +79 -0
  108. package/src/source/prop.ts +34 -0
  109. package/src/source/refusal.ts +7 -0
  110. package/src/source/rules.ts +298 -0
  111. package/src/source/stamp.ts +28 -0
  112. package/src/source/story-file.ts +40 -0
  113. package/src/source/story.ts +162 -0
  114. package/src/source/structure.ts +253 -0
  115. package/src/source/style.ts +143 -0
  116. package/src/source/svelte/elements.ts +154 -0
  117. package/src/source/svelte/svelte.ts +11 -0
  118. package/src/source/tag.ts +99 -0
  119. package/src/source/tailwind.ts +46 -0
  120. package/src/source/tokens.ts +56 -0
  121. package/src/source/vue/elements.ts +236 -0
  122. package/src/source/vue/vue.ts +11 -0
@@ -0,0 +1,25 @@
1
+ // The Nuxt module `dev` adds to a Nuxt app. Nitro serves a route with a cache
2
+ // rule from its cache, so the frame would show the page as it was before an
3
+ // edit. Nitro builds that cache from the route rules at startup and no
4
+ // request skips it, so the module removes the cache rules before Nitro
5
+ // starts.
6
+ type Rules = Record<string, Record<string, unknown>>;
7
+
8
+ type Nuxt = { hook(name: "nitro:config", run: (config: { routeRules?: Rules }) => void): void };
9
+
10
+ const CACHING = ["cache", "swr", "isr"];
11
+
12
+ export function uncached(rules: Rules = {}): Rules {
13
+ return Object.fromEntries(
14
+ Object.entries(rules).map(([route, rule]) => [
15
+ route,
16
+ Object.fromEntries(Object.entries(rule).filter(([key]) => !CACHING.includes(key))),
17
+ ]),
18
+ );
19
+ }
20
+
21
+ export function uncachedModule(_options: unknown, nuxt: Nuxt) {
22
+ nuxt.hook("nitro:config", (config) => {
23
+ config.routeRules = uncached(config.routeRules);
24
+ });
25
+ }
@@ -0,0 +1,15 @@
1
+ // Run by `build` in a project's root, under the preload, for a project with no
2
+ // build script: it builds from the project's config, as `vite build` would.
3
+
4
+ import type * as Vite from "vite";
5
+
6
+ async function viteOf(root: string): Promise<typeof Vite> {
7
+ try {
8
+ return (await import(Bun.resolveSync("vite", root))) as typeof Vite;
9
+ } catch {
10
+ return await import("vite");
11
+ }
12
+ }
13
+
14
+ const vite = await viteOf(process.cwd());
15
+ await vite.build();
@@ -0,0 +1,19 @@
1
+ // Run by `dev` in a project's root, under the preload, as Vite's own CLI
2
+ // would run: Vite serves the pages from the project's config and its
3
+ // index.html. The project's own Vite runs its config, so its plugins meet the
4
+ // version they were written for. lienzo's copy serves a project that has none.
5
+
6
+ import type * as Vite from "vite";
7
+
8
+ async function viteOf(root: string): Promise<typeof Vite> {
9
+ try {
10
+ return (await import(Bun.resolveSync("vite", root))) as typeof Vite;
11
+ } catch {
12
+ return await import("vite");
13
+ }
14
+ }
15
+
16
+ const vite = await viteOf(process.cwd());
17
+ const server = await vite.createServer();
18
+
19
+ await server.listen();
@@ -0,0 +1,96 @@
1
+ import { rm } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { changesOf, cloneAt, type Change } from "../job/job.ts";
4
+ import { CONFIG } from "../project/config.ts";
5
+
6
+ // What a session opens in its clone: the dev server, reachable on the session's
7
+ // public port, and the path of the canvas on it.
8
+ export type Opened = { canvas: string; close(): Promise<void> };
9
+
10
+ export type Open = (dir: string) => Promise<Opened>;
11
+
12
+ // The control side of a hosted authoring session, for a container that holds no
13
+ // credentials. The caller starts it once; the dev server then answers on its
14
+ // own port.
15
+ //
16
+ // POST /start body: {repo, sha, token?, root?, config?}
17
+ // -> {ok: true, canvas} or {ok: false, reason}
18
+ // GET /changed -> {repo, sha, changed}, the files the edits wrote
19
+ //
20
+ // A session is one clone and one dev server. A second start is refused.
21
+ //
22
+ // `root` is the folder of the clone the project lives in. `config` is the
23
+ // project's stored lienzo.json: it is written into that folder when the commit
24
+ // has none, and is not a change until an edit alters it.
25
+ export function sessionServer(open: Open, work: string, port: number) {
26
+ // `repo` is kept without the token.
27
+ let started:
28
+ | { dir: string; repo: string; sha: string; opened: Opened; seeded?: Change }
29
+ | undefined;
30
+ let starting = false;
31
+
32
+ return Bun.serve({
33
+ port,
34
+ idleTimeout: 0,
35
+ async fetch(request) {
36
+ const { pathname } = new URL(request.url);
37
+
38
+ if (request.method === "POST" && pathname === "/start") {
39
+ if (starting || started)
40
+ return Response.json({ ok: false, reason: "started" }, { status: 409 });
41
+ starting = true;
42
+
43
+ const {
44
+ token,
45
+ repo,
46
+ sha,
47
+ root = "",
48
+ config,
49
+ } = (await request.json()) as {
50
+ repo: string;
51
+ sha: string;
52
+ token?: string;
53
+ root?: string;
54
+ config?: unknown;
55
+ };
56
+ // Git echoes the clone URL, so a reason must not carry the token out.
57
+ const hide = (reason: string) => (token ? reason.replaceAll(token, "***") : reason);
58
+ const url = token ? repo.replace("https://", `https://x-access-token:${token}@`) : repo;
59
+ let dir: string | undefined;
60
+ try {
61
+ dir = await cloneAt(work, url, sha);
62
+ const project = path.join(dir, root);
63
+ const file = path.join(project, CONFIG);
64
+ let seeded: Change | undefined;
65
+ if (config !== undefined && !(await Bun.file(file).exists())) {
66
+ const content = `${JSON.stringify(config, null, 2)}\n`;
67
+ await Bun.write(file, content);
68
+ seeded = { path: path.relative(dir, file), content };
69
+ }
70
+ started = { dir, repo, sha, opened: await open(project), seeded };
71
+
72
+ return Response.json({ ok: true, canvas: started.opened.canvas });
73
+ } catch (error) {
74
+ if (dir) await rm(dir, { recursive: true, force: true });
75
+ const reason = error instanceof Error ? error.message : String(error);
76
+
77
+ return Response.json({ ok: false, reason: hide(reason) }, { status: 422 });
78
+ } finally {
79
+ starting = false;
80
+ }
81
+ }
82
+
83
+ if (request.method === "GET" && pathname === "/changed") {
84
+ if (!started) return Response.json({ ok: false, reason: "not started" }, { status: 409 });
85
+ const { seeded } = started;
86
+ const changed = (await changesOf(started.dir)).filter(
87
+ (file) => !(seeded && file.path === seeded.path && file.content === seeded.content),
88
+ );
89
+
90
+ return Response.json({ ok: true, repo: started.repo, sha: started.sha, changed });
91
+ }
92
+
93
+ return new Response("not found", { status: 404 });
94
+ },
95
+ });
96
+ }
@@ -0,0 +1,24 @@
1
+ import readline from "node:readline/promises";
2
+ import type { Approve } from "./consent.ts";
3
+
4
+ export function askOnTerminal(input: NodeJS.ReadStream, output: NodeJS.WriteStream): Approve {
5
+ let turn: Promise<unknown> = Promise.resolve();
6
+
7
+ return (command, message) => {
8
+ if (!input.isTTY) return Promise.resolve(false);
9
+
10
+ const answered = turn.then(async () => {
11
+ const terminal = readline.createInterface({ input, output });
12
+ const subject = message.split("\n")[0] || command;
13
+ const answer = await terminal.question(
14
+ `designer asks for ${command}: "${subject}". Accept? [y/N] `,
15
+ );
16
+ terminal.close();
17
+
18
+ return answer.trim().toLowerCase() === "y";
19
+ });
20
+ turn = answered.catch(() => undefined);
21
+
22
+ return answered;
23
+ };
24
+ }
@@ -0,0 +1,140 @@
1
+ import { MirrorHost } from "../mirror/host.ts";
2
+ import type { Order } from "../mirror/transport.ts";
3
+ import { declined, type Approve } from "./consent.ts";
4
+ import { decode, encode, type Frame } from "./frame.ts";
5
+
6
+ // What the dev server must not take from a viewer's request, or hand back as
7
+ // the relay carries it: the host and the body's framing belong to the hop.
8
+ const REQUEST_DROPPED = new Set(["host", "connection", "content-length", "origin", "referer"]);
9
+ const RESPONSE_DROPPED = new Set(["content-encoding", "content-length", "transfer-encoding"]);
10
+
11
+ // A redirect to the dev server's own origin becomes a path, which the viewer's
12
+ // browser resolves on the host it is on. Other origins stay as they are.
13
+ function viewerLocation(site: string, location: string): string {
14
+ const target = new URL(location, site);
15
+
16
+ return target.origin === new URL(site).origin
17
+ ? `${target.pathname}${target.search}${target.hash}`
18
+ : location;
19
+ }
20
+
21
+ // The dev server's answer to a request the edge relayed. A redirect goes back
22
+ // to the viewer's browser, which follows it on its own host.
23
+ export async function answer(site: string, request: Frame): Promise<Frame> {
24
+ const head = request.head;
25
+ if (!("method" in head)) throw new Error("not a request");
26
+
27
+ const headers = head.headers.filter(([name]) => !REQUEST_DROPPED.has(name.toLowerCase()));
28
+ const hasBody = head.method !== "GET" && head.method !== "HEAD";
29
+
30
+ try {
31
+ const response = await fetch(new URL(head.path, site), {
32
+ method: head.method,
33
+ headers,
34
+ body: hasBody ? request.body : undefined,
35
+ redirect: "manual",
36
+ });
37
+
38
+ return {
39
+ head: {
40
+ id: head.id,
41
+ status: response.status,
42
+ headers: [...response.headers]
43
+ .filter(([name]) => !RESPONSE_DROPPED.has(name))
44
+ .map(([name, value]) => [
45
+ name,
46
+ name === "location" ? viewerLocation(site, value) : value,
47
+ ]),
48
+ },
49
+ body: new Uint8Array(await response.arrayBuffer()),
50
+ };
51
+ } catch (error) {
52
+ return {
53
+ head: { id: head.id, status: 502, headers: [["content-type", "text/plain"]] },
54
+ body: new TextEncoder().encode(`the dev server did not answer: ${(error as Error).message}`),
55
+ };
56
+ }
57
+ }
58
+
59
+ export type Shared = {
60
+ id: string;
61
+ link: string;
62
+ close: () => void;
63
+ };
64
+
65
+ type Options = {
66
+ site: string;
67
+ edge: string;
68
+ token: string;
69
+ name: string;
70
+ fetch?: typeof fetch;
71
+ approve?: Approve;
72
+ // How long to wait before the nth reconnect, in milliseconds.
73
+ backoff?: (attempt: number) => number;
74
+ };
75
+
76
+ const RETRY_LIMIT = 10_000;
77
+
78
+ // Registers a share at the edge and keeps the websocket to it open, answering
79
+ // each request the edge relays from `site`. The link is the edge's answer.
80
+ // A dropped socket is opened again until `close`.
81
+ export async function share(options: Options): Promise<Shared> {
82
+ const call = options.fetch ?? fetch;
83
+ const registered = await call(new URL("/shares", options.edge), {
84
+ method: "POST",
85
+ headers: { authorization: `Bearer ${options.token}` },
86
+ body: JSON.stringify({ name: options.name }),
87
+ });
88
+ if (!registered.ok)
89
+ throw new Error(`${options.edge} refused the share: ${await registered.text()}`);
90
+ const { id, link, connect } = (await registered.json()) as {
91
+ id: string;
92
+ link: string;
93
+ connect: string;
94
+ };
95
+
96
+ let closed = false;
97
+ let socket: WebSocket | undefined;
98
+ const mirror = new MirrorHost({
99
+ site: options.site,
100
+ send: (delivery) => {
101
+ if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(delivery));
102
+ },
103
+ });
104
+ const backoff = options.backoff ?? ((attempt) => Math.min(RETRY_LIMIT, 250 * 2 ** attempt));
105
+
106
+ const open = (attempt: number) => {
107
+ if (closed) return;
108
+ const next = new WebSocket(connect, {
109
+ headers: { authorization: `Bearer ${options.token}` },
110
+ } as unknown as string[]);
111
+ next.binaryType = "arraybuffer";
112
+ socket = next;
113
+
114
+ next.onopen = () => {
115
+ attempt = 0;
116
+ };
117
+ next.onmessage = async (event) => {
118
+ if (typeof event.data === "string") return mirror.order(JSON.parse(event.data) as Order);
119
+ const request = decode(event.data as ArrayBuffer);
120
+ const response =
121
+ (await declined(request, options.approve ?? (async () => false))) ??
122
+ (await answer(options.site, request));
123
+ if (next.readyState === WebSocket.OPEN) next.send(encode(response));
124
+ };
125
+ next.onclose = () => {
126
+ if (!closed) setTimeout(() => open(attempt + 1), backoff(attempt));
127
+ };
128
+ };
129
+ open(0);
130
+
131
+ return {
132
+ id,
133
+ link,
134
+ close: () => {
135
+ closed = true;
136
+ socket?.close();
137
+ void mirror.close();
138
+ },
139
+ };
140
+ }
@@ -0,0 +1,39 @@
1
+ import { API } from "../protocol.ts";
2
+ import type { Frame } from "./frame.ts";
3
+
4
+ export type Approve = (command: string, message: string) => Promise<boolean>;
5
+
6
+ const GATED = new Set(["change.commit", "change.propose"]);
7
+ const RUN = `${API}run`;
8
+
9
+ type Run = { name?: unknown; params?: { message?: unknown } };
10
+
11
+ function runOf(request: Frame): Run | undefined {
12
+ const head = request.head;
13
+ if (!("method" in head) || head.method !== "POST" || head.path.split("?")[0] !== RUN) return;
14
+
15
+ try {
16
+ return JSON.parse(new TextDecoder().decode(request.body)) as Run;
17
+ } catch {
18
+ return undefined;
19
+ }
20
+ }
21
+
22
+ function refusal(request: Frame, reason: string): Frame {
23
+ const id = request.head.id;
24
+
25
+ return {
26
+ head: { id, status: 200, headers: [["content-type", "application/json"]] },
27
+ body: new TextEncoder().encode(JSON.stringify({ ok: false, reason })),
28
+ };
29
+ }
30
+
31
+ export async function declined(request: Frame, approve: Approve): Promise<Frame | undefined> {
32
+ const run = runOf(request);
33
+ if (typeof run?.name !== "string" || !GATED.has(run.name)) return undefined;
34
+
35
+ const message = typeof run.params?.message === "string" ? run.params.message : "";
36
+ if (await approve(run.name, message)) return undefined;
37
+
38
+ return refusal(request, "the developer did not accept it");
39
+ }
@@ -0,0 +1,26 @@
1
+ // One message on the relay's websocket: a request a viewer made, or the
2
+ // response the developer's server gave. A message is the head's length as four
3
+ // big-endian bytes, the head as JSON, and the body's bytes.
4
+ export type Head =
5
+ | { id: number; method: string; path: string; headers: [string, string][] }
6
+ | { id: number; status: number; headers: [string, string][] };
7
+
8
+ export type Frame = { head: Head; body: Uint8Array<ArrayBuffer> };
9
+
10
+ export function encode(frame: Frame): Uint8Array<ArrayBuffer> {
11
+ const head = new TextEncoder().encode(JSON.stringify(frame.head));
12
+ const bytes = new Uint8Array(4 + head.length + frame.body.length);
13
+ new DataView(bytes.buffer).setUint32(0, head.length);
14
+ bytes.set(head, 4);
15
+ bytes.set(frame.body, 4 + head.length);
16
+
17
+ return bytes;
18
+ }
19
+
20
+ export function decode(data: ArrayBuffer | Uint8Array): Frame {
21
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
22
+ const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0);
23
+ const head = JSON.parse(new TextDecoder().decode(bytes.subarray(4, 4 + length))) as Head;
24
+
25
+ return { head, body: bytes.slice(4 + length) };
26
+ }
@@ -0,0 +1,10 @@
1
+ import type { Language } from "../language.ts";
2
+ import { defaultImports, elements } from "./elements.ts";
3
+
4
+ // Astro components in `.astro` files.
5
+ export const astro: Language = {
6
+ extensions: [".astro"],
7
+ classAttribute: "class",
8
+ elements,
9
+ defaultImports,
10
+ };
@@ -0,0 +1,60 @@
1
+ import { parse as parseAstro } from "@astrojs/compiler-rs";
2
+ import { defaultImportsOf, type Node } from "../estree.ts";
3
+ import { elementsOf } from "../jsx/elements.ts";
4
+ import type { Attribute, Element } from "../language.ts";
5
+
6
+ // Lowercase tags Astro consumes rather than draws. An attribute on a
7
+ // `<script>` also turns off Astro's processing of it.
8
+ const CONSUMED = new Set(["script", "style", "slot"]);
9
+
10
+ // Directives that set an element's content from an expression.
11
+ const CONTENT = new Set(["set:html", "set:text"]);
12
+
13
+ // Astro's compiler reads a component into the ESTree AST of oxc: the
14
+ // frontmatter as a program, the template as JSX nodes.
15
+ function parse(file: string, source: string): Node {
16
+ const { ast, diagnostics } = parseAstro(source);
17
+
18
+ const first = diagnostics.find((diagnostic) => diagnostic.severity === "error");
19
+ if (first) throw new Error(`${file}: ${first.text}`);
20
+
21
+ return ast as Node;
22
+ }
23
+
24
+ // `class:list` merges into `class` at render, so it reads as a computed
25
+ // `class`.
26
+ function astroAttribute(attribute: Attribute): Attribute {
27
+ if (attribute.name !== "class:list") return attribute;
28
+
29
+ const { start, end } = attribute;
30
+ return {
31
+ name: "class",
32
+ start,
33
+ end,
34
+ value: attribute.value && { ...attribute.value, literal: undefined, member: undefined },
35
+ };
36
+ }
37
+
38
+ function astroElement(element: Element): Element {
39
+ const attributes = element.attributes.map(astroAttribute);
40
+ const computed = element.attributes.some((attribute) => CONTENT.has(attribute.name));
41
+
42
+ return {
43
+ ...element,
44
+ host: element.host && !CONSUMED.has(element.name),
45
+ attributes,
46
+ text: computed ? undefined : element.text,
47
+ };
48
+ }
49
+
50
+ // Every element of the template, in source order. Throws on a syntax error.
51
+ export function elements(file: string, source: string): Element[] {
52
+ return elementsOf(source, parse(file, source)).map(astroElement);
53
+ }
54
+
55
+ // The default imports of the frontmatter, which the template sees.
56
+ export function defaultImports(file: string, source: string): Map<string, string> {
57
+ const frontmatter = parse(file, source).frontmatter as { program: Node };
58
+
59
+ return defaultImportsOf(frontmatter.program);
60
+ }
@@ -0,0 +1,42 @@
1
+ import path from "node:path";
2
+ import { languageOf, type StyleBlock } from "./language.ts";
3
+ import { refuse, type Refusal } from "./refusal.ts";
4
+
5
+ type Reader = (file: string, source: string) => StyleBlock[];
6
+
7
+ const whole: Reader = (_file, source) => [{ start: 0, css: source }];
8
+
9
+ function readerOf(file: string): { ok: true; read: Reader } | Refusal {
10
+ if (path.extname(file) === ".css") return { ok: true, read: whole };
11
+
12
+ const found = languageOf(file);
13
+ const styles = found.ok ? found.language.styles : undefined;
14
+
15
+ return styles
16
+ ? { ok: true, read: styles }
17
+ : refuse(`${file} is not a stylesheet or a component with style blocks`);
18
+ }
19
+
20
+ // Whether lienzo reads CSS in the file, from its name alone.
21
+ export function holdsCss(file: string): { ok: true } | Refusal {
22
+ const reader = readerOf(file);
23
+
24
+ return reader.ok ? { ok: true } : reader;
25
+ }
26
+
27
+ // The CSS of a file: all of a stylesheet, or each style block of a component.
28
+ // A block in Sass, Less or another language is refused: a preprocessor turns
29
+ // it into other CSS, so a rule found in the browser cannot be placed in it.
30
+ export function blocksOf(
31
+ file: string,
32
+ source: string,
33
+ ): { ok: true; blocks: StyleBlock[] } | Refusal {
34
+ const reader = readerOf(file);
35
+ if (!reader.ok) return reader;
36
+
37
+ const blocks = reader.read(file, source);
38
+ const other = blocks.find((block) => block.lang !== undefined && block.lang !== "css");
39
+ if (other) return refuse(`${file} has a <style lang="${other.lang}">; lienzo edits plain CSS`);
40
+
41
+ return { ok: true, blocks };
42
+ }
@@ -0,0 +1,48 @@
1
+ import postcss, { type AtRule, type Container, type Declaration, type Document } from "postcss";
2
+
3
+ // The value of a declaration as the stylesheet states it, and its offsets.
4
+ export type Value = { value: string; start: number; end: number };
5
+
6
+ const CONDITIONS = ["media", "supports", "container"];
7
+
8
+ // Throws when the CSS does not parse, with the line that failed.
9
+ export function parseCss(file: string, source: string) {
10
+ return postcss.parse(source, { from: file });
11
+ }
12
+
13
+ // Inside `@media`, `@supports` or `@container`: a declaration there holds for
14
+ // some screens only.
15
+ export function conditional(node: Container | Document | undefined): boolean {
16
+ if (!node || node.type === "root" || node.type === "document") return false;
17
+ if (node.type === "atrule" && CONDITIONS.includes((node as AtRule).name)) return true;
18
+
19
+ return conditional(node.parent);
20
+ }
21
+
22
+ // Everything between the colon and the `;` or the end of the rule, with
23
+ // `!important`: a new value replaces the flag too, so it is never doubled. The
24
+ // space before `;` stays outside the span.
25
+ export function valueOf(declaration: Declaration): Value {
26
+ const source = declaration.source!.input.css;
27
+ const opening = declaration.source!.start!.offset;
28
+ const start = opening + declaration.prop.length + (declaration.raws.between ?? ":").length;
29
+ const close = declaration.source!.end!.offset;
30
+ const value = source.slice(start, close).replace(/;$/, "").trimEnd();
31
+
32
+ return { value, start, end: start + value.length };
33
+ }
34
+
35
+ // The value, trimmed, when it can stand as one declaration's value. A `;`,
36
+ // brace, open comment, string or bracket would spill into the rest of the
37
+ // stylesheet.
38
+ export function cleanValue(value: string): string | undefined {
39
+ const next = value.trim();
40
+ if (!next || /[;{}]/.test(next)) return undefined;
41
+
42
+ try {
43
+ const parsed = postcss.parse(`a{b:${next}}`).first as Container | undefined;
44
+ return parsed?.nodes?.length === 1 && parsed.first?.type === "decl" ? next : undefined;
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ }
@@ -0,0 +1,55 @@
1
+ // What oxc and Svelte's parser both produce: ESTree nodes with offsets.
2
+
3
+ export type Node = { type: string; start: number; end: number; [key: string]: unknown };
4
+
5
+ // `styles.card` or `styles["card"]`: one member of one object.
6
+ export type MemberName = { object: string; property: string };
7
+
8
+ export function isNode(value: unknown): value is Node {
9
+ return typeof value === "object" && value !== null && "type" in value;
10
+ }
11
+
12
+ export function walk(node: Node, visit: (node: Node) => void) {
13
+ visit(node);
14
+
15
+ for (const value of Object.values(node)) {
16
+ if (Array.isArray(value)) {
17
+ for (const item of value) if (isNode(item)) walk(item, visit);
18
+ } else if (isNode(value)) {
19
+ walk(value, visit);
20
+ }
21
+ }
22
+ }
23
+
24
+ export function memberOf(expression: Node): MemberName | undefined {
25
+ if (expression.type !== "MemberExpression") return undefined;
26
+ if (!isNode(expression.object) || expression.object.type !== "Identifier") return undefined;
27
+
28
+ const object = expression.object.name as string;
29
+ const key = expression.property;
30
+ if (!isNode(key)) return undefined;
31
+
32
+ if (!expression.computed && key.type === "Identifier") {
33
+ return { object, property: key.name as string };
34
+ }
35
+ if (expression.computed && key.type === "Literal" && typeof key.value === "string") {
36
+ return { object, property: key.value };
37
+ }
38
+
39
+ return undefined;
40
+ }
41
+
42
+ // What each default import of a program names: `import styles from
43
+ // "./a.module.css"` maps `styles` to `./a.module.css`.
44
+ export function defaultImportsOf(program: Node, into = new Map<string, string>()) {
45
+ for (const statement of program.body as Node[]) {
46
+ if (statement.type !== "ImportDeclaration" || !isNode(statement.source)) continue;
47
+
48
+ for (const specifier of statement.specifiers as Node[]) {
49
+ if (specifier.type !== "ImportDefaultSpecifier" || !isNode(specifier.local)) continue;
50
+ into.set(specifier.local.name as string, statement.source.value as string);
51
+ }
52
+ }
53
+
54
+ return into;
55
+ }
@@ -0,0 +1,68 @@
1
+ import { childAt } from "./structure.ts";
2
+ import type { Location } from "./location.ts";
3
+ import { refuse, type Refusal } from "./refusal.ts";
4
+
5
+ export type Extracted = { ok: true; source: string; component: string };
6
+
7
+ const JSX_FILE = /\.[jt]sx$/;
8
+ const IMPORT = /^import\s[^;]*?["'][^"']+["'];?[ \t]*$/gm;
9
+
10
+ function lastImportEnd(source: string): number {
11
+ let end = 0;
12
+ for (const found of source.matchAll(IMPORT)) end = found.index + found[0].length;
13
+
14
+ return end;
15
+ }
16
+
17
+ function indentOf(source: string, offset: number): string {
18
+ const start = source.lastIndexOf("\n", offset - 1) + 1;
19
+ const lead = source.slice(start, offset);
20
+
21
+ return /^[ \t]*$/.test(lead) ? lead : "";
22
+ }
23
+
24
+ function dedent(text: string, indent: string): string {
25
+ return text
26
+ .split("\n")
27
+ .map((line, index) => (index > 0 && line.startsWith(indent) ? line.slice(indent.length) : line))
28
+ .join("\n");
29
+ }
30
+
31
+ // Moves the element at `at` into a component named `name` that the file
32
+ // imports from `./name`. An element with `{...}` in it may use values of the
33
+ // file, which the new component cannot see, so it refuses.
34
+ export function extractElement(
35
+ file: string,
36
+ source: string,
37
+ at: Location,
38
+ name: string,
39
+ ): Extracted | Refusal {
40
+ if (!JSX_FILE.test(file)) return refuse(`${file} is not a JSX file`);
41
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name)) return refuse(`"${name}" is not a component name`);
42
+ if (new RegExp(`\\b${name}\\b`).test(source))
43
+ return refuse(`${file} already uses the name ${name}`);
44
+
45
+ const found = childAt(source, at);
46
+ if (!found.ok) return found;
47
+
48
+ const { element } = found;
49
+ const text = source.slice(element.start, element.end);
50
+ if (text.includes("{")) {
51
+ return refuse(`<${element.name}> holds expressions in {}, which may use values of ${file}`);
52
+ }
53
+
54
+ const body = dedent(text, indentOf(source, element.start))
55
+ .split("\n")
56
+ .map((line) => (line === "" ? line : ` ${line}`))
57
+ .join("\n");
58
+ const component = `export function ${name}() {\n return (\n${body}\n );\n}\n`;
59
+
60
+ const swapped = `${source.slice(0, element.start)}<${name} />${source.slice(element.end)}`;
61
+ const end = lastImportEnd(swapped);
62
+ const semicolon = swapped.slice(0, end).endsWith(";") || end === 0 ? ";" : "";
63
+ const line = `import { ${name} } from "./${name}"${semicolon}`;
64
+ const code =
65
+ end === 0 ? `${line}\n\n${swapped}` : `${swapped.slice(0, end)}\n${line}${swapped.slice(end)}`;
66
+
67
+ return { ok: true, source: code, component };
68
+ }