@runic-artifex/vite-plugin-runic 0.17.0 → 0.18.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.
package/README.md CHANGED
@@ -27,7 +27,7 @@ or later 24.x, or Node 26.
27
27
  same as omitting the option: the development client is injected while serving,
28
28
  and the Runic dock appears when `DevTools()` is registered. `true` also requires
29
29
  `DevTools()`: serving without it fails with
30
- [`RUNICP007`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/docs/diagnostics.md#runicp007).
30
+ [`RUNICP007`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/docs/diagnostics.md#runicp007).
31
31
  `false` turns off both the dock and the development client.
32
32
  `maxTimelineEntries` sets how many timeline entries the dock keeps: 200 by
33
33
  default, rounded down and limited to 1 to 500.
@@ -87,7 +87,7 @@ or large states are shown shallower. It is part of `/__runic/state` (`views`)
87
87
  and of the copied diagnostic state, which hold no failures.
88
88
 
89
89
  A command that the Bridge answered `superseded` (a
90
- [command scoped to its page](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/packages/web/vite-plugin-runic/../views/README.md#scoped-commands) called from an earlier page)
90
+ [command scoped to its page](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/web/vite-plugin-runic/../views/README.md#scoped-commands) called from an earlier page)
91
91
  resolves like one that ran, so the page shows nothing. The client reports it
92
92
  as a timeline entry (`kind: "command"`, label `<member> superseded`,
93
93
  `detail.code: "superseded"` with the route, member, the epoch it was issued for
@@ -97,7 +97,64 @@ commands** card. With the Angular CLI, read both from `/__runic/state`.
97
97
  The inspector runs only where the development client does: never in a build.
98
98
  `@runic-artifex/views` reports to it only once the client asked for it
99
99
  (`runic.views.inspector` in the
100
- [shared globals](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.0/specs/application/README.md#shared-globals)).
100
+ [shared globals](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/specs/application/README.md#shared-globals)).
101
+
102
+ ## Component build target
103
+
104
+ Trusted component mode embeds a guest's Views as a custom element in a host
105
+ page's own document instead of a frame. `component` adds that build next to the
106
+ page:
107
+
108
+ ```ts
109
+ // vite.config.ts
110
+ export default defineConfig({
111
+ base: "./",
112
+ plugins: [react(), runic({ desktop: true, component: { entry: "src/component.tsx" } })],
113
+ });
114
+ ```
115
+
116
+ The entry's default export is the mount function of
117
+ [`@runic-artifex/views/component`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/web/vite-plugin-runic/../views/README.md#components). `vite build`
118
+ then builds every environment, as `vite build --app` does, and after them the
119
+ `runic_component` environment into `_runic_component/` of the build output:
120
+
121
+ | File | Content |
122
+ | --- | --- |
123
+ | `component.js` | An ES module that defines the element when it loads and exports `tag`, the name it defined, and the element class as default. It bundles the framework runtime and its own copy of `@runic-artifex/views`: import maps are document-global, so a component cannot share the host page's. |
124
+ | `runic-component-meta.js` | The tag and the CSS, which the module imports. |
125
+ | `runic-component.json` | `{ version: 1, name, module, tag }`, which the guest reads to answer a component attach. |
126
+ | `assets/` | Chunks and assets above the inline limit. |
127
+
128
+ - **Tags.** The tag is `<name>-<hash>`: `component.name` (by default the root
129
+ `package.json`'s `name`, made a valid prefix: `@acme/check-tool` becomes
130
+ `acme-check-tool`) and the first 8 hex digits of a hash of the build. Two
131
+ guests, and two builds of one guest, therefore never define the same tag. The
132
+ same build loaded from a second origin, such as two running instances of one
133
+ application, is defined as `<tag>-2`; read the module's `tag` export. Tags are
134
+ prefixed in every engine: scoped custom element registries would let a
135
+ component keep plain names, but WebKitGTK 2.54 does not implement them, and
136
+ one naming rule for every engine is what the host page, tests and devtools see.
137
+ A component that defines custom elements of its own should prefix them with
138
+ the `tag` its mount function gets.
139
+ - **CSS.** The build's CSS, in one stylesheet, becomes constructable stylesheets
140
+ that every element adopts in its shadow root; nothing is added to the
141
+ document. Theme variables of the host page inherit into the shadow root.
142
+ `:root` and `html` rules match nothing there; use `:host`. `@font-face` rules in
143
+ a shadow root have no effect in Chromium: use the host page's fonts.
144
+ - **Addresses.** Chunks, assets and the CSS's `url()` references resolve against
145
+ the module's own URL, so they load from the guest's origin, absolutely, in the
146
+ host page's document. Runic Desktop serves the guest's `_runic_component/` with
147
+ CORS for exactly the origin of the host page that embeds it, and refuses it to
148
+ every other origin. This requires base `./`, which
149
+ `component` sets when the configuration has none.
150
+ - **No document state.** The element touches no history, title, global listener,
151
+ `<html lang dir>` or document stylesheet; its own `lang` and `dir` follow its
152
+ instance's text locale.
153
+
154
+ The development server serves the page only: develop the component's Views on the
155
+ page, where they run in the page instance, and build the component with
156
+ `vite build`. The development client and the dock observe the page instance, not
157
+ a component's.
101
158
 
102
159
  ## SvelteKit and Angular
103
160
 
@@ -0,0 +1,51 @@
1
+ import type { EnvironmentOptions, Rollup, ViteBuilder } from "vite";
2
+ type OutputBundle = Rollup.OutputBundle;
3
+ /** The directory of the component under the page's build output, which the guest's surface serves with CORS. */
4
+ export declare const componentDirectory = "_runic_component";
5
+ /** The component's module, in {@link componentDirectory}. */
6
+ export declare const componentModule = "component.js";
7
+ /** The manifest the guest reads to answer a component attach: `{ version, name, module, tag }`. */
8
+ export declare const componentManifest = "runic-component.json";
9
+ /** The name of the Vite environment that builds the component. */
10
+ export declare const componentEnvironment = "runic_component";
11
+ export interface RunicComponentOptions {
12
+ /**
13
+ * The component's entry module, relative to the Vite root. Its default export is the mount function
14
+ * (`RunicComponentMount` of `@runic-artifex/views/component`), which renders the guest's Views into the element.
15
+ */
16
+ readonly entry: string;
17
+ /**
18
+ * The guest's tag prefix: a lowercase letter, then lowercase letters, digits and hyphens. The element's tag is
19
+ * `<name>-<hash>`, with a hash of the build, so two guests, and two builds of one guest, never define the same tag.
20
+ * Defaults to the `name` of the root's `package.json`, made a valid prefix.
21
+ */
22
+ readonly name?: string;
23
+ }
24
+ interface ResolvedComponent {
25
+ readonly entry: string;
26
+ readonly name: string | undefined;
27
+ }
28
+ export declare function resolveComponentOptions(options: RunicComponentOptions | undefined): ResolvedComponent | undefined;
29
+ /** The tag prefix of a package name: `@acme/check-tool` becomes `acme-check-tool`. */
30
+ export declare function componentPrefix(packageName: string | undefined): string;
31
+ /** The Vite environment that builds the component into `<outDir>/_runic_component`. */
32
+ export declare function componentEnvironmentOptions(outDir: string): EnvironmentOptions;
33
+ /** Builds the component after the environments the configuration builds, unless its own `buildApp` built it. */
34
+ export declare function buildComponent(builder: ViteBuilder): Promise<void>;
35
+ /** The hooks of the component environment, which the `runic` plugin calls for that environment only. */
36
+ export interface ComponentHooks {
37
+ resolveId(id: string): string | {
38
+ id: string;
39
+ external: true;
40
+ } | undefined;
41
+ load(id: string): string | undefined;
42
+ generateBundle(context: {
43
+ emitFile: (file: {
44
+ type: "asset";
45
+ fileName: string;
46
+ source: string;
47
+ }) => unknown;
48
+ }, bundle: OutputBundle): void;
49
+ }
50
+ export declare function componentHooks(component: ResolvedComponent, root: () => string): ComponentHooks;
51
+ export {};
@@ -0,0 +1,136 @@
1
+ // The `component` build target (trusted component mode, `region-component/1`): next to the page, `vite build` builds
2
+ // an ES module that defines the guest's custom element (`defineRunicComponent` in `@runic-artifex/views/component`). It
3
+ // bundles the framework runtime and its own copy of `@runic-artifex/views`, takes its CSS as constructable stylesheets
4
+ // instead of document stylesheets, and addresses its chunks and assets relative to its own URL, so that they load from
5
+ // the guest's origin in the host page's document.
6
+ import { createHash } from "node:crypto";
7
+ import { readFileSync } from "node:fs";
8
+ import { isAbsolute, join, resolve } from "node:path";
9
+ /** The directory of the component under the page's build output, which the guest's surface serves with CORS. */
10
+ export const componentDirectory = "_runic_component";
11
+ /** The component's module, in {@link componentDirectory}. */
12
+ export const componentModule = "component.js";
13
+ /** The manifest the guest reads to answer a component attach: `{ version, name, module, tag }`. */
14
+ export const componentManifest = "runic-component.json";
15
+ /** The name of the Vite environment that builds the component. */
16
+ export const componentEnvironment = "runic_component";
17
+ const entryId = "virtual:runic/component-entry";
18
+ const resolvedEntryId = `\0${entryId}`;
19
+ const metaId = "virtual:runic/component-meta";
20
+ // The generated module that holds the tag and the stylesheets, which are known only once the bundle is written.
21
+ const metaFile = "runic-component-meta.js";
22
+ const namePattern = /^[a-z][a-z0-9-]*$/;
23
+ export function resolveComponentOptions(options) {
24
+ if (options === undefined)
25
+ return undefined;
26
+ if (options === null || typeof options !== "object" || typeof options.entry !== "string" || options.entry === "") {
27
+ throw new TypeError("component.entry must name the component's entry module.");
28
+ }
29
+ if (options.name !== undefined && (typeof options.name !== "string" || !namePattern.test(options.name) || options.name.length > 64)) {
30
+ throw new TypeError("component.name must be a lowercase letter followed by lowercase letters, digits and hyphens, at most 64 characters.");
31
+ }
32
+ return { entry: options.entry, name: options.name };
33
+ }
34
+ /** The tag prefix of a package name: `@acme/check-tool` becomes `acme-check-tool`. */
35
+ export function componentPrefix(packageName) {
36
+ const words = (packageName ?? "").toLowerCase().split(/[^a-z0-9]+/).filter((word) => word !== "");
37
+ const prefix = words.join("-").replace(/^[^a-z]+/, "").slice(0, 64).replace(/-+$/, "");
38
+ return prefix === "" ? "runic-component" : prefix;
39
+ }
40
+ function packageName(root) {
41
+ try {
42
+ const name = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name;
43
+ return typeof name === "string" ? name : undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ /** The Vite environment that builds the component into `<outDir>/_runic_component`. */
50
+ export function componentEnvironmentOptions(outDir) {
51
+ return {
52
+ consumer: "client",
53
+ build: {
54
+ outDir: join(outDir, componentDirectory),
55
+ emptyOutDir: true,
56
+ copyPublicDir: false,
57
+ // One stylesheet, which the bundle adopts in each element's shadow root; no chunk adds a <link> to the document.
58
+ cssCodeSplit: false,
59
+ modulePreload: false,
60
+ manifest: false,
61
+ rolldownOptions: {
62
+ input: { component: entryId },
63
+ preserveEntrySignatures: "strict",
64
+ output: { format: "es", entryFileNames: componentModule },
65
+ },
66
+ },
67
+ };
68
+ }
69
+ /** Builds the component after the environments the configuration builds, unless its own `buildApp` built it. */
70
+ export async function buildComponent(builder) {
71
+ const component = builder.environments[componentEnvironment];
72
+ if (component === undefined || component.isBuilt)
73
+ return;
74
+ const others = Object.values(builder.environments).filter((environment) => environment !== component);
75
+ // Vite builds every environment when no buildApp built one; this hook runs after the configuration's, so it does so.
76
+ if (others.every((environment) => !environment.isBuilt)) {
77
+ for (const environment of others)
78
+ await builder.build(environment);
79
+ }
80
+ await builder.build(component);
81
+ }
82
+ export function componentHooks(component, root) {
83
+ let prefix = component.name;
84
+ return {
85
+ resolveId(id) {
86
+ if (id === entryId)
87
+ return resolvedEntryId;
88
+ // Written in generateBundle, next to the module.
89
+ if (id === metaId)
90
+ return { id: `./${metaFile}`, external: true };
91
+ return undefined;
92
+ },
93
+ load(id) {
94
+ if (id !== resolvedEntryId)
95
+ return undefined;
96
+ const entry = isAbsolute(component.entry) ? component.entry : resolve(root(), component.entry);
97
+ return [
98
+ `import mount from ${JSON.stringify(entry)};`,
99
+ `import meta from ${JSON.stringify(metaId)};`,
100
+ `import { defineRunicComponent } from "@runic-artifex/views/component";`,
101
+ `const definition = defineRunicComponent({ tag: meta.tag, styles: meta.styles, mount });`,
102
+ `export const tag = definition.tag;`,
103
+ `export default definition.element;`,
104
+ ].join("\n");
105
+ },
106
+ generateBundle(context, bundle) {
107
+ prefix ??= componentPrefix(packageName(root()));
108
+ const styles = [];
109
+ const hash = createHash("sha256");
110
+ for (const fileName of Object.keys(bundle).sort()) {
111
+ const item = bundle[fileName];
112
+ if (item.type === "asset" && fileName.endsWith(".css")) {
113
+ // Vite marks the end of its CSS with a comment of its own.
114
+ styles.push({ text: String(item.source).replace(/\/\*\$vite\$:\d+\*\/\s*$/, ""), file: fileName });
115
+ delete bundle[fileName];
116
+ }
117
+ hash.update(fileName).update("\0");
118
+ hash.update(item.type === "chunk" ? item.code : item.source).update("\0");
119
+ }
120
+ const tag = `${prefix}-${hash.digest("hex").slice(0, 8)}`;
121
+ // Relative to the module, which loads from the guest's origin: a constructed stylesheet resolves its relative
122
+ // url() against the host page otherwise.
123
+ const styleList = styles.map((style) => `{ text: ${JSON.stringify(style.text)}, href: new URL(${JSON.stringify(style.file)}, import.meta.url).href }`);
124
+ context.emitFile({
125
+ type: "asset",
126
+ fileName: metaFile,
127
+ source: `export default { tag: ${JSON.stringify(tag)}, styles: [${styleList.join(", ")}] };\n`,
128
+ });
129
+ context.emitFile({
130
+ type: "asset",
131
+ fileName: componentManifest,
132
+ source: `${JSON.stringify({ version: 1, name: prefix, module: componentModule, tag }, null, 2)}\n`,
133
+ });
134
+ },
135
+ };
136
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { Plugin } from "vite";
2
2
  import type { RunicDiagnosticEntry } from "./diagnostics.js";
3
+ import { type RunicComponentOptions } from "./component.js";
4
+ export type { RunicComponentOptions } from "./component.js";
3
5
  export { runicDevSessionProxy } from "./dev-session.js";
4
6
  export type { RunicDevSessionProxyOptions } from "./dev-session.js";
5
7
  export type { RunicDevelopmentState, RunicViewSnapshot } from "./timeline.js";
@@ -43,5 +45,11 @@ export interface RunicViteOptions {
43
45
  /** Absolute development bootstrap URL; production uses the surface-relative default. */
44
46
  bootstrapUrl?: string;
45
47
  }>;
48
+ /**
49
+ * Adds the `component` build target (trusted component mode): `vite build` also builds the guest's Views as an ES
50
+ * module that defines a custom element, into `_runic_component/` of the build output. Requires base `./`. The
51
+ * development server serves the page only.
52
+ */
53
+ readonly component?: RunicComponentOptions;
46
54
  }
47
55
  export declare function runic(options?: RunicViteOptions): RunicVitePlugin;
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { rewriteHostScripts, webRootPrefix } from "./host-scripts.js";
4
4
  import { clientOptionsKey, connectionEvent, diagnosticEvent, diagnosticsPath, viewEvent } from "./channel.js";
5
5
  import { answerClientMessage, answerState, devSessionValue, devSessionVariable, statePath } from "./dev-session.js";
6
6
  import { createDevelopmentTimeline, initialDevelopmentState, timelineLimit, withoutFailures } from "./timeline.js";
7
+ import { buildComponent, componentEnvironment, componentEnvironmentOptions, componentHooks, resolveComponentOptions, } from "./component.js";
7
8
  export { runicDevSessionProxy } from "./dev-session.js";
8
9
  const virtualClientId = "virtual:runic/client";
9
10
  const resolvedVirtualClientId = `\0${virtualClientId}`;
@@ -35,6 +36,11 @@ export function runic(options = {}) {
35
36
  if (!html && desktopBootstrapUrl !== undefined) {
36
37
  throw new TypeError("desktop requires html: true: the Desktop bootstrap is a script tag the plugin adds to the HTML.");
37
38
  }
39
+ const component = resolveComponentOptions(options.component);
40
+ const relocatable = desktopBootstrapUrl !== undefined || component !== undefined;
41
+ const relocatableOption = desktopBootstrapUrl !== undefined ? "desktop: true" : "component";
42
+ const components = component === undefined ? undefined : componentHooks(component, () => resolvedRoot);
43
+ const inComponent = (environment) => components !== undefined && environment?.name === componentEnvironment;
38
44
  const timeline = createDevelopmentTimeline(initialDevelopmentState(options.contract), maxTimelineEntries, (state) => {
39
45
  sharedState?.mutate((draft) => Object.assign(draft, structuredClone(state)));
40
46
  void jsonRenderer?.updateSpec(createDevtoolsSpec(state));
@@ -88,13 +94,22 @@ export function runic(options = {}) {
88
94
  // load and reloading the page, which drops a host's Bridge connection.
89
95
  return client ? { optimizeDeps: { include: [clientPackageId] } } : undefined;
90
96
  }
91
- if (desktopBootstrapUrl === undefined)
97
+ if (!relocatable)
92
98
  return undefined;
93
99
  if (config.base !== undefined && config.base !== "./") {
94
- throw new TypeError("desktop: true requires Vite base to be './' for relocatable surface output.");
100
+ throw new TypeError(`${relocatableOption} requires Vite base to be './' for relocatable surface output.`);
95
101
  }
96
- return { base: "./" };
102
+ const result = { base: "./" };
103
+ if (component !== undefined && environment.isSsrBuild !== true) {
104
+ // The component builds as an environment of its own next to the page; `builder` makes `vite build` build
105
+ // every environment, as `vite build --app` does.
106
+ result.environments = { [componentEnvironment]: componentEnvironmentOptions(config.build?.outDir ?? "dist") };
107
+ if (config.builder === undefined)
108
+ result.builder = {};
109
+ }
110
+ return result;
97
111
  },
112
+ buildApp: { order: "post", handler: buildComponent },
98
113
  // With html: false there is no transformIndexHtml property at all: SvelteKit warns about any plugin that has one.
99
114
  ...(html ? {
100
115
  // The build parses HTML in a later transform, so host scripts are marked
@@ -115,8 +130,8 @@ export function runic(options = {}) {
115
130
  } : {}),
116
131
  api: { reportDiagnostic: (entry) => { timeline.appendDiagnostic(entry); } },
117
132
  configResolved(resolved) {
118
- if (resolved.command === "build" && desktopBootstrapUrl !== undefined && resolved.base !== "./") {
119
- throw new TypeError("desktop: true requires the resolved Vite base to be './' for relocatable surface output.");
133
+ if (resolved.command === "build" && relocatable && resolved.base !== "./") {
134
+ throw new TypeError(`${relocatableOption} requires the resolved Vite base to be './' for relocatable surface output.`);
120
135
  }
121
136
  if (resolved.command === "serve" && options.devtools === true &&
122
137
  !resolved.plugins.some((plugin) => plugin.name === "vite:devtools:server")) {
@@ -148,6 +163,11 @@ export function runic(options = {}) {
148
163
  });
149
164
  },
150
165
  resolveId(id, importer, resolveOptions) {
166
+ if (inComponent(this.environment)) {
167
+ const resolved = components.resolveId(id);
168
+ if (resolved !== undefined)
169
+ return resolved;
170
+ }
151
171
  if (id === virtualClientId || (id === clientPackageId && importer !== resolvedVirtualClientId)) {
152
172
  // The client runs only in a served page. An application import of the package goes through the virtual
153
173
  // module too, so that it takes this plugin's options and channel, and is empty in the build.
@@ -158,6 +178,11 @@ export function runic(options = {}) {
158
178
  return id === clientOptionsId ? resolvedClientOptionsId : undefined;
159
179
  },
160
180
  load(id) {
181
+ if (inComponent(this.environment)) {
182
+ const loaded = components.load(id);
183
+ if (loaded !== undefined)
184
+ return loaded;
185
+ }
161
186
  if (id === resolvedEmptyClientId)
162
187
  return "export {};";
163
188
  if (id === resolvedClientOptionsId) {
@@ -172,6 +197,14 @@ export function runic(options = {}) {
172
197
  // Imports evaluate in order, so the options are set before the client reads them.
173
198
  return `import ${JSON.stringify(clientOptionsId)};\nimport ${JSON.stringify(clientPackageId)};`;
174
199
  },
200
+ generateBundle: {
201
+ // After Vite's CSS plugin wrote the component's stylesheet.
202
+ order: "post",
203
+ handler(_output, bundle) {
204
+ if (inComponent(this.environment))
205
+ components.generateBundle(this, bundle);
206
+ },
207
+ },
175
208
  devtools: {
176
209
  async setup(context) {
177
210
  if (!client)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/vite-plugin-runic",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "Vite 8 development and DevTools integration for Runic applications",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -43,11 +43,17 @@
43
43
  }
44
44
  },
45
45
  "devDependencies": {
46
+ "@runic-artifex/react": "0.18.0",
47
+ "@runic-artifex/views": "0.18.0",
48
+ "@runic-artifex/vue": "0.18.0",
46
49
  "@types/node": "24.19.1",
47
50
  "@vitejs/devtools": "0.7.6",
48
51
  "@vitejs/devtools-kit": "0.7.6",
52
+ "react": "19.3.0",
53
+ "react-dom": "19.3.0",
49
54
  "typescript": "6.0.3",
50
- "vite": "8.3.4"
55
+ "vite": "8.3.4",
56
+ "vue": "3.5.43"
51
57
  },
52
58
  "engines": {
53
59
  "node": "^24.18.0 || ^26.0.0"
@@ -61,7 +67,7 @@
61
67
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
62
68
  "directory": "packages/web/vite-plugin-runic"
63
69
  },
64
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.0/packages/web/vite-plugin-runic#readme",
70
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/vite-plugin-runic#readme",
65
71
  "bugs": {
66
72
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
67
73
  },
@@ -72,5 +78,5 @@
72
78
  "vite-plugin",
73
79
  "devtools"
74
80
  ],
75
- "gitHead": "daeb17e5c3fb0b625d5d988d359cd12ffa51f8c6"
81
+ "gitHead": "e025c0ab74aa76547e2d0307de223c43d5271228"
76
82
  }