@stillwind/integration 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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +67 -2
  3. package/dist/NPM-THIRD-PARTY-LICENSES +52 -0
  4. package/dist/astro/development.d.ts +15 -0
  5. package/dist/astro/development.js +34 -0
  6. package/dist/astro/development.js.map +1 -0
  7. package/dist/astro/index.d.ts +17 -0
  8. package/dist/astro/index.js +194 -0
  9. package/dist/astro/index.js.map +1 -0
  10. package/dist/astro/middleware.d.ts +2 -0
  11. package/dist/astro/middleware.js +64 -0
  12. package/dist/astro/middleware.js.map +1 -0
  13. package/dist/binding-files-Ds5NpyVV.js +45 -0
  14. package/dist/binding-files-Ds5NpyVV.js.map +1 -0
  15. package/dist/emission-BVi5aRbb.js +520 -0
  16. package/dist/emission-BVi5aRbb.js.map +1 -0
  17. package/dist/fresh/index.d.ts +10 -0
  18. package/dist/fresh/index.js +55 -0
  19. package/dist/fresh/index.js.map +1 -0
  20. package/dist/gen-mapping-D7jFzOEh.js +559 -0
  21. package/dist/gen-mapping-D7jFzOEh.js.map +1 -0
  22. package/dist/index-DFfbZxNT.d.ts +12 -0
  23. package/dist/next/css-loader.d.ts +14 -0
  24. package/dist/next/css-loader.js +58 -0
  25. package/dist/next/css-loader.js.map +1 -0
  26. package/dist/next/index.d.ts +15 -0
  27. package/dist/next/index.js +66 -0
  28. package/dist/next/index.js.map +1 -0
  29. package/dist/node-loader-D-3Ynpy1.d.ts +19 -0
  30. package/dist/nuxt/index.d.ts +13 -0
  31. package/dist/nuxt/index.js +64 -0
  32. package/dist/nuxt/index.js.map +1 -0
  33. package/dist/plugin-C_ZFfzo2.js +2572 -0
  34. package/dist/plugin-C_ZFfzo2.js.map +1 -0
  35. package/dist/plugin-aV0zIIAe.d.ts +278 -0
  36. package/dist/plugin-mPiBLdqa.js +79 -0
  37. package/dist/plugin-mPiBLdqa.js.map +1 -0
  38. package/dist/project-BNw0nZBE.d.ts +58 -0
  39. package/dist/project-C3IH7geC.js +182 -0
  40. package/dist/project-C3IH7geC.js.map +1 -0
  41. package/dist/project-DUGu8g_L.d.ts +15 -0
  42. package/dist/rsbuild/index.d.ts +28 -0
  43. package/dist/rsbuild/index.js +77 -0
  44. package/dist/rsbuild/index.js.map +1 -0
  45. package/dist/rspack/index.d.ts +3 -0
  46. package/dist/rspack/index.js +1 -0
  47. package/dist/rules-BvKsL2at.js +91 -0
  48. package/dist/rules-BvKsL2at.js.map +1 -0
  49. package/dist/session-B9_rp9TH.d.ts +72 -0
  50. package/dist/session-DHUCQMG5.js +117 -0
  51. package/dist/session-DHUCQMG5.js.map +1 -0
  52. package/dist/source-map-loader-CBLiYaBI.d.ts +128 -0
  53. package/dist/sveltekit/handle.d.ts +13 -0
  54. package/dist/sveltekit/handle.js +16 -0
  55. package/dist/sveltekit/handle.js.map +1 -0
  56. package/dist/trace-mapping-DV_eP3r7.d.ts +58 -0
  57. package/dist/turbopack/css-loader.d.ts +15 -0
  58. package/dist/turbopack/css-loader.js +44 -0
  59. package/dist/turbopack/css-loader.js.map +1 -0
  60. package/dist/turbopack/index.d.ts +54 -0
  61. package/dist/turbopack/index.js +1 -0
  62. package/dist/turbopack/loader.d.ts +13 -0
  63. package/dist/turbopack/loader.js +70 -0
  64. package/dist/turbopack/loader.js.map +1 -0
  65. package/dist/turbopack/node-loader.d.ts +2 -0
  66. package/dist/turbopack/node-loader.js +20 -0
  67. package/dist/turbopack/node-loader.js.map +1 -0
  68. package/dist/turbopack/stillwind-turbopack.css +0 -0
  69. package/dist/vite/index.d.ts +3 -0
  70. package/dist/vite/index.js +1 -0
  71. package/dist/vite/runtime-source-map.d.ts +19 -0
  72. package/dist/vite/runtime-source-map.js +106 -0
  73. package/dist/vite/runtime-source-map.js.map +1 -0
  74. package/dist/vite/runtime.d.ts +58 -0
  75. package/dist/vite/runtime.js +90 -0
  76. package/dist/vite/runtime.js.map +1 -0
  77. package/dist/webpack/css-loader.d.ts +17 -0
  78. package/dist/webpack/css-loader.js +36 -0
  79. package/dist/webpack/css-loader.js.map +1 -0
  80. package/dist/webpack/css-map-loader.d.ts +24 -0
  81. package/dist/webpack/css-map-loader.js +43 -0
  82. package/dist/webpack/css-map-loader.js.map +1 -0
  83. package/dist/webpack/document-loader.d.ts +12 -0
  84. package/dist/webpack/document-loader.js +19 -0
  85. package/dist/webpack/document-loader.js.map +1 -0
  86. package/dist/webpack/fragment-loader.d.ts +9 -0
  87. package/dist/webpack/fragment-loader.js +23 -0
  88. package/dist/webpack/fragment-loader.js.map +1 -0
  89. package/dist/webpack/index.d.ts +3 -0
  90. package/dist/webpack/index.js +1 -0
  91. package/dist/webpack/loader.d.ts +35 -0
  92. package/dist/webpack/loader.js +199 -0
  93. package/dist/webpack/loader.js.map +1 -0
  94. package/dist/webpack/source-loader.d.ts +11 -0
  95. package/dist/webpack/source-loader.js +17 -0
  96. package/dist/webpack/source-loader.js.map +1 -0
  97. package/dist/webpack/source-map-loader.d.ts +2 -0
  98. package/dist/webpack/source-map-loader.js +35 -0
  99. package/dist/webpack/source-map-loader.js.map +1 -0
  100. package/dist/webpack/stillwind-fragment.d.ts +1 -0
  101. package/dist/webpack/stillwind-fragment.js +1 -0
  102. package/dist/webpack/stillwind-webpack.css +1 -0
  103. package/package.json +133 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Stillwind contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # Stillwind build integrations
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stillwind compiles Tailwind CSS v4 utilities into component props and static CSS.
4
+ It uses theme rules and compiler checks to keep styling code in order, even when
5
+ AI agents write much of it.
6
+
7
+ `@stillwind/integration` provides build tool integrations for Stillwind. It reads
8
+ `stillwind.config.*`, compiles styles during development and production builds,
9
+ and delivers generated CSS through the selected build tool.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ vp i stillwind
15
+ vp i -D @stillwind/integration
16
+ ```
17
+
18
+ Create the stylesheet and project configuration described in the
19
+ [Getting started](https://stillwind.dev/docs) guide.
20
+
21
+ ## Vite
22
+
23
+ Place Stillwind before your framework's JSX transform:
24
+
25
+ ```ts
26
+ import { stillwind } from "@stillwind/integration/vite";
27
+ import react from "@vitejs/plugin-react";
28
+ import { defineConfig } from "vite-plus";
29
+
30
+ export default defineConfig({
31
+ plugins: [stillwind(), react()],
32
+ });
33
+ ```
34
+
35
+ Keep your application's other framework plugins. When a framework splits routes
36
+ or server functions before JSX compilation, its splitting plugin must run before
37
+ Stillwind.
38
+
39
+ ## Other build tools
40
+
41
+ | Host | Entrypoint | Registration |
42
+ | --------- | ---------------------------------- | ------------------------------------------------------------------------- |
43
+ | Astro | `@stillwind/integration/astro` | `integrations: [stillwind()]` |
44
+ | Fresh 2 | `@stillwind/integration/fresh` | Add `stillwind()` after `fresh()` in the Vite config |
45
+ | Nuxt | `@stillwind/integration/nuxt` | `modules: [stillwind()]` |
46
+ | SvelteKit | `@stillwind/integration/vite` | Add `stillwind()` before `sveltekit()`; add the SSR handle from the guide |
47
+ | Next.js | `@stillwind/integration/next` | `withStillwind(nextConfig)` |
48
+ | webpack | `@stillwind/integration/webpack` | `plugins: [new StillwindPlugin()]` |
49
+ | Rspack | `@stillwind/integration/rspack` | `plugins: [new StillwindPlugin()]` |
50
+ | Rsbuild | `@stillwind/integration/rsbuild` | `plugins: [pluginStillwind()]` |
51
+ | Turbopack | `@stillwind/integration/turbopack` | Add `stillwindRules({ entries })` to the host's rules |
52
+
53
+ [Framework integrations](https://stillwind.dev/docs/integrations) shows the registration and plugin order
54
+ for each build tool. The [integration contract](https://github.com/SegaraRai/stillwind/blob/main/docs/integrations.md) also covers
55
+ SSR setup and host limitations.
56
+
57
+ ## Configuration and checks
58
+
59
+ Use `stillwind()` or the equivalent constructor without options to read the project
60
+ configuration. `configFile` selects another file, `project` selects a named project,
61
+ and inline settings override the selected project. Several projects must have an
62
+ unambiguous selection. See [Several projects](https://stillwind.dev/docs/configuration#several-projects).
63
+
64
+ Build integrations report compiler errors and skip lint checks. Run
65
+ `stillwind lint` separately to enforce lint rules.
66
+
67
+ For split stylesheets, server-only styles, or Shadow DOM, see
68
+ [CSS delivery in the guide](https://github.com/SegaraRai/stillwind/blob/main/docs/integrations.md#css-delivery).
@@ -0,0 +1,52 @@
1
+ @stillwind/integration includes the following npm packages.
2
+
3
+ ================================================================================
4
+ @jridgewell/gen-mapping 0.3.13 (MIT) https://github.com/jridgewell/sourcemaps.git
5
+ @jridgewell/remapping 2.3.5 (MIT) https://github.com/jridgewell/sourcemaps.git
6
+ @jridgewell/sourcemap-codec 1.6.0 (MIT) https://github.com/jridgewell/sourcemaps.git
7
+ @jridgewell/trace-mapping 0.3.31 (MIT) https://github.com/jridgewell/sourcemaps.git
8
+ ================================================================================
9
+
10
+ Copyright 2024 Justin Ridgewell <justin@ridgewell.name>
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in
20
+ all copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+
30
+ ================================================================================
31
+ @jridgewell/resolve-uri 3.1.2 (MIT) https://github.com/jridgewell/resolve-uri
32
+ ================================================================================
33
+
34
+ Copyright 2019 Justin Ridgewell <jridgewell@google.com>
35
+
36
+ Permission is hereby granted, free of charge, to any person obtaining a copy
37
+ of this software and associated documentation files (the "Software"), to deal
38
+ in the Software without restriction, including without limitation the rights
39
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
40
+ copies of the Software, and to permit persons to whom the Software is
41
+ furnished to do so, subject to the following conditions:
42
+
43
+ The above copyright notice and this permission notice shall be included in
44
+ all copies or substantial portions of the Software.
45
+
46
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
47
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
48
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
49
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
50
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
51
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
52
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Registers an in-process CSS getter, replacing any previous getter for the same identity.
3
+ * @param id - Bridge and server-environment identity used by the generated SSR module.
4
+ * @param getCss - Getter for the current document plan, invoked on each SSR request.
5
+ * @returns A disposer that removes only this registration and preserves a later replacement.
6
+ */
7
+ export declare function registerDevelopmentCss(id: string, getCss: () => Promise<string>): () => void;
8
+ /**
9
+ * Reads the current CSS from a registered project.
10
+ * @param id - Identity registered by the active development bridge.
11
+ * @returns The current document stylesheet from the registered getter.
12
+ * @throws If the registration is absent or its getter fails.
13
+ */
14
+ export declare function getDevelopmentCss(id: string): Promise<string>;
15
+ //# sourceMappingURL=development.d.ts.map
@@ -0,0 +1,34 @@
1
+ import process from "node:process";
2
+ // src/astro/development.ts
3
+ const projectsKey = Symbol.for("@stillwind/integration.astro.development-css");
4
+ const host = process;
5
+ /**
6
+ * Registers an in-process CSS getter, replacing any previous getter for the same identity.
7
+ * @param id - Bridge and server-environment identity used by the generated SSR module.
8
+ * @param getCss - Getter for the current document plan, invoked on each SSR request.
9
+ * @returns A disposer that removes only this registration and preserves a later replacement.
10
+ */
11
+ function registerDevelopmentCss(id, getCss) {
12
+ (host[projectsKey] ??= /* @__PURE__ */ new Map()).set(id, getCss);
13
+ return () => {
14
+ const current = host[projectsKey];
15
+ if (current?.get(id) === getCss) {
16
+ current.delete(id);
17
+ if (!current.size) delete host[projectsKey];
18
+ }
19
+ };
20
+ }
21
+ /**
22
+ * Reads the current CSS from a registered project.
23
+ * @param id - Identity registered by the active development bridge.
24
+ * @returns The current document stylesheet from the registered getter.
25
+ * @throws If the registration is absent or its getter fails.
26
+ */
27
+ async function getDevelopmentCss(id) {
28
+ const getCss = host[projectsKey]?.get(id);
29
+ if (!getCss) throw new Error("Stillwind Astro development project is unavailable");
30
+ return getCss();
31
+ }
32
+ export { getDevelopmentCss, registerDevelopmentCss };
33
+
34
+ //# sourceMappingURL=development.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"development.js","names":[],"sources":["../../src/astro/development.ts"],"sourcesContent":["import process from \"node:process\";\n\nconst projectsKey = Symbol.for(\"@stillwind/integration.astro.development-css\");\n\n/** Active CSS getters keyed by bridge and server-environment identity. */\ntype Projects = Map<string, () => Promise<string>>;\n\n// Vite module runners can evaluate another copy of this module in the same process.\nconst host = process as NodeJS.Process & {\n /** Registry shared across copies evaluated by Vite module runners in this process. */\n [projectsKey]?: Projects;\n};\n\n/**\n * Registers an in-process CSS getter, replacing any previous getter for the same identity.\n * @param id - Bridge and server-environment identity used by the generated SSR module.\n * @param getCss - Getter for the current document plan, invoked on each SSR request.\n * @returns A disposer that removes only this registration and preserves a later replacement.\n */\nexport function registerDevelopmentCss(id: string, getCss: () => Promise<string>): () => void {\n const projects = (host[projectsKey] ??= new Map());\n projects.set(id, getCss);\n return () => {\n const current = host[projectsKey];\n if (current?.get(id) === getCss) {\n current.delete(id);\n if (!current.size) {\n delete host[projectsKey];\n }\n }\n };\n}\n\n/**\n * Reads the current CSS from a registered project.\n * @param id - Identity registered by the active development bridge.\n * @returns The current document stylesheet from the registered getter.\n * @throws If the registration is absent or its getter fails.\n */\nexport async function getDevelopmentCss(id: string): Promise<string> {\n const getCss = host[projectsKey]?.get(id);\n if (!getCss) {\n throw new Error(\"Stillwind Astro development project is unavailable\");\n }\n return getCss();\n}\n"],"mappings":";;AAEA,MAAM,cAAc,OAAO,IAAI,8CAA8C;AAM7E,MAAM,OAAO;;;;;;;AAWb,SAAgB,uBAAuB,IAAY,QAA2C;CAE5F,CADkB,KAAK,iCAAiB,IAAI,IAAI,EAAA,CACvC,IAAI,IAAI,MAAM;CACvB,aAAa;EACX,MAAM,UAAU,KAAK;EACrB,IAAI,SAAS,IAAI,EAAE,MAAM,QAAQ;GAC/B,QAAQ,OAAO,EAAE;GACjB,IAAI,CAAC,QAAQ,MACX,OAAO,KAAK;EAEhB;CACF;AACF;;;;;;;AAQA,eAAsB,kBAAkB,IAA6B;CACnE,MAAM,SAAS,KAAK,YAAY,EAAE,IAAI,EAAE;CACxC,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,oDAAoD;CAEtE,OAAO,OAAO;AAChB"}
@@ -0,0 +1,17 @@
1
+ import { t as IntegrationConfig } from "../project-DUGu8g_L.js";
2
+ import { AstroIntegration } from "astro";
3
+ /**
4
+ * Creates an Astro integration that applies Stillwind CSS to server-rendered documents and client
5
+ * islands.
6
+ *
7
+ * Development SSR reads current CSS through a server bridge and embeds it in HTML. Production SSR
8
+ * inserts links from the stylesheet manifest.
9
+ *
10
+ * @param config - File discovery, project selection, compiler overrides, and Vite CSS emission.
11
+ * Omission discovers stillwind.config.* from Astro's application root when Vite is configured.
12
+ * @returns An Astro integration that installs Stillwind Vite plugins, middleware, and document
13
+ * stylesheet modules.
14
+ */
15
+ export declare function stillwind(config?: IntegrationConfig): AstroIntegration;
16
+ export type { IntegrationConfig };
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,194 @@
1
+ import { i as renderChunkStyles, r as createViteProject, t as createVitePlugins } from "../plugin-C_ZFfzo2.js";
2
+ import { registerDevelopmentCss } from "./development.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { fileURLToPath } from "node:url";
5
+ import { moduleSourceMap } from "@stillwind/host";
6
+ // src/astro/index.ts
7
+ /** Virtual server module imported by Astro middleware to obtain document stylesheet markup. */
8
+ const ID = "virtual:stillwind/astro-styles";
9
+ /** Virtual client module that updates inline SSR styles when development CSS changes. */
10
+ const CLIENT_ID = ID + "/client";
11
+ /** External server module that connects SSR rendering to the active development compiler. */
12
+ const BRIDGE_ID = "@stillwind/integration/internal/astro-development";
13
+ /**
14
+ * JavaScript string literal replaced with stylesheet links after the production graph is rendered.
15
+ */
16
+ const MARKER = "\"__STILLWIND_ASTRO_STYLES_574f6dfce7c69466ab9516fb7fc6199a__\"";
17
+ /**
18
+ * Creates an Astro integration that applies Stillwind CSS to server-rendered documents and client
19
+ * islands.
20
+ *
21
+ * Development SSR reads current CSS through a server bridge and embeds it in HTML. Production SSR
22
+ * inserts links from the stylesheet manifest.
23
+ *
24
+ * @param config - File discovery, project selection, compiler overrides, and Vite CSS emission.
25
+ * Omission discovers stillwind.config.* from Astro's application root when Vite is configured.
26
+ * @returns An Astro integration that installs Stillwind Vite plugins, middleware, and document
27
+ * stylesheet modules.
28
+ */
29
+ function stillwind(config = {}) {
30
+ let applicationRoot;
31
+ const project = createViteProject(config, () => applicationRoot);
32
+ const plugins = createVitePlugins(project);
33
+ const bridgeIds = /* @__PURE__ */ new WeakMap();
34
+ const bridges = /* @__PURE__ */ new WeakMap();
35
+ const bridgeId = (configuration) => {
36
+ let id = bridgeIds.get(configuration);
37
+ if (!id) {
38
+ id = randomUUID();
39
+ bridgeIds.set(configuration, id);
40
+ }
41
+ return id;
42
+ };
43
+ return {
44
+ name: "@stillwind/integration",
45
+ hooks: {
46
+ /**
47
+ * Captures Astro's root and installs middleware plus Stillwind's Vite and document plugins.
48
+ * @param options - Astro setup operations and application configuration.
49
+ */
50
+ "astro:config:setup"({ config: astroConfig, updateConfig, addMiddleware }) {
51
+ applicationRoot = fileURLToPath(astroConfig.root);
52
+ addMiddleware({
53
+ entrypoint: fileURLToPath(new URL("./middleware.js", import.meta.url)).replaceAll("\\", "/"),
54
+ order: "pre"
55
+ });
56
+ updateConfig({ vite: { plugins: [plugins, {
57
+ name: "stillwind:astro-document",
58
+ /**
59
+ * Registers a current-CSS bridge for each server environment and ties cleanup to server closure.
60
+ * @param server - Vite server whose environments resolve SSR dependencies and register watches.
61
+ * @throws If no SSR environment is available.
62
+ */
63
+ configureServer(server) {
64
+ if (!server.environments.ssr) throw new Error("Stillwind Astro requires an SSR environment");
65
+ const generation = project.forConfig(server.config);
66
+ const id = bridgeId(server.config);
67
+ return () => {
68
+ const disposers = Object.entries(server.environments).filter(([name]) => name !== "client").map(([name, environment]) => {
69
+ const dispose = registerDevelopmentCss(`${id}:${name}`, async () => {
70
+ return (await generation.documentPlan(name, {
71
+ resolve: (specifier, importer, options) => environment.pluginContainer.resolveId(specifier, importer, options),
72
+ addWatchFile: (id) => {
73
+ server.watcher.add(id);
74
+ },
75
+ warn: (message) => {
76
+ server.config.logger.warn(message);
77
+ }
78
+ })).css;
79
+ });
80
+ bridges.set(environment, dispose);
81
+ return dispose;
82
+ });
83
+ /** Removes all bridge registrations owned by this server configuration. */
84
+ const dispose = () => {
85
+ for (const dispose of disposers) dispose();
86
+ };
87
+ server.httpServer?.once("close", dispose);
88
+ };
89
+ },
90
+ /** Removes the development bridge owned by the closing environment. */
91
+ closeBundle() {
92
+ if (this.environment) bridges.get(this.environment)?.();
93
+ },
94
+ /**
95
+ * Resolves stylesheet virtual modules and keeps the development bridge external on the server.
96
+ * @param source - Authored module specifier.
97
+ * @returns A virtual identity, an external bridge, or undefined for unrelated requests.
98
+ * @throws If a client environment imports server-only styles or the CSS bridge.
99
+ */
100
+ resolveId(source) {
101
+ if (source === BRIDGE_ID) {
102
+ if (this.environment?.name === "client") this.error("Stillwind Astro CSS bridge is server-only");
103
+ return {
104
+ id: source,
105
+ external: true
106
+ };
107
+ }
108
+ if (source === ID || source === CLIENT_ID) {
109
+ if (source === ID && this.environment?.name === "client") this.error("Stillwind Astro styles are server-only");
110
+ return "\0" + source;
111
+ }
112
+ },
113
+ /**
114
+ * Generates SSR stylesheet markup or the client listener that refreshes inline SSR CSS.
115
+ * @param source - Resolved virtual module identity including its leading NUL.
116
+ * @returns Generated JavaScript, or undefined for unrelated modules. Production markup retains a manifest placeholder.
117
+ */
118
+ load(source) {
119
+ const configuration = this.environment.getTopLevelConfig();
120
+ const generation = project.forConfig(configuration);
121
+ if (source === "\0" + CLIENT_ID) {
122
+ const endpoint = generation.settings.publicBase + "__stillwind/style.css?environment=ssr";
123
+ return `// Stillwind SSR CSS (astro client)
124
+ if (import.meta.hot) {
125
+ let revision = 0;
126
+ import.meta.hot.on("stillwind:css", async () => {
127
+ const requested = ++revision;
128
+ const response = await fetch(${JSON.stringify(endpoint)});
129
+ if (!response.ok) {
130
+ throw new Error("Stillwind SSR CSS: " + response.status);
131
+ }
132
+ const css = await response.text();
133
+ if (requested === revision) {
134
+ for (const style of document.querySelectorAll("style[data-stillwind-ssr]")) {
135
+ style.textContent = css;
136
+ }
137
+ }
138
+ });
139
+ }
140
+ `;
141
+ }
142
+ if (source !== "\0" + ID) return;
143
+ if (generation.settings.watching) {
144
+ const script = `<script type="module" src="${generation.settings.publicBase}@id/__x00__${CLIENT_ID}"><\/script>`;
145
+ return `// Stillwind SSR CSS (astro with hot reload)
146
+ import { getDevelopmentCss } from ${JSON.stringify(BRIDGE_ID)};
147
+
148
+ export async function getStyles() {
149
+ return "<style data-stillwind-ssr>" + escapeInlineCss(await getDevelopmentCss(${JSON.stringify(`${bridgeId(configuration)}:${this.environment.name}`)})) + "</style>" + ${JSON.stringify(script)};
150
+ }
151
+
152
+ function escapeInlineCss(css) {
153
+ return css.replace(/<\\/style/gi, (match) => match.replace("/", "\\\\/"));
154
+ }
155
+ `;
156
+ }
157
+ return `// Stillwind SSR CSS (astro)
158
+ export async function getStyles() {
159
+ return ${MARKER};
160
+ }
161
+ `;
162
+ },
163
+ /**
164
+ * Delivers client CSS and replaces the SSR marker with stylesheet links.
165
+ * @param code - Rendered server or client JavaScript.
166
+ * @param chunk - Chunk whose filename identifies the generated source map.
167
+ * @returns Changed JavaScript and its map, or nothing when no styles need delivery.
168
+ */
169
+ renderChunk(code, chunk) {
170
+ const generation = project.forConfig(this.environment.getTopLevelConfig());
171
+ if (this.environment.name === "client" && generation.config.emission !== "split") return renderChunkStyles(generation, "client", this, code, chunk, true);
172
+ if (!code.includes(MARKER)) return;
173
+ const styles = (generation.buildOutput(this.environment.name)?.manifest?.parts ?? []).map((part) => `<link rel="stylesheet" href="${part.href.replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}">`).join("");
174
+ const index = code.indexOf(MARKER);
175
+ if (index < 0) this.error("Cannot locate the Astro stylesheet placeholder");
176
+ const replacement = JSON.stringify(styles);
177
+ const output = code.slice(0, index) + replacement + code.slice(index + 61);
178
+ return {
179
+ code: output,
180
+ map: JSON.stringify(moduleSourceMap(code, output, chunk.fileName, [{
181
+ originalStart: index,
182
+ originalEnd: index + 61,
183
+ generatedStart: index,
184
+ generatedEnd: index + replacement.length
185
+ }], [], ""))
186
+ };
187
+ }
188
+ }] } });
189
+ } }
190
+ };
191
+ }
192
+ export { stillwind };
193
+
194
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/astro/index.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { moduleSourceMap } from \"@stillwind/host\";\nimport type { AstroIntegration } from \"astro\";\nimport type { ResolvedConfig } from \"vite\";\n\nimport { renderChunkStyles } from \"../vite/chunk-styles.ts\";\nimport { createVitePlugins } from \"../vite/plugin.ts\";\nimport {\n createViteProject,\n type EnvironmentOwner,\n type IntegrationConfig,\n} from \"../vite/project.ts\";\nimport { registerDevelopmentCss } from \"./development.ts\";\n\nexport type { IntegrationConfig } from \"../vite/project.ts\";\n\n/** Virtual server module imported by Astro middleware to obtain document stylesheet markup. */\nconst ID = \"virtual:stillwind/astro-styles\";\n\n/** Virtual client module that updates inline SSR styles when development CSS changes. */\nconst CLIENT_ID = ID + \"/client\";\n\n/** External server module that connects SSR rendering to the active development compiler. */\nconst BRIDGE_ID = \"@stillwind/integration/internal/astro-development\";\n\n/**\n * JavaScript string literal replaced with stylesheet links after the production graph is rendered.\n */\nconst MARKER = '\"__STILLWIND_ASTRO_STYLES_574f6dfce7c69466ab9516fb7fc6199a__\"';\n\n/**\n * Creates an Astro integration that applies Stillwind CSS to server-rendered documents and client\n * islands.\n *\n * Development SSR reads current CSS through a server bridge and embeds it in HTML. Production SSR\n * inserts links from the stylesheet manifest.\n *\n * @param config - File discovery, project selection, compiler overrides, and Vite CSS emission.\n * Omission discovers stillwind.config.* from Astro's application root when Vite is configured.\n * @returns An Astro integration that installs Stillwind Vite plugins, middleware, and document\n * stylesheet modules.\n */\nexport function stillwind(config: IntegrationConfig = {}): AstroIntegration {\n let applicationRoot: string | undefined;\n\n const project = createViteProject(config, () => applicationRoot);\n const plugins = createVitePlugins(project);\n const bridgeIds = new WeakMap<ResolvedConfig, string>();\n const bridges = new WeakMap<EnvironmentOwner, () => void>();\n const bridgeId = (configuration: ResolvedConfig) => {\n let id = bridgeIds.get(configuration);\n if (!id) {\n id = randomUUID();\n bridgeIds.set(configuration, id);\n }\n return id;\n };\n\n return {\n name: \"@stillwind/integration\",\n hooks: {\n /**\n * Captures Astro's root and installs middleware plus Stillwind's Vite and document plugins.\n * @param options - Astro setup operations and application configuration.\n */\n \"astro:config:setup\"({ config: astroConfig, updateConfig, addMiddleware }) {\n applicationRoot = fileURLToPath(astroConfig.root);\n addMiddleware({\n entrypoint: fileURLToPath(new URL(\"./middleware.js\", import.meta.url)).replaceAll(\n \"\\\\\",\n \"/\",\n ),\n order: \"pre\",\n });\n updateConfig({\n vite: {\n plugins: [\n plugins,\n {\n name: \"stillwind:astro-document\",\n /**\n * Registers a current-CSS bridge for each server environment and ties cleanup to server closure.\n * @param server - Vite server whose environments resolve SSR dependencies and register watches.\n * @throws If no SSR environment is available.\n */\n configureServer(server) {\n if (!server.environments.ssr) {\n throw new Error(\"Stillwind Astro requires an SSR environment\");\n }\n const generation = project.forConfig(server.config);\n const id = bridgeId(server.config);\n return () => {\n const disposers = Object.entries(server.environments)\n .filter(([name]) => name !== \"client\")\n .map(([name, environment]) => {\n const dispose = registerDevelopmentCss(`${id}:${name}`, async () => {\n const plan = await generation.documentPlan(name, {\n resolve: (specifier, importer, options) =>\n environment.pluginContainer.resolveId(specifier, importer, options),\n addWatchFile: (id) => {\n server.watcher.add(id);\n },\n warn: (message) => {\n server.config.logger.warn(message);\n },\n });\n return plan.css;\n });\n bridges.set(environment, dispose);\n return dispose;\n });\n /** Removes all bridge registrations owned by this server configuration. */\n const dispose = () => {\n for (const dispose of disposers) {\n dispose();\n }\n };\n server.httpServer?.once(\"close\", dispose);\n };\n },\n /** Removes the development bridge owned by the closing environment. */\n closeBundle() {\n if (this.environment) {\n bridges.get(this.environment)?.();\n }\n },\n /**\n * Resolves stylesheet virtual modules and keeps the development bridge external on the server.\n * @param source - Authored module specifier.\n * @returns A virtual identity, an external bridge, or undefined for unrelated requests.\n * @throws If a client environment imports server-only styles or the CSS bridge.\n */\n resolveId(source) {\n if (source === BRIDGE_ID) {\n if (this.environment?.name === \"client\") {\n this.error(\"Stillwind Astro CSS bridge is server-only\");\n }\n return {\n id: source,\n external: true,\n };\n }\n if (source === ID || source === CLIENT_ID) {\n if (source === ID && this.environment?.name === \"client\") {\n this.error(\"Stillwind Astro styles are server-only\");\n }\n return \"\\0\" + source;\n }\n return undefined;\n },\n /**\n * Generates SSR stylesheet markup or the client listener that refreshes inline SSR CSS.\n * @param source - Resolved virtual module identity including its leading NUL.\n * @returns Generated JavaScript, or undefined for unrelated modules. Production markup retains a manifest placeholder.\n */\n load(source) {\n const configuration = this.environment.getTopLevelConfig();\n const generation = project.forConfig(configuration);\n if (source === \"\\0\" + CLIENT_ID) {\n const endpoint =\n generation.settings.publicBase + \"__stillwind/style.css?environment=ssr\";\n return `// Stillwind SSR CSS (astro client)\nif (import.meta.hot) {\n let revision = 0;\n import.meta.hot.on(\"stillwind:css\", async () => {\n const requested = ++revision;\n const response = await fetch(${JSON.stringify(endpoint)});\n if (!response.ok) {\n throw new Error(\"Stillwind SSR CSS: \" + response.status);\n }\n const css = await response.text();\n if (requested === revision) {\n for (const style of document.querySelectorAll(\"style[data-stillwind-ssr]\")) {\n style.textContent = css;\n }\n }\n });\n}\n`;\n }\n if (source !== \"\\0\" + ID) {\n return;\n }\n if (generation.settings.watching) {\n const script = `<script type=\"module\" src=\"${generation.settings.publicBase}@id/__x00__${CLIENT_ID}\"></script>`;\n return `// Stillwind SSR CSS (astro with hot reload)\nimport { getDevelopmentCss } from ${JSON.stringify(BRIDGE_ID)};\n\nexport async function getStyles() {\n return \"<style data-stillwind-ssr>\" + escapeInlineCss(await getDevelopmentCss(${JSON.stringify(`${bridgeId(configuration)}:${this.environment.name}`)})) + \"</style>\" + ${JSON.stringify(script)};\n}\n\nfunction escapeInlineCss(css) {\n return css.replace(/<\\\\/style/gi, (match) => match.replace(\"/\", \"\\\\\\\\/\"));\n}\n`;\n }\n return `// Stillwind SSR CSS (astro)\nexport async function getStyles() {\n return ${MARKER};\n}\n`;\n },\n /**\n * Delivers client CSS and replaces the SSR marker with stylesheet links.\n * @param code - Rendered server or client JavaScript.\n * @param chunk - Chunk whose filename identifies the generated source map.\n * @returns Changed JavaScript and its map, or nothing when no styles need delivery.\n */\n renderChunk(code, chunk) {\n const generation = project.forConfig(this.environment.getTopLevelConfig());\n\n if (\n this.environment.name === \"client\" &&\n generation.config.emission !== \"split\"\n ) {\n return renderChunkStyles(generation, \"client\", this, code, chunk, true);\n }\n\n if (!code.includes(MARKER)) {\n return;\n }\n\n const build = generation.buildOutput(this.environment.name);\n const styles = (build?.manifest?.parts ?? [])\n .map(\n (part) =>\n `<link rel=\"stylesheet\" href=\"${part.href.replaceAll(\"&\", \"&amp;\").replaceAll('\"', \"&quot;\")}\">`,\n )\n .join(\"\");\n const index = code.indexOf(MARKER);\n if (index < 0) {\n this.error(\"Cannot locate the Astro stylesheet placeholder\");\n }\n const replacement = JSON.stringify(styles);\n const output =\n code.slice(0, index) + replacement + code.slice(index + MARKER.length);\n return {\n code: output,\n map: JSON.stringify(\n moduleSourceMap(\n code,\n output,\n chunk.fileName,\n [\n {\n originalStart: index,\n originalEnd: index + MARKER.length,\n generatedStart: index,\n generatedEnd: index + replacement.length,\n },\n ],\n [],\n \"\",\n ),\n ),\n };\n },\n },\n ],\n },\n });\n },\n },\n };\n}\n"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ export declare const onRequest: import("astro").MiddlewareHandler;
2
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1,64 @@
1
+ import { defineMiddleware } from "astro:middleware";
2
+ import { getStyles } from "virtual:stillwind/astro-styles";
3
+ // src/astro/document.ts
4
+ /**
5
+ * Inserts trusted stylesheet markup before the first closing head tag in a UTF-8 HTML response.
6
+ * Preserves the response status and headers except content-length and etag, whose values describe the original body.
7
+ * Returns a streaming response; documents without a closing head retain their original content.
8
+ * @param response - Response whose body contains UTF-8 HTML. A missing body returns the same response.
9
+ * @param styles - Trusted markup inserted without escaping before the first case-insensitive closing head tag.
10
+ * @returns A response that consumes the original body stream and removes content-length and etag.
11
+ */
12
+ function insertStyles(response, styles) {
13
+ if (!response.body) return response;
14
+ const decoder = new TextDecoder();
15
+ const encoder = new TextEncoder();
16
+ let pending = "";
17
+ let inserted = false;
18
+ const body = response.body.pipeThrough(new TransformStream({
19
+ /**
20
+ * Decodes a chunk and buffers text until the closing head tag permits insertion.
21
+ * @param chunk - Next bytes from the original UTF-8 stream.
22
+ * @param controller - Receives encoded output after insertion or for subsequent chunks.
23
+ */
24
+ transform(chunk, controller) {
25
+ const text = decoder.decode(chunk, { stream: true });
26
+ if (inserted) {
27
+ controller.enqueue(encoder.encode(text));
28
+ return;
29
+ }
30
+ pending += text;
31
+ const index = pending.search(/<\/head>/i);
32
+ if (index < 0) return;
33
+ controller.enqueue(encoder.encode(pending.slice(0, index) + styles + pending.slice(index)));
34
+ pending = "";
35
+ inserted = true;
36
+ },
37
+ /**
38
+ * Emits remaining text and completes UTF-8 decoding when the input stream ends.
39
+ * @param controller - Receives buffered HTML when no closing head was found, or trailing decoder text.
40
+ */
41
+ flush(controller) {
42
+ controller.enqueue(encoder.encode(pending + decoder.decode()));
43
+ }
44
+ }));
45
+ const headers = new Headers(response.headers);
46
+ headers.delete("content-length");
47
+ headers.delete("etag");
48
+ return new Response(body, {
49
+ status: response.status,
50
+ statusText: response.statusText,
51
+ headers
52
+ });
53
+ }
54
+ // src/astro/middleware.ts
55
+ const onRequest = defineMiddleware(async (_context, next) => {
56
+ const response = await next();
57
+ if (!response.body || !response.headers.get("content-type")?.startsWith("text/html")) return response;
58
+ const styles = await getStyles();
59
+ if (!styles) return response;
60
+ return insertStyles(response, styles);
61
+ });
62
+ export { onRequest };
63
+
64
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.js","names":[],"sources":["../../src/astro/document.ts","../../src/astro/middleware.ts"],"sourcesContent":["/**\n * Inserts trusted stylesheet markup before the first closing head tag in a UTF-8 HTML response.\n * Preserves the response status and headers except content-length and etag, whose values describe the original body.\n * Returns a streaming response; documents without a closing head retain their original content.\n * @param response - Response whose body contains UTF-8 HTML. A missing body returns the same response.\n * @param styles - Trusted markup inserted without escaping before the first case-insensitive closing head tag.\n * @returns A response that consumes the original body stream and removes content-length and etag.\n */\nexport function insertStyles(response: Response, styles: string): Response {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let pending = \"\";\n let inserted = false;\n const body = response.body.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n /**\n * Decodes a chunk and buffers text until the closing head tag permits insertion.\n * @param chunk - Next bytes from the original UTF-8 stream.\n * @param controller - Receives encoded output after insertion or for subsequent chunks.\n */\n transform(chunk, controller) {\n const text = decoder.decode(chunk, { stream: true });\n if (inserted) {\n controller.enqueue(encoder.encode(text));\n return;\n }\n pending += text;\n const index = pending.search(/<\\/head>/i);\n if (index < 0) {\n return;\n }\n controller.enqueue(encoder.encode(pending.slice(0, index) + styles + pending.slice(index)));\n pending = \"\";\n inserted = true;\n },\n /**\n * Emits remaining text and completes UTF-8 decoding when the input stream ends.\n * @param controller - Receives buffered HTML when no closing head was found, or trailing decoder text.\n */\n flush(controller) {\n controller.enqueue(encoder.encode(pending + decoder.decode()));\n },\n }),\n );\n\n const headers = new Headers(response.headers);\n headers.delete(\"content-length\");\n headers.delete(\"etag\");\n\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n","/// <reference types=\"astro/client\" />\n\nimport { defineMiddleware } from \"astro:middleware\";\nimport { getStyles } from \"virtual:stillwind/astro-styles\";\n\nimport { insertStyles } from \"./document.ts\";\n\nexport const onRequest = defineMiddleware(async (_context, next) => {\n const response = await next();\n if (!response.body || !response.headers.get(\"content-type\")?.startsWith(\"text/html\")) {\n return response;\n }\n const styles = await getStyles();\n if (!styles) {\n return response;\n }\n return insertStyles(response, styles);\n});\n"],"mappings":";;;;;;;;;;;AAQA,SAAgB,aAAa,UAAoB,QAA0B;CACzE,IAAI,CAAC,SAAS,MACZ,OAAO;CAGT,MAAM,UAAU,IAAI,YAAY;CAChC,MAAM,UAAU,IAAI,YAAY;CAChC,IAAI,UAAU;CACd,IAAI,WAAW;CACf,MAAM,OAAO,SAAS,KAAK,YACzB,IAAI,gBAAwC;;;;;;EAM1C,UAAU,OAAO,YAAY;GAC3B,MAAM,OAAO,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;GACnD,IAAI,UAAU;IACZ,WAAW,QAAQ,QAAQ,OAAO,IAAI,CAAC;IACvC;GACF;GACA,WAAW;GACX,MAAM,QAAQ,QAAQ,OAAO,WAAW;GACxC,IAAI,QAAQ,GACV;GAEF,WAAW,QAAQ,QAAQ,OAAO,QAAQ,MAAM,GAAG,KAAK,IAAI,SAAS,QAAQ,MAAM,KAAK,CAAC,CAAC;GAC1F,UAAU;GACV,WAAW;EACb;;;;;EAKA,MAAM,YAAY;GAChB,WAAW,QAAQ,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC,CAAC;EAC/D;CACF,CAAC,CACH;CAEA,MAAM,UAAU,IAAI,QAAQ,SAAS,OAAO;CAC5C,QAAQ,OAAO,gBAAgB;CAC/B,QAAQ,OAAO,MAAM;CAErB,OAAO,IAAI,SAAS,MAAM;EACxB,QAAQ,SAAS;EACjB,YAAY,SAAS;EACrB;CACF,CAAC;AACH;;ACnDA,MAAa,YAAY,iBAAiB,OAAO,UAAU,SAAS;CAClE,MAAM,WAAW,MAAM,KAAK;CAC5B,IAAI,CAAC,SAAS,QAAQ,CAAC,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,GACjF,OAAO;CAET,MAAM,SAAS,MAAM,UAAU;CAC/B,IAAI,CAAC,QACH,OAAO;CAET,OAAO,aAAa,UAAU,MAAM;AACtC,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { createRequire } from "node:module";
2
+ import { fileURLToPath } from "node:url";
3
+ import path from "node:path";
4
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
5
+ // src/binding-files.ts
6
+ /**
7
+ * Returns existing runtime files from the generated loader and installed binding
8
+ * packages. Watching both locations covers napi-rs's local and packaged loading.
9
+ * Missing optional packages are skipped. Other filesystem and resolution errors
10
+ * propagate to the caller.
11
+ * @returns Distinct absolute runtime paths in discovery order, including the generated loader entry.
12
+ * @throws If metadata, filesystem access, or resolution fails beyond a missing optional package.
13
+ */
14
+ function nativeBindingFiles() {
15
+ const entry = fileURLToPath(import.meta.resolve("@stillwind/native"));
16
+ const require = createRequire(entry);
17
+ const files = /* @__PURE__ */ new Set([entry]);
18
+ /**
19
+ * Adds native and WASM runtime companions from an installed runtime directory.
20
+ * @param directory - Existing directory to enumerate. Matching filenames are added to files.
21
+ * @throws If enumeration fails.
22
+ */
23
+ const collect = (directory) => {
24
+ for (const name of readdirSync(directory)) if ((name.startsWith("stillwind_native.") || name.startsWith("wasi-worker")) && /\.(node|wasm|cjs|mjs|js)$/.test(name)) files.add(path.join(directory, name));
25
+ };
26
+ collect(path.dirname(entry));
27
+ const manifest = JSON.parse(readFileSync(new URL(import.meta.resolve("@stillwind/native/package.json")), "utf8"));
28
+ for (const name of Object.keys(manifest.optionalDependencies)) {
29
+ let runtime;
30
+ try {
31
+ runtime = require.resolve(name);
32
+ } catch (error) {
33
+ if (error.code === "MODULE_NOT_FOUND") continue;
34
+ throw error;
35
+ }
36
+ if (existsSync(runtime)) {
37
+ files.add(runtime);
38
+ collect(path.dirname(runtime));
39
+ }
40
+ }
41
+ return [...files];
42
+ }
43
+ export { nativeBindingFiles as t };
44
+
45
+ //# sourceMappingURL=binding-files-Ds5NpyVV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding-files-Ds5NpyVV.js","names":[],"sources":["../src/binding-files.ts"],"sourcesContent":["import { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Returns existing runtime files from the generated loader and installed binding\n * packages. Watching both locations covers napi-rs's local and packaged loading.\n * Missing optional packages are skipped. Other filesystem and resolution errors\n * propagate to the caller.\n * @returns Distinct absolute runtime paths in discovery order, including the generated loader entry.\n * @throws If metadata, filesystem access, or resolution fails beyond a missing optional package.\n */\nexport function nativeBindingFiles(): string[] {\n const entry = fileURLToPath(import.meta.resolve(\"@stillwind/native\"));\n const require = createRequire(entry);\n const files = new Set([entry]);\n /**\n * Adds native and WASM runtime companions from an installed runtime directory.\n * @param directory - Existing directory to enumerate. Matching filenames are added to files.\n * @throws If enumeration fails.\n */\n const collect = (directory: string) => {\n for (const name of readdirSync(directory)) {\n if (\n (name.startsWith(\"stillwind_native.\") || name.startsWith(\"wasi-worker\")) &&\n /\\.(node|wasm|cjs|mjs|js)$/.test(name)\n ) {\n files.add(path.join(directory, name));\n }\n }\n };\n collect(path.dirname(entry));\n const manifest = JSON.parse(\n readFileSync(new URL(import.meta.resolve(\"@stillwind/native/package.json\")), \"utf8\"),\n ) as {\n /** Optional binding package names mapped to their version requirements in generated metadata. */\n optionalDependencies: Record<string, string>;\n };\n for (const name of Object.keys(manifest.optionalDependencies)) {\n let runtime: string;\n try {\n runtime = require.resolve(name);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\") {\n continue;\n }\n throw error;\n }\n if (existsSync(runtime)) {\n files.add(runtime);\n collect(path.dirname(runtime));\n }\n }\n return [...files];\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,qBAA+B;CAC7C,MAAM,QAAQ,cAAc,YAAY,QAAQ,mBAAmB,CAAC;CACpE,MAAM,UAAU,cAAc,KAAK;CACnC,MAAM,wBAAQ,IAAI,IAAI,CAAC,KAAK,CAAC;;;;;;CAM7B,MAAM,WAAW,cAAsB;EACrC,KAAK,MAAM,QAAQ,YAAY,SAAS,GACtC,KACG,KAAK,WAAW,mBAAmB,KAAK,KAAK,WAAW,aAAa,MACtE,4BAA4B,KAAK,IAAI,GAErC,MAAM,IAAI,KAAK,KAAK,WAAW,IAAI,CAAC;CAG1C;CACA,QAAQ,KAAK,QAAQ,KAAK,CAAC;CAC3B,MAAM,WAAW,KAAK,MACpB,aAAa,IAAI,IAAI,YAAY,QAAQ,gCAAgC,CAAC,GAAG,MAAM,CACrF;CAIA,KAAK,MAAM,QAAQ,OAAO,KAAK,SAAS,oBAAoB,GAAG;EAC7D,IAAI;EACJ,IAAI;GACF,UAAU,QAAQ,QAAQ,IAAI;EAChC,SAAS,OAAO;GACd,IAAK,MAAgC,SAAS,oBAC5C;GAEF,MAAM;EACR;EACA,IAAI,WAAW,OAAO,GAAG;GACvB,MAAM,IAAI,OAAO;GACjB,QAAQ,KAAK,QAAQ,OAAO,CAAC;EAC/B;CACF;CACA,OAAO,CAAC,GAAG,KAAK;AAClB"}