@open-pioneer/vite-plugin-pioneer 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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog @open-pioneer/vite-plugin-pioneer
2
+
3
+ ## v0.1.0
4
+
5
+ - Initial release
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,154 @@
1
+ # Pioneer vite plugin
2
+
3
+ Implements certain build-time features required by pioneer apps.
4
+
5
+ Usage:
6
+
7
+ ```js
8
+ // In your vite configuration file
9
+ import { pioneer } from "vite-plugin-pioneer";
10
+
11
+ export default defineConfig({
12
+ // ...
13
+ plugins: [
14
+ pioneer({
15
+ // See configuration reference below
16
+ rootSite: true
17
+ })
18
+ // ...
19
+ ]
20
+ });
21
+ ```
22
+
23
+ ## Configuration reference
24
+
25
+ All configuration properties are optional.
26
+ At least one of `rootSite`, `sites` or `apps` should be non-empty for a successful build.
27
+
28
+ ```ts
29
+ export interface PioneerPluginOptions {
30
+ /**
31
+ * Whether to include the root `index.html` site (by default at `src/index.html`) in the build.
32
+ *
33
+ * The file is always available when using the development server, but may be excluded when
34
+ * when deploying the project as it often contains content for testing.
35
+ *
36
+ * @default false
37
+ */
38
+ rootSite?: boolean;
39
+
40
+ /**
41
+ * List of sites to include in the build.
42
+ *
43
+ * Sites are located at `src/sites/<SITE_NAME>/index.html` by convention.
44
+ *
45
+ * @default []
46
+ */
47
+ sites?: string[] | undefined | false;
48
+
49
+ /**
50
+ * List of apps to include in the build.
51
+ * Apps typically register a custom web component.
52
+ *
53
+ * Apps are located at `src/apps/<APP_NAME>/app.<EXT>` by default.
54
+ * When an app is included in the build, the `dist` directory will
55
+ * contain a `<APP_NAME>.js` that can be directly imported from the browser.
56
+ *
57
+ * Multiple extensions are supported for the app's main entry point: .ts, .tsx, .js and .jsx.
58
+ *
59
+ * @default []
60
+ */
61
+ apps?: string[] | undefined | false;
62
+ }
63
+ ```
64
+
65
+ ## Features
66
+
67
+ ### Multi page support
68
+
69
+ Vite is by default configured to create a single page application (i.e. a single html file with assets).
70
+ The pioneer repository supports multiple deployment modes that can each be achieved by configuring this plugin:
71
+
72
+ 1. Building a single page application.
73
+ Configure `rootSite: true` and leave `sites` and `apps` empty.
74
+
75
+ 2. Building one or more web components.
76
+ Configure the `apps` parameter:
77
+
78
+ ```js
79
+ pioneer({
80
+ // Creates a my-app.js file in dist/ that can be imported from the browser.
81
+ apps: ["my-app"]
82
+ });
83
+ ```
84
+
85
+ 3. Building a multi page application.
86
+ This is convenient for testing and also sometimes for production, since it allows for demonstrating apps in multiple configuration.
87
+
88
+ For example, a project might have a set of sample sites for local development and testing:
89
+
90
+ ```js
91
+ pioneer({
92
+ // Only enable sites during testing.
93
+ // `testing` can be, for example, initialized from the environment or from a local configuration file.
94
+ //
95
+ // See https://vitejs.dev/config/#configuring-vite for more details
96
+ sites: testing && ["sample-1", "sample-2"],
97
+
98
+ // Always deploy my-app.js as a web component.
99
+ apps: ["my-app"]
100
+ });
101
+ ```
102
+
103
+ This plugin internally configures the rollup options inside vite's config to achieve above goals.
104
+ `build.rollupOptions.input` and `.output` should not be altered manually when using this plugin.
105
+
106
+ ## Development
107
+
108
+ To manually build the plugin, run `pnpm run build`.
109
+ This build does _not_ include tests.
110
+
111
+ `pnpm run watch` will continuously rebuild the code (including tests files).
112
+
113
+ `pnpm run test` will execute all tests using mocha.
114
+ If you create a new test file, make sure to list it in `src/all.test.ts`.
115
+ It will not run otherwise.
116
+
117
+ ### Debugging the vite plugin
118
+
119
+ Run vite dev with the `DEBUG` environment variable set.
120
+ This will enable debug logging:
121
+
122
+ ```bash
123
+ $ DEBUG="open-pioneer:*" pnpm exec vite dev --clearScreen=false
124
+ ```
125
+
126
+ will print something like
127
+
128
+ ```plain
129
+ open-pioneer:metadata Request for app metadata of /home/michael/projects/starter/src/apps/date-app +0ms
130
+ open-pioneer:metadata Request for package metadata of /home/michael/projects/starter/src/apps/date-app +1ms
131
+ open-pioneer:metadata Analyzing package at /home/michael/projects/starter/src/apps/date-app +14ms
132
+ open-pioneer:metadata Visiting package directory /home/michael/projects/starter/src/apps/date-app. +0ms
133
+ open-pioneer:codegen Adding manual watch for /home/michael/projects/starter/src/apps/date-app/package.json +0ms
134
+ open-pioneer:codegen Adding manual watch for /home/michael/projects/starter/src/apps/date-app/build.config.mjs +70ms
135
+ ...
136
+ ```
137
+
138
+ You can also add a `--debug` flag to `vite` to show vite's internal log messages.
139
+
140
+ ## License
141
+
142
+ Copyright 2023 con terra GmbH and contributors
143
+
144
+ Licensed under the Apache License, Version 2.0 (the "License");
145
+ you may not use this file except in compliance with the License.
146
+ You may obtain a copy of the License at
147
+
148
+ http://www.apache.org/licenses/LICENSE-2.0
149
+
150
+ Unless required by applicable law or agreed to in writing, software
151
+ distributed under the License is distributed on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
153
+ See the License for the specific language governing permissions and
154
+ limitations under the License.
package/client.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ // SPDX-FileCopyrightText: con terra GmbH and contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ declare module "open-pioneer:app" {
4
+ import { type PackageMetadata, type ObservableBox } from "@open-pioneer/runtime/metadata";
5
+
6
+ /**
7
+ * Metadata for packages contained in the app.
8
+ */
9
+ declare const packages: Record<string, PackageMetadata>;
10
+
11
+ /**
12
+ * Combined styles of all packages contained in the app.
13
+ */
14
+ declare const styles: ObservableBox<string>;
15
+ }
16
+
17
+ /**
18
+ * Provides react hooks to a module.
19
+ * The module must be inside a valid pioneer package (or app).
20
+ *
21
+ * The generated hooks will ensure that hooks return data structures and services
22
+ * for the correct package, and that dependency declarations are valid.
23
+ */
24
+ declare module "open-pioneer:react-hooks" {
25
+ // eslint-disable-next-line unused-imports/no-unused-imports
26
+ import { type ServiceType, type InterfaceName } from "@open-pioneer/runtime";
27
+ import { type UseServiceOptions } from "@open-pioneer/react-integration";
28
+ export { type UseServiceOptions };
29
+
30
+ /**
31
+ * Returns an implementation of the given interface.
32
+ *
33
+ * A complete interface name is required (e.g. "logging.LogService").
34
+ *
35
+ * In order to use a service, it must be declared as an UI-dependency in the package's configuration file.
36
+ */
37
+ export function useService<IFace extends InterfaceName>(
38
+ interfaceName: IFace,
39
+ options?: UseServiceOptions
40
+ ): ServiceType<IFace>;
41
+ export function useService(serviceName: string, options?: UseServiceOptions): unknown;
42
+
43
+ /**
44
+ * Returns all implementations of the given interface.
45
+ *
46
+ * A complete interface name is required (e.g. "logging.LogService").
47
+ *
48
+ * In order to use all services, it must be declared as an UI-dependency (`all: true`) in the package's configuration file.
49
+ */
50
+ export function useServices<InterfaceName extends InterfaceName>(
51
+ interfaceName: InterfaceName
52
+ ): ServiceType<InterfaceName>[];
53
+ export function useServices(serviceName: string): unknown[];
54
+
55
+ /**
56
+ * Returns the properties of the calling component's package.
57
+ */
58
+ export function useProperties(): Readonly<Record<string, unknown>>;
59
+ }
package/dist/index.js ADDED
@@ -0,0 +1,70 @@
1
+ "use strict";var ve=Object.create;var _=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var be=(e,t)=>{for(var n in t)_(e,n,{get:t[n],enumerable:!0})},G=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of _e(t))!xe.call(e,r)&&r!==n&&_(e,r,{get:()=>t[r],enumerable:!(a=Ae(t,r))||a.enumerable});return e};var w=(e,t,n)=>(n=e!=null?ve(we(e)):{},G(t||!e||!e.__esModule?_(n,"default",{value:e,enumerable:!0}):n,e)),Ne=e=>G(_({},"__esModule",{value:!0}),e);var kt={};be(kt,{pioneer:()=>Mt});module.exports=Ne(kt);var Ee=require("node:fs"),y=require("node:path"),v=require("vite");var K=require("debug");function x(e){let t=(0,K.debug)(e);return function(...a){t(...a)}}var D=w(require("@babel/generator")),P=w(require("@babel/template")),i=w(require("@babel/types"));var b=class{existing=new Map;generate(t){let n=Ie(t),a=this.existing,r=a.get(n)??0;return a.set(n,r+1),r===0?n:`${n}_${r}`}};function Ie(e){let t=e.replace(/[^A-Za-z0-9_]+/g,"_");return t=t.replace(/[\d_]+$/,""),/^\d/.test(t)&&(t="_"+t),t||"var"}var Fe=P.default.statement(`
2
+ import { %%SERVICE_NAME%% as %%IMPORT_NAME%% } from %%IMPORT_SOURCE%%;
3
+ `),Oe=P.default.expression(`
4
+ {
5
+ name: %%PACKAGE_NAME%%,
6
+ services: %%PACKAGE_SERVICES%%,
7
+ ui: %%PACKAGE_UI%%,
8
+ properties: %%PROPERTIES%%
9
+ }
10
+ `),$e=P.default.expression(`
11
+ {
12
+ name: %%SERVICE_NAME%%,
13
+ clazz: %%SERVICE_IMPORT%%,
14
+ provides: %%SERVICE_INTERFACES%%,
15
+ references: %%SERVICE_REFERENCES%%
16
+ }
17
+ `),Le=P.default.expression(`
18
+ {
19
+ name: %%INTERFACE_NAME%%,
20
+ qualifier: %%QUALIFIER%%
21
+ }
22
+ `),je=P.default.expression(`
23
+ {
24
+ name: %%INTERFACE_NAME%%,
25
+ qualifier: %%QUALIFIER%%,
26
+ all: %%ALL%%
27
+ }
28
+ `),Ue=P.default.expression(`
29
+ {
30
+ references: %%UI_REFERENCES%%
31
+ }
32
+ `),ze=P.default.expression(`
33
+ {
34
+ value: %%VALUE%%,
35
+ required: %%REQUIRED%%
36
+ }
37
+ `);function H(e){let t=new b,n=i.objectExpression([]),a=[];for(let s of e){if(Je(s))continue;let o=Te(s,{importServiceClass(c,d,l){let f=t.generate(c),u=Fe({SERVICE_NAME:i.identifier(d),IMPORT_NAME:i.identifier(f),IMPORT_SOURCE:i.stringLiteral(l)});return a.push(u),f}});n.properties.push(i.objectProperty(i.stringLiteral(s.name),o))}let r=i.program([...a,i.exportDefaultDeclaration(n)]);return(0,D.default)(r).code}function Te(e,t){let n=i.objectExpression([]);for(let o of e.config.services){if(!e.entryPointPath)throw new Error(`Package '${e.name}' must have a valid entry point (typically index.ts or index.js).
38
+ The entry point can be configured by setting the 'main' property in the package.json file.`);let c=t.importServiceClass(e.name+"_"+o.name,o.name,e.entryPointPath),d=$e({SERVICE_NAME:i.stringLiteral(o.name),SERVICE_IMPORT:i.identifier(c),SERVICE_INTERFACES:i.arrayExpression(o.provides.map(l=>Le({INTERFACE_NAME:i.stringLiteral(l.name),QUALIFIER:l.qualifier==null?Q():i.stringLiteral(l.qualifier)}))),SERVICE_REFERENCES:i.objectExpression(Object.entries(o.references).map(([l,f])=>i.objectProperty(i.stringLiteral(l),q(f))))});n.properties.push(i.objectProperty(i.stringLiteral(o.name),d))}let a=Ue({UI_REFERENCES:i.arrayExpression(e.config.ui.references.map(o=>q(o)))}),r=i.objectExpression(e.config.properties.map(o=>i.objectProperty(i.stringLiteral(o.name),ze({VALUE:j(o.defaultValue),REQUIRED:i.booleanLiteral(o.required)}))));return Oe({PACKAGE_NAME:i.stringLiteral(e.name),PACKAGE_SERVICES:n,PACKAGE_UI:a,PROPERTIES:r})}function Je(e){let t=e.config;return!(t.services.length||t.styles||t.ui.references.length||t.properties.length)}function j(e){if(e==null)return i.nullLiteral();if(typeof e=="string")return i.stringLiteral(e);if(typeof e=="number")return i.numericLiteral(e);if(typeof e=="boolean")return i.booleanLiteral(e);if(Array.isArray(e))return i.arrayExpression(e.map(t=>j(t)));if(typeof e=="object")return i.objectExpression(Object.entries(e).map(([t,n])=>i.objectProperty(i.stringLiteral(t),j(n))));throw new Error(`Unexpected value while serializing JSON: ${e}.`)}function q(e){return je({INTERFACE_NAME:i.stringLiteral(e.name),QUALIFIER:e.qualifier?i.stringLiteral(e.qualifier):Q(),ALL:i.booleanLiteral(e.all??!1)})}function Q(){return i.unaryExpression("void",i.numericLiteral(0))}var S=require("fs/promises"),M=require("path"),O=require("vite");var g=class extends Error{};var N=w(require("node:fs")),I=require("node:path");function U(e){return N.promises.access(e,N.constants.F_OK).then(()=>!0).catch(()=>!1)}function W(e,t){let n=(0,I.relative)(t,e);return!!(n&&!n.startsWith("..")&&!(0,I.isAbsolute)(n))}var ee=require("node:url");var p=require("zod"),Y=require("zod-validation-error"),Be=p.z.union([p.z.string(),p.z.number(),p.z.boolean(),p.z.null()]),z=p.z.lazy(()=>p.z.union([Be,p.z.array(z),p.z.record(z)])),Ve=p.z.strictObject({required:p.z.boolean().optional()}),Z=p.z.strictObject({name:p.z.string(),qualifier:p.z.string().optional(),all:p.z.boolean().optional()}),Ge=p.z.strictObject({name:p.z.string(),qualifier:p.z.string().optional()}),Ke=p.z.strictObject({references:p.z.array(p.z.string().or(Z)).optional()}),qe=p.z.strictObject({provides:p.z.string().or(p.z.array(p.z.string().or(Ge))).optional(),references:p.z.record(p.z.string(),p.z.string().or(Z)).optional()}),De=p.z.strictObject({styles:p.z.string().optional(),services:p.z.record(p.z.string(),qe).optional(),ui:Ke.optional(),properties:p.z.record(p.z.string(),z).optional(),propertiesMeta:p.z.record(p.z.string(),Ve).optional()});function X(e){let t=De.safeParse(e);if(t.success)return t.data;throw(0,Y.fromZodError)(t.error)}var T="build.config.mjs",He=0;async function te(e){let n=await import(`${(0,ee.pathToFileURL)(e)}?id=${++He}`);if(!n||!n.default)throw new Error("The module must contain a default export.");let a=n.default;return Qe(a)}function Qe(e){let t=X(e);return Ye(t)}var We=/[\\/]build\.config\.mjs($|\?)/;function ne(e){return We.test(e)}function Ye(e){return{styles:e.styles,services:Object.entries(e.services??{}).map(([t,n])=>Ze(t,n)),ui:tt(e.ui),properties:nt(e.properties,e.propertiesMeta)}}function Ze(e,t){return{name:e,provides:Xe(t.provides),references:et(t.references)}}function Xe(e){return e?typeof e=="string"?[{name:e}]:e.map(t=>typeof t=="string"?{name:t}:t):[]}function et(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ae(n)])):{}}function ae(e){return typeof e=="string"?{name:e}:e}function tt(e){var t;return{references:((t=e==null?void 0:e.references)==null?void 0:t.map(ae))??[]}}function nt(e,t){var a;let n=[];for(let[r,s]of Object.entries(e??{})){let o=((a=t==null?void 0:t[r])==null?void 0:a.required)??!1;n.push({name:r,defaultValue:s,required:o})}return n}var E=!!process.env.DEBUG,h=x("open-pioneer:metadata"),F=class{sourceRoot;packageMetadataCache=new Map;packageMetadataByName=new Map;packageMetadataJobs=new Map;constructor(t){this.sourceRoot=t}reset(){this.packageMetadataCache.clear(),this.packageMetadataJobs.clear()}onFileChanged(t){(dt(t)||ne(t))&&this.invalidatePackageMetadata((0,M.dirname)(t))}async getAppMetadata(t,n){E&&h(`Request for app metadata of ${n}`);let a=await this.getPackageMetadata(t,{type:"absolute",directory:n});if(!a)throw new g(`Failed to parse app metadata in ${n}. Ensure that the app is a valid local package.`);let r=new Map;r.set(a.name,a);let s=async(c,d)=>{let l=c.map(async f=>{let u=await this.getPackageMetadata(t,{type:"unresolved",packageName:f,importedFrom:d});u&&(r.has(u.name)||r.set(u.name,u),await s(u.dependencies,u.packageJsonPath))});return await Promise.all(l)};return await s(a.dependencies,a.packageJsonPath),{name:a.name,directory:a.directory,packageJsonPath:a.packageJsonPath,packages:Array.from(r.values())}}async getPackageMetadata(t,n){E&&h(`Request for package metadata of ${it(n)}`);let a=await this.resolvePackageLocation(t,n);if(!ct(a,this.sourceRoot)){E&&h(`Skipping non-local package '${a}'.`);return}let r=this.getPackageMetadataFromCache(a);return r?(E&&h(`Returning cached metadata for '${r.metadata.name}'`),re(r.watchFiles,t),r.metadata):await this.schedulePackageMetadataJob(t,a)}async schedulePackageMetadataJob(t,n){let a=this.packageMetadataJobs,r=a.get(n);if(r){E&&h(`Waiting for already running analysis of ${n}`);let c=await r;return re(c.watchFiles,t),c.metadata}let s=new Set,o={...t,addWatchFile(c){t.addWatchFile(c),s.add(c)}};return r=at(o,n).then(c=>{E&&h(`Metadata for '${c.name}': %O`,c);let d={metadata:c,watchFiles:s};return a.get(n)===r&&this.putPackageMetadataInCache(n,d),d}).finally(()=>{a.get(n)===r&&a.delete(n)}),this.packageMetadataJobs.set(n,r),(await r).metadata}getPackageMetadataFromCache(t){return this.packageMetadataCache.get(J(t))}putPackageMetadataInCache(t,n){let a=n.metadata,r=a.name,s=J(t),o=this.packageMetadataByName.get(r);if(o&&o.directory!==a.directory)throw new g(`Found package '${r}' at two different locations ${o.directory} and ${a.directory}`);this.packageMetadataCache.set(s,n),this.packageMetadataByName.set(r,a)}invalidatePackageMetadata(t){let n=J(t),a=this.packageMetadataCache.get(n);a&&(this.packageMetadataByName.delete(a.metadata.name),this.packageMetadataCache.delete(n))}async resolvePackageLocation(t,n){if(n.type==="absolute")return await(0,S.realpath)(n.directory);let a=`${n.packageName}/package.json`,r=await t.resolve(a,(0,O.normalizePath)(n.importedFrom),{skipSelf:!0});if(!r||r.external)throw new g(`Request for '${a}' did not result in a local file (required by '${n.importedFrom}').`);let s=await(0,S.realpath)((0,M.dirname)(r.id));return E&&h(`Found package '${n.packageName}' at ${s}`),s}};function re(e,t){for(let n of e)t.addWatchFile(n)}function J(e){return(0,O.normalizePath)(e)}async function at(e,t){var l;E&&h(`Visiting package directory ${t}.`);let n=(0,M.join)(t,"package.json");e.addWatchFile(n);let{name:a,dependencies:r}=await rt(e,n),s=(0,M.join)(t,T),o;if(e.addWatchFile((0,O.normalizePath)(s)),await U(s))try{o=await te(s)}catch(f){let u=f.message||"Unknown error";throw new g(`Failed to load build config ${s}: ${u}`)}else throw new g(`Expected a ${T} in ${t}`);let c;if(o.services.length)try{c=(l=await e.resolve(t))==null?void 0:l.id}catch(f){e.warn(`Failed to resolve entry point for package ${t}: ${f}`)}let d;if(o.styles){try{d=await ot(e,t,o.styles)}catch(f){throw new g(`Failed to resolve css file for package ${t}: ${f}`)}if(!d)throw new g(`Failed to find css file '${o.styles}' in ${t}`)}return{name:a,directory:t,packageJsonPath:n,entryPointPath:c,cssFilePath:d,dependencies:r,config:o}}async function rt(e,t){if(!await U(t))throw new g(`Expected a 'package.json' file at ${t}`);let n;try{n=JSON.parse(await(0,S.readFile)(t,"utf-8"))}catch(o){throw new g(`Failed to read ${t}: ${o}`)}let a=n.name;if(typeof a!="string")throw new g(`Expected 'name' to be a string in ${t}`);let r=n.dependencies??{};if(typeof r!="object")throw new g(`Expected a valid 'dependencies' object in ${t}`);let s=Object.keys(r);return{name:a,dependencies:s}}async function ot(e,t,n){let a=await e.resolve(`./${n}`,`${t}/package.json`,{skipSelf:!0});return a==null?void 0:a.id}function it(e){switch(e.type){case"absolute":return`${e.directory}`;case"unresolved":return`'${e.packageName}' required by ${e.importedFrom}`}}var st=/[\\/]node_modules[\\/]/;function ct(e,t){return W(e,t)&&!st.test(e)}var pt=/[\\/]package\.json($|\?)/;function dt(e){return pt.test(e)}function oe(e){let t=n=>`@import ${JSON.stringify(n)};`;return e.filter(n=>!!n.cssFilePath).map(n=>t(n.cssFilePath)).join(`
39
+ `)}var se=require("node:path"),gt=/[?&]open-pioneer-app(?:$|&)/,lt=/[?&]open-pioneer-packages(?:$|&)/,ft=/[?&]open-pioneer-styles(?:$|&)/,ut=/[/\\]@@open-pioneer-react-hooks(?:\?|$)/,mt=/^(.*?)(?:\?|$)/,ce="open-pioneer-app",pe="open-pioneer-packages",de="open-pioneer-styles",ge="@@open-pioneer-react-hooks";function le(e){if(e.match(ut))return{type:"package-hooks",packageDirectory:(0,se.dirname)(ie(e))};let t;if(e.match(gt))t="app-meta";else if(e.match(lt))t="app-packages";else if(e.match(ft))t="app-css";else return;let n=ie(e);return{type:t,importer:n}}function ie(e){var n;let t=(n=e.match(mt))==null?void 0:n[1];if(!t||e[0]=="\0")throw new Error(`Failed to get actual source file from '${e}'.`);return t}function fe(e,t){let n=`${e}?${pe}`,a=`${e}?${de}&inline&lang.css`;return`
40
+ import { createBox } from ${JSON.stringify(t)};
41
+ import packages from ${JSON.stringify(n)};
42
+ import stylesString from ${JSON.stringify(a)};
43
+
44
+ const styles = createBox(stylesString);
45
+ if (import.meta.hot) {
46
+ import.meta.hot.data.styles ??= styles;
47
+ import.meta.hot.accept((mod) => {
48
+ if (mod && mod.packages === packages) {
49
+ import.meta.hot.data.styles.setValue(mod.styles.value);
50
+ return;
51
+ }
52
+
53
+ // Cannot handle all other changes the moment; trigger reload.
54
+ import.meta.hot.invalidate();
55
+ });
56
+ }
57
+
58
+ export {
59
+ packages,
60
+ styles
61
+ };
62
+ `.trim()}var he=require("node:fs/promises");function ue(e,t){return`
63
+ import { useServiceInternal, useServicesInternal, usePropertiesInternal } from ${JSON.stringify(t)};
64
+
65
+ const PACKAGE_NAME = ${JSON.stringify(e)};
66
+ export const useService = /*@__PURE__*/ useServiceInternal.bind(undefined, PACKAGE_NAME);
67
+ export const useServices = /*@__PURE__*/ useServicesInternal.bind(undefined, PACKAGE_NAME);
68
+ export const useProperties = /*@__PURE__*/ usePropertiesInternal.bind(undefined, PACKAGE_NAME);
69
+ `.trim()}var k=!!process.env.DEBUG,R=x("open-pioneer:codegen");function ye(){let e=new Map,t,n,a,r,s;return{name:"pioneer:codegen",async buildStart(){e.clear(),n==null||n.reset();let o=async c=>{let d=await this.resolve(c,__filename);return d||this.error(`Failed to find '${c}'.`),d.id};r=await o("@open-pioneer/runtime/react-integration"),s=await o("@open-pioneer/runtime/metadata")},configResolved(o){t=o,n=new F(t.root)},configureServer(o){a=o,o.watcher.on("all",(c,d)=>{let l=e.get((0,v.normalizePath)(d));if(l){k&&R(`File changed: ${d}`),n.onFileChanged(d);for(let f of l){let u=o.moduleGraph.getModuleById(f);u&&(k&&R(`Triggering hmr of ${f}`),o.reloadModule(u).catch(A=>{t.logger.error(`Failed to trigger hmr: ${A}`)}))}}})},async resolveId(o,c){try{if(o==="open-pioneer:app"){if(!c)throw new g("Must be imported from a source file.");return c+"?"+ce}if(o==="open-pioneer:react-hooks"){if(!c)throw new g("Must be imported from a source file.");let d=Pe((0,y.dirname)(c),t.root);if(!d)throw new g(`Failed to find package.json for package from '${c}'.`);return`${(0,y.dirname)(d)}/${ge}`}}catch(d){me(this,d)}},async load(o){var c;try{let d=le(o);if(!d)return;if(d.type==="package-hooks"){let C=d.packageDirectory,m=(c=await this.resolve(C+"/package.json"))==null?void 0:c.id;if(!m)throw new g(`Failed to resolve package.json in ${C}`);let Se=await ht(this,m),V=ue(Se,r);return k&&R("Generated hooks code: %O",V),V}let{type:l,importer:f}=d;if(l==="app-meta")return fe(f,s);let u=Pe((0,y.dirname)(f),t.root);if(!u)throw new g(`Failed to find package.json for app from '${f}'.`);let A=Pt(this,o,a,e),B=(0,y.dirname)(u);switch(l){case"app-packages":{let C=await n.getAppMetadata(A,B),m=H(C.packages);return k&&R("Generated app metadata: %O",m),m}case"app-css":{let C=await n.getAppMetadata(A,B),m=oe(C.packages);return k&&R("Generated app css: %O",m),m}}}catch(d){me(this,d)}}}}function Pt(e,t,n,a){return{warn:e.warn,resolve:e.resolve,addWatchFile:r=>{n&&(k&&R(`Adding manual watch for ${r}`),n.watcher.add(r),Et(a,r,t)),e.addWatchFile(r)}}}function me(e,t){t instanceof g&&e.error(t);let n=String(t.message)||"Unknown error";e.error("Internal error: "+n)}function Et(e,t,n){let a=(0,v.normalizePath)(t),r=e.get(a);r||(r=new Set,e.set(a,r)),r.add(n)}function Pe(e,t){let n=e;for(;n;){let a=(0,y.join)(n,"package.json");if((0,Ee.existsSync)(a))return a;if((0,v.normalizePath)(n)==(0,v.normalizePath)(t))return;let r=(0,y.dirname)(n);n=r===n||r==="."?"":r}}async function ht(e,t){let n;try{let a=await(0,he.readFile)(t,"utf-8");n=JSON.parse(a).name}catch(a){throw new g(`Failed to read package.json file: ${a}`)}if(!n)throw new g(`Failed to read package name from '${t}'.`);return n}var L=require("node:fs"),$=require("node:path"),Me=require("node:path"),ke=require("node:process");function Re(e){let t=(e==null?void 0:e.rootSite)??!1,n=(e==null?void 0:e.apps)||[],a=(e==null?void 0:e.sites)||[],r;return{name:"pioneer:mpa",config(s){let o=s.root??(0,ke.cwd)();return{build:{rollupOptions:{input:yt({apps:n,sites:a,rootSite:t,sourceRoot:o}),output:{entryFileNames(l){return n.includes(l.name)?"[name].js":Me.posix.join(r.build.assetsDir,"[name]-[hash].js")}}}}}},configResolved(s){r=s}}}function yt(e){let t=e.apps.map(s=>{let o=(0,$.resolve)(e.sourceRoot,"apps",s,"app"),c=Ct(o);return{name:s,path:c}}),n=e.sites.map(s=>{let o=(0,$.resolve)(e.sourceRoot,"sites",s,"index.html");if(!(0,L.existsSync)(o))throw new Error(`Failed to find site '${s}' at ${o}. Please ensure that the site name is spelled correctly.`);return{name:s,path:o}});if(e.rootSite){let s=(0,$.resolve)(e.sourceRoot,"index.html");if(!(0,L.existsSync)(s))throw new Error(`Failed to find root site at ${s}. Please create the missing file.`);n.push({name:"index",path:s})}let a={},r=0;for(let{name:s,path:o}of[t,n].flat()){let c=a[s];if(c)throw new Error(`Entry point '${s}' was defined twice (paths ${c} and ${o}). Please remove the duplicated entry.`);a[s]=o,++r}if(r===0)throw new Error("You must configure at least one site or one app in the pioneer plugin options.");return a}var Ce=[".ts",".tsx",".js",".jsx"];function Ct(e){for(let n of Ce){let a=e+n;if((0,L.existsSync)(a))return a}let t=Ce.join(", ");throw new Error(`Failed to find a matching entry point file for '${e}'. Supported extensions are ${t}. Ensure that the app name is spelled correctly or create the missing file.`)}function Mt(e){return[Re(e),ye()]}0&&(module.exports={pioneer});
70
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/codegenPlugin.ts", "../src/utils/debug.ts", "../src/codegen/generatePackagesMetadata.ts", "../src/codegen/IdGenerator.ts", "../src/metadata/MetadataRepository.ts", "../src/ReportableError.ts", "../src/utils/fileUtils.ts", "../src/metadata/parseBuildConfig.ts", "../src/metadata/BuildConfigSchema.ts", "../src/codegen/generateCombinedCss.ts", "../src/codegen/shared.ts", "../src/codegen/generateAppMetadata.ts", "../src/codegen/generateReactHooks.ts", "../src/mpaPlugin.ts"],
4
+ "sourcesContent": ["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Plugin } from \"vite\";\nimport { codegenPlugin } from \"./codegenPlugin\";\nimport { mpaPlugin } from \"./mpaPlugin\";\nimport type { PioneerPluginOptions } from \"../types\";\nexport { type PioneerPluginOptions };\n\nexport function pioneer(options?: PioneerPluginOptions): Plugin[] {\n return [mpaPlugin(options), codegenPlugin()];\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { PluginContext } from \"rollup\";\nimport { normalizePath, Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport { createDebugger } from \"./utils/debug\";\nimport { generatePackagesMetadata } from \"./codegen/generatePackagesMetadata\";\nimport { MetadataContext, MetadataRepository } from \"./metadata/MetadataRepository\";\nimport { generateCombinedCss } from \"./codegen/generateCombinedCss\";\nimport { generateAppMetadata } from \"./codegen/generateAppMetadata\";\nimport { APP_META_QUERY, PACKAGE_HOOKS, parseVirtualAppModuleId } from \"./codegen/shared\";\nimport { readFile } from \"node:fs/promises\";\nimport { generateReactHooks } from \"./codegen/generateReactHooks\";\nimport { ReportableError } from \"./ReportableError\";\n\nconst isDebug = !!process.env.DEBUG;\nconst debug = createDebugger(\"open-pioneer:codegen\");\n\nexport function codegenPlugin(): Plugin {\n // key: normalized path to package json.\n // value: set of module ids that must be invalidated.\n const manualDeps = new Map<string, Set<string>>();\n\n let config!: ResolvedConfig;\n let metadata!: MetadataRepository;\n let devServer: ViteDevServer | undefined;\n\n let reactIntegrationId!: string;\n let metadataId!: string;\n return {\n name: \"pioneer:codegen\",\n\n async buildStart(this: PluginContext) {\n manualDeps.clear();\n metadata?.reset();\n\n // TODO: use require.resolve instead (requires built js?).\n const resolve = async (rawModuleId: string) => {\n const resolvedResult = await this.resolve(rawModuleId, __filename);\n if (!resolvedResult) {\n this.error(`Failed to find '${rawModuleId}'.`);\n }\n return resolvedResult.id;\n };\n\n reactIntegrationId = await resolve(\"@open-pioneer/runtime/react-integration\");\n metadataId = await resolve(\"@open-pioneer/runtime/metadata\");\n },\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n metadata = new MetadataRepository(config.root);\n },\n\n configureServer(server) {\n devServer = server;\n\n // Trigger manual module reload when a watched file changes.\n server.watcher.on(\"all\", (_, path) => {\n const moduleIds = manualDeps.get(normalizePath(path));\n if (!moduleIds) {\n return;\n }\n\n isDebug && debug(`File changed: ${path}`);\n metadata.onFileChanged(path);\n for (const moduleId of moduleIds) {\n const mod = server.moduleGraph.getModuleById(moduleId);\n if (mod) {\n isDebug && debug(`Triggering hmr of ${moduleId}`);\n server.reloadModule(mod).catch((err) => {\n config.logger.error(`Failed to trigger hmr: ${err}`);\n });\n }\n }\n });\n },\n\n async resolveId(this: PluginContext, moduleId, importer) {\n try {\n if (moduleId === \"open-pioneer:app\") {\n if (!importer) {\n throw new ReportableError(\"Must be imported from a source file.\");\n }\n return importer + \"?\" + APP_META_QUERY;\n }\n if (moduleId === \"open-pioneer:react-hooks\") {\n if (!importer) {\n throw new ReportableError(\"Must be imported from a source file.\");\n }\n\n const packageJsonPath = findPackageJson(dirname(importer), config.root);\n if (!packageJsonPath) {\n throw new ReportableError(\n `Failed to find package.json for package from '${importer}'.`\n );\n }\n return `${dirname(packageJsonPath)}/${PACKAGE_HOOKS}`;\n }\n } catch (e) {\n reportError(this, e);\n }\n },\n\n async load(this: PluginContext, moduleId) {\n try {\n const virtualModule = parseVirtualAppModuleId(moduleId);\n if (!virtualModule) {\n return undefined;\n }\n\n if (virtualModule.type === \"package-hooks\") {\n const directory = virtualModule.packageDirectory;\n // use forward slashes instead of platform separator\n const packageJsonPath = (await this.resolve(directory + \"/package.json\"))?.id;\n if (!packageJsonPath) {\n throw new ReportableError(`Failed to resolve package.json in ${directory}`);\n }\n\n const packageName = await getPackageName(this, packageJsonPath);\n const generatedSourceCode = generateReactHooks(packageName, reactIntegrationId);\n isDebug && debug(\"Generated hooks code: %O\", generatedSourceCode);\n return generatedSourceCode;\n }\n\n const { type, importer } = virtualModule;\n if (type === \"app-meta\") {\n return generateAppMetadata(importer, metadataId);\n }\n\n const pkgJsonPath = findPackageJson(dirname(importer), config.root);\n if (!pkgJsonPath) {\n throw new ReportableError(\n `Failed to find package.json for app from '${importer}'.`\n );\n }\n\n const context = buildMetadataContext(this, moduleId, devServer, manualDeps);\n const appDir = dirname(pkgJsonPath);\n switch (type) {\n case \"app-packages\": {\n const appMetadata = await metadata.getAppMetadata(context, appDir);\n const generatedSourceCode = generatePackagesMetadata(appMetadata.packages);\n isDebug && debug(\"Generated app metadata: %O\", generatedSourceCode);\n return generatedSourceCode;\n }\n case \"app-css\": {\n const appMetadata = await metadata.getAppMetadata(context, appDir);\n const generatedSourceCode = generateCombinedCss(appMetadata.packages);\n isDebug && debug(\"Generated app css: %O\", generatedSourceCode);\n return generatedSourceCode;\n }\n }\n } catch (e) {\n reportError(this, e);\n }\n }\n };\n}\n\n// Patches the addWatchFile function for manual watching\nfunction buildMetadataContext(\n ctx: PluginContext,\n moduleId: string,\n devServer: ViteDevServer | undefined,\n manualDeps: Map<string, Set<string>>\n): MetadataContext {\n return {\n warn: ctx.warn,\n resolve: ctx.resolve,\n addWatchFile: (id) => {\n if (devServer) {\n // TODO: Is there a better way? We want to trigger a hot reload when\n // one of the build.config files or package.json files change!\n isDebug && debug(`Adding manual watch for ${id}`);\n devServer.watcher.add(id);\n addManualDep(manualDeps, id, moduleId);\n }\n ctx.addWatchFile(id);\n }\n };\n}\n\nfunction reportError(ctx: PluginContext, error: unknown) {\n if (error instanceof ReportableError) {\n ctx.error(error);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const message = String((error as any).message) || \"Unknown error\";\n ctx.error(\"Internal error: \" + message);\n}\n\nfunction addManualDep(manualDeps: Map<string, Set<string>>, file: string, moduleId: string) {\n const normalizedPath = normalizePath(file);\n let moduleIds = manualDeps.get(normalizedPath);\n if (!moduleIds) {\n moduleIds = new Set();\n manualDeps.set(normalizedPath, moduleIds);\n }\n moduleIds.add(moduleId);\n}\n\nfunction findPackageJson(startDir: string, rootDir: string) {\n let dir = startDir;\n while (dir) {\n const candidate = join(dir, \"package.json\");\n if (existsSync(candidate)) {\n return candidate;\n }\n\n if (normalizePath(dir) == normalizePath(rootDir)) {\n return undefined;\n }\n\n const parent = dirname(dir);\n dir = parent === dir || parent === \".\" ? \"\" : parent;\n }\n return undefined;\n}\n\nasync function getPackageName(ctx: PluginContext, packageJsonPath: string) {\n let name: string;\n try {\n const content = await readFile(packageJsonPath, \"utf-8\");\n name = JSON.parse(content).name;\n } catch (e) {\n throw new ReportableError(`Failed to read package.json file: ${e}`);\n }\n if (!name) {\n throw new ReportableError(`Failed to read package name from '${packageJsonPath}'.`);\n }\n return name;\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { debug } from \"debug\";\n\nexport interface Debugger {\n (msg: string, ...args: unknown[]): void;\n}\n\nexport function createDebugger(namespace: string): Debugger {\n const logger = debug(namespace);\n return function debugFunction(...args) {\n logger(...args);\n };\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport generate from \"@babel/generator\";\nimport template from \"@babel/template\";\nimport * as nodes from \"@babel/types\";\nimport { ReferenceConfig } from \"@open-pioneer/build-support\";\nimport { PackageMetadata } from \"../metadata/MetadataRepository\";\nimport { IdGenerator } from \"./IdGenerator\";\n\nconst SERVICE_IMPORT = template.statement(`\n import { %%SERVICE_NAME%% as %%IMPORT_NAME%% } from %%IMPORT_SOURCE%%;\n`);\n\nconst PKG_OBJECT = template.expression(`\n {\n name: %%PACKAGE_NAME%%,\n services: %%PACKAGE_SERVICES%%,\n ui: %%PACKAGE_UI%%,\n properties: %%PROPERTIES%%\n }\n`);\n\nconst SERVICE_OBJECT = template.expression(`\n {\n name: %%SERVICE_NAME%%,\n clazz: %%SERVICE_IMPORT%%,\n provides: %%SERVICE_INTERFACES%%,\n references: %%SERVICE_REFERENCES%%\n }\n`);\n\nconst INTERFACE_OBJECT = template.expression(`\n {\n name: %%INTERFACE_NAME%%,\n qualifier: %%QUALIFIER%%\n }\n`);\n\nconst REFERENCE_OBJECT = template.expression(`\n {\n name: %%INTERFACE_NAME%%,\n qualifier: %%QUALIFIER%%,\n all: %%ALL%%\n }\n`);\n\nconst UI_OBJECT = template.expression(`\n {\n references: %%UI_REFERENCES%%\n }\n`);\n\nconst PROPERTY_OBJECT = template.expression(`\n {\n value: %%VALUE%%,\n required: %%REQUIRED%%\n }\n`);\n\nexport type PackageMetadataInput = Pick<PackageMetadata, \"name\" | \"config\" | \"entryPointPath\">;\n\n/**\n * Generates a combined metadata structure that is essentially a Record<string, metadata.PackageMetadata>.\n * The object contents must match the shape required by the runtime (declared in runtime/metadata/index.ts).\n */\nexport function generatePackagesMetadata(packages: PackageMetadataInput[]): string {\n const idGenerator = new IdGenerator();\n const packagesMetadata = nodes.objectExpression([]);\n const imports: nodes.Statement[] = [];\n for (const pkg of packages) {\n if (skipPackage(pkg)) {\n continue;\n }\n\n const packageMetadata = generatePackageMetadata(pkg, {\n importServiceClass(variableName, className, entryPoint) {\n const id = idGenerator.generate(variableName);\n const renderedImporter = SERVICE_IMPORT({\n SERVICE_NAME: nodes.identifier(className),\n IMPORT_NAME: nodes.identifier(id),\n IMPORT_SOURCE: nodes.stringLiteral(entryPoint)\n });\n imports.push(renderedImporter);\n return id;\n }\n });\n packagesMetadata.properties.push(\n nodes.objectProperty(nodes.stringLiteral(pkg.name), packageMetadata)\n );\n }\n\n const program = nodes.program([...imports, nodes.exportDefaultDeclaration(packagesMetadata)]);\n return generate(program).code;\n}\n\n/**\n * Generates the metadata object for a single package.\n * As a side effect, service imports for required service classes will be emitted through a callback.\n */\nfunction generatePackageMetadata(\n pkg: PackageMetadataInput,\n options: {\n /**\n * Adds an import to the containing module.\n * Returns the actual variable name associated with the service.\n */\n importServiceClass(variableName: string, className: string, entryPoint: string): string;\n }\n): nodes.Expression {\n const servicesObject = nodes.objectExpression([]);\n for (const service of pkg.config.services) {\n if (!pkg.entryPointPath) {\n throw new Error(\n `Package '${pkg.name}' must have a valid entry point (typically index.ts or index.js).\\n` +\n \"The entry point can be configured by setting the 'main' property in the package.json file.\"\n );\n }\n\n const importName = options.importServiceClass(\n pkg.name + \"_\" + service.name,\n service.name,\n pkg.entryPointPath\n );\n const serviceObject = SERVICE_OBJECT({\n SERVICE_NAME: nodes.stringLiteral(service.name),\n SERVICE_IMPORT: nodes.identifier(importName),\n SERVICE_INTERFACES: nodes.arrayExpression(\n service.provides.map((p) =>\n INTERFACE_OBJECT({\n INTERFACE_NAME: nodes.stringLiteral(p.name),\n QUALIFIER:\n p.qualifier == null ? undefinedNode() : nodes.stringLiteral(p.qualifier)\n })\n )\n ),\n SERVICE_REFERENCES: nodes.objectExpression(\n Object.entries(service.references).map(([referenceName, referenceConfig]) =>\n nodes.objectProperty(\n nodes.stringLiteral(referenceName),\n referenceObject(referenceConfig)\n )\n )\n )\n });\n\n servicesObject.properties.push(\n nodes.objectProperty(nodes.stringLiteral(service.name), serviceObject)\n );\n }\n\n const uiObject = UI_OBJECT({\n UI_REFERENCES: nodes.arrayExpression(\n pkg.config.ui.references.map((r) => referenceObject(r))\n )\n });\n\n const propertiesObject = nodes.objectExpression(\n pkg.config.properties.map((prop) =>\n nodes.objectProperty(\n nodes.stringLiteral(prop.name),\n PROPERTY_OBJECT({\n VALUE: jsonToExpression(prop.defaultValue),\n REQUIRED: nodes.booleanLiteral(prop.required)\n })\n )\n )\n );\n\n const pkgObject = PKG_OBJECT({\n PACKAGE_NAME: nodes.stringLiteral(pkg.name),\n PACKAGE_SERVICES: servicesObject,\n PACKAGE_UI: uiObject,\n PROPERTIES: propertiesObject\n });\n return pkgObject;\n}\n\n/**\n * Returns true if the package does not contain any relevant metadata.\n */\nfunction skipPackage(pkg: PackageMetadataInput) {\n const config = pkg.config;\n if (config.services.length) {\n return false;\n }\n if (config.styles) {\n return false;\n }\n if (config.ui.references.length) {\n return false;\n }\n if (config.properties.length) {\n return false;\n }\n return true;\n}\n\nfunction jsonToExpression(json: unknown): nodes.Expression {\n if (json == null) {\n return nodes.nullLiteral();\n }\n if (typeof json === \"string\") {\n return nodes.stringLiteral(json);\n }\n if (typeof json === \"number\") {\n return nodes.numericLiteral(json);\n }\n if (typeof json === \"boolean\") {\n return nodes.booleanLiteral(json);\n }\n if (Array.isArray(json)) {\n return nodes.arrayExpression(json.map((item) => jsonToExpression(item)));\n }\n if (typeof json === \"object\") {\n return nodes.objectExpression(\n Object.entries(json).map(([name, value]) =>\n nodes.objectProperty(nodes.stringLiteral(name), jsonToExpression(value))\n )\n );\n }\n throw new Error(`Unexpected value while serializing JSON: ${json}.`);\n}\n\nfunction referenceObject(referenceConfig: ReferenceConfig): nodes.Expression {\n return REFERENCE_OBJECT({\n INTERFACE_NAME: nodes.stringLiteral(referenceConfig.name),\n QUALIFIER: referenceConfig.qualifier\n ? nodes.stringLiteral(referenceConfig.qualifier)\n : undefinedNode(),\n ALL: nodes.booleanLiteral(referenceConfig.all ?? false)\n });\n}\n\nfunction undefinedNode() {\n return nodes.unaryExpression(\"void\", nodes.numericLiteral(0));\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nexport class IdGenerator {\n private existing = new Map<string, number>();\n\n /**\n * Returns a unique identifier (in the context of this instance) that resembles the input value.\n */\n generate(input: string): string {\n const clean = cleanName(input);\n\n const existing = this.existing;\n const count = existing.get(clean) ?? 0;\n existing.set(clean, count + 1);\n return count === 0 ? clean : `${clean}_${count}`;\n }\n}\n\nfunction cleanName(input: string) {\n let clean = input.replace(/[^A-Za-z0-9_]+/g, \"_\"); // remove non-alphanumeric\n clean = clean.replace(/[\\d_]+$/, \"\"); // strip trailing numbers / underscore to prevent conflicts\n if (/^\\d/.test(clean)) {\n clean = \"_\" + clean; // ensure variable name does not start with a number\n }\n return clean || \"var\";\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { readFile, realpath } from \"fs/promises\";\nimport { dirname, join } from \"path\";\nimport { PluginContext } from \"rollup\";\nimport { normalizePath } from \"vite\";\nimport { ReportableError } from \"../ReportableError\";\nimport { createDebugger } from \"../utils/debug\";\nimport { fileExists, isInDirectory } from \"../utils/fileUtils\";\nimport {\n BUILD_CONFIG_NAME,\n isBuildConfig,\n loadBuildConfig,\n NormalizedPackageConfig\n} from \"./parseBuildConfig\";\n\nconst isDebug = !!process.env.DEBUG;\nconst debug = createDebugger(\"open-pioneer:metadata\");\n\n/**\n * Contains build-time information about an app.\n */\nexport interface AppMetadata {\n /** App name. */\n name: string;\n\n /** Directory on disk. */\n directory: string;\n\n /** Path to package.json file. */\n packageJsonPath: string;\n\n /**\n * Packages used by the app.\n * Includes the app package itself!\n */\n packages: PackageMetadata[];\n}\n\n/**\n * Contains build-time information about a package.\n */\nexport interface PackageMetadata {\n /** Package name. */\n name: string;\n\n /** Directory on disk. */\n directory: string;\n\n /** Path to package.json file. */\n packageJsonPath: string;\n\n /** Path to entry point (contains service exports). */\n entryPointPath: string | undefined;\n\n /** Path to the resolved css file (if any). */\n cssFilePath: string | undefined;\n\n /** Runtime dependencies (from package.json). */\n dependencies: string[];\n\n /** Parsed metadata (from build config file). */\n config: NormalizedPackageConfig;\n}\n\nexport type MetadataContext = Pick<PluginContext, \"addWatchFile\" | \"resolve\" | \"warn\">;\n\nexport interface ResolvedPackageLocation {\n type: \"absolute\";\n directory: string;\n}\n\nexport interface UnresolvedPackageLocation {\n type: \"unresolved\";\n packageName: string;\n importedFrom: string;\n}\n\nexport type PackageLocation = ResolvedPackageLocation | UnresolvedPackageLocation;\n\n/**\n * Tracks metadata and the files that were used to parse that metadata.\n * watchFiles should be propagated when a caller receives a cached result,\n * otherwise hot reloading may not be triggered correctly on file changes.\n */\ninterface MetadataCacheEntry {\n metadata: PackageMetadata;\n watchFiles: ReadonlySet<string>;\n}\n\n/**\n * Provides metadata about apps and packages.\n * Metadata is read from disk on demand and will then be cached\n * until one of the file dependencies has changed.\n */\nexport class MetadataRepository {\n private sourceRoot: string;\n\n // Key: package directory on disk, value: existing metadata\n private packageMetadataCache = new Map<string, MetadataCacheEntry>();\n\n // Key: package name (known to cache), value: metadata\n private packageMetadataByName = new Map<string, PackageMetadata>();\n\n // Deduplicated jobs (only visit a directory once).\n // Key: package directory on disk\n private packageMetadataJobs = new Map<string, Promise<MetadataCacheEntry>>();\n\n /**\n * @param sourceRoot Source folder on disk, needed to detect 'local' packages\n */\n constructor(sourceRoot: string) {\n this.sourceRoot = sourceRoot;\n }\n\n reset() {\n this.packageMetadataCache.clear();\n this.packageMetadataJobs.clear();\n }\n\n onFileChanged(path: string) {\n if (isPackageJson(path) || isBuildConfig(path)) {\n this.invalidatePackageMetadata(dirname(path));\n }\n }\n\n /**\n * Returns the combined application metadata of the app in `appDirectory`.\n * Starting from the app's package.json, dependencies will be visited recursively.\n *\n * For packages that use our package extensions (services etc.), metadata will be gathered and\n * will be returned here.\n */\n async getAppMetadata(ctx: MetadataContext, appDirectory: string): Promise<AppMetadata> {\n isDebug && debug(`Request for app metadata of ${appDirectory}`);\n\n const appPackageMetadata = await this.getPackageMetadata(ctx, {\n type: \"absolute\",\n directory: appDirectory\n });\n if (!appPackageMetadata) {\n throw new ReportableError(\n `Failed to parse app metadata in ${appDirectory}. Ensure that the app is a valid local package.`\n );\n }\n\n // Map to ensure that we don't return duplicates. Key: package name\n const packageMetadataByName = new Map<string, PackageMetadata>();\n packageMetadataByName.set(appPackageMetadata.name, appPackageMetadata);\n\n // Recursively visit all dependencies.\n // Detected metadata is placed into `packageMetadata`.\n const visitDependencies = async (dependencies: string[], importedFrom: string) => {\n const jobs = dependencies.map(async (packageName) => {\n const packageMetadata = await this.getPackageMetadata(ctx, {\n type: \"unresolved\",\n packageName,\n importedFrom\n });\n if (packageMetadata) {\n if (!packageMetadataByName.has(packageMetadata.name)) {\n packageMetadataByName.set(packageMetadata.name, packageMetadata);\n }\n await visitDependencies(\n packageMetadata.dependencies,\n packageMetadata.packageJsonPath\n );\n }\n });\n return await Promise.all(jobs);\n };\n await visitDependencies(\n appPackageMetadata.dependencies,\n appPackageMetadata.packageJsonPath\n );\n\n const appMetadata: AppMetadata = {\n name: appPackageMetadata.name,\n directory: appPackageMetadata.directory,\n packageJsonPath: appPackageMetadata.packageJsonPath,\n packages: Array.from(packageMetadataByName.values())\n };\n return appMetadata;\n }\n\n async getPackageMetadata(\n ctx: MetadataContext,\n loc: PackageLocation\n ): Promise<PackageMetadata | undefined> {\n isDebug && debug(`Request for package metadata of ${formatPackageLocation(loc)}`);\n\n const packageDir = await this.resolvePackageLocation(ctx, loc);\n\n // This would have to be changed when packages from the 'outside' are also supported in the future.\n if (!isLocalPackage(packageDir, this.sourceRoot)) {\n isDebug && debug(`Skipping non-local package '${packageDir}'.`);\n return undefined;\n }\n\n // Check the cache\n const cacheEntry = this.getPackageMetadataFromCache(packageDir);\n if (cacheEntry) {\n isDebug && debug(`Returning cached metadata for '${cacheEntry.metadata.name}'`);\n propagateWatchFiles(cacheEntry.watchFiles, ctx);\n return cacheEntry.metadata;\n }\n return await this.schedulePackageMetadataJob(ctx, packageDir);\n }\n\n private async schedulePackageMetadataJob(ctx: MetadataContext, packageDir: string) {\n // Deduplicate concurrent jobs for the same directory.\n const jobs = this.packageMetadataJobs;\n let job = jobs.get(packageDir);\n if (job) {\n isDebug && debug(`Waiting for already running analysis of ${packageDir}`);\n const entry = await job;\n propagateWatchFiles(entry.watchFiles, ctx);\n return entry.metadata;\n }\n\n const watchFiles = new Set<string>();\n const trackingCtx: MetadataContext = {\n ...ctx,\n addWatchFile(id) {\n ctx.addWatchFile(id);\n watchFiles.add(id);\n }\n };\n job = parsePackageMetadata(trackingCtx, packageDir)\n .then((metadata) => {\n isDebug && debug(`Metadata for '${metadata.name}': %O`, metadata);\n const entry: MetadataCacheEntry = {\n metadata,\n watchFiles\n };\n if (jobs.get(packageDir) === job) {\n this.putPackageMetadataInCache(packageDir, entry);\n }\n return entry;\n })\n .finally(() => {\n if (jobs.get(packageDir) === job) {\n jobs.delete(packageDir);\n }\n });\n this.packageMetadataJobs.set(packageDir, job);\n return (await job).metadata;\n }\n\n private getPackageMetadataFromCache(packageDir: string): MetadataCacheEntry | undefined {\n return this.packageMetadataCache.get(packageCacheKey(packageDir));\n }\n\n private putPackageMetadataInCache(packageDir: string, entry: MetadataCacheEntry) {\n const metadata = entry.metadata;\n const name = metadata.name;\n const key = packageCacheKey(packageDir);\n\n // Ensure only one version of a package exists in the app\n const existingMetadata = this.packageMetadataByName.get(name);\n if (existingMetadata && existingMetadata.directory !== metadata.directory) {\n throw new ReportableError(\n `Found package '${name}' at two different locations ${existingMetadata.directory} and ${metadata.directory}`\n );\n }\n\n this.packageMetadataCache.set(key, entry);\n this.packageMetadataByName.set(name, metadata);\n }\n\n private invalidatePackageMetadata(packageDir: string) {\n const key = packageCacheKey(packageDir);\n const entry = this.packageMetadataCache.get(key);\n if (entry) {\n this.packageMetadataByName.delete(entry.metadata.name);\n this.packageMetadataCache.delete(key);\n }\n }\n\n private async resolvePackageLocation(ctx: MetadataContext, loc: PackageLocation) {\n if (loc.type === \"absolute\") {\n return await realpath(loc.directory);\n }\n\n // Try to locate the package via rollup resolve.\n const unresolvedPackageJson = `${loc.packageName}/package.json`;\n const packageJsonLocation = await ctx.resolve(\n unresolvedPackageJson,\n normalizePath(loc.importedFrom),\n {\n skipSelf: true\n }\n );\n if (!packageJsonLocation || packageJsonLocation.external) {\n throw new ReportableError(\n `Request for '${unresolvedPackageJson}' did not result in a local file (required by '${loc.importedFrom}').`\n );\n }\n\n const packageDir = await realpath(dirname(packageJsonLocation.id));\n isDebug && debug(`Found package '${loc.packageName}' at ${packageDir}`);\n return packageDir;\n }\n}\n\nfunction propagateWatchFiles(watchFiles: Iterable<string>, ctx: MetadataContext) {\n for (const file of watchFiles) {\n ctx.addWatchFile(file);\n }\n}\n\nfunction packageCacheKey(packageDir: string) {\n return normalizePath(packageDir);\n}\n\nexport async function parsePackageMetadata(\n ctx: MetadataContext,\n packageDir: string\n): Promise<PackageMetadata> {\n isDebug && debug(`Visiting package directory ${packageDir}.`);\n\n const packageJsonPath = join(packageDir, \"package.json\");\n\n ctx.addWatchFile(packageJsonPath);\n const { name: packageName, dependencies } = await parsePackageJson(ctx, packageJsonPath);\n\n const buildConfigPath = join(packageDir, BUILD_CONFIG_NAME);\n let buildConfig: NormalizedPackageConfig | undefined;\n ctx.addWatchFile(normalizePath(buildConfigPath));\n if (await fileExists(buildConfigPath)) {\n try {\n buildConfig = await loadBuildConfig(buildConfigPath);\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const msg = (e as any).message || \"Unknown error\";\n throw new ReportableError(`Failed to load build config ${buildConfigPath}: ${msg}`);\n }\n } else {\n throw new ReportableError(`Expected a ${BUILD_CONFIG_NAME} in ${packageDir}`);\n }\n\n let entryPoint: string | undefined;\n if (buildConfig.services.length) {\n try {\n entryPoint = (await ctx.resolve(packageDir))?.id;\n } catch (e) {\n ctx.warn(`Failed to resolve entry point for package ${packageDir}: ${e}`);\n }\n }\n\n let cssFile: string | undefined;\n if (buildConfig.styles) {\n try {\n cssFile = await resolveLocalFile(ctx, packageDir, buildConfig.styles);\n } catch (e) {\n throw new ReportableError(`Failed to resolve css file for package ${packageDir}: ${e}`);\n }\n if (!cssFile) {\n throw new ReportableError(\n `Failed to find css file '${buildConfig.styles}' in ${packageDir}`\n );\n }\n }\n\n return {\n name: packageName,\n directory: packageDir,\n packageJsonPath: packageJsonPath,\n entryPointPath: entryPoint,\n cssFilePath: cssFile,\n dependencies,\n config: buildConfig\n };\n}\n\nasync function parsePackageJson(ctx: MetadataContext, packageJsonPath: string) {\n if (!(await fileExists(packageJsonPath))) {\n throw new ReportableError(`Expected a 'package.json' file at ${packageJsonPath}`);\n }\n\n let packageJsonContent;\n try {\n packageJsonContent = JSON.parse(await readFile(packageJsonPath, \"utf-8\"));\n } catch (e) {\n throw new ReportableError(`Failed to read ${packageJsonPath}: ${e}`);\n }\n\n const packageName = packageJsonContent.name;\n if (typeof packageName !== \"string\") {\n throw new ReportableError(`Expected 'name' to be a string in ${packageJsonPath}`);\n }\n\n const dependencies = packageJsonContent.dependencies ?? {};\n if (typeof dependencies !== \"object\") {\n throw new ReportableError(`Expected a valid 'dependencies' object in ${packageJsonPath}`);\n }\n\n const dependencyNames = Object.keys(dependencies);\n return {\n name: packageName,\n dependencies: dependencyNames\n };\n}\n\nasync function resolveLocalFile(ctx: MetadataContext, packageDir: string, localModuleId: string) {\n const result = await ctx.resolve(`./${localModuleId}`, `${packageDir}/package.json`, {\n skipSelf: true\n });\n return result?.id;\n}\n\nfunction formatPackageLocation(loc: PackageLocation) {\n switch (loc.type) {\n case \"absolute\":\n return `${loc.directory}`;\n case \"unresolved\":\n return `'${loc.packageName}' required by ${loc.importedFrom}`;\n }\n}\n\nconst NODE_MODULES_RE = /[\\\\/]node_modules[\\\\/]/;\n\nfunction isLocalPackage(file: string, sourceDir: string) {\n return isInDirectory(file, sourceDir) && !NODE_MODULES_RE.test(file);\n}\n\nconst PACKAGE_JSON_RE = /[\\\\/]package\\.json($|\\?)/;\n\nfunction isPackageJson(file: string) {\n return PACKAGE_JSON_RE.test(file);\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nexport class ReportableError extends Error {}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport * as fs from \"node:fs\";\nimport { isAbsolute, relative } from \"node:path\";\n\n/**\n * Asynchronously checks for the existence of `file`.\n */\nexport function fileExists(file: string): Promise<boolean> {\n return fs.promises\n .access(file, fs.constants.F_OK)\n .then(() => true)\n .catch(() => false);\n}\n\n/**\n * Returns true if `candidate` is a child of `directory`.\n */\nexport function isInDirectory(candidate: string, directory: string): boolean {\n const rel = relative(directory, candidate);\n const isChild = rel && !rel.startsWith(\"..\") && !isAbsolute(rel);\n return !!isChild;\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { pathToFileURL } from \"node:url\";\nimport {\n BuildConfig,\n PropertyMetaConfig,\n ProvidesConfig,\n ReferenceConfig,\n ServiceConfig\n} from \"@open-pioneer/build-support\";\nimport { verifyBuildConfigSchema } from \"./BuildConfigSchema\";\n\nexport const BUILD_CONFIG_NAME = \"build.config.mjs\";\n\nexport interface NormalizedPackageConfig {\n services: NormalizedServiceConfig[];\n styles: string | undefined;\n ui: NormalizedUiConfig;\n properties: NormalizedProperty[];\n}\n\nexport interface NormalizedServiceConfig {\n name: string;\n provides: ProvidesConfig[];\n references: Record<string, ReferenceConfig>;\n}\n\nexport interface NormalizedUiConfig {\n references: ReferenceConfig[];\n}\n\nexport interface NormalizedProperty {\n name: string;\n defaultValue: unknown;\n required: boolean;\n}\n\nlet requestId = 0;\n\n/**\n * Loads and parses a build configuration file from the given path on disk.\n */\nexport async function loadBuildConfig(path: string): Promise<NormalizedPackageConfig> {\n const fileURL = pathToFileURL(path);\n const importedModule = (await import(`${fileURL}?id=${++requestId}`)) as Record<\n string,\n unknown\n >;\n if (!importedModule || !importedModule.default) {\n throw new Error(`The module must contain a default export.`);\n }\n\n const config = importedModule.default;\n return parseBuildConfig(config);\n}\n\n/**\n * Parses a build configuration object and validates it.\n */\nexport function parseBuildConfig(object: unknown): NormalizedPackageConfig {\n const rawConfig = verifyBuildConfigSchema(object);\n return normalizeConfig(rawConfig);\n}\n\nconst BUILD_CONFIG_RE = /[\\\\/]build\\.config\\.mjs($|\\?)/;\n\nexport function isBuildConfig(file: string) {\n return BUILD_CONFIG_RE.test(file);\n}\n\nfunction normalizeConfig(rawConfig: BuildConfig): NormalizedPackageConfig {\n return {\n styles: rawConfig.styles,\n services: Object.entries(rawConfig.services ?? {}).map(([serviceName, serviceConfig]) => {\n return normalizeServiceConfig(serviceName, serviceConfig);\n }),\n ui: normalizeUiConfig(rawConfig.ui),\n properties: normalizeProperties(rawConfig.properties, rawConfig.propertiesMeta)\n };\n}\n\nfunction normalizeServiceConfig(name: string, rawConfig: ServiceConfig): NormalizedServiceConfig {\n return {\n name: name,\n provides: normalizeProvidesConfig(rawConfig.provides),\n references: normalizeReferencesConfig(rawConfig.references)\n };\n}\n\nfunction normalizeProvidesConfig(rawConfig: ServiceConfig[\"provides\"]): ProvidesConfig[] {\n if (!rawConfig) {\n return [];\n }\n\n if (typeof rawConfig === \"string\") {\n return [\n {\n name: rawConfig\n }\n ];\n }\n\n return rawConfig.map((providesConfig) => {\n const normalized: ProvidesConfig =\n typeof providesConfig === \"string\" ? { name: providesConfig } : providesConfig;\n return normalized;\n });\n}\n\nfunction normalizeReferencesConfig(\n rawConfig: ServiceConfig[\"references\"]\n): Record<string, ReferenceConfig> {\n if (!rawConfig) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(rawConfig).map(([referenceName, referenceConfig]) => {\n return [referenceName, normalizeReferenceConfig(referenceConfig)];\n })\n );\n}\n\nfunction normalizeReferenceConfig(rawConfig: string | ReferenceConfig): ReferenceConfig {\n if (typeof rawConfig === \"string\") {\n return { name: rawConfig };\n }\n return rawConfig;\n}\n\nfunction normalizeUiConfig(rawConfig: BuildConfig[\"ui\"]): NormalizedUiConfig {\n return {\n references: rawConfig?.references?.map(normalizeReferenceConfig) ?? []\n };\n}\n\nfunction normalizeProperties(\n properties: Record<string, unknown> | undefined,\n propertiesMeta: Record<string, PropertyMetaConfig> | undefined\n): NormalizedProperty[] {\n const result: NormalizedProperty[] = [];\n for (const [name, defaultValue] of Object.entries(properties ?? {})) {\n const required = propertiesMeta?.[name]?.required ?? false;\n result.push({\n name,\n defaultValue,\n required\n });\n }\n return result;\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { z } from \"zod\";\nimport {\n BuildConfig,\n PropertyMetaConfig,\n ProvidesConfig,\n ReferenceConfig,\n ServiceConfig,\n UiConfig\n} from \"@open-pioneer/build-support\";\nimport { fromZodError } from \"zod-validation-error\";\n\nconst LITERAL_SCHEMA = z.union([z.string(), z.number(), z.boolean(), z.null()]);\n\ntype Literal = z.infer<typeof LITERAL_SCHEMA>;\n\ntype Json = Literal | { [key: string]: Json } | Json[];\n\nconst JSON_SCHEMA: z.ZodType<Json> = z.lazy(() =>\n z.union([LITERAL_SCHEMA, z.array(JSON_SCHEMA), z.record(JSON_SCHEMA)])\n);\n\nconst PROPERTY_META_SCHEMA: z.ZodType<PropertyMetaConfig> = z.strictObject({\n required: z.boolean().optional()\n});\n\nconst REFERENCE_CONFIG_SCHEMA: z.ZodType<ReferenceConfig> = z.strictObject({\n name: z.string(),\n qualifier: z.string().optional(),\n all: z.boolean().optional()\n});\n\nconst PROVIDES_CONFIG_SCHEMA: z.ZodType<ProvidesConfig> = z.strictObject({\n name: z.string(),\n qualifier: z.string().optional()\n});\n\nconst UI_CONFIG_SCHEMA: z.ZodType<UiConfig> = z.strictObject({\n references: z.array(z.string().or(REFERENCE_CONFIG_SCHEMA)).optional()\n});\n\nconst SERVICE_CONFIG_SCHEMA: z.ZodType<ServiceConfig> = z.strictObject({\n provides: z\n .string()\n .or(z.array(z.string().or(PROVIDES_CONFIG_SCHEMA)))\n .optional(),\n references: z.record(z.string(), z.string().or(REFERENCE_CONFIG_SCHEMA)).optional()\n});\n\nconst BUILD_CONFIG_SCHEMA: z.ZodType<BuildConfig> = z.strictObject({\n styles: z.string().optional(),\n services: z.record(z.string(), SERVICE_CONFIG_SCHEMA).optional(),\n ui: UI_CONFIG_SCHEMA.optional(),\n properties: z.record(z.string(), JSON_SCHEMA).optional(),\n propertiesMeta: z.record(z.string(), PROPERTY_META_SCHEMA).optional()\n});\n\n/**\n * Ensures that `value` conforms to the {@link BuildConfig} interface.\n * Throws an error if that is not the case.\n *\n * @returns `value` but casted to the appropriate type.\n */\nexport function verifyBuildConfigSchema(value: unknown): BuildConfig {\n const result = BUILD_CONFIG_SCHEMA.safeParse(value);\n if (result.success) {\n return result.data;\n }\n throw fromZodError(result.error);\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { PackageMetadata } from \"../metadata/MetadataRepository\";\n\nexport type PackageMetadataInput = Pick<PackageMetadata, \"cssFilePath\">;\n\n/**\n * Generates a css file that imports the css file defined by the packages.\n */\nexport function generateCombinedCss(packages: PackageMetadataInput[]) {\n const cssImport = (file: string) => `@import ${JSON.stringify(file)};`;\n return packages\n .filter((pkg) => !!pkg.cssFilePath)\n .map((pkg) => cssImport(pkg.cssFilePath!)) // eslint-disable-line @typescript-eslint/no-non-null-assertion\n .join(\"\\n\");\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { dirname } from \"node:path\";\n\nconst APP_META_RE = /[?&]open-pioneer-app(?:$|&)/;\nconst APP_PACKAGES_RE = /[?&]open-pioneer-packages(?:$|&)/;\nconst APP_CSS_RE = /[?&]open-pioneer-styles(?:$|&)/;\nconst APP_HOOKS_RE = /[/\\\\]@@open-pioneer-react-hooks(?:\\?|$)/;\nconst SOURCE_FILE_RE = /^(.*?)(?:\\?|$)/;\n\nexport const APP_META_QUERY = \"open-pioneer-app\";\nexport const APP_PACKAGES_QUERY = \"open-pioneer-packages\";\nexport const APP_CSS_QUERY = \"open-pioneer-styles\";\nexport const PACKAGE_HOOKS = \"@@open-pioneer-react-hooks\";\n\nexport interface VirtualAppModule {\n type: \"app-meta\" | \"app-packages\" | \"app-css\";\n importer: string;\n}\n\nexport interface VirtualPackageModule {\n type: \"package-hooks\";\n packageDirectory: string;\n}\n\nexport function parseVirtualAppModuleId(\n moduleId: string\n): VirtualAppModule | VirtualPackageModule | undefined {\n if (moduleId.match(APP_HOOKS_RE)) {\n return {\n type: \"package-hooks\",\n packageDirectory: dirname(getSourceFile(moduleId))\n };\n }\n\n let type: VirtualAppModule[\"type\"];\n if (moduleId.match(APP_META_RE)) {\n type = \"app-meta\";\n } else if (moduleId.match(APP_PACKAGES_RE)) {\n type = \"app-packages\";\n } else if (moduleId.match(APP_CSS_RE)) {\n type = \"app-css\";\n } else {\n return undefined;\n }\n\n const importer = getSourceFile(moduleId);\n return { type, importer };\n}\n\nfunction getSourceFile(moduleId: string) {\n const sourceFile = moduleId.match(SOURCE_FILE_RE)?.[1];\n if (!sourceFile || moduleId[0] == \"\\0\") {\n throw new Error(`Failed to get actual source file from '${moduleId}'.`);\n }\n return sourceFile;\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { APP_CSS_QUERY, APP_PACKAGES_QUERY } from \"./shared\";\n\n/**\n * Generates the main app metadata module.\n * It delegates the actual metadata generation to auxiliary modules.\n */\nexport function generateAppMetadata(importer: string, metadataModuleId: string) {\n /*\n CSS loading: \n - 'inline' loads the css as a string literal.\n - the suffix (e.g. '.css') at the very end is important to trigger the correct vite plugin!\n - I would like to import css as an url instead (separate file),\n but that currently hinges on https://github.com/vitejs/vite/pull/11084\n\n - TODO: .scss support (will currently trigger the esbuild plugin and an error because the file contains both .ts and .scss)\n\n Hot reloading:\n - See https://vitejs.dev/guide/api-hmr.html for vite's HMR API\n - When a css string changes, the module exporting the `stylesString` below changes.\n We accept those changes through the `import.meta.hot.accept` mechanism by\n calling the `setValue` method on the old observable box value.\n The runtime has a reference to the box and watches for changes (only during development!)\n - The code below takes care to use the _correct_ `styles` box (every module has its own, even the new version).\n `import.meta.hot.data` is shared between all versions of the module, so we always use the first box.\n */\n const packagesModule = `${importer}?${APP_PACKAGES_QUERY}`;\n const cssModule = `${importer}?${APP_CSS_QUERY}&inline&lang.css`;\n return `\nimport { createBox } from ${JSON.stringify(metadataModuleId)};\nimport packages from ${JSON.stringify(packagesModule)};\nimport stylesString from ${JSON.stringify(cssModule)};\n\nconst styles = createBox(stylesString);\nif (import.meta.hot) {\n import.meta.hot.data.styles ??= styles;\n import.meta.hot.accept((mod) => {\n if (mod && mod.packages === packages) {\n import.meta.hot.data.styles.setValue(mod.styles.value);\n return;\n }\n \n // Cannot handle all other changes the moment; trigger reload.\n import.meta.hot.invalidate();\n });\n}\n\nexport {\n packages,\n styles\n};\n`.trim();\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nexport function generateReactHooks(packageName: string, runtimeModuleId: string) {\n return `\nimport { useServiceInternal, useServicesInternal, usePropertiesInternal } from ${JSON.stringify(\n runtimeModuleId\n )};\n\nconst PACKAGE_NAME = ${JSON.stringify(packageName)};\nexport const useService = /*@__PURE__*/ useServiceInternal.bind(undefined, PACKAGE_NAME);\nexport const useServices = /*@__PURE__*/ useServicesInternal.bind(undefined, PACKAGE_NAME);\nexport const useProperties = /*@__PURE__*/ usePropertiesInternal.bind(undefined, PACKAGE_NAME);\n `.trim();\n}\n", "// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Plugin, ResolvedConfig } from \"vite\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { posix } from \"node:path\";\nimport { cwd } from \"node:process\";\nimport { type PioneerPluginOptions } from \".\";\nimport { RollupOptions } from \"rollup\";\n\nexport function mpaPlugin(options: PioneerPluginOptions | undefined): Plugin {\n const rootSite = options?.rootSite ?? false;\n const apps = options?.apps || [];\n const sites = options?.sites || [];\n\n let resolvedConfig: ResolvedConfig;\n return {\n name: \"pioneer:mpa\",\n\n config(config) {\n const sourceRoot = config.root ?? cwd();\n const entryPoints = gatherEntryPoints({ apps, sites, rootSite, sourceRoot });\n const rollupOptions: RollupOptions = {\n input: entryPoints,\n output: {\n entryFileNames(chunk) {\n if (apps.includes(chunk.name)) {\n return \"[name].js\";\n }\n\n // This will rename the .js files that belong to a .html site, they don't need a public name.\n return posix.join(resolvedConfig.build.assetsDir, \"[name]-[hash].js\");\n }\n }\n };\n\n return {\n build: {\n rollupOptions\n }\n };\n },\n\n configResolved(config) {\n resolvedConfig = config;\n }\n };\n}\n\nfunction gatherEntryPoints(options: {\n apps: string[];\n sites: string[];\n rootSite: boolean;\n sourceRoot: string;\n}): Record<string, string> {\n const apps = options.apps.map((appName) => {\n const prefix = resolve(options.sourceRoot, \"apps\", appName, \"app\");\n const path = findMatchingEntryPointFile(prefix);\n return {\n name: appName,\n path: path\n };\n });\n\n /*\n * Vite does not respect the entry point name for html files, it\n * put each html site at a location mirroring the source directory structure (e.g. site/<SITE>/index.html\n * instead of SITE.html).\n *\n * There are multiple vite mpa plugins that handle custom html paths which can either be used\n * directly or as inspiration.\n */\n const sites = options.sites.map((siteName) => {\n const path = resolve(options.sourceRoot, \"sites\", siteName, \"index.html\");\n if (!existsSync(path)) {\n throw new Error(\n `Failed to find site '${siteName}' at ${path}. Please ensure that the site name is spelled correctly.`\n );\n }\n return {\n name: siteName,\n path: path\n };\n });\n if (options.rootSite) {\n const path = resolve(options.sourceRoot, \"index.html\");\n if (!existsSync(path)) {\n throw new Error(`Failed to find root site at ${path}. Please create the missing file.`);\n }\n sites.push({\n name: \"index\",\n path: path\n });\n }\n\n const entryPoints: Record<string, string> = {};\n let entryPointCount = 0;\n for (const { name, path } of [apps, sites].flat()) {\n const existingPath = entryPoints[name];\n if (existingPath) {\n throw new Error(\n `Entry point '${name}' was defined twice (paths ${existingPath} and ${path}). Please remove the duplicated entry.`\n );\n }\n entryPoints[name] = path;\n ++entryPointCount;\n }\n if (entryPointCount === 0) {\n throw new Error(\n \"You must configure at least one site or one app in the pioneer plugin options.\"\n );\n }\n return entryPoints;\n}\n\nconst EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".jsx\"];\n\nfunction findMatchingEntryPointFile(prefix: string) {\n for (const ext of EXTENSIONS) {\n const candidate = prefix + ext;\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n const extensions = EXTENSIONS.join(\", \");\n throw new Error(\n `Failed to find a matching entry point file for '${prefix}'. Supported extensions are ${extensions}. Ensure that the app name is spelled correctly or create the missing file.`\n );\n}\n"],
5
+ "mappings": "skBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,aAAAE,KAAA,eAAAC,GAAAH,ICEA,IAAAI,GAA2B,mBAC3BC,EAA8B,qBAE9BC,EAAqE,gBCHrE,IAAAC,EAAsB,iBAMf,SAASC,EAAeC,EAA6B,CACxD,IAAMC,KAAS,SAAMD,CAAS,EAC9B,OAAO,YAA0BE,EAAM,CACnCD,EAAO,GAAGC,CAAI,CAClB,CACJ,CCXA,IAAAC,EAAqB,+BACrBC,EAAqB,8BACrBC,EAAuB,2BCFhB,IAAMC,EAAN,KAAkB,CACb,SAAW,IAAI,IAKvB,SAASC,EAAuB,CAC5B,IAAMC,EAAQC,GAAUF,CAAK,EAEvBG,EAAW,KAAK,SAChBC,EAAQD,EAAS,IAAIF,CAAK,GAAK,EACrC,OAAAE,EAAS,IAAIF,EAAOG,EAAQ,CAAC,EACtBA,IAAU,EAAIH,EAAQ,GAAGA,KAASG,GAC7C,CACJ,EAEA,SAASF,GAAUF,EAAe,CAC9B,IAAIC,EAAQD,EAAM,QAAQ,kBAAmB,GAAG,EAChD,OAAAC,EAAQA,EAAM,QAAQ,UAAW,EAAE,EAC/B,MAAM,KAAKA,CAAK,IAChBA,EAAQ,IAAMA,GAEXA,GAAS,KACpB,CDhBA,IAAMI,GAAiB,EAAAC,QAAS,UAAU;AAAA;AAAA,CAEzC,EAEKC,GAAa,EAAAD,QAAS,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAOtC,EAEKE,GAAiB,EAAAF,QAAS,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAO1C,EAEKG,GAAmB,EAAAH,QAAS,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA,CAK5C,EAEKI,GAAmB,EAAAJ,QAAS,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CA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EAAEI,CACN,CACA,GAAIA,IAAoB,EACpB,MAAM,IAAI,MACN,gFACJ,EAEJ,OAAOD,CACX,CAEA,IAAMI,GAAa,CAAC,MAAO,OAAQ,MAAO,MAAM,EAEhD,SAASN,GAA2BF,EAAgB,CAChD,QAAWS,KAAOD,GAAY,CAC1B,IAAME,EAAYV,EAASS,EAC3B,MAAI,cAAWC,CAAS,EACpB,OAAOA,CAEf,CAEA,IAAMC,EAAaH,GAAW,KAAK,IAAI,EACvC,MAAM,IAAI,MACN,mDAAmDR,gCAAqCW,8EAC5F,CACJ,CdzHO,SAASC,GAAQC,EAA0C,CAC9D,MAAO,CAACC,GAAUD,CAAO,EAAGE,GAAc,CAAC,CAC/C",
6
+ "names": ["src_exports", "__export", "pioneer", "__toCommonJS", "import_node_fs", "import_node_path", "import_vite", "import_debug", "createDebugger", "namespace", "logger", "args", "import_generator", "import_template", "nodes", "IdGenerator", "input", "clean", "cleanName", "existing", "count", "SERVICE_IMPORT", "template", "PKG_OBJECT", "SERVICE_OBJECT", "INTERFACE_OBJECT", "REFERENCE_OBJECT", "UI_OBJECT", "PROPERTY_OBJECT", "generatePackagesMetadata", "packages", "idGenerator", "IdGenerator", "packagesMetadata", "imports", "pkg", "skipPackage", "packageMetadata", "generatePackageMetadata", "variableName", "className", "entryPoint", "id", "renderedImporter", "program", "generate", "options", "servicesObject", "service", "importName", "serviceObject", "p", "undefinedNode", "referenceName", "referenceConfig", "referenceObject", "uiObject", "r", "propertiesObject", "prop", "jsonToExpression", "config", "json", "item", "name", "value", "import_promises", "import_path", "import_vite", "ReportableError", "fs", "import_node_path", "fileExists", "file", "isInDirectory", "candidate", "directory", "rel", "import_node_url", "import_zod", "import_zod_validation_error", "LITERAL_SCHEMA", "JSON_SCHEMA", "PROPERTY_META_SCHEMA", "REFERENCE_CONFIG_SCHEMA", "PROVIDES_CONFIG_SCHEMA", "UI_CONFIG_SCHEMA", "SERVICE_CONFIG_SCHEMA", "BUILD_CONFIG_SCHEMA", "verifyBuildConfigSchema", "value", "result", "BUILD_CONFIG_NAME", "requestId", "loadBuildConfig", "path", "importedModule", "config", "parseBuildConfig", "object", "rawConfig", "verifyBuildConfigSchema", "normalizeConfig", "BUILD_CONFIG_RE", "isBuildConfig", "file", "serviceName", "serviceConfig", "normalizeServiceConfig", "normalizeUiConfig", "normalizeProperties", "name", "normalizeProvidesConfig", "normalizeReferencesConfig", "providesConfig", "referenceName", "referenceConfig", "normalizeReferenceConfig", "_a", "properties", "propertiesMeta", "result", "defaultValue", "required", "isDebug", "debug", "createDebugger", "MetadataRepository", "sourceRoot", "path", "isPackageJson", "isBuildConfig", "ctx", "appDirectory", "appPackageMetadata", "ReportableError", "packageMetadataByName", "visitDependencies", "dependencies", "importedFrom", "jobs", "packageName", "packageMetadata", "loc", "formatPackageLocation", "packageDir", "isLocalPackage", "cacheEntry", "propagateWatchFiles", "job", "entry", "watchFiles", "trackingCtx", "id", "parsePackageMetadata", "metadata", "packageCacheKey", "name", "key", "existingMetadata", "unresolvedPackageJson", "packageJsonLocation", "file", "_a", "packageJsonPath", "parsePackageJson", "buildConfigPath", "BUILD_CONFIG_NAME", "buildConfig", "fileExists", "loadBuildConfig", "e", "msg", "entryPoint", "cssFile", "resolveLocalFile", "packageJsonContent", "dependencyNames", "localModuleId", "result", "NODE_MODULES_RE", "sourceDir", "isInDirectory", "PACKAGE_JSON_RE", "generateCombinedCss", "packages", "cssImport", "file", "pkg", "import_node_path", "APP_META_RE", "APP_PACKAGES_RE", "APP_CSS_RE", "APP_HOOKS_RE", "SOURCE_FILE_RE", "APP_META_QUERY", "APP_PACKAGES_QUERY", "APP_CSS_QUERY", "PACKAGE_HOOKS", "parseVirtualAppModuleId", "moduleId", "getSourceFile", "type", "importer", "_a", "sourceFile", "generateAppMetadata", "importer", "metadataModuleId", "packagesModule", "APP_PACKAGES_QUERY", "cssModule", "APP_CSS_QUERY", "import_promises", "generateReactHooks", "packageName", "runtimeModuleId", "isDebug", "debug", "createDebugger", "codegenPlugin", "manualDeps", "config", "metadata", "devServer", "reactIntegrationId", "metadataId", "resolve", "rawModuleId", "resolvedResult", "resolvedConfig", "MetadataRepository", "server", "_", "path", "moduleIds", "moduleId", "mod", "err", "importer", "ReportableError", "APP_META_QUERY", "packageJsonPath", "findPackageJson", "PACKAGE_HOOKS", "e", "reportError", "_a", "virtualModule", "parseVirtualAppModuleId", "directory", "packageName", "getPackageName", "generatedSourceCode", "generateReactHooks", "type", "generateAppMetadata", "pkgJsonPath", "context", "buildMetadataContext", "appDir", "appMetadata", "generatePackagesMetadata", "generateCombinedCss", "ctx", "id", "addManualDep", "error", "message", "file", "normalizedPath", "startDir", "rootDir", "dir", "candidate", "parent", "name", "content", "import_node_fs", "import_node_path", "import_node_process", "mpaPlugin", "options", "rootSite", "apps", "sites", "resolvedConfig", "config", "sourceRoot", "gatherEntryPoints", "chunk", "appName", "prefix", "path", "findMatchingEntryPointFile", "siteName", "entryPoints", "entryPointCount", "name", "existingPath", "EXTENSIONS", "ext", "candidate", "extensions", "pioneer", "options", "mpaPlugin", "codegenPlugin"]
7
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@open-pioneer/vite-plugin-pioneer",
3
+ "version": "0.1.0",
4
+ "main": "dist/index.js",
5
+ "types": "types.d.ts",
6
+ "type": "commonjs",
7
+ "license": "Apache-2.0",
8
+ "files": [
9
+ "dist/**/*.js",
10
+ "dist/**/*.js.map",
11
+ "client.d.ts",
12
+ "types.d.ts",
13
+ "CHANGELOG.md",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "peerDependencies": {
18
+ "vite": "^4.0.0",
19
+ "@open-pioneer/runtime": "*"
20
+ },
21
+ "dependencies": {
22
+ "@babel/generator": "^7.20.14",
23
+ "@babel/template": "^7.20.7",
24
+ "@babel/types": "^7.20.7",
25
+ "@rollup/pluginutils": "^5.0.2",
26
+ "debug": "^4.3.4",
27
+ "zod": "^3.20.2",
28
+ "zod-validation-error": "^0.3.1"
29
+ },
30
+ "devDependencies": {
31
+ "@types/babel__generator": "^7.6.4",
32
+ "@types/babel__template": "^7.4.1",
33
+ "@types/debug": "^4.1.7",
34
+ "esbuild": "^0.17.5",
35
+ "npm-run-all": "^4.1.5",
36
+ "rimraf": "^4.1.2",
37
+ "rollup": "^3.13.0",
38
+ "vite": "^4.1.1",
39
+ "@open-pioneer/build-support": "^0.1.0",
40
+ "@open-pioneer/vite-plugin-pioneer": "^0.1.0"
41
+ },
42
+ "scripts": {
43
+ "clean": "rimraf dist temp",
44
+ "build": "node esbuild.config.js build",
45
+ "build-dev": "node esbuild.config.js buildDev",
46
+ "dev": "node esbuild.config.js watch",
47
+ "test": "pnpm run build-dev && rimraf temp && mocha dist/all.test.js",
48
+ "test-debug": "pnpm run build-dev && rimraf temp && mocha --node-option inspect-brk dist/all.test.js"
49
+ }
50
+ }
package/types.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ // SPDX-FileCopyrightText: con terra GmbH and contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ export interface PioneerPluginOptions {
4
+ /**
5
+ * Whether to include the root `index.html` site (by default at `src/index.html`) in the build.
6
+ *
7
+ * The file is always available when using the development server, but may be excluded when
8
+ * when deploying the project as it often contains content for testing.
9
+ *
10
+ * @default false
11
+ */
12
+ rootSite?: boolean;
13
+
14
+ /**
15
+ * List of sites to include in the build.
16
+ *
17
+ * Sites are located at `src/sites/<SITE_NAME>/index.html` by default.
18
+ *
19
+ * @default []
20
+ */
21
+ sites?: string[] | undefined | false;
22
+
23
+ /**
24
+ * List of apps to include in the build.
25
+ * Apps typically register a custom web component.
26
+ *
27
+ * Apps are located at `src/apps/<APP_NAME>/app.<EXT>` by default.
28
+ * When an app is included in the build, the `dist` directory will
29
+ * contain a `app.js` that can be directly imported from the browser.
30
+ *
31
+ * Multiple extensions are supported for the app's main entry point: .ts, .tsx, .js and .jsx.
32
+ *
33
+ * @default []
34
+ */
35
+ apps?: string[] | undefined | false;
36
+ }
37
+
38
+ declare function pioneer(options?: PioneerPluginOptions): Plugin[];