@open-pioneer/vite-plugin-pioneer 0.5.3 → 0.6.1

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/dist/index.js CHANGED
@@ -1,46 +1,966 @@
1
- "use strict";var $e=Object.create;var j=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty;var Le=(e,t)=>{for(var n in t)j(e,n,{get:t[n],enumerable:!0})},Z=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fe(t))!Oe.call(e,i)&&i!==n&&j(e,i,{get:()=>t[i],enumerable:!(r=Ne(t,i))||r.enumerable});return e};var w=(e,t,n)=>(n=e!=null?$e(be(e)):{},Z(t||!e||!e.__esModule?j(n,"default",{value:e,enumerable:!0}):n,e)),je=e=>Z(j({},"__esModule",{value:!0}),e);var bt={};Le(bt,{pioneer:()=>Ft});module.exports=je(bt);var Re=require("node:fs"),A=require("node:path"),_=require("vite");var X=require("debug");function V(e){let t=(0,X.debug)(e);return function(...r){t(...r)}}var te=w(require("@babel/generator")),v=w(require("@babel/template")),c=w(require("@babel/types"));var u=class extends Error{};var U=class{existing=new Map;generate(t){let n=Ve(t),r=this.existing,i=r.get(n)??0;return r.set(n,i+1),i===0?n:`${n}_${i}`}};function Ve(e){let t=e.replace(/[^A-Za-z0-9_]+/g,"_");return t=t.replace(/[\d_]+$/,""),/^\d/.test(t)&&(t="_"+t),t||"var"}var Ue=v.default.statement(`
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ pioneer: () => pioneer
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+
37
+ // src/codegenPlugin.ts
38
+ var import_node_fs = require("node:fs");
39
+ var import_node_path3 = require("node:path");
40
+ var import_vite3 = require("vite");
41
+
42
+ // src/utils/debug.ts
43
+ var import_debug = require("debug");
44
+ function createDebugger(namespace) {
45
+ const logger = (0, import_debug.debug)(namespace);
46
+ return function debugFunction(...args) {
47
+ logger(...args);
48
+ };
49
+ }
50
+
51
+ // src/codegen/generatePackagesMetadata.ts
52
+ var import_generator = __toESM(require("@babel/generator"));
53
+ var import_template = __toESM(require("@babel/template"));
54
+ var nodes = __toESM(require("@babel/types"));
55
+
56
+ // src/ReportableError.ts
57
+ var ReportableError = class extends Error {
58
+ };
59
+
60
+ // src/codegen/IdGenerator.ts
61
+ var IdGenerator = class {
62
+ existing = /* @__PURE__ */ new Map();
63
+ /**
64
+ * Returns a unique identifier (in the context of this instance) that resembles the input value.
65
+ */
66
+ generate(input) {
67
+ const clean = cleanName(input);
68
+ const existing = this.existing;
69
+ const count = existing.get(clean) ?? 0;
70
+ existing.set(clean, count + 1);
71
+ return count === 0 ? clean : `${clean}_${count}`;
72
+ }
73
+ };
74
+ function cleanName(input) {
75
+ let clean = input.replace(/[^A-Za-z0-9_]+/g, "_");
76
+ clean = clean.replace(/[\d_]+$/, "");
77
+ if (/^\d/.test(clean)) {
78
+ clean = "_" + clean;
79
+ }
80
+ return clean || "var";
81
+ }
82
+
83
+ // src/codegen/generatePackagesMetadata.ts
84
+ var SERVICE_IMPORT = import_template.default.statement(`
2
85
  import { %%SERVICE_NAME%% as %%IMPORT_NAME%% } from %%IMPORT_SOURCE%%;
3
- `),ze=v.default.expression(`
86
+ `);
87
+ var PKG_OBJECT = import_template.default.expression(`
4
88
  {
5
89
  name: %%PACKAGE_NAME%%,
6
90
  services: %%PACKAGE_SERVICES%%,
7
91
  ui: %%PACKAGE_UI%%,
8
92
  properties: %%PROPERTIES%%
9
93
  }
10
- `),De=v.default.expression(`
94
+ `);
95
+ var SERVICE_OBJECT = import_template.default.expression(`
11
96
  {
12
97
  name: %%SERVICE_NAME%%,
13
98
  clazz: %%SERVICE_IMPORT%%,
14
99
  provides: %%SERVICE_INTERFACES%%,
15
100
  references: %%SERVICE_REFERENCES%%
16
101
  }
17
- `),Te=v.default.expression(`
102
+ `);
103
+ var INTERFACE_OBJECT = import_template.default.expression(`
18
104
  {
19
105
  name: %%INTERFACE_NAME%%,
20
106
  qualifier: %%QUALIFIER%%
21
107
  }
22
- `),Je=v.default.expression(`
108
+ `);
109
+ var REFERENCE_OBJECT = import_template.default.expression(`
23
110
  {
24
111
  name: %%INTERFACE_NAME%%,
25
112
  qualifier: %%QUALIFIER%%,
26
113
  all: %%ALL%%
27
114
  }
28
- `),Ge=v.default.expression(`
115
+ `);
116
+ var UI_OBJECT = import_template.default.expression(`
29
117
  {
30
118
  references: %%UI_REFERENCES%%
31
119
  }
32
- `),Ke=v.default.expression(`
120
+ `);
121
+ var PROPERTY_OBJECT = import_template.default.expression(`
33
122
  {
34
123
  value: %%VALUE%%,
35
124
  required: %%REQUIRED%%
36
125
  }
37
- `);function ne(e){let t=new U,n=c.objectExpression([]),r=[];for(let o of e){let a=Be(o,{importServiceClass(s,p,d){let l=t.generate(s),g=Ue({SERVICE_NAME:c.identifier(p),IMPORT_NAME:c.identifier(l),IMPORT_SOURCE:c.stringLiteral(d)});return r.push(g),l}});n.properties.push(c.objectProperty(c.stringLiteral(o.name),a))}let i=c.program([...r,c.exportDefaultDeclaration(n)]);return(0,te.default)(i).code}function Be(e,t){let n=c.objectExpression([]);for(let a of e.config.services){if(!e.servicesModulePath)throw new u(`Package '${e.name}' must have a valid services module (typically 'services.ts' or 'services.js').
38
- The entry point can be configured by setting the 'servicesModule' property in the build.config.mjs.`);let s=t.importServiceClass(e.name+"_"+a.name,a.name,e.servicesModulePath),p=De({SERVICE_NAME:c.stringLiteral(a.name),SERVICE_IMPORT:c.identifier(s),SERVICE_INTERFACES:c.arrayExpression(a.provides.map(d=>Te({INTERFACE_NAME:c.stringLiteral(d.name),QUALIFIER:d.qualifier==null?re():c.stringLiteral(d.qualifier)}))),SERVICE_REFERENCES:c.objectExpression(Object.entries(a.references).map(([d,l])=>c.objectProperty(c.stringLiteral(d),ee(l))))});n.properties.push(c.objectProperty(c.stringLiteral(a.name),p))}let r=Ge({UI_REFERENCES:c.arrayExpression(e.config.ui.references.map(a=>ee(a)))}),i=c.objectExpression(e.config.properties.map(a=>c.objectProperty(c.stringLiteral(a.name),Ke({VALUE:K(a.defaultValue),REQUIRED:c.booleanLiteral(a.required)}))));return ze({PACKAGE_NAME:c.stringLiteral(e.name),PACKAGE_SERVICES:n,PACKAGE_UI:r,PROPERTIES:i})}function K(e){if(e==null)return c.nullLiteral();if(typeof e=="string")return c.stringLiteral(e);if(typeof e=="number")return c.numericLiteral(e);if(typeof e=="boolean")return c.booleanLiteral(e);if(Array.isArray(e))return c.arrayExpression(e.map(t=>K(t)));if(typeof e=="object")return c.objectExpression(Object.entries(e).map(([t,n])=>c.objectProperty(c.stringLiteral(t),K(n))));throw new Error(`Unexpected value while serializing JSON: ${e}.`)}function ee(e){return Je({INTERFACE_NAME:c.stringLiteral(e.name),QUALIFIER:e.qualifier?c.stringLiteral(e.qualifier):re(),ALL:c.booleanLiteral(e.all??!1)})}function re(){return c.unaryExpression("void",c.numericLiteral(0))}var F=require("fs/promises"),I=require("path"),R=require("vite");var z=w(require("node:fs")),D=require("node:path");function T(e){return z.promises.access(e,z.constants.F_OK).then(()=>!0).catch(()=>!1)}function ae(e,t){let n=(0,D.relative)(t,e);return!!(n&&!n.startsWith("..")&&!(0,D.isAbsolute)(n))}var $=class{values=new Map;jobs=new Map;provider;constructor(t){this.provider=t}invalidate(t){var i,o;let n=this.provider.getId(t),r=this.values.get(n);this.values.delete(n),this.jobs.delete(n),r&&((o=(i=this.provider).onInvalidate)==null||o.call(i,t,r))}async get(t,...n){var l;let r=this.provider,i=r.getId(t),o=this.values,a=o.get(i);if(a)return(l=r.onCachedReturn)==null||l.call(r,t,a),Promise.resolve(a);let s=this.jobs,p=s.get(i);if(p)return p;let d=r.getValue(t,...n);s.set(i,d);try{let g=await d;return s.get(i)===d&&o.set(i,g),g}finally{s.get(i)===d&&s.delete(i)}}};var N=require("@open-pioneer/build-common"),ie=require("node:path");async function oe(e){let t=await(0,N.loadBuildConfig)(e);return We(t)}function se(e){return(0,ie.basename)(e)===N.BUILD_CONFIG_NAME}function We(e){return{styles:e.styles,i18n:e.i18n,services:Object.entries(e.services??{}).map(([t,n])=>qe(t,n)),servicesModule:e.servicesModule,ui:He(e.ui),properties:Ze(e.properties,e.propertiesMeta)}}function qe(e,t){return{name:e,provides:Qe(t.provides),references:Ye(t.references)}}function Qe(e){return e?typeof e=="string"?[{name:e}]:e.map(t=>typeof t=="string"?{name:t}:t):[]}function Ye(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ce(n)])):{}}function ce(e){return typeof e=="string"?{name:e}:e}function He(e){var t;return{references:((t=e==null?void 0:e.references)==null?void 0:t.map(ce))??[]}}function Ze(e,t){var r;let n=[];for(let[i,o]of Object.entries(e??{})){let a=((r=t==null?void 0:t[i])==null?void 0:r.required)??!1;n.push({name:i,defaultValue:o,required:a})}return n}var de=require("fs/promises"),pe=require("js-yaml"),x=require("zod"),le=require("zod-validation-error");var B=x.z.lazy(()=>x.z.record(x.z.union([x.z.string(),B])).nullish()),Xe=x.z.strictObject({messages:B.nullish().optional(),overrides:x.z.record(B).nullish().optional()}).nullish();async function ge(e){let t;try{t=await(0,de.readFile)(e,"utf-8")}catch(n){throw new u(`Failed to read ${e}: ${n}`)}try{return et(t)}catch(n){throw new u(`Failed to parse ${e}: ${n}`)}}function et(e){let t=(0,pe.load)(e);return tt(t)}function tt(e){let t=Xe.safeParse(e);if(!t.success)throw(0,le.fromZodError)(t.error);let n=t.data;return{messages:ue((n==null?void 0:n.messages)??void 0),overrides:nt((n==null?void 0:n.overrides)??void 0)}}function ue(e){let t=new Map,n=[],r=o=>{for(let[a,s]of Object.entries(o))typeof s=="string"?i(a,s):s&&(n.push(a),r(s),n.pop())},i=(o,a)=>{let s=[...n,o].join(".");if(t.has(s))throw new Error(`Message '${s}' was already defined.`);t.set(s,a)};return e&&r(e),t}function nt(e){let t=new Map;if(e)for(let[n,r]of Object.entries(e)){let i=ue(r??void 0);t.set(n,i)}return t}var W=require("@open-pioneer/build-common"),y=!!process.env.DEBUG,E=V("open-pioneer:metadata"),J=class{sourceRoot;packageMetadataCache;i18nCache;constructor(t){this.sourceRoot=t,this.packageMetadataCache=this.createPackageMetadataCache(),this.i18nCache=this.createI18nCache()}reset(){this.packageMetadataCache=this.createPackageMetadataCache(),this.i18nCache=this.createI18nCache()}onFileChanged(t){(dt(t)||se(t))&&this.packageMetadataCache.invalidate((0,I.dirname)(t)),this.i18nCache.invalidate(t)}async getAppMetadata(t,n){y&&E(`Request for app metadata of ${n}`);let r=await this.getPackageMetadata(t,{type:"absolute",directory:n});if(!r)throw new u(`Failed to parse app metadata in ${n}. Ensure that the app is a valid local package.`);let i=Array.from(r.i18nPaths.keys()),o=new Map;o.set(r.name,r);let a=async(p,d)=>{let l=p.map(async g=>{let f=await this.getPackageMetadata(t,{type:"unresolved",packageName:g,importedFrom:d});f&&(o.has(f.name)||o.set(f.name,f),await a(f.dependencies,f.packageJsonPath))});return await Promise.all(l)};return await a(r.dependencies,r.packageJsonPath),{name:r.name,directory:r.directory,locales:i,packageJsonPath:r.packageJsonPath,packages:Array.from(o.values())}}async getPackageMetadata(t,n){y&&E(`Request for package metadata of ${it(n)}`);let r=await this.resolvePackageLocation(t,n);if(!st(r,this.sourceRoot)){y&&E(`Skipping non-local package '${r}'.`);return}let i=await this.packageMetadataCache.get(r,t);fe(i.watchFiles,t);for(let o of i.warnings)t.warn(o);return i.metadata}async getI18nFile(t,n){let{i18n:r,watchFiles:i}=await this.i18nCache.get(n,t);return fe(i,t),r}async resolvePackageLocation(t,n){if(n.type==="absolute")return await(0,F.realpath)(n.directory);let r=`${n.packageName}/package.json`,i=await t.resolve(r,(0,R.normalizePath)(n.importedFrom),{skipSelf:!0});if(!i||i.external)throw new u(`Failed to find '${r}' (from '${n.importedFrom}'), is the dependency installed correctly?`);let o=await(0,F.realpath)((0,I.dirname)(i.id));return y&&E(`Found package '${n.packageName}' at ${o}`),o}createI18nCache(){return new $({getId(t){return(0,R.normalizePath)(t)},async getValue(t,n){return y&&E(`Loading i18n file ${t}`),n.addWatchFile(t),{i18n:await ge(t),watchFiles:new Set([t])}},onInvalidate(t){y&&E(`Removed cache entry for i18n file ${t}`)},onCachedReturn(t){y&&E(`Returning cached entry for i18n file ${t}`)}})}createPackageMetadataCache(){let t={_byName:new Map,getId(n){return(0,R.normalizePath)(n)},async getValue(n,r){y&&E(`Loading metadata for package at ${n}`);let i=new Set,o=[],a={resolve:r.resolve,addWatchFile(d){r.addWatchFile(d),i.add(d)},warn(d){o.push(typeof d=="string"?{message:d}:d)}},s=await rt(a,n);y&&E(`Metadata for '${s.name}': %O`,s);let p=this._byName.get(s.name);if(p&&(0,R.normalizePath)(p.directory)!==(0,R.normalizePath)(s.directory))throw new u(`Found package '${s.name}' at two different locations ${p.directory} and ${s.directory}`);return this._byName.set(s.name,s),{metadata:s,watchFiles:i,warnings:o}},onInvalidate(n,r){y&&E(`Removed cache entry for '${r.metadata.name}'`),this._byName.delete(r.metadata.name)},onCachedReturn(n,r){y&&E(`Returning cached metadata for '${r.metadata.name}'`)}};return new $(t)}};function fe(e,t){for(let n of e)t.addWatchFile(n)}async function rt(e,t){y&&E(`Visiting package directory ${t}.`);let n=(0,I.join)(t,"package.json");e.addWatchFile(n);let{name:r,dependencies:i}=await at(e,n),o=(0,I.join)(t,W.BUILD_CONFIG_NAME),a;if(e.addWatchFile((0,R.normalizePath)(o)),await T(o))try{a=await oe(o)}catch(l){let g=l.message||"Unknown error";throw new u(`Failed to load build config ${o}: ${g}`)}else throw new u(`Expected a ${W.BUILD_CONFIG_NAME} in ${t}`);let s;if(a.services.length)try{s=await me(e,t,a.servicesModule??"./services")}catch(l){e.warn(`Failed to resolve entry point for package ${t}: ${l}`)}let p;if(a.styles){try{p=await me(e,t,a.styles)}catch(l){throw new u(`Failed to resolve css file for package ${t}: ${l}`)}if(!p)throw new u(`Failed to find css file '${a.styles}' in ${t}`)}let d=new Map;if(a.i18n)for(let l of a.i18n){if(d.has(l))throw new u(`Locale '${l}' was defined twice in ${o}`);let g=(0,I.join)(t,"i18n",`${l}.yaml`);if(e.addWatchFile(g),!await T(g))throw new u(`i18n file '${g}' does not exist.`);d.set(l,(0,R.normalizePath)(g))}return{name:r,directory:t,packageJsonPath:n,servicesModulePath:s,cssFilePath:p,i18nPaths:d,dependencies:i,config:a}}async function at(e,t){if(!await T(t))throw new u(`Expected a 'package.json' file at ${t}`);let n;try{n=JSON.parse(await(0,F.readFile)(t,"utf-8"))}catch(a){throw new u(`Failed to read ${t}: ${a}`)}let r=n.name;if(typeof r!="string")throw new u(`Expected 'name' to be a string in ${t}`);let i=n.dependencies??{};if(typeof i!="object")throw new u(`Expected a valid 'dependencies' object in ${t}`);let o=Object.keys(i);return{name:r,dependencies:o}}async function me(e,t,n){let r=await e.resolve(`./${n}`,`${t}/package.json`,{skipSelf:!0});return r==null?void 0:r.id}function it(e){switch(e.type){case"absolute":return`${e.directory}`;case"unresolved":return`'${e.packageName}' required by ${e.importedFrom}`}}var ot=/[\\/]node_modules[\\/]/;function st(e,t){return ae(e,t)&&!ot.test(e)}var ct=/[\\/]package\.json($|\?)/;function dt(e){return ct.test(e)}function he(e){let t=n=>`@import ${JSON.stringify(n)};`;return e.filter(n=>!!n.cssFilePath).map(n=>t(n.cssFilePath)).join(`
39
- `)}var b=require("node:path/posix"),ye=require("vite"),S="@@open-pioneer-app",pt="open-pioneer-app",lt=/[?&]open-pioneer-app(?:$|&)/,gt="open-pioneer-packages",ut=/[?&]open-pioneer-packages(?:$|&)/,ft="open-pioneer-styles",mt=/[?&]open-pioneer-styles(?:$|&)/,ht="open-pioneer-i18n-index",yt=/[?&]open-pioneer-i18n-index(?:$|&)/,Et="open-pioneer-i18n",Pt=/[?&]open-pioneer-i18n(?:$|&)/,Mt=/[?&]locale=(?<locale>.*?)(?:$|&)/,Ee="@@open-pioneer-react-hooks",Ct=/^(.*?)(?:\?|$)/;function q(e){let t=(0,ye.normalizePath)(e);if(!t||t.includes("\\0"))return;let n=vt(t);if(!n)return;let r=(0,b.basename)(n);if(r===Ee)return{type:"package-hooks",packageDirectory:(0,b.dirname)(n)};if(r===S)return kt(n,t)}function kt(e,t){var r,i;let n=(0,b.dirname)(e);if(t.match(lt))return{type:"app-meta",packageDirectory:n};if(t.match(ut))return{type:"app-packages",packageDirectory:n};if(t.match(mt))return{type:"app-css",packageDirectory:n};if(t.match(yt))return{type:"app-i18n-index",packageDirectory:n};if(t.match(Pt)){let o="app-i18n",a=(i=(r=t.match(Mt))==null?void 0:r.groups)==null?void 0:i.locale;if(!a)throw new Error("Missing locale name in i18n module request");return{type:o,packageDirectory:n,locale:a}}throw new Error(`Unexpected module id: ${t}`)}function M(e){switch(e.type){case"package-hooks":return`${e.packageDirectory}/${Ee}`;case"app-meta":return`${e.packageDirectory}/${S}?${pt}`;case"app-packages":return`${e.packageDirectory}/${S}?${gt}`;case"app-css":return`${e.packageDirectory}/${S}?${ft}`;case"app-i18n-index":return`${e.packageDirectory}/${S}?${ht}`;case"app-i18n":return`${e.packageDirectory}/${S}?${Et}&locale=${e.locale}`}}function vt(e){var n;let t=(n=e.match(Ct))==null?void 0:n[1];if(!(!t||e[0]=="\0"))return t}function Pe(e,t){let n=M({type:"app-packages",packageDirectory:e}),r=M({type:"app-css",packageDirectory:e})+"&inline&lang.scss",i=M({type:"app-i18n-index",packageDirectory:e});return`
40
- import { createBox } from ${JSON.stringify(t)};
41
- import packages from ${JSON.stringify(n)};
42
- import stylesString from ${JSON.stringify(r)};
43
- import { locales, loadMessages } from ${JSON.stringify(i)};
126
+ `);
127
+ function generatePackagesMetadata({ appName, packages }) {
128
+ const idGenerator = new IdGenerator();
129
+ const packagesMetadata = nodes.objectExpression([]);
130
+ const imports = [];
131
+ let overrides;
132
+ for (const pkg of packages) {
133
+ if (pkg.name === appName) {
134
+ overrides = pkg.config.overrides;
135
+ } else if (pkg.config.overrides.size > 0) {
136
+ throw new ReportableError(
137
+ `Unexpected 'overrides' in package '${pkg.name}'. Overrides are only supported in the app.`
138
+ );
139
+ }
140
+ }
141
+ for (const pkg of packages) {
142
+ const packageOverrides = overrides == null ? void 0 : overrides.get(pkg.name);
143
+ const packageMetadata = generatePackageMetadata(pkg, {
144
+ enableService(serviceName) {
145
+ var _a, _b;
146
+ return ((_b = (_a = packageOverrides == null ? void 0 : packageOverrides.services) == null ? void 0 : _a.get(serviceName)) == null ? void 0 : _b.enabled) ?? true;
147
+ },
148
+ importServiceClass(variableName, className, moduleId) {
149
+ const id = idGenerator.generate(variableName);
150
+ const renderedImporter = SERVICE_IMPORT({
151
+ SERVICE_NAME: nodes.identifier(className),
152
+ IMPORT_NAME: nodes.identifier(id),
153
+ IMPORT_SOURCE: nodes.stringLiteral(moduleId)
154
+ });
155
+ imports.push(renderedImporter);
156
+ return id;
157
+ }
158
+ });
159
+ packagesMetadata.properties.push(
160
+ nodes.objectProperty(nodes.stringLiteral(pkg.name), packageMetadata)
161
+ );
162
+ }
163
+ const program2 = nodes.program([...imports, nodes.exportDefaultDeclaration(packagesMetadata)]);
164
+ return (0, import_generator.default)(program2).code;
165
+ }
166
+ function generatePackageMetadata(pkg, options) {
167
+ const servicesObject = nodes.objectExpression([]);
168
+ for (const service of pkg.config.services.values()) {
169
+ if (!options.enableService(service.serviceName)) {
170
+ continue;
171
+ }
172
+ if (!pkg.servicesModulePath) {
173
+ throw new ReportableError(
174
+ `Package '${pkg.name}' must have a valid services module (typically 'services.ts' or 'services.js').
175
+ The entry point can be configured by setting the 'servicesModule' property in the build.config.mjs.`
176
+ );
177
+ }
178
+ const importName = options.importServiceClass(
179
+ pkg.name + "_" + service.serviceName,
180
+ service.serviceName,
181
+ pkg.servicesModulePath
182
+ );
183
+ const serviceObject = SERVICE_OBJECT({
184
+ SERVICE_NAME: nodes.stringLiteral(service.serviceName),
185
+ SERVICE_IMPORT: nodes.identifier(importName),
186
+ SERVICE_INTERFACES: nodes.arrayExpression(
187
+ service.provides.map(
188
+ (p) => INTERFACE_OBJECT({
189
+ INTERFACE_NAME: nodes.stringLiteral(p.interfaceName),
190
+ QUALIFIER: p.qualifier == null ? undefinedNode() : nodes.stringLiteral(p.qualifier)
191
+ })
192
+ )
193
+ ),
194
+ SERVICE_REFERENCES: nodes.objectExpression(
195
+ Array.from(service.references.entries()).map(
196
+ ([referenceName, referenceConfig]) => nodes.objectProperty(
197
+ nodes.stringLiteral(referenceName),
198
+ referenceObject(referenceConfig)
199
+ )
200
+ )
201
+ )
202
+ });
203
+ servicesObject.properties.push(
204
+ nodes.objectProperty(nodes.stringLiteral(service.serviceName), serviceObject)
205
+ );
206
+ }
207
+ const uiObject = UI_OBJECT({
208
+ UI_REFERENCES: nodes.arrayExpression(pkg.config.uiReferences.map((r) => referenceObject(r)))
209
+ });
210
+ const propertiesObject = nodes.objectExpression(
211
+ Array.from(pkg.config.properties.values()).map(
212
+ (prop) => nodes.objectProperty(
213
+ nodes.stringLiteral(prop.propertyName),
214
+ PROPERTY_OBJECT({
215
+ VALUE: jsonToExpression(prop.defaultValue),
216
+ REQUIRED: nodes.booleanLiteral(prop.required)
217
+ })
218
+ )
219
+ )
220
+ );
221
+ const pkgObject = PKG_OBJECT({
222
+ PACKAGE_NAME: nodes.stringLiteral(pkg.name),
223
+ PACKAGE_SERVICES: servicesObject,
224
+ PACKAGE_UI: uiObject,
225
+ PROPERTIES: propertiesObject
226
+ });
227
+ return pkgObject;
228
+ }
229
+ function jsonToExpression(json) {
230
+ if (json == null) {
231
+ return nodes.nullLiteral();
232
+ }
233
+ if (typeof json === "string") {
234
+ return nodes.stringLiteral(json);
235
+ }
236
+ if (typeof json === "number") {
237
+ return nodes.numericLiteral(json);
238
+ }
239
+ if (typeof json === "boolean") {
240
+ return nodes.booleanLiteral(json);
241
+ }
242
+ if (Array.isArray(json)) {
243
+ return nodes.arrayExpression(json.map((item) => jsonToExpression(item)));
244
+ }
245
+ if (typeof json === "object") {
246
+ return nodes.objectExpression(
247
+ Object.entries(json).map(
248
+ ([name, value]) => nodes.objectProperty(nodes.stringLiteral(name), jsonToExpression(value))
249
+ )
250
+ );
251
+ }
252
+ throw new Error(`Unexpected value while serializing JSON: ${json}.`);
253
+ }
254
+ function referenceObject(ref) {
255
+ return REFERENCE_OBJECT({
256
+ INTERFACE_NAME: nodes.stringLiteral(ref.interfaceName),
257
+ QUALIFIER: ref.qualifier ? nodes.stringLiteral(ref.qualifier) : undefinedNode(),
258
+ ALL: nodes.booleanLiteral(ref.type === "all" ? true : false)
259
+ // TODO: Rework internal app format
260
+ });
261
+ }
262
+ function undefinedNode() {
263
+ return nodes.unaryExpression("void", nodes.numericLiteral(0));
264
+ }
265
+
266
+ // src/metadata/MetadataRepository.ts
267
+ var import_promises2 = require("fs/promises");
268
+ var import_path = require("path");
269
+ var import_vite = require("vite");
270
+
271
+ // src/utils/fileUtils.ts
272
+ var fs = __toESM(require("node:fs"));
273
+ var import_node_path = require("node:path");
274
+ function fileExists(file) {
275
+ return fs.promises.access(file, fs.constants.F_OK).then(() => true).catch(() => false);
276
+ }
277
+ function isInDirectory(candidate, directory) {
278
+ const rel = (0, import_node_path.relative)(directory, candidate);
279
+ const isChild = rel && !rel.startsWith("..") && !(0, import_node_path.isAbsolute)(rel);
280
+ return !!isChild;
281
+ }
282
+
283
+ // src/utils/Cache.ts
284
+ var Cache = class {
285
+ values = /* @__PURE__ */ new Map();
286
+ jobs = /* @__PURE__ */ new Map();
287
+ provider;
288
+ constructor(provider) {
289
+ this.provider = provider;
290
+ }
291
+ /**
292
+ * Removes an entry associated with the given key.
293
+ */
294
+ invalidate(key) {
295
+ var _a, _b;
296
+ const id = this.provider.getId(key);
297
+ const oldValue = this.values.get(id);
298
+ this.values.delete(id);
299
+ this.jobs.delete(id);
300
+ if (oldValue) {
301
+ (_b = (_a = this.provider).onInvalidate) == null ? void 0 : _b.call(_a, key, oldValue);
302
+ }
303
+ }
304
+ /**
305
+ * Retrieves the value associated with `key`.
306
+ * A cached result will be used if present, otherwise the
307
+ * cache provider will be called.
308
+ *
309
+ * Note: computations may throw errors.
310
+ * Errors will not be cached.
311
+ *
312
+ * @param key the lookup key
313
+ * @param context an arbitrary set of values that will be forwarded to the provider
314
+ * should be provider be called.
315
+ * @returns the value associated with `key`
316
+ */
317
+ async get(key, ...context) {
318
+ var _a;
319
+ const provider = this.provider;
320
+ const id = provider.getId(key);
321
+ const values = this.values;
322
+ const existingValue = values.get(id);
323
+ if (existingValue) {
324
+ (_a = provider.onCachedReturn) == null ? void 0 : _a.call(provider, key, existingValue);
325
+ return Promise.resolve(existingValue);
326
+ }
327
+ const jobs = this.jobs;
328
+ const existingJob = jobs.get(id);
329
+ if (existingJob) {
330
+ return existingJob;
331
+ }
332
+ const job = provider.getValue(key, ...context);
333
+ jobs.set(id, job);
334
+ try {
335
+ const value = await job;
336
+ if (jobs.get(id) === job) {
337
+ values.set(id, value);
338
+ }
339
+ return value;
340
+ } finally {
341
+ if (jobs.get(id) === job) {
342
+ jobs.delete(id);
343
+ }
344
+ }
345
+ }
346
+ };
347
+
348
+ // src/metadata/parseBuildConfig.ts
349
+ var import_build_common = require("@open-pioneer/build-common");
350
+ var import_node_path2 = require("node:path");
351
+ async function loadBuildConfig(path) {
352
+ const rawConfig = await (0, import_build_common.loadBuildConfig)(path);
353
+ return (0, import_build_common.createPackageConfigFromBuildConfig)(rawConfig);
354
+ }
355
+ function isBuildConfig(file) {
356
+ return (0, import_node_path2.basename)(file) === import_build_common.BUILD_CONFIG_NAME;
357
+ }
358
+
359
+ // src/metadata/parseI18nYaml.ts
360
+ var import_promises = require("fs/promises");
361
+ var import_js_yaml = require("js-yaml");
362
+ var import_zod = require("zod");
363
+ var import_zod_validation_error = require("zod-validation-error");
364
+ var MESSAGES_SCHEMA = import_zod.z.lazy(
365
+ () => import_zod.z.record(import_zod.z.union([import_zod.z.string(), MESSAGES_SCHEMA])).nullish()
366
+ );
367
+ var I18N_SCHEMA = import_zod.z.strictObject({
368
+ messages: MESSAGES_SCHEMA.nullish().optional(),
369
+ overrides: import_zod.z.record(MESSAGES_SCHEMA).nullish().optional()
370
+ }).nullish();
371
+ async function loadI18nFile(path) {
372
+ let content;
373
+ try {
374
+ content = await (0, import_promises.readFile)(path, "utf-8");
375
+ } catch (e) {
376
+ throw new ReportableError(`Failed to read ${path}`, { cause: e });
377
+ }
378
+ try {
379
+ return parseI18nYaml(content);
380
+ } catch (e) {
381
+ throw new ReportableError(`Failed to parse ${path}`, { cause: e });
382
+ }
383
+ }
384
+ function parseI18nYaml(yaml) {
385
+ const data = (0, import_js_yaml.load)(yaml);
386
+ return parseI18nFile(data);
387
+ }
388
+ function parseI18nFile(data) {
389
+ const result = I18N_SCHEMA.safeParse(data);
390
+ if (!result.success) {
391
+ throw (0, import_zod_validation_error.fromZodError)(result.error);
392
+ }
393
+ const rawI18n = result.data;
394
+ return {
395
+ messages: gatherMessages((rawI18n == null ? void 0 : rawI18n.messages) ?? void 0),
396
+ overrides: gatherOverrides((rawI18n == null ? void 0 : rawI18n.overrides) ?? void 0)
397
+ };
398
+ }
399
+ function gatherMessages(data) {
400
+ const messages = /* @__PURE__ */ new Map();
401
+ const prefix = [];
402
+ const visitChildren = (record) => {
403
+ for (const [key, value] of Object.entries(record)) {
404
+ if (typeof value === "string") {
405
+ visitMessage(key, value);
406
+ } else if (value) {
407
+ prefix.push(key);
408
+ visitChildren(value);
409
+ prefix.pop();
410
+ }
411
+ }
412
+ };
413
+ const visitMessage = (key, message) => {
414
+ const id = [...prefix, key].join(".");
415
+ if (messages.has(id)) {
416
+ throw new Error(`Message '${id}' was already defined.`);
417
+ }
418
+ messages.set(id, message);
419
+ };
420
+ if (data) {
421
+ visitChildren(data);
422
+ }
423
+ return messages;
424
+ }
425
+ function gatherOverrides(data) {
426
+ const overrides = /* @__PURE__ */ new Map();
427
+ if (data) {
428
+ for (const [key, value] of Object.entries(data)) {
429
+ const messages = gatherMessages(value ?? void 0);
430
+ overrides.set(key, messages);
431
+ }
432
+ }
433
+ return overrides;
434
+ }
435
+
436
+ // src/metadata/MetadataRepository.ts
437
+ var import_build_common2 = require("@open-pioneer/build-common");
438
+
439
+ // src/utils/package.ts
440
+ var PACKAGE_NAME = "@open-pioneer/vite-plugin-pioneer";
441
+
442
+ // src/metadata/MetadataRepository.ts
443
+ var isDebug = !!process.env.DEBUG;
444
+ var debug2 = createDebugger("open-pioneer:metadata");
445
+ var MetadataRepository = class {
446
+ sourceRoot;
447
+ // Key: package directory on disk, value: existing metadata
448
+ packageMetadataCache;
449
+ // Cache for the contents of i18n files.
450
+ // Key: path on disk.
451
+ i18nCache;
452
+ // Cache for package locations & package.json contents
453
+ packageDataCache = /* @__PURE__ */ new Map();
454
+ /**
455
+ * @param sourceRoot Source folder on disk, needed to detect 'local' packages
456
+ */
457
+ constructor(sourceRoot) {
458
+ this.sourceRoot = sourceRoot;
459
+ this.packageMetadataCache = this.createPackageMetadataCache();
460
+ this.i18nCache = this.createI18nCache();
461
+ }
462
+ reset() {
463
+ this.packageMetadataCache = this.createPackageMetadataCache();
464
+ this.i18nCache = this.createI18nCache();
465
+ this.packageDataCache.clear();
466
+ }
467
+ /**
468
+ * Called by the plugin when a file has been changed.
469
+ * The cached data associated with that file (if any) will be removed.
470
+ */
471
+ onFileChanged(path) {
472
+ if (isPackageJson(path) || isBuildConfig(path)) {
473
+ this.packageMetadataCache.invalidate((0, import_path.dirname)(path));
474
+ }
475
+ this.i18nCache.invalidate(path);
476
+ }
477
+ /**
478
+ * Returns the combined application metadata of the app in `appDirectory`.
479
+ * Starting from the app's package.json, dependencies will be visited recursively.
480
+ *
481
+ * For packages that use our package extensions (services etc.), metadata will be gathered and
482
+ * will be returned here.
483
+ */
484
+ async getAppMetadata(ctx, appDirectory) {
485
+ isDebug && debug2(`Request for app metadata of ${appDirectory}`);
486
+ const appPackageMetadata = await this.getPackageMetadata(ctx, {
487
+ type: "absolute",
488
+ directory: appDirectory
489
+ });
490
+ if (!appPackageMetadata) {
491
+ throw new ReportableError(
492
+ `Failed to parse app metadata in ${appDirectory}. Ensure that the app is a valid local package.`
493
+ );
494
+ }
495
+ const appLocales = Array.from(appPackageMetadata.i18nPaths.keys());
496
+ const packageMetadataByName = /* @__PURE__ */ new Map();
497
+ packageMetadataByName.set(appPackageMetadata.name, appPackageMetadata);
498
+ const visitDependencies = async (dependencies, importedFrom) => {
499
+ const jobs = dependencies.map(async (dependency) => {
500
+ const packageMetadata = await this.getPackageMetadata(ctx, {
501
+ type: "unresolved",
502
+ dependency,
503
+ importedFrom
504
+ });
505
+ if (packageMetadata) {
506
+ if (!packageMetadataByName.has(packageMetadata.name)) {
507
+ packageMetadataByName.set(packageMetadata.name, packageMetadata);
508
+ }
509
+ await visitDependencies(
510
+ packageMetadata.dependencies,
511
+ packageMetadata.packageJsonPath
512
+ );
513
+ }
514
+ });
515
+ return await Promise.all(jobs);
516
+ };
517
+ await visitDependencies(
518
+ appPackageMetadata.dependencies,
519
+ appPackageMetadata.packageJsonPath
520
+ );
521
+ const appMetadata = {
522
+ name: appPackageMetadata.name,
523
+ directory: appPackageMetadata.directory,
524
+ locales: appLocales,
525
+ packageJsonPath: appPackageMetadata.packageJsonPath,
526
+ packages: Array.from(packageMetadataByName.values())
527
+ };
528
+ return appMetadata;
529
+ }
530
+ /**
531
+ * Returns package metadata associated with the given package.
532
+ */
533
+ async getPackageMetadata(ctx, loc) {
534
+ isDebug && debug2(`Request for package metadata of ${formatPackageLocation(loc)}`);
535
+ const packageDir = await this.resolvePackageLocation(loc);
536
+ if (!packageDir) {
537
+ return void 0;
538
+ }
539
+ const entry = await this.packageMetadataCache.get(packageDir, ctx);
540
+ propagateWatchFiles(entry.watchFiles, ctx);
541
+ for (const warning of entry.warnings) {
542
+ ctx.warn(warning);
543
+ }
544
+ if (entry.metadata.type === "plain") {
545
+ isDebug && debug2(`Skipping package '${packageDir}'.`);
546
+ return void 0;
547
+ }
548
+ return entry.metadata;
549
+ }
550
+ /**
551
+ * Returns the parsed contents of the given i18n file.
552
+ */
553
+ async getI18nFile(ctx, path) {
554
+ const { i18n, watchFiles } = await this.i18nCache.get(path, ctx);
555
+ propagateWatchFiles(watchFiles, ctx);
556
+ return i18n;
557
+ }
558
+ async resolvePackageLocation(loc) {
559
+ if (loc.type === "absolute") {
560
+ return await (0, import_promises2.realpath)(loc.directory);
561
+ }
562
+ const { packageName, optional } = loc.dependency;
563
+ const { resolvePackageData } = await import("vite");
564
+ const packageData = await resolvePackageData(
565
+ packageName,
566
+ loc.importedFrom,
567
+ false,
568
+ this.packageDataCache
569
+ );
570
+ if (!packageData) {
571
+ if (optional) {
572
+ isDebug && debug2(`Optional package '${packageName}' was not found.`);
573
+ return void 0;
574
+ }
575
+ throw new ReportableError(
576
+ `Failed to find package '${packageName}' (from '${loc.importedFrom}'), is the dependency installed correctly?`
577
+ );
578
+ }
579
+ const packageDir = await (0, import_promises2.realpath)(packageData.dir);
580
+ isDebug && debug2(`Found package '${packageName}' at ${packageDir}`);
581
+ return packageDir;
582
+ }
583
+ createI18nCache() {
584
+ return new Cache({
585
+ getId(path) {
586
+ return (0, import_vite.normalizePath)(path);
587
+ },
588
+ async getValue(path, ctx) {
589
+ isDebug && debug2(`Loading i18n file ${path}`);
590
+ ctx.addWatchFile(path);
591
+ const entry = {
592
+ i18n: await loadI18nFile(path),
593
+ watchFiles: /* @__PURE__ */ new Set([path])
594
+ };
595
+ return entry;
596
+ },
597
+ onInvalidate(path) {
598
+ isDebug && debug2(`Removed cache entry for i18n file ${path}`);
599
+ },
600
+ onCachedReturn(path) {
601
+ isDebug && debug2(`Returning cached entry for i18n file ${path}`);
602
+ }
603
+ });
604
+ }
605
+ createPackageMetadataCache() {
606
+ const sourceRoot = this.sourceRoot;
607
+ const provider = {
608
+ _byName: /* @__PURE__ */ new Map(),
609
+ getId(directory) {
610
+ return (0, import_vite.normalizePath)(directory);
611
+ },
612
+ async getValue(directory, ctx) {
613
+ isDebug && debug2(`Loading metadata for package at ${directory}`);
614
+ const watchFiles = /* @__PURE__ */ new Set();
615
+ const warnings = [];
616
+ const trackingCtx = {
617
+ resolve: ctx.resolve,
618
+ addWatchFile(id) {
619
+ ctx.addWatchFile(id);
620
+ watchFiles.add(id);
621
+ },
622
+ warn(msg) {
623
+ warnings.push(typeof msg === "string" ? { message: msg } : msg);
624
+ }
625
+ };
626
+ const metadata = await parsePackageMetadata(trackingCtx, directory, sourceRoot);
627
+ isDebug && debug2(`Metadata for '${metadata.name}': %O`, metadata);
628
+ if (metadata.type === "pioneer-package") {
629
+ const existingMetadata = this._byName.get(metadata.name);
630
+ if (existingMetadata && (0, import_vite.normalizePath)(existingMetadata.directory) !== (0, import_vite.normalizePath)(metadata.directory)) {
631
+ throw new ReportableError(
632
+ `Found package '${metadata.name}' at two different locations ${existingMetadata.directory} and ${metadata.directory}`
633
+ );
634
+ }
635
+ this._byName.set(metadata.name, metadata);
636
+ }
637
+ return {
638
+ metadata,
639
+ watchFiles,
640
+ warnings
641
+ };
642
+ },
643
+ onInvalidate(directory, entry) {
644
+ isDebug && debug2(`Removed cache entry for '${entry.metadata.name}'`);
645
+ this._byName.delete(entry.metadata.name);
646
+ },
647
+ onCachedReturn(directory, entry) {
648
+ isDebug && debug2(`Returning cached metadata for '${entry.metadata.name}'`);
649
+ }
650
+ };
651
+ return new Cache(provider);
652
+ }
653
+ };
654
+ function propagateWatchFiles(watchFiles, ctx) {
655
+ for (const file of watchFiles) {
656
+ ctx.addWatchFile(file);
657
+ }
658
+ }
659
+ async function parsePackageMetadata(ctx, packageDir, sourceRoot) {
660
+ const mode = isLocalPackage(packageDir, sourceRoot) ? "local" : "external";
661
+ isDebug && debug2(`Visiting package directory ${packageDir} in mode ${mode}.`);
662
+ const packageJsonPath = (0, import_path.join)(packageDir, "package.json");
663
+ ctx.addWatchFile(packageJsonPath);
664
+ const {
665
+ name: packageName,
666
+ dependencies,
667
+ frameworkMetadata
668
+ } = await parsePackageJson(ctx, packageJsonPath);
669
+ const configResult = await readConfig(
670
+ ctx,
671
+ packageDir,
672
+ mode,
673
+ frameworkMetadata,
674
+ packageName,
675
+ packageJsonPath
676
+ );
677
+ if (!configResult) {
678
+ return {
679
+ type: "plain",
680
+ name: packageName,
681
+ directory: packageDir
682
+ };
683
+ }
684
+ const { config, configPath } = configResult;
685
+ let servicesModule;
686
+ if (config.services.size) {
687
+ try {
688
+ servicesModule = await resolveLocalFile(
689
+ ctx,
690
+ packageDir,
691
+ config.servicesModule ?? "./services"
692
+ );
693
+ } catch (e) {
694
+ ctx.warn({
695
+ message: `Failed to resolve entry point for package ${packageDir}`,
696
+ cause: e
697
+ });
698
+ }
699
+ }
700
+ let cssFile;
701
+ if (config.styles) {
702
+ try {
703
+ cssFile = await resolveLocalFile(ctx, packageDir, config.styles);
704
+ } catch (e) {
705
+ throw new ReportableError(`Failed to resolve css file for package ${packageDir}`, {
706
+ cause: e
707
+ });
708
+ }
709
+ if (!cssFile) {
710
+ throw new ReportableError(
711
+ `Failed to find css file '${config.styles}' in ${packageDir}`
712
+ );
713
+ }
714
+ }
715
+ const i18nPaths = /* @__PURE__ */ new Map();
716
+ for (const locale of config.languages) {
717
+ if (i18nPaths.has(locale)) {
718
+ throw new ReportableError(`Locale '${locale}' was defined twice in ${configPath}`);
719
+ }
720
+ const path = (0, import_path.join)(packageDir, "i18n", `${locale}.yaml`);
721
+ ctx.addWatchFile(path);
722
+ if (!await fileExists(path)) {
723
+ throw new ReportableError(`i18n file '${path}' does not exist.`);
724
+ }
725
+ i18nPaths.set(locale, (0, import_vite.normalizePath)(path));
726
+ }
727
+ return {
728
+ type: "pioneer-package",
729
+ name: packageName,
730
+ directory: packageDir,
731
+ packageJsonPath,
732
+ servicesModulePath: servicesModule,
733
+ cssFilePath: cssFile,
734
+ i18nPaths,
735
+ dependencies,
736
+ config
737
+ };
738
+ }
739
+ async function readConfig(ctx, packageDir, mode, frameworkMetadata, packageName, packageJsonPath) {
740
+ switch (mode) {
741
+ case "local": {
742
+ const buildConfigPath = (0, import_path.join)(packageDir, import_build_common2.BUILD_CONFIG_NAME);
743
+ let buildConfig;
744
+ ctx.addWatchFile((0, import_vite.normalizePath)(buildConfigPath));
745
+ if (await fileExists(buildConfigPath)) {
746
+ try {
747
+ buildConfig = await loadBuildConfig(buildConfigPath);
748
+ } catch (e) {
749
+ throw new ReportableError(`Failed to load build config ${buildConfigPath}`, {
750
+ cause: e
751
+ });
752
+ }
753
+ } else {
754
+ throw new ReportableError(`Expected a ${import_build_common2.BUILD_CONFIG_NAME} in ${packageDir}`);
755
+ }
756
+ return { configPath: buildConfigPath, config: buildConfig };
757
+ }
758
+ case "external": {
759
+ if (!frameworkMetadata) {
760
+ return void 0;
761
+ }
762
+ const metadataResult = import_build_common2.PackageMetadataV1.parsePackageMetadata(frameworkMetadata);
763
+ if (metadataResult.type === "error") {
764
+ if (metadataResult.code === "unsupported-version") {
765
+ throw new ReportableError(
766
+ `Package '${packageName}' in ${packageDir} uses an unsupported metadata version. You will likely have to update ${PACKAGE_NAME}.
767
+
768
+ ` + metadataResult.message,
769
+ { cause: metadataResult.cause }
770
+ );
771
+ }
772
+ throw new ReportableError(
773
+ `Failed to parse metadata of package '${packageName}' in ${packageDir}: ${metadataResult.message}`,
774
+ { cause: metadataResult.cause }
775
+ );
776
+ }
777
+ return {
778
+ configPath: packageJsonPath,
779
+ config: (0, import_build_common2.createPackageConfigFromPackageMetadata)(metadataResult.value)
780
+ };
781
+ }
782
+ }
783
+ }
784
+ async function parsePackageJson(ctx, packageJsonPath) {
785
+ if (!await fileExists(packageJsonPath)) {
786
+ throw new ReportableError(`Expected a 'package.json' file at ${packageJsonPath}`);
787
+ }
788
+ let packageJsonContent;
789
+ try {
790
+ packageJsonContent = JSON.parse(await (0, import_promises2.readFile)(packageJsonPath, "utf-8"));
791
+ } catch (e) {
792
+ throw new ReportableError(`Failed to read ${packageJsonPath}`, { cause: e });
793
+ }
794
+ const packageName = packageJsonContent.name;
795
+ if (typeof packageName !== "string") {
796
+ throw new ReportableError(`Expected 'name' to be a string in ${packageJsonPath}`);
797
+ }
798
+ const dependencies = packageJsonContent.dependencies ?? {};
799
+ if (typeof dependencies !== "object") {
800
+ throw new ReportableError(`Expected a valid 'dependencies' object in ${packageJsonPath}`);
801
+ }
802
+ const peerDependencies = packageJsonContent.peerDependencies ?? {};
803
+ if (typeof peerDependencies !== "object") {
804
+ throw new ReportableError(
805
+ `Expected a valid 'peerDependencies' object in ${packageJsonPath}`
806
+ );
807
+ }
808
+ const optionalDependencies = packageJsonContent.optionalDependencies ?? {};
809
+ if (typeof optionalDependencies !== "object") {
810
+ throw new ReportableError(
811
+ `Expected a valid 'optionalDependencies' object in ${packageJsonPath}`
812
+ );
813
+ }
814
+ const allDependencies = [
815
+ ...Object.keys(dependencies).map((packageName2) => ({ packageName: packageName2, optional: false })),
816
+ ...Object.keys(peerDependencies).map((packageName2) => {
817
+ var _a, _b;
818
+ return {
819
+ packageName: packageName2,
820
+ optional: ((_b = (_a = packageJsonContent == null ? void 0 : packageJsonContent.peerDependenciesMeta) == null ? void 0 : _a[packageName2]) == null ? void 0 : _b.optional) ?? false
821
+ };
822
+ }),
823
+ ...Object.keys(optionalDependencies).map((packageName2) => ({ packageName: packageName2, optional: true }))
824
+ ];
825
+ const frameworkMetadata = packageJsonContent[import_build_common2.PackageMetadataV1.PACKAGE_JSON_KEY] ?? void 0;
826
+ return {
827
+ name: packageName,
828
+ dependencies: allDependencies,
829
+ frameworkMetadata
830
+ };
831
+ }
832
+ async function resolveLocalFile(ctx, packageDir, localModuleId) {
833
+ const result = await ctx.resolve(`./${localModuleId}`, `${packageDir}/package.json`, {
834
+ skipSelf: true
835
+ });
836
+ return result == null ? void 0 : result.id;
837
+ }
838
+ function formatPackageLocation(loc) {
839
+ switch (loc.type) {
840
+ case "absolute":
841
+ return `${loc.directory}`;
842
+ case "unresolved": {
843
+ let name = `'${loc.dependency.packageName}'`;
844
+ if (loc.dependency.optional) {
845
+ name += " (optional)";
846
+ }
847
+ return `${name} required by ${loc.importedFrom}`;
848
+ }
849
+ }
850
+ }
851
+ var NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
852
+ function isLocalPackage(file, sourceDir) {
853
+ return isInDirectory(file, sourceDir) && !NODE_MODULES_RE.test(file);
854
+ }
855
+ var PACKAGE_JSON_RE = /[\\/]package\.json($|\?)/;
856
+ function isPackageJson(file) {
857
+ return PACKAGE_JSON_RE.test(file);
858
+ }
859
+
860
+ // src/codegen/generateCombinedCss.ts
861
+ function generateCombinedCss(packages) {
862
+ const cssImport = (file) => `@import ${JSON.stringify(file)};`;
863
+ return packages.filter((pkg) => !!pkg.cssFilePath).map((pkg) => cssImport(pkg.cssFilePath)).join("\n");
864
+ }
865
+
866
+ // src/codegen/shared.ts
867
+ var import_posix = require("node:path/posix");
868
+ var import_vite2 = require("vite");
869
+ var APP_MODULE = "@@open-pioneer-app";
870
+ var APP_META_QUERY = "open-pioneer-app";
871
+ var APP_META_RE = /[?&]open-pioneer-app(?:$|&)/;
872
+ var APP_PACKAGES_QUERY = "open-pioneer-packages";
873
+ var APP_PACKAGES_RE = /[?&]open-pioneer-packages(?:$|&)/;
874
+ var APP_CSS_QUERY = "open-pioneer-styles";
875
+ var APP_CSS_RE = /[?&]open-pioneer-styles(?:$|&)/;
876
+ var APP_I18N_INDEX_QUERY = "open-pioneer-i18n-index";
877
+ var APP_I18N_INDEX_RE = /[?&]open-pioneer-i18n-index(?:$|&)/;
878
+ var APP_I18N_QUERY = "open-pioneer-i18n";
879
+ var APP_I18N_RE = /[?&]open-pioneer-i18n(?:$|&)/;
880
+ var APP_I18N_LOCALE_RE = /[?&]locale=(?<locale>.*?)(?:$|&)/;
881
+ var PACKAGE_HOOKS_MODULE = "@@open-pioneer-react-hooks";
882
+ var SOURCE_FILE_RE = /^(.*?)(?:\?|$)/;
883
+ function parseVirtualModuleId(inputModuleId) {
884
+ const moduleId = (0, import_vite2.normalizePath)(inputModuleId);
885
+ if (!moduleId || moduleId.includes("\\0")) {
886
+ return void 0;
887
+ }
888
+ const sourceFile = getSourceFile(moduleId);
889
+ if (!sourceFile) {
890
+ return void 0;
891
+ }
892
+ const base = (0, import_posix.basename)(sourceFile);
893
+ if (base === PACKAGE_HOOKS_MODULE) {
894
+ return {
895
+ type: "package-hooks",
896
+ packageDirectory: (0, import_posix.dirname)(sourceFile)
897
+ };
898
+ }
899
+ if (base === APP_MODULE) {
900
+ return parseAppModuleId(sourceFile, moduleId);
901
+ }
902
+ return void 0;
903
+ }
904
+ function parseAppModuleId(sourceFile, moduleId) {
905
+ var _a, _b;
906
+ const packageDirectory = (0, import_posix.dirname)(sourceFile);
907
+ if (moduleId.match(APP_META_RE)) {
908
+ const type = "app-meta";
909
+ return { type, packageDirectory };
910
+ } else if (moduleId.match(APP_PACKAGES_RE)) {
911
+ const type = "app-packages";
912
+ return { type, packageDirectory };
913
+ } else if (moduleId.match(APP_CSS_RE)) {
914
+ const type = "app-css";
915
+ return { type, packageDirectory };
916
+ } else if (moduleId.match(APP_I18N_INDEX_RE)) {
917
+ const type = "app-i18n-index";
918
+ return { type, packageDirectory };
919
+ } else if (moduleId.match(APP_I18N_RE)) {
920
+ const type = "app-i18n";
921
+ const locale = (_b = (_a = moduleId.match(APP_I18N_LOCALE_RE)) == null ? void 0 : _a.groups) == null ? void 0 : _b["locale"];
922
+ if (!locale) {
923
+ throw new Error("Missing locale name in i18n module request");
924
+ }
925
+ return { type, packageDirectory, locale };
926
+ }
927
+ throw new Error(`Unexpected module id: ${moduleId}`);
928
+ }
929
+ function serializeModuleId(mod) {
930
+ switch (mod.type) {
931
+ case "package-hooks":
932
+ return `${mod.packageDirectory}/${PACKAGE_HOOKS_MODULE}`;
933
+ case "app-meta":
934
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_META_QUERY}`;
935
+ case "app-packages":
936
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_PACKAGES_QUERY}`;
937
+ case "app-css":
938
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_CSS_QUERY}`;
939
+ case "app-i18n-index":
940
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_INDEX_QUERY}`;
941
+ case "app-i18n":
942
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_QUERY}&locale=${mod.locale}`;
943
+ }
944
+ }
945
+ function getSourceFile(moduleId) {
946
+ var _a;
947
+ const sourceFile = (_a = moduleId.match(SOURCE_FILE_RE)) == null ? void 0 : _a[1];
948
+ if (!sourceFile || moduleId[0] == "\0") {
949
+ return void 0;
950
+ }
951
+ return sourceFile;
952
+ }
953
+
954
+ // src/codegen/generateAppMetadata.ts
955
+ function generateAppMetadata(packageDirectory, metadataModuleId) {
956
+ const packagesModule = serializeModuleId({ type: "app-packages", packageDirectory });
957
+ const cssModule = serializeModuleId({ type: "app-css", packageDirectory }) + "&inline&lang.scss";
958
+ const i18nModule = serializeModuleId({ type: "app-i18n-index", packageDirectory });
959
+ return `
960
+ import { createBox } from ${JSON.stringify(metadataModuleId)};
961
+ import packages from ${JSON.stringify(packagesModule)};
962
+ import stylesString from ${JSON.stringify(cssModule)};
963
+ import { locales, loadMessages } from ${JSON.stringify(i18nModule)};
44
964
 
45
965
  const styles = createBox(stylesString);
46
966
  if (import.meta.hot) {
@@ -62,25 +982,476 @@ export {
62
982
  locales,
63
983
  loadMessages
64
984
  };
65
- `.trim()}var we=require("node:fs/promises");function Me(e,t){return`
66
- import { useServiceInternal, useServicesInternal, usePropertiesInternal, useIntlInternal } from ${JSON.stringify(t)};
985
+ `.trim();
986
+ }
987
+
988
+ // src/codegenPlugin.ts
989
+ var import_promises3 = require("node:fs/promises");
990
+
991
+ // src/codegen/generateReactHooks.ts
992
+ function generateReactHooks(packageName, runtimeModuleId) {
993
+ return `
994
+ import { useServiceInternal, useServicesInternal, usePropertiesInternal, useIntlInternal } from ${JSON.stringify(
995
+ runtimeModuleId
996
+ )};
67
997
 
68
- const PACKAGE_NAME = ${JSON.stringify(e)};
998
+ const PACKAGE_NAME = ${JSON.stringify(packageName)};
69
999
  export const useService = /*@__PURE__*/ useServiceInternal.bind(undefined, PACKAGE_NAME);
70
1000
  export const useServices = /*@__PURE__*/ useServicesInternal.bind(undefined, PACKAGE_NAME);
71
1001
  export const useProperties = /*@__PURE__*/ usePropertiesInternal.bind(undefined, PACKAGE_NAME);
72
1002
  export const useIntl = /*@__PURE__*/ useIntlInternal.bind(undefined, PACKAGE_NAME);
73
- `.trim()}var h=w(require("@babel/types")),G=w(require("@babel/template"));var Q=w(require("@babel/generator"));var Rt=G.default.program(`
1003
+ `.trim();
1004
+ }
1005
+
1006
+ // src/codegen/generateI18n.ts
1007
+ var nodes2 = __toESM(require("@babel/types"));
1008
+ var import_template2 = __toESM(require("@babel/template"));
1009
+ var import_generator2 = __toESM(require("@babel/generator"));
1010
+ var INDEX_TEMPLATE = import_template2.default.program(`
74
1011
  export const locales = %%LOCALES_ARRAY%%;
75
1012
 
76
1013
  export function loadMessages(locale) {
77
1014
  %%LOCALE_SWITCH%%
78
1015
  throw new Error(\`Unsupported locale: '\${locale}'\`);
79
1016
  }
80
- `),wt=G.default.statement(`
1017
+ `);
1018
+ var IMPORT_TEMPLATE = import_template2.default.statement(`
81
1019
  return import(%%MODULE_ID%%).then(mod => mod.default);
82
- `),xt=G.default.program(`
1020
+ `);
1021
+ var MESSAGES_TEMPLATE = import_template2.default.program(`
83
1022
  const messages = JSON.parse(%%SERIALIZED%%);
84
1023
  export default messages;
85
- `);function Ce(e,t){let n=h.arrayExpression(t.map(o=>h.stringLiteral(o))),r=h.switchStatement(h.identifier("locale"),t.map(o=>{let a=M({type:"app-i18n",packageDirectory:e,locale:o}),s=wt({MODULE_ID:h.stringLiteral(a)});return h.switchCase(h.stringLiteral(o),[s])})),i=Rt({LOCALES_ARRAY:n,LOCALE_SWITCH:r});return(0,Q.default)(i).code}async function ke(e){let{locale:t,appName:n,packages:r,loadI18n:i}=e,o=new Map,a=new Set,s;for(let g of r){g.i18nPaths.size!==0&&a.add(g.name);let f=g.i18nPaths.get(t);if(!f)continue;let{messages:m,overrides:P}=await i(f);if(g.name===n)s=P;else if(P.size!==0)throw new u(`Unexpected 'overrides' block in '${f}'. Overrides are only supported in the app.`);o.set(g.name,m)}if(s)for(let[g,f]of s.entries()){let m=o.get(g);if(!m){o.set(g,f);continue}let P=new Map([...m,...f]);o.set(g,P)}for(let g of a)if(!o.get(g))throw new u(`Package '${g}' requires messages for locale '${t}'. Either update the package or add messages from the app via 'overrides'.`);let p={};for(let[g,f]of o.entries())p[g]=Object.fromEntries(f.entries());let d=JSON.stringify(p),l=xt({SERIALIZED:h.stringLiteral(d)});return(0,Q.default)(l).code}var C=!!process.env.DEBUG,k=V("open-pioneer:codegen");function xe(){let e=new Map,t,n,r,i,o;return{name:"pioneer:codegen",async buildStart(){e.clear(),n==null||n.reset();let a=async s=>{let p=await this.resolve(s,__filename);return p||this.error(`Failed to find '${s}'.`),p.id};i=await a("@open-pioneer/runtime/react-integration"),o=await a("@open-pioneer/runtime/metadata")},configResolved(a){t=a,n=new J(t.root)},configureServer(a){r=a,a.watcher.on("all",(s,p)=>{let d=e.get((0,_.normalizePath)(p));if(d){C&&k(`File changed: ${p}`),n.onFileChanged(p);for(let l of d){let g=a.moduleGraph.getModuleById(l);g&&(C&&k(`Triggering hmr of ${l}`),a.reloadModule(g).catch(f=>{t.logger.error(`Failed to trigger hmr: ${f}`)}))}}})},async resolveId(a,s){try{if(!s)return;if(q(a))return a;let p=()=>{let d=St((0,A.dirname)(s),t.root);if(!d)throw new u(`Failed to find package.json for package from '${s}'.`);let l=(0,A.dirname)(d);return(0,_.normalizePath)(l)};if(a==="open-pioneer:app")return M({type:"app-meta",packageDirectory:p()});if(a==="open-pioneer:react-hooks")return M({type:"package-hooks",packageDirectory:p()})}catch(p){ve(this,p)}},async load(a){var s,p;try{let d=q(a);if(!d)return;C&&k("Loading virtual module %O",d);let l=(s=await this.resolve(d.packageDirectory+"/package.json"))==null?void 0:s.id;if(!l)throw new u(`Failed to resolve package.json in ${d.packageDirectory}`);if(d.type==="package-hooks"){let m=d.packageDirectory,P=(p=await this.resolve(m+"/package.json"))==null?void 0:p.id;if(!P)throw new u(`Failed to resolve package.json in ${m}`);let _e=await _t(this,P),H=Me(_e,i);return C&&k("Generated hooks code: %O",H),H}if(d.type==="app-meta")return Pe(d.packageDirectory,o);let g=It(this,a,r,e),f=await n.getAppMetadata(g,(0,A.dirname)(l));switch(d.type){case"app-packages":{let m=ne(f.packages);return C&&k("Generated app metadata: %O",m),m}case"app-css":{let m=he(f.packages);return C&&k("Generated app css: %O",m),m}case"app-i18n-index":{let m=Ce(d.packageDirectory,f.locales);return C&&k("Generated i18n lookup: %O",m),m}case"app-i18n":{let m=await ke({locale:d.locale,appName:f.name,packages:f.packages,loadI18n(P){return n.getI18nFile(g,P)}});return C&&k("Generated i18n messages: %O",m),m}}}catch(d){ve(this,d)}}}}function It(e,t,n,r){return{warn:e.warn,resolve:e.resolve,addWatchFile:i=>{n&&(C&&k(`Adding manual watch for ${i}`),n.watcher.add(i),At(r,i,t)),e.addWatchFile(i)}}}function ve(e,t){t instanceof u&&e.error(t);let n=String(t.message)||"Unknown error";e.error("Internal error: "+n)}function At(e,t,n){let r=(0,_.normalizePath)(t),i=e.get(r);i||(i=new Set,e.set(r,i)),i.add(n)}function St(e,t){let n=e;for(;n;){let r=(0,A.join)(n,"package.json");if((0,Re.existsSync)(r))return r;if((0,_.normalizePath)(n)==(0,_.normalizePath)(t))return;let i=(0,A.dirname)(n);n=i===n||i==="."?"":i}}async function _t(e,t){let n;try{let r=await(0,we.readFile)(t,"utf-8");n=JSON.parse(r).name}catch(r){throw new u(`Failed to read package.json file: ${r}`)}if(!n)throw new u(`Failed to read package name from ${t}.`);return n}var L=require("node:fs"),O=require("node:path"),Y=require("node:path"),Ae=require("node:process");function Se(e){let t=(e==null?void 0:e.rootSite)??!1,n=(e==null?void 0:e.apps)||[],r=(e==null?void 0:e.sites)||[],i;return{name:"pioneer:mpa",config(o){let a=o.root??(0,Ae.cwd)(),{entryPoints:s,appNames:p}=$t({apps:n,sites:r,rootSite:t,sourceRoot:a});return{build:{rollupOptions:{input:s,output:{entryFileNames(l){return p.includes(l.name)?"[name].js":Y.posix.join(i.build.assetsDir,"[hash:12].js")},chunkFileNames(l){return Y.posix.join(i.build.assetsDir,"[hash:12].js")}}}}}},configResolved(o){i=o}}}function $t(e){let t;Array.isArray(e.apps)?t=e.apps.map(a=>{let s=(0,O.resolve)(e.sourceRoot,"apps",a,"app"),p=Nt(a,s);return{name:a,path:p}}):t=Object.entries(e.apps).map(([a,s])=>{let p=(0,O.resolve)(e.sourceRoot,s);if(!(0,L.existsSync)(p))throw new Error(`Failed to find app '${a}' at ${p}. Ensure that the path is spelled correctly.`);return{name:a,path:p}});let n=e.sites.map(a=>{let s=(0,O.resolve)(e.sourceRoot,a,"index.html");if(!(0,L.existsSync)(s))throw new Error(`Failed to find site at ${s}. Ensure that the site name in your vite configuration is spelled correctly.`);return{name:a,path:s}});if(e.rootSite){let a=(0,O.resolve)(e.sourceRoot,"index.html");if(!(0,L.existsSync)(a))throw new Error(`Failed to find root site at ${a}. Create the missing file or set 'rootSite' to false.`);n.push({name:"index",path:a})}let r={},i=0;for(let{name:a,path:s}of[t,n].flat()){let p=r[a];if(p)throw new Error(`Entry point '${a}' was defined twice (paths ${p} and ${s}). Remove the duplicated entry.`);r[a]=s,++i}if(i===0)throw new Error("You must configure at least one site or one app in the pioneer plugin options.");let o=t.map(({name:a})=>a);return{entryPoints:r,appNames:o}}var Ie=[".ts",".tsx",".js",".jsx"];function Nt(e,t){for(let r of Ie){let i=t+r;if((0,L.existsSync)(i))return i}let n=Ie.join(", ");throw new Error(`Failed to find a matching entry point file for app '${e}' at ${t}. Supported extensions are ${n}. Ensure that the app name is spelled correctly or create the missing file.`)}function Ft(e){return[Se(e),xe()]}0&&(module.exports={pioneer});
1024
+ `);
1025
+ function generateI18nIndex(packageDirectory, locales) {
1026
+ const localesArray = nodes2.arrayExpression(
1027
+ locales.map((locale) => nodes2.stringLiteral(locale))
1028
+ );
1029
+ const switchStmt = nodes2.switchStatement(
1030
+ nodes2.identifier("locale"),
1031
+ locales.map((locale) => {
1032
+ const localeModuleId = serializeModuleId({
1033
+ type: "app-i18n",
1034
+ packageDirectory,
1035
+ locale
1036
+ });
1037
+ const importStatement = IMPORT_TEMPLATE({
1038
+ MODULE_ID: nodes2.stringLiteral(localeModuleId)
1039
+ });
1040
+ return nodes2.switchCase(nodes2.stringLiteral(locale), [importStatement]);
1041
+ })
1042
+ );
1043
+ const program2 = INDEX_TEMPLATE({
1044
+ LOCALES_ARRAY: localesArray,
1045
+ LOCALE_SWITCH: switchStmt
1046
+ });
1047
+ return (0, import_generator2.default)(program2).code;
1048
+ }
1049
+ async function generateI18nMessages(options) {
1050
+ const { locale, appName, packages, loadI18n } = options;
1051
+ const packageMessages = /* @__PURE__ */ new Map();
1052
+ const packagesNeedingMessages = /* @__PURE__ */ new Set();
1053
+ let packageOverrides;
1054
+ for (const pkg of packages) {
1055
+ if (pkg.i18nPaths.size !== 0) {
1056
+ packagesNeedingMessages.add(pkg.name);
1057
+ }
1058
+ const filePath = pkg.i18nPaths.get(locale);
1059
+ if (!filePath) {
1060
+ continue;
1061
+ }
1062
+ const { messages, overrides } = await loadI18n(filePath);
1063
+ if (pkg.name === appName) {
1064
+ packageOverrides = overrides;
1065
+ } else if (overrides.size !== 0) {
1066
+ throw new ReportableError(
1067
+ `Unexpected 'overrides' block in '${filePath}'. Overrides are only supported in the app.`
1068
+ );
1069
+ }
1070
+ packageMessages.set(pkg.name, messages);
1071
+ }
1072
+ if (packageOverrides) {
1073
+ for (const [packageName, messages] of packageOverrides.entries()) {
1074
+ const existingMessages = packageMessages.get(packageName);
1075
+ if (!existingMessages) {
1076
+ packageMessages.set(packageName, messages);
1077
+ continue;
1078
+ }
1079
+ const updatedMessages = new Map([...existingMessages, ...messages]);
1080
+ packageMessages.set(packageName, updatedMessages);
1081
+ }
1082
+ }
1083
+ for (const packageName of packagesNeedingMessages) {
1084
+ const messages = packageMessages.get(packageName);
1085
+ if (!messages) {
1086
+ throw new ReportableError(
1087
+ `Package '${packageName}' requires messages for locale '${locale}'. Either update the package or add messages from the app via 'overrides'.`
1088
+ );
1089
+ }
1090
+ }
1091
+ const allMessages = {};
1092
+ for (const [packageName, messages] of packageMessages.entries()) {
1093
+ allMessages[packageName] = Object.fromEntries(messages.entries());
1094
+ }
1095
+ const serialized = JSON.stringify(allMessages);
1096
+ const program2 = MESSAGES_TEMPLATE({
1097
+ SERIALIZED: nodes2.stringLiteral(serialized)
1098
+ });
1099
+ return (0, import_generator2.default)(program2).code;
1100
+ }
1101
+
1102
+ // src/codegenPlugin.ts
1103
+ var isDebug2 = !!process.env.DEBUG;
1104
+ var debug3 = createDebugger("open-pioneer:codegen");
1105
+ function codegenPlugin() {
1106
+ const manualDeps = /* @__PURE__ */ new Map();
1107
+ let config;
1108
+ let repository;
1109
+ let devServer;
1110
+ let reactIntegrationId;
1111
+ let metadataId;
1112
+ return {
1113
+ name: "pioneer:codegen",
1114
+ async buildStart() {
1115
+ manualDeps.clear();
1116
+ repository == null ? void 0 : repository.reset();
1117
+ const resolve2 = async (rawModuleId) => {
1118
+ const resolvedResult = await this.resolve(rawModuleId, __filename);
1119
+ if (!resolvedResult) {
1120
+ this.error(`Failed to find '${rawModuleId}'.`);
1121
+ }
1122
+ return resolvedResult.id;
1123
+ };
1124
+ reactIntegrationId = await resolve2("@open-pioneer/runtime/react-integration");
1125
+ metadataId = await resolve2("@open-pioneer/runtime/metadata");
1126
+ },
1127
+ configResolved(resolvedConfig) {
1128
+ config = resolvedConfig;
1129
+ repository = new MetadataRepository(config.root);
1130
+ },
1131
+ configureServer(server) {
1132
+ devServer = server;
1133
+ server.watcher.on("all", (_, path) => {
1134
+ const moduleIds = manualDeps.get((0, import_vite3.normalizePath)(path));
1135
+ if (!moduleIds) {
1136
+ return;
1137
+ }
1138
+ isDebug2 && debug3(`File changed: ${path}`);
1139
+ repository.onFileChanged(path);
1140
+ for (const moduleId of moduleIds) {
1141
+ const mod = server.moduleGraph.getModuleById(moduleId);
1142
+ if (mod) {
1143
+ isDebug2 && debug3(`Triggering hmr of ${moduleId}`);
1144
+ server.reloadModule(mod).catch((err) => {
1145
+ config.logger.error(`Failed to trigger hmr`, { error: err });
1146
+ });
1147
+ }
1148
+ }
1149
+ });
1150
+ },
1151
+ async resolveId(moduleId, importer) {
1152
+ try {
1153
+ if (!importer) {
1154
+ return void 0;
1155
+ }
1156
+ if (parseVirtualModuleId(moduleId)) {
1157
+ return moduleId;
1158
+ }
1159
+ const getPackageDirectory = () => {
1160
+ const packageJsonPath = findPackageJson((0, import_node_path3.dirname)(importer), config.root);
1161
+ if (!packageJsonPath) {
1162
+ throw new ReportableError(
1163
+ `Failed to find package.json for package from '${importer}'.`
1164
+ );
1165
+ }
1166
+ const packageDir = (0, import_node_path3.dirname)(packageJsonPath);
1167
+ return (0, import_vite3.normalizePath)(packageDir);
1168
+ };
1169
+ if (moduleId === "open-pioneer:app") {
1170
+ return serializeModuleId({
1171
+ type: "app-meta",
1172
+ packageDirectory: getPackageDirectory()
1173
+ });
1174
+ }
1175
+ if (moduleId === "open-pioneer:react-hooks") {
1176
+ return serializeModuleId({
1177
+ type: "package-hooks",
1178
+ packageDirectory: getPackageDirectory()
1179
+ });
1180
+ }
1181
+ } catch (e) {
1182
+ reportError(this, e);
1183
+ }
1184
+ },
1185
+ async load(moduleId) {
1186
+ var _a, _b;
1187
+ try {
1188
+ const mod = parseVirtualModuleId(moduleId);
1189
+ if (!mod) {
1190
+ return void 0;
1191
+ }
1192
+ isDebug2 && debug3("Loading virtual module %O", mod);
1193
+ const packageJsonPath = (_a = await this.resolve(mod.packageDirectory + "/package.json")) == null ? void 0 : _a.id;
1194
+ if (!packageJsonPath) {
1195
+ throw new ReportableError(
1196
+ `Failed to resolve package.json in ${mod.packageDirectory}`
1197
+ );
1198
+ }
1199
+ if (mod.type === "package-hooks") {
1200
+ const directory = mod.packageDirectory;
1201
+ const packageJsonPath2 = (_b = await this.resolve(directory + "/package.json")) == null ? void 0 : _b.id;
1202
+ if (!packageJsonPath2) {
1203
+ throw new ReportableError(`Failed to resolve package.json in ${directory}`);
1204
+ }
1205
+ const packageName = await getPackageName(this, packageJsonPath2);
1206
+ const generatedSourceCode = generateReactHooks(packageName, reactIntegrationId);
1207
+ isDebug2 && debug3("Generated hooks code: %O", generatedSourceCode);
1208
+ return generatedSourceCode;
1209
+ }
1210
+ if (mod.type === "app-meta") {
1211
+ return generateAppMetadata(mod.packageDirectory, metadataId);
1212
+ }
1213
+ const context = buildMetadataContext(this, moduleId, devServer, manualDeps);
1214
+ const appMetadata = await repository.getAppMetadata(
1215
+ context,
1216
+ (0, import_node_path3.dirname)(packageJsonPath)
1217
+ );
1218
+ switch (mod.type) {
1219
+ case "app-packages": {
1220
+ const generatedSourceCode = generatePackagesMetadata({
1221
+ appName: appMetadata.name,
1222
+ packages: appMetadata.packages
1223
+ });
1224
+ isDebug2 && debug3("Generated app metadata: %O", generatedSourceCode);
1225
+ return generatedSourceCode;
1226
+ }
1227
+ case "app-css": {
1228
+ const generatedSourceCode = generateCombinedCss(appMetadata.packages);
1229
+ isDebug2 && debug3("Generated app css: %O", generatedSourceCode);
1230
+ return generatedSourceCode;
1231
+ }
1232
+ case "app-i18n-index": {
1233
+ const generatedSourceCode = generateI18nIndex(
1234
+ mod.packageDirectory,
1235
+ appMetadata.locales
1236
+ );
1237
+ isDebug2 && debug3("Generated i18n lookup: %O", generatedSourceCode);
1238
+ return generatedSourceCode;
1239
+ }
1240
+ case "app-i18n": {
1241
+ const generatedSourceCode = await generateI18nMessages({
1242
+ locale: mod.locale,
1243
+ appName: appMetadata.name,
1244
+ packages: appMetadata.packages,
1245
+ loadI18n(path) {
1246
+ return repository.getI18nFile(context, path);
1247
+ }
1248
+ });
1249
+ isDebug2 && debug3("Generated i18n messages: %O", generatedSourceCode);
1250
+ return generatedSourceCode;
1251
+ }
1252
+ }
1253
+ } catch (e) {
1254
+ reportError(this, e);
1255
+ }
1256
+ }
1257
+ };
1258
+ }
1259
+ function buildMetadataContext(ctx, moduleId, devServer, manualDeps) {
1260
+ return {
1261
+ warn: ctx.warn,
1262
+ resolve: ctx.resolve,
1263
+ addWatchFile: (id) => {
1264
+ if (devServer) {
1265
+ isDebug2 && debug3(`Adding manual watch for ${id}`);
1266
+ devServer.watcher.add(id);
1267
+ addManualDep(manualDeps, id, moduleId);
1268
+ }
1269
+ ctx.addWatchFile(id);
1270
+ }
1271
+ };
1272
+ }
1273
+ function reportError(ctx, error) {
1274
+ if (error instanceof ReportableError) {
1275
+ ctx.error(error);
1276
+ }
1277
+ const message = String(error.message) || "Unknown error";
1278
+ ctx.error({
1279
+ message: "Internal error: " + message,
1280
+ cause: error
1281
+ });
1282
+ }
1283
+ function addManualDep(manualDeps, file, moduleId) {
1284
+ const normalizedPath = (0, import_vite3.normalizePath)(file);
1285
+ let moduleIds = manualDeps.get(normalizedPath);
1286
+ if (!moduleIds) {
1287
+ moduleIds = /* @__PURE__ */ new Set();
1288
+ manualDeps.set(normalizedPath, moduleIds);
1289
+ }
1290
+ moduleIds.add(moduleId);
1291
+ }
1292
+ function findPackageJson(startDir, rootDir) {
1293
+ let dir = startDir;
1294
+ while (dir) {
1295
+ const candidate = (0, import_node_path3.join)(dir, "package.json");
1296
+ if ((0, import_node_fs.existsSync)(candidate)) {
1297
+ return candidate;
1298
+ }
1299
+ if ((0, import_vite3.normalizePath)(dir) == (0, import_vite3.normalizePath)(rootDir)) {
1300
+ return void 0;
1301
+ }
1302
+ const parent = (0, import_node_path3.dirname)(dir);
1303
+ dir = parent === dir || parent === "." ? "" : parent;
1304
+ }
1305
+ return void 0;
1306
+ }
1307
+ async function getPackageName(ctx, packageJsonPath) {
1308
+ let name;
1309
+ try {
1310
+ const content = await (0, import_promises3.readFile)(packageJsonPath, "utf-8");
1311
+ name = JSON.parse(content).name;
1312
+ } catch (e) {
1313
+ throw new ReportableError(`Failed to read package.json file`, { cause: e });
1314
+ }
1315
+ if (!name) {
1316
+ throw new ReportableError(`Failed to read package name from ${packageJsonPath}.`);
1317
+ }
1318
+ return name;
1319
+ }
1320
+
1321
+ // src/mpaPlugin.ts
1322
+ var import_node_fs2 = require("node:fs");
1323
+ var import_node_path4 = require("node:path");
1324
+ var import_node_path5 = require("node:path");
1325
+ var import_node_process = require("node:process");
1326
+ function mpaPlugin(options) {
1327
+ const rootSite = (options == null ? void 0 : options.rootSite) ?? false;
1328
+ const apps = (options == null ? void 0 : options.apps) || [];
1329
+ const sites = (options == null ? void 0 : options.sites) || [];
1330
+ let resolvedConfig;
1331
+ return {
1332
+ name: "pioneer:mpa",
1333
+ config(config) {
1334
+ const sourceRoot = config.root ?? (0, import_node_process.cwd)();
1335
+ const { entryPoints, appNames } = gatherEntryPoints({
1336
+ apps,
1337
+ sites,
1338
+ rootSite,
1339
+ sourceRoot
1340
+ });
1341
+ const rollupOptions = {
1342
+ input: entryPoints,
1343
+ output: {
1344
+ entryFileNames(chunk) {
1345
+ if (appNames.includes(chunk.name)) {
1346
+ return "[name].js";
1347
+ }
1348
+ return import_node_path5.posix.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1349
+ },
1350
+ chunkFileNames(chunk) {
1351
+ return import_node_path5.posix.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1352
+ }
1353
+ }
1354
+ };
1355
+ return {
1356
+ build: {
1357
+ rollupOptions
1358
+ }
1359
+ };
1360
+ },
1361
+ configResolved(config) {
1362
+ resolvedConfig = config;
1363
+ }
1364
+ };
1365
+ }
1366
+ function gatherEntryPoints(options) {
1367
+ let apps;
1368
+ if (Array.isArray(options.apps)) {
1369
+ apps = options.apps.map((appName) => {
1370
+ const prefix = (0, import_node_path4.resolve)(options.sourceRoot, "apps", appName, "app");
1371
+ const path = findMatchingEntryPointFile(appName, prefix);
1372
+ return {
1373
+ name: appName,
1374
+ path
1375
+ };
1376
+ });
1377
+ } else {
1378
+ apps = Object.entries(options.apps).map(([name, appPath]) => {
1379
+ const path = (0, import_node_path4.resolve)(options.sourceRoot, appPath);
1380
+ if (!(0, import_node_fs2.existsSync)(path)) {
1381
+ throw new Error(
1382
+ `Failed to find app '${name}' at ${path}. Ensure that the path is spelled correctly.`
1383
+ );
1384
+ }
1385
+ return { name, path };
1386
+ });
1387
+ }
1388
+ const sites = options.sites.map((sitePath) => {
1389
+ const path = (0, import_node_path4.resolve)(options.sourceRoot, sitePath, "index.html");
1390
+ if (!(0, import_node_fs2.existsSync)(path)) {
1391
+ throw new Error(
1392
+ `Failed to find site at ${path}. Ensure that the site name in your vite configuration is spelled correctly.`
1393
+ );
1394
+ }
1395
+ return {
1396
+ name: sitePath,
1397
+ path
1398
+ };
1399
+ });
1400
+ if (options.rootSite) {
1401
+ const path = (0, import_node_path4.resolve)(options.sourceRoot, "index.html");
1402
+ if (!(0, import_node_fs2.existsSync)(path)) {
1403
+ throw new Error(
1404
+ `Failed to find root site at ${path}. Create the missing file or set 'rootSite' to false.`
1405
+ );
1406
+ }
1407
+ sites.push({
1408
+ name: "index",
1409
+ path
1410
+ });
1411
+ }
1412
+ const entryPoints = {};
1413
+ let entryPointCount = 0;
1414
+ for (const { name, path } of [apps, sites].flat()) {
1415
+ const existingPath = entryPoints[name];
1416
+ if (existingPath) {
1417
+ throw new Error(
1418
+ `Entry point '${name}' was defined twice (paths ${existingPath} and ${path}). Remove the duplicated entry.`
1419
+ );
1420
+ }
1421
+ entryPoints[name] = path;
1422
+ ++entryPointCount;
1423
+ }
1424
+ if (entryPointCount === 0) {
1425
+ throw new Error(
1426
+ "You must configure at least one site or one app in the pioneer plugin options."
1427
+ );
1428
+ }
1429
+ const appNames = apps.map(({ name }) => name);
1430
+ return {
1431
+ entryPoints,
1432
+ appNames
1433
+ };
1434
+ }
1435
+ var EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
1436
+ function findMatchingEntryPointFile(appName, prefix) {
1437
+ for (const ext of EXTENSIONS) {
1438
+ const candidate = prefix + ext;
1439
+ if ((0, import_node_fs2.existsSync)(candidate)) {
1440
+ return candidate;
1441
+ }
1442
+ }
1443
+ const extensions = EXTENSIONS.join(", ");
1444
+ throw new Error(
1445
+ `Failed to find a matching entry point file for app '${appName}' at ${prefix}. Supported extensions are ${extensions}. Ensure that the app name is spelled correctly or create the missing file.`
1446
+ );
1447
+ }
1448
+
1449
+ // src/index.ts
1450
+ function pioneer(options) {
1451
+ return [mpaPlugin(options), codegenPlugin()];
1452
+ }
1453
+ // Annotate the CommonJS export names for ESM import in node:
1454
+ 0 && (module.exports = {
1455
+ pioneer
1456
+ });
86
1457
  //# sourceMappingURL=index.js.map