@metricinsights/pp-dev 1.5.0-beta.31 → 1.5.0-beta.33
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/TEMPLATE_VARIABLES.md +25 -25
- package/dist/cjs/auth.provider-C3O8wdGc.js +2 -0
- package/dist/cjs/auth.provider-C3O8wdGc.js.map +1 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/cli.js.map +1 -1
- package/dist/cjs/index-DnVkH9ZF.js +2 -0
- package/dist/cjs/index-DnVkH9ZF.js.map +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/internal.middleware-63EM6Z98.js +2 -0
- package/dist/cjs/internal.middleware-63EM6Z98.js.map +1 -0
- package/dist/cjs/migrate-oVYAMhLH.js +2 -0
- package/dist/cjs/{migrate-Gi9k9cLw.js.map → migrate-oVYAMhLH.js.map} +1 -1
- package/dist/cjs/plugin.js +1 -1
- package/dist/cjs/plugin.js.map +1 -1
- package/dist/cjs/{version-manifest-CVBuIKBS.js → version-manifest-fusPAO4h.js} +2 -2
- package/dist/cjs/{version-manifest-CVBuIKBS.js.map → version-manifest-fusPAO4h.js.map} +1 -1
- package/dist/cjs/version-plugin-B6tVqztE.js +2 -0
- package/dist/cjs/{version-plugin-DBdqn2Rn.js.map → version-plugin-B6tVqztE.js.map} +1 -1
- package/dist/client/index.html +1 -3
- package/dist/client/request-inspector.html +90 -79
- package/dist/client/variables-editor.html +47 -40
- package/dist/esm/auth.provider-sKqGOS5N.js +2 -0
- package/dist/esm/auth.provider-sKqGOS5N.js.map +1 -0
- package/dist/esm/cli.js +1 -1
- package/dist/esm/cli.js.map +1 -1
- package/dist/esm/index-DEFt8X6C.js +2 -0
- package/dist/esm/index-DEFt8X6C.js.map +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/internal.middleware-BVjskCUz.js +2 -0
- package/dist/esm/internal.middleware-BVjskCUz.js.map +1 -0
- package/dist/esm/migrate-BxksV7OV.js +2 -0
- package/dist/esm/{migrate-CCBRuVfj.js.map → migrate-BxksV7OV.js.map} +1 -1
- package/dist/esm/plugin.js +1 -1
- package/dist/esm/plugin.js.map +1 -1
- package/dist/esm/version-manifest-CGzLQLmu.js +2 -0
- package/dist/esm/{version-manifest-CyzmnFOe.js.map → version-manifest-CGzLQLmu.js.map} +1 -1
- package/dist/esm/version-plugin-Byv2M38F.js +2 -0
- package/dist/esm/{version-plugin-6rxIgQ-I.js.map → version-plugin-Byv2M38F.js.map} +1 -1
- package/package.json +1 -1
- package/dist/cjs/auth.provider-fI0tFsf5.js +0 -2
- package/dist/cjs/auth.provider-fI0tFsf5.js.map +0 -1
- package/dist/cjs/index-Ty1d2YCg.js +0 -2
- package/dist/cjs/index-Ty1d2YCg.js.map +0 -1
- package/dist/cjs/migrate-Gi9k9cLw.js +0 -2
- package/dist/cjs/request-capture.middleware-6DhFLyIz.js +0 -2
- package/dist/cjs/request-capture.middleware-6DhFLyIz.js.map +0 -1
- package/dist/cjs/version-plugin-DBdqn2Rn.js +0 -2
- package/dist/esm/auth.provider-DDUsu1H1.js +0 -2
- package/dist/esm/auth.provider-DDUsu1H1.js.map +0 -1
- package/dist/esm/index-tD-QICGk.js +0 -2
- package/dist/esm/index-tD-QICGk.js.map +0 -1
- package/dist/esm/migrate-CCBRuVfj.js +0 -2
- package/dist/esm/request-capture.middleware-VElwjU1W.js +0 -2
- package/dist/esm/request-capture.middleware-VElwjU1W.js.map +0 -1
- package/dist/esm/version-manifest-CyzmnFOe.js +0 -2
- package/dist/esm/version-plugin-6rxIgQ-I.js +0 -2
package/TEMPLATE_VARIABLES.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# `__template_variables.json` schema (MI reference)
|
|
2
2
|
|
|
3
|
-
This file is what Metric Insights (MI) writes/reads for a Portal Page **template**'s variables — its definitions (types, defaults, per-field config) live here, while the
|
|
3
|
+
This file is what Metric Insights (MI) writes/reads for a Portal Page **template**'s variables — its definitions (types, defaults, per-field config) live here, while the _live_ values a page currently has are stored separately on the page itself (see below). pp-dev's standalone [Variables Editor](./README.md#variables-editor) page (`src/lib/variables-editor.ts`, backed by `src/lib/page-variables-diff.ts`) reads and writes this file's contents; the older backup/sync flow (`src/lib/dist.service.ts`, `TEMPLATE_VARIABLES_FILE_NAME`) only ever tracked it as an opaque blob (hash) for diffing, never parsing it.
|
|
4
4
|
|
|
5
5
|
## File location
|
|
6
6
|
|
|
@@ -12,12 +12,12 @@ This file is what Metric Insights (MI) writes/reads for a Portal Page **template
|
|
|
12
12
|
|
|
13
13
|
```jsonc
|
|
14
14
|
{
|
|
15
|
-
"tags": [
|
|
15
|
+
"tags": [/* TemplateVariableTag[] — see below */],
|
|
16
16
|
"settings": {
|
|
17
17
|
"image_capture_timeout": 0,
|
|
18
18
|
"image_capture_on_event": "...",
|
|
19
|
-
"image_capture_css_selector": "..."
|
|
20
|
-
}
|
|
19
|
+
"image_capture_css_selector": "...",
|
|
20
|
+
},
|
|
21
21
|
}
|
|
22
22
|
```
|
|
23
23
|
|
|
@@ -25,23 +25,23 @@ This file is what Metric Insights (MI) writes/reads for a Portal Page **template
|
|
|
25
25
|
|
|
26
26
|
## `TemplateVariableTag` fields
|
|
27
27
|
|
|
28
|
-
| Field
|
|
29
|
-
|
|
30
|
-
| `name`
|
|
31
|
-
| `uid`
|
|
32
|
-
| `tag_type`
|
|
33
|
-
| `tag_source`
|
|
34
|
-
| `default_value`
|
|
35
|
-
| `additional_options`
|
|
36
|
-
| `description`
|
|
37
|
-
| `use_hmtl_editor_ind`
|
|
38
|
-
| `use_raw_html_ind`
|
|
39
|
-
| `use_json_editor_ind`
|
|
40
|
-
| `javascript_code`
|
|
41
|
-
| `display_order`
|
|
42
|
-
| `portal_page_template_tag_id` | `number`
|
|
43
|
-
| `portal_page_template_id`
|
|
44
|
-
| `use_js_code_ind`
|
|
28
|
+
| Field | Type | Notes |
|
|
29
|
+
| ----------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
30
|
+
| `name` | `string` | Unique variable name. This is the key that appears in the live page's `tags` (`{name, value}[]`, see below) and in `[VarName]` placeholders substituted by `pp.middleware.ts#buildPage()`. |
|
|
31
|
+
| `uid` | `string` | Stable md5 identifier, survives renames across syncs. |
|
|
32
|
+
| `tag_type` | `enum` | One of: `text`, `select`, `multiselect`, `file`, `list`, `color`, `boolean`. (`boolean` is a newer addition — older templates may not have it.) |
|
|
33
|
+
| `tag_source` | `enum` | One of: `static`, `page`, `element`, `folder`, `segment`, `dataset`, `dataset_data`, `announcement`, `group`, `category`, `custom_attribute`, `page_entity`. Describes where the value/options come from, not the value's shape. |
|
|
34
|
+
| `default_value` | `string` | Default value for the variable. For `tag_type: "list"`, this is a **JSON-encoded array** (string-of-JSON, not a nested array). |
|
|
35
|
+
| `additional_options` | `array \| object \| string` | Decoded JSON in the exported file (re-stringified on ingest). Shape depends on `tag_type` and, for `select`/`multiselect`, on `tag_source` — see the dedicated section below for the full per-source breakdown. Always absent/unused for `boolean`. |
|
|
36
|
+
| `description` | `string` | Markdown, rendered as such in MI's editor UI. |
|
|
37
|
+
| `use_hmtl_editor_ind` | `'Y' \| 'N'` | Whether the value is edited via a rich HTML editor. |
|
|
38
|
+
| `use_raw_html_ind` | `'Y' \| 'N'` | When `'Y'`, MI skips XSS-encoding the value on save (see caveat below). |
|
|
39
|
+
| `use_json_editor_ind` | `'Y' \| 'N'` | Whether the value is edited via a JSON editor. |
|
|
40
|
+
| `javascript_code` | `string \| null` | Optional JS snippet, with `[value]` substituted at render time. |
|
|
41
|
+
| `display_order` | `number` | Present explicitly in real exports (not just implied by array index) — matches the tag's position in `tags`. |
|
|
42
|
+
| `portal_page_template_tag_id` | `number` | MI's internal row id for this tag. Not needed to write a schema by hand — MI regenerates it. |
|
|
43
|
+
| `portal_page_template_id` | `number` | The owning template's id — same for every tag in one file. |
|
|
44
|
+
| `use_js_code_ind` | `'Y' \| 'N'` | Companion flag for `javascript_code` (whether it's active), seen alongside `use_hmtl_editor_ind`/`use_raw_html_ind`/`use_json_editor_ind` in real exports. |
|
|
45
45
|
|
|
46
46
|
There is **no** `label` or `required` field, and no generic `options`/`enum` key — option lists live inside `additional_options`.
|
|
47
47
|
|
|
@@ -67,10 +67,10 @@ A `list` variable isn't limited to flat strings. When `additional_options` is a
|
|
|
67
67
|
|
|
68
68
|
```ts
|
|
69
69
|
interface ListItemFieldConfig {
|
|
70
|
-
name: string;
|
|
70
|
+
name: string; // becomes the object key on each list item
|
|
71
71
|
type: 'textarea' | 'color' | 'select' | 'multi-select' | 'file';
|
|
72
|
-
source?: string;
|
|
73
|
-
additional_options?: string;
|
|
72
|
+
source?: string; // select/multi-select only — where THIS field's options come from
|
|
73
|
+
additional_options?: string; // not actually read for select/multi-select — see below
|
|
74
74
|
options?: (string | { id?: string; text?: string })[]; // select/multi-select only — the option list itself
|
|
75
75
|
}
|
|
76
76
|
```
|
|
@@ -106,7 +106,7 @@ None of this is server-enforced (see below) — it's purely what the authoring f
|
|
|
106
106
|
|
|
107
107
|
## `additional_options` per `tag_type`/`tag_source` — what MI's options-loading endpoint actually reads
|
|
108
108
|
|
|
109
|
-
The create-form's field visibility above is about what a human can
|
|
109
|
+
The create-form's field visibility above is about what a human can _type into_; this is about what MI's backend actually _reads back out_ when it needs to list a `select`/`multiselect` variable's options. The two don't always agree:
|
|
110
110
|
|
|
111
111
|
- **`select`/`multiselect`, `tag_source: "static"`**: `additional_options` **is** the option list — an array where each entry is either a plain string, or an object with `id`/`text`: `[{"id":"1","text":"One"},"Two"]`. A plain string entry uses itself as both the stored value and the label.
|
|
112
112
|
- **`select`/`multiselect`, `tag_source: "dataset_data"`**: `{dataset_id, key_column, text_column}` — MI pulls id/label pairs live from that dataset, using `key_column` for the id and `text_column` for the label.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const e=require("picocolors"),t=require("node:path"),i=require("fs"),r=require("path"),s=require("ejs"),n=require("url"),o=require("node:net"),a=require("vite");var p="undefined"!=typeof document?document.currentScript:null;const d=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function l(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const i in e)t[i]=e[i];return t.default=e,Object.freeze(t)}const c=d(t),u=l(i),f=l(r),h=d(s),m=r.resolve("undefined"!=typeof __filename&&__filename||n.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("auth.provider-C3O8wdGc.js",document.baseURI).href),"../../.."),v=r.resolve("undefined"!=typeof __filename&&__filename||n.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("auth.provider-C3O8wdGc.js",document.baseURI).href),"../.."),g=i.existsSync(r.resolve(m,"package.json"))?m:v,P=r.resolve(g,"dist/client/client.js"),{version:w,name:y}=JSON.parse(i.readFileSync(r.resolve(g,"package.json")).toString()),b=w,_=y,E="info";let x,A;function D(){return x??={level:E,logger:a.createLogger(E)},x.logger}function L(e){return void 0!==e&&e!==x?.level&&(x={level:e,logger:a.createLogger(e)}),A??={info:(e,t)=>D().info(e,t),warn:(e,t)=>D().warn(e,t),warnOnce:(e,t)=>D().warnOnce(e,t),error:(e,t)=>D().error(e,t),clearScreen:e=>D().clearScreen(e),hasErrorLogged:e=>D().hasErrorLogged(e),get hasWarned(){return D().hasWarned},set hasWarned(e){D().hasWarned=e}},A}const R=e.createColors();function T(e,t){if(!e||e.includes("\0")||c.posix.isAbsolute(e)||c.win32.isAbsolute(e)||c.win32.parse(e).root)throw new Error(`[pp-dev] ${t} must be a relative path inside its output directory.`);const i=c.posix.normalize(e.replace(/\\/g,"/"));if("."===i||".."===i||i.startsWith("../"))throw new Error(`[pp-dev] ${t} must stay inside its output directory.`);return i}function S(e){return T(`${e.replace(/^@/,"").replace(/[\\/]+/g,"-")}.zip`,"default ZIP output file name")}const j=["top-left","top-right","bottom-left","bottom-right"],N=2147483647;function I(e,t){const i=e.mi?.mode??"standalone",r=e.app?.type??"template",s=e.mi?.apiVersion??7,n=e.mi?.url??process.env.MI_BACKEND_URL;if(!(e.app?.name??t))throw new Error("[pp-dev] app.name is required (or set package.json#name)");const o=e.sync?.maxBackups;if(void 0!==o&&!1!==o&&!(Number.isInteger(o)&&o>=0))throw new Error(`[pp-dev] sync.maxBackups must be a whole number ≥ 0 or false (0 and false keep every backup), got ${JSON.stringify(o)}`);const a=e.sync?.buildTimeoutMs;if(void 0!==a&&!(Number.isInteger(a)&&a>0&&a<=N))throw new Error(`[pp-dev] sync.buildTimeoutMs must be a whole number of milliseconds between 1 and 2147483647, got ${JSON.stringify(a)}`);if(e.mi?.include&&"standalone"!==i)throw console.warn('[pp-dev] mi.include is only valid when mi.mode is "standalone"'),new Error('[pp-dev] mi.include requires mi.mode to be "standalone"');if(!n){if("embedding"===i||"template"===r)throw new Error('[pp-dev] mi.url is required when mi.mode is "embedding" or app.type is "template"');"standalone"===i&&"page"===r&&console.warn("[pp-dev] mi.url is not set — dev server will run without a backend proxy")}if("template"===r&&!e.app?.id)throw new Error('[pp-dev] app.id is required when app.type is "template"');if("page"===r&&n&&("standalone"===i||s>=7)&&!e.app?.id)throw new Error('[pp-dev] app.id is required when backend page data is loaded for app.type "page"');if(void 0!==e.devPanel?.position&&!j.includes(e.devPanel.position))throw new Error(`[pp-dev] devPanel.position must be one of: ${j.join(", ")}`);const p=e.server?.allowedHosts;if(!(void 0===p||!0===p||Array.isArray(p)&&p.every(e=>"string"==typeof e&&""!==e.trim())))throw new Error(`[pp-dev] server.allowedHosts must be a list of host names or true, got ${JSON.stringify(p)}`)}function $(e,t){const{mi:i={},app:r={},proxy:s={},build:n={},sync:o={},inspector:a={},devPanel:p={},users:d={},server:l={}}=e,c=i.mode??"standalone",u=r.type??"template",f=i.apiVersion??7,h="standalone"===c;let m=!1;"top-bar"===i.include?m=!0:"shared-components"===i.include&&(m={addSharedComponentsScripts:!0,addRootElement:!1});const v="page"===u,g=r.name??t;if(!g)throw new Error("[pp-dev] app.name is required (or set package.json#name)");const P="VERSION-v{packageversion}-{currentDate}.json";let w;const y=n.zip;let b;w=!1!==y&&(!0===y||void 0===y?{outFileName:S(g),outDir:"dist-zip"}:{outFileName:T(y.fileName??S(g),"build.zip.fileName"),outDir:y.outDir??"dist-zip",...y.inDir?{inDir:y.inDir}:{}});const _=n.versionFile;let E;b=!1!==_&&(!0===_||void 0===_?{versionFileTemplate:P,enabled:!0}:{versionFileTemplate:T(_.fileNameTemplate??P,"build.versionFile.fileNameTemplate"),enabled:_.enabled??!0});const x=n.imageOptimisations;return E=!1!==x&&(!0===x||void 0===x?{}:x),{templateName:g,backendBaseURL:i.url??process.env.MI_BACKEND_URL,appId:r.id,templateLess:v,miHudLess:h,integrateMiTopBar:m,enableProxyCache:s.cache??!0,proxyCacheTTL:s.cacheTtl??6e5,disableSSLValidation:s.tls?.allowSelfSigned??!1,imageOptimizer:E,outDir:n.outDir??"dist",distZip:w,versionPlugin:b,syncBackupsDir:o.backupsDir??"backups",syncMaxBackups:o.maxBackups,syncBuildTimeoutMs:o.buildTimeoutMs,v7Features:f>=7,personalAccessToken:i.token??process.env.MI_ACCESS_TOKEN,inspectorEnabled:a.enabled??!0,inspectorMaxMemory:a.maxMemory??1073741824,inspectorCaptureLimit:a.captureLimit??10485760,devPanelPosition:p.position??"bottom-right",devPanelHidden:p.hidden??!1,devPanelAutoHide:p.autoHide??!1,persistUsers:d.persist??!1,allowedHosts:!0===l.allowedHosts||(l.allowedHosts??[]).map(e=>e.trim().toLowerCase())}}const C=Object.freeze({__proto__:null,normalizePPDevConfig:$,validatePPDevConfig:I}),O=f.dirname(P),k=f.join(O,"index.html");let H=null;function U(e){return{css:f.posix.join(e,_,"client/client.css"),js:f.posix.join(e,_,"client/client.js")}}function M(e){return function(){if(H)return H;const e=u.readFileSync(k,{encoding:"utf8"});return H=h.compile(e,{openDelimiter:"{",closeDelimiter:"}",async:!1,rmWhitespace:!0,compileDebug:!1}),H}()({PACKAGE_NAME:_,VERSION:b,backendBaseURL:e.backendBaseURL,templateLess:e.templateLess,appId:e.appId,canSync:e.canSync??!0,devPanelPosition:e.devPanelPosition??"bottom-right",devPanelHidden:e.devPanelHidden??!1,devPanelAutoHide:e.devPanelAutoHide??!1})}const B={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};const F=new Set(["GET","HEAD","OPTIONS"]);function V(e){return!0===e?[]:e.filter(e=>!e.startsWith("."))}function q(e,t=[]){const i=e.headers.origin,r=e.headers.host;if("string"==typeof i){if("null"===i)return'Origin "null" (a sandboxed or file:// page)';let e;try{e=new URL(i)}catch{return`unreadable Origin "${i}"`}if("localhost"===(s=e.hostname)||s.endsWith(".localhost")||"[::1]"===s||/^127(?:\.\d{1,3}){3}$/.test(s)||V(t).includes(e.hostname))return null;const n=r?function(e,t){try{return new URL(`${e}//${t}`).host}catch{return}}(e.protocol,r):void 0;return n&&e.host===n?null:`Origin ${e.origin} is neither this dev server (${r??"no Host"}) nor this machine`}var s;const n=e.headers["sec-fetch-site"];return F.has((e.method??"GET").toUpperCase())||"cross-site"!==n?null:"sent from a cross-site page"}class W{state={isAuthenticated:!1,isRedirected:!1};listeners=new Set;getState(){return{...this.state}}isAuthenticated(){return this.state.isAuthenticated}isRedirected(){return this.state.isRedirected}setAuthenticated(e){this.state.isAuthenticated=e,this.notifyListeners()}setRedirected(e){this.state.isRedirected=e,this.notifyListeners()}updateState(e){void 0!==e.isAuthenticated&&(this.state.isAuthenticated=e.isAuthenticated),void 0!==e.isRedirected&&(this.state.isRedirected=e.isRedirected),this.notifyListeners()}reset(){this.state={isAuthenticated:!1,isRedirected:!1},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{try{e(this.getState())}catch(e){L().error(`Error in auth state listener: ${e instanceof Error?e.stack??e.message:String(e)}`)}})}}const z=new W;exports.AuthProvider=W,exports.PACKAGE_NAME=_,exports.PATH_PAGE_PREFIX="/p",exports.PATH_TEMPLATE_LOCAL_PREFIX="/pl",exports.PATH_TEMPLATE_PREFIX="/pt",exports.PP_DEV_CLIENT_ENTRY=P,exports.PP_DEV_CONFIG_NAMES=[".pp-dev.config.js",".pp-dev.config.cjs",".pp-dev.config.mjs",".pp-dev.config.ts",".pp-dev.config.cts",".pp-dev.config.mts",".pp-dev.config.json","pp-dev.config.js","pp-dev.config.cjs","pp-dev.config.mjs","pp-dev.config.ts","pp-dev.config.cts","pp-dev.config.mts","pp-dev.config.json"],exports.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR="PP_DEV_NEXT_BUILD_DIST_DIR",exports.PP_DEV_NEXT_BUILD_ENV_VAR="PP_DEV_NEXT_BUILD",exports.PP_DEV_PACKAGE_DIR=g,exports.VERSION=b,exports.authProvider=z,exports.colors=R,exports.createDefaultZipFileName=S,exports.createDevPanelAssetMiddleware=function(e){const t=f.posix.join(e,_,"client")+"/",i=new Set(["client.js","client.css","client.js.map","client.css.map"]);return(e,r,s)=>{const n=(e.url??"").split("?")[0];if(!n.startsWith(t))return void s();const o=n.slice(t.length);if(!i.has(o))return void s();const a=f.join(O,o);u.readFile(a,(e,t)=>{e?s():(r.statusCode=200,r.setHeader("Content-Type",B[f.extname(o)]??"application/octet-stream"),r.setHeader("Cache-Control","no-cache"),r.end(t))})}},exports.createLogger=L,exports.createOriginGuard=function(e=[]){return(t,i,r)=>{const s=q(t,e);s?i.status(403).json({error:`Blocked by pp-dev: ${s}.`}):r()}},exports.crossOriginReason=q,exports.exactAllowedHosts=V,exports.getDevPanelAssetPaths=U,exports.hostNotAllowedMessage=function(e){const t=JSON.stringify((e??"").replace(/:\d*$/,""));return`Blocked by pp-dev: this host (${t}) is not allowed. To allow it, add ${t} to server.allowedHosts in the pp-dev config.`},exports.injectDevPanel=function(e,t,i){if(!/<\/?(html|body|head)\b/i.test(e))return e;const{css:r,js:s}=U(t),n=M(i),o=`<link rel="stylesheet" href="${r}">`,a=`${n}${`<script type="module" src="${s}"><\/script>`}`;let p=e,d=!1;if(/<\/head>/i.test(p)&&(p=p.replace(/<\/head>/i,e=>`${o}${e}`),d=!0),/<body[^>]*>/i.test(p)){const e=d?"":o;p=p.replace(/<body[^>]*>/i,t=>`${t}${e}${a}`)}else p=`${d?"":o}${p}${a}`;return p},exports.isHostAllowed=function(e,t){if(void 0===e||!0===t)return!0;const i=function(e){const t=e.trim().toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");return e>0&&6===o.isIP(t.slice(1,e))?{ip:!0}:void 0}const i=t.replace(/:\d*$/,"");if(i&&!i.includes(":"))return 4===o.isIP(i)?{ip:!0}:{hostname:i}}(e);if(void 0===i)return!1;if("ip"in i)return!0;const{hostname:r}=i;return"localhost"===r||r.endsWith(".localhost")||function(e,t){return t.some(t=>t===e||t.startsWith(".")&&(t.slice(1)===e||e.endsWith(t)))}(r,t)},exports.normalizePPDevConfig=$,exports.normalizeRelativeOutputPath=T,exports.ppDevConfig=C,exports.renderDevPanelMarkup=M,exports.resolveOutputFilePath=function(e,t,i){const r=T(t,i),s=c.resolve(e),n=c.resolve(s,...r.split("/")),o=c.relative(s,n);if(".."===o||o.startsWith(`..${c.sep}`)||c.isAbsolute(o))throw new Error(`[pp-dev] ${i} must resolve inside its output directory.`);return n},exports.resolveZipSourceDir=function(e,t,i){return c.resolve(e,i||t)},exports.validatePPDevConfig=I;
|
|
2
|
+
//# sourceMappingURL=auth.provider-C3O8wdGc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.provider-C3O8wdGc.js","sources":["../../../src/constants.ts","../../../src/lib/logger.ts","../../../src/lib/helpers/color.helper.ts","../../../src/lib/output-path.ts","../../../src/lib/pp-dev-config.ts","../../../src/lib/dev-panel.ts","../../../src/lib/helpers/origin-guard.ts","../../../src/lib/auth.provider.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["afterBundlePath","resolve","__filename","fileURLToPath","document","require","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","beforeBundlePath","PP_DEV_PACKAGE_DIR","existsSync","PP_DEV_CLIENT_ENTRY","version","name","JSON","parse","readFileSync","toString","VERSION","PACKAGE_NAME","DEFAULT_LEVEL","current","shared","active","level","logger","createViteLogger","createLogger","undefined","info","msg","options","warn","warnOnce","error","clearScreen","type","hasErrorLogged","hasWarned","value","colors","createColors","normalizeRelativeOutputPath","relativePath","optionName","includes","path","posix","isAbsolute","win32","root","Error","normalized","normalize","replace","startsWith","createDefaultZipFileName","appName","DEV_PANEL_POSITIONS","MAX_TIMER_DELAY_MS","validatePPDevConfig","config","templateName","miMode","mi","mode","appType","app","apiVersion","miUrl","url","process","env","MI_BACKEND_URL","maxBackups","sync","Number","isInteger","stringify","buildTimeoutMs","include","console","id","devPanel","position","join","allowedHosts","server","Array","isArray","every","host","trim","normalizePPDevConfig","proxy","build","inspector","users","miHudLess","integrateMiTopBar","addSharedComponentsScripts","addRootElement","templateLess","resolvedName","defaultVersionFileTemplate","distZip","zipCfg","zip","versionPlugin","outFileName","outDir","fileName","inDir","vfCfg","versionFile","imageOptimizer","versionFileTemplate","enabled","fileNameTemplate","imgCfg","imageOptimisations","backendBaseURL","appId","enableProxyCache","cache","proxyCacheTTL","cacheTtl","disableSSLValidation","tls","allowSelfSigned","syncBackupsDir","backupsDir","syncMaxBackups","syncBuildTimeoutMs","v7Features","personalAccessToken","token","MI_ACCESS_TOKEN","inspectorEnabled","inspectorMaxMemory","maxMemory","inspectorCaptureLimit","captureLimit","devPanelPosition","devPanelHidden","hidden","devPanelAutoHide","autoHide","persistUsers","persist","map","toLowerCase","CLIENT_DIST_DIR","dirname","TEMPLATE_PATH","compiledTemplate","getDevPanelAssetPaths","base","css","js","renderDevPanelMarkup","data","templateContent","fs","encoding","ejs","compile","openDelimiter","closeDelimiter","async","rmWhitespace","compileDebug","getTemplate","template","canSync","CONTENT_TYPES","SAFE_METHODS","Set","exactAllowedHosts","filter","crossOriginReason","req","origin","headers","originUrl","hostname","endsWith","test","requestHost","scheme","normalizeHost","protocol","fetchSite","has","method","AuthProvider","state","isAuthenticated","isRedirected","listeners","getState","this","setAuthenticated","authenticated","notifyListeners","setRedirected","redirected","updateState","updates","reset","subscribe","listener","add","delete","forEach","stack","message","String","authProvider","assetPrefix","allowed","res","next","pathname","split","slice","length","filePath","readFile","err","content","statusCode","setHeader","extname","end","reason","status","json","html","panelMarkup","linkTag","bodyPrepend","result","linkInjected","headEnd","head","bodyStart","named","trimmed","indexOf","isIP","ip","readHostHeader","some","matchesAllowedHost","directory","safeRelativePath","resolvedDirectory","resolvedFile","relativeToDirectory","relative","sep","projectRoot"],"mappings":"0eAIMA,EAAkBC,EAAAA,QAEC,oBAAfC,YAA8BA,YAAeC,EAAAA,cAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,4BAAAR,SAAAS,SAAAN,MACnE,YAGIO,EAAmBb,EAAAA,QAEA,oBAAfC,YAA8BA,YAAeC,EAAAA,cAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,4BAAAR,SAAAS,SAAAN,MACnE,SAGWQ,EAAqBC,EAAAA,WAAWf,UAAQD,EAAiB,iBAClEA,EACAc,EAESG,EAAsBhB,EAAAA,QAAQc,EAAoB,0BAEzDG,QAAEA,EAAOC,KAAEA,GAASC,KAAKC,MAAMC,EAAAA,aAAarB,EAAAA,QAAQc,EAAoB,iBAAiBQ,YAElFC,EAAUN,EACVO,EAAeN,ECvBtBO,EAA0B,OAEhC,IAAIC,EACAC,EAEJ,SAASC,IAGP,OAFAF,IAAY,CAAEG,MAAOJ,EAAeK,OAAQC,EAAAA,aAAiBN,IAEtDC,EAAQI,MACjB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AKT,EAAKuN,QACzCvN,EAAKE,WAAWmN,GAEhB,MAAM,IAAIhN,MAAM,YAAYP,+CAG9B,OAAOsN,CACT,uCAnBoCI,EAAqBxJ,EAAgBE,GACvE,OAAOlE,EAAKnD,QAAQ2Q,EAAatJ,GAASF,EAC5C"}
|
package/dist/cjs/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";const e=require("cac"),t=require("./auth.provider-fI0tFsf5.js"),o=require("path"),n=require("node:perf_hooks"),i=require("vite"),r=require("./request-capture.middleware-6DhFLyIz.js"),s=require("chokidar"),a=require("./index-Ty1d2YCg.js"),l=require("fs"),c=require("node:events"),d=require("url"),p=require("ws"),f=require("node:child_process"),u=require("dir-compare"),g=require("diff-match-patch"),h=require("isbinaryfile"),m=require("os"),v=require("crypto"),w=require("./version-manifest-CVBuIKBS.js");require("picocolors"),require("node:path"),require("node:net"),require("zlib"),require("axios"),require("node:http"),require("node:https"),require("process"),require("jszip"),require("child_process"),require("module"),require("http-proxy-middleware"),require("node:string_decoder"),require("node:crypto"),require("node:fs"),require("node:os"),require("express"),require("node:module"),require("./helpers.js"),require("ejs"),require("fs/promises"),require("util");const b=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function y(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const o in e)t[o]=e[o];return t.default=e,Object.freeze(t)}const P=y(o),x=y(l),S=y(u),T=b(g),L=y(m),E=y(v);function k(e){return null!=e&&!1!==e}let D=null;const I=new WeakMap;function F(e,o){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;I.set(e,o);const n=t.createLogger();o.print&&n.info(t.colors.dim(t.colors.green(" ➜"))+t.colors.dim(" press ")+t.colors.bold("h")+t.colors.dim(" to show help"));const i=(o.customShortcuts??[]).filter(k).concat($);D?.(),D=null;let r=!1;const s=process.stdin.isPaused(),a=process.stdin,l=Boolean(a.isRaw),c=async o=>{if(""===o)return void function(e=process){"win32"===e.platform?e.emit("SIGINT","SIGINT"):e.kill(e.pid,"SIGINT")}();if(""===o)return void await e.close().finally(()=>process.exit(0));if(r)return;"h"===o&&n.info(["",t.colors.bold(" Shortcuts"),...i.map(e=>t.colors.dim(" press ")+t.colors.bold(e.key)+t.colors.dim(` to ${e.description}`))].join("\n"));const s=i.find(e=>e.key===o);s&&(r=!0,await s.action(e),r=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",c).setEncoding("utf8").resume();const d=e.httpServer,p=()=>{D===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),s&&process.stdin.pause(),D=null)};D=p,d.on("close",p)}const $=[{key:"r",description:"restart the server",async action(e){const t=I.get(e);await e.restart(),t&&F(e,{...t,print:!1})}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally(()=>process.exit())}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}],C="pp-dev:ready",j="pp-dev:shutdown";function _(e){return e instanceof Error?e.stack??e.message:String(e)}function N({logger:e,knownRejections:o=[],shutdown:n,shutdownTimeoutMs:i=5e3,processRef:r=process}){let s=!1,a=!1,l=0;const c=async(o,c,{repeatable:d=!0}={})=>{if((e=>{l=Math.max(l,e)})(c),s){if(d&&(e=>"SIGINT"===e||"SIGTERM"===e||"SIGHUP"===e)(o)){if(a)return void(a=!1);e.warn(t.colors.yellow(`\n⚠️ Received ${o} again, exiting without waiting for the shutdown`)),r.exit(l)}return}s=!0,a=!d,e.info(t.colors.yellow(`\n🛑 Received ${o}, shutting down gracefully...`));const p=setTimeout(()=>{e.error(t.colors.red(`⏰ Shutdown did not finish within ${i} ms, forcing exit`)),r.exit(1)},i);try{await n(),clearTimeout(p),e.info(t.colors.green("✅ Graceful shutdown completed")),r.exit(l)}catch(o){clearTimeout(p),e.error(t.colors.red(`❌ Error during graceful shutdown: ${_(o)}`)),r.exit(1)}},d=()=>{c("SIGINT",0)},p=()=>{c("SIGTERM",0)},f=()=>{c("SIGHUP",0)},u=o=>{e.error(t.colors.red(`❌ Uncaught exception: ${_(o)}`)),c("uncaughtException",1)},g=n=>{const i=o.find(e=>e.matches(n));i?e.info(t.colors.dim(i.message)):e.error(t.colors.red(`❌ Unhandled promise rejection (the server keeps running): ${_(n)}`))},h=e=>{(function(e){return"object"==typeof e&&null!==e&&e.type===j&&"string"==typeof e.reason})(e)&&c(e.reason,0,{repeatable:!1})},m=()=>{c("the end of the pp-dev process",0,{repeatable:!1})},v="function"==typeof r.send;return r.on("SIGINT",d),r.on("SIGTERM",p),r.on("SIGHUP",f),r.on("uncaughtException",u),r.on("unhandledRejection",g),v&&(r.on("message",h),r.on("disconnect",m)),()=>{r.off("SIGINT",d),r.off("SIGTERM",p),r.off("SIGHUP",f),r.off("uncaughtException",u),r.off("unhandledRejection",g),v&&(r.off("message",h),r.off("disconnect",m))}}const A=["--","c","config","base","l","logLevel","clearScreen","configLoader","profile","d","debug","f","filter","m","mode","force","w","changelog","distZip","distZipDir","distZipFilename","versionManifest","versionFileTemplate","webpack","turbopack"];function R(e){const t={...e};for(const e of A)delete t[e];return"sourcemap"in t&&(t.sourcemap="true"===t.sourcemap||"false"!==t.sourcemap&&t.sourcemap),"watch"in t&&(t.watch=t.watch?{}:void 0),t}const M=["https","open","cors","strictPort","force"];const H=[...t.PP_DEV_CONFIG_NAMES,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"];function q(e){return e instanceof Error?e.stack??e.message:String(e)}function O(e,o,n,i={}){const{debounceMs:r=500}=i,a=P.resolve(e),l=new Set(H),c=s.watch(a,{ignored:(e,t)=>!!t&&(t.isDirectory()?P.resolve(e)!==a:!l.has(P.basename(e))),depth:0,persistent:!0,ignoreInitial:!0,followSymlinks:!1});let d=null,p=!1,f=!1,u=!1;const g=()=>{d&&clearTimeout(d),d=setTimeout(()=>{(async()=>{if(d=null,!u)if(p)f=!0;else{p=!0;try{n(t.colors.yellow("🔄 Restarting dev server due to config change...")),await o()}catch(e){n(t.colors.red(`❌ Failed to restart dev server: ${q(e)}`))}finally{p=!1}f&&!u&&(f=!1,n(t.colors.blue("🔧 Config changed again during the restart")),g())}})()},r)},h=e=>o=>{n(t.colors.blue(`🔧 Config file ${e}: ${P.relative(a,o)}`)),g()};c.on("change",h("changed")),c.on("add",h("added")),c.on("unlink",h("removed")),c.on("error",e=>{n(t.colors.red(`❌ Config watcher error: ${q(e)}`))});const m=new Promise(e=>{c.once("ready",()=>{n(t.colors.blue("🔧 Config file watcher started")),e()})});return{watcher:c,ready:m,async close(){u=!0,d&&(clearTimeout(d),d=null),await c.close()}}}function V(e){if(!e||"object"!=typeof e||!("message"in e))return!1;const t=String(e.message);return/Turbopack is not supported/i.test(t)||/native bindings are not available/i.test(t)||/Only WebAssembly \(WASM\) bindings were loaded/i.test(t)}const U=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};async function z(e){const{root:t,mode:o,command:n,isPreview:r}=e,s=P.resolve(process.cwd(),t??".");a.loadPPDevEnv(o,s);const l=await i.loadConfigFromFile({mode:o,command:n,...r?{isPreview:r}:{}},e.configFile,t,e.logLevel);let c=await a.getViteConfig(e.buildOverrides,{mode:o,root:s});if(l){const e={...l.config};delete e.plugins,c=i.mergeConfig(c,e)}return{config:c,envDir:s}}let W=global.__pp_dev_profile_session,G=0;const Z=e=>{if(W)return new Promise((o,n)=>{W.post("Profiler.stop",(i,{profile:r})=>{if(i)n(i);else{const n=P.resolve(`./pp-dev-profile-${G++}.cpuprofile`);x.writeFileSync(n,JSON.stringify(r)),e(t.colors.yellow(`CPU profile written to ${t.colors.white(t.colors.dim(n))}`)),W=void 0,o()}})})};function B(e){e.once("error",()=>e.destroy()),e.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n",()=>e.destroy())}class J{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;allowedHosts;constructor({allowedHosts:e=[]}={}){this.allowedHosts=e,this.wss=new p.WebSocketServer({noServer:!0}),this.wss.on("connection",e=>this.onConnection(e)),this.wss.on("error",e=>this.fireLifecycle("error",e)),this.ws={on:(e,t)=>{"close"!==e&&"error"!==e?this.getEventSet(e).add(t):this.getLifecycleSet(e).add(t)},off:(e,t)=>{"close"!==e&&"error"!==e?this.eventListeners.get(e)?.delete(t):this.lifecycleListeners.get(e)?.delete(t)},send:(e,t)=>{if("string"==typeof e)for(const o of this.clients.keys())this.sendToSocket(o,e,t);else{const t=JSON.stringify(e);for(const e of this.clients.keys())e.readyState===p.WebSocket.OPEN&&e.send(t)}}}}handleUpgrade(e,o,n){return(e.url??"").split("?")[0]===r.PP_DEV_HMR_WS_PATH&&(t.crossOriginReason(e,this.allowedHosts)?(B(o),!0):(this.wss.handleUpgrade(e,o,n,t=>{this.wss.emit("connection",t,e)}),!0))}async close(){this.fireLifecycle("close");for(const e of this.clients.keys())e.terminate();this.clients.clear(),await new Promise(e=>this.wss.close(()=>e()))}onConnection(e){const t={send:(t,o)=>this.sendToSocket(e,t,o),socket:e};this.clients.set(e,t),e.on("message",e=>this.onMessage(t,e)),e.on("close",()=>this.clients.delete(e)),e.on("error",()=>{})}onMessage(e,o){let n;try{n=JSON.parse(o.toString())}catch{return}if(!n||"custom"!==n.type||"string"!=typeof n.event)return;const i=this.eventListeners.get(n.event);if(i)for(const o of i)try{o(n.data,e)}catch(e){t.createLogger().error(`ws handler for "${n.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===p.WebSocket.OPEN&&e.send(JSON.stringify({type:"custom",event:t,data:o}))}fireLifecycle(e,t){for(const o of this.lifecycleListeners.get(e)??[])try{o(t)}catch{}}getEventSet(e){let t=this.eventListeners.get(e);return t||(t=new Set,this.eventListeners.set(e,t)),t}getLifecycleSet(e){let t=this.lifecycleListeners.get(e);return t||(t=new Set,this.lifecycleListeners.set(e,t)),t}}const X={matches:e=>e instanceof Error&&"Worker creator already registered"===e.message,message:"Next.js kept its Turbopack worker pool from before the restart ('Worker creator already registered')"};const K="PP_DEV_NEXT_SERVER_PROCESS";function Y(){const[,e,...t]=process.argv;if(!e)throw new Error("pp-dev next: cannot start the server process, no script in process.argv");return f.fork(e,t,{env:{...process.env,[K]:"1"},stdio:"inherit",execArgv:process.execArgv})}async function Q(e,t="development"){const[{loadPPDevEnv:o},{clearConfigCache:n,getConfig:i,getPkg:r},{validatePPDevConfig:s}]=await Promise.all([Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.env),Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.config),Promise.resolve().then(()=>require("./auth.provider-fI0tFsf5.js")).then(e=>e.ppDevConfig)]);o(t,e),n();s(await i(e),r(e).name)}function ee(e){return e instanceof Error?e.message:String(e)}const te=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class oe{oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(e){const{oldAssetsPath:o,newAssetsPath:n,destinationPath:i,changelogTemplate:r,diffFileTemplateHandler:s,diffLineTemplateHandler:a,changelogFilename:l,contextLines:c}=e;if(this.logger=t.createLogger(),!o||!n||!i)throw new Error("Previous assets path, current assets path and destination path are required");if(o===n)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(n))throw new Error(`Current assets path ${n} does not exist`);if(this.isZipFile(o)){const e=P.resolve(L.tmpdir(),E.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(n)){const e=P.resolve(L.tmpdir(),E.createHash("md5").update(n).digest("hex"));this.newAssetsPath=this.unzipFile(n,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(n))throw new Error(`Invalid current assets path ${n}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(n);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${n} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=i,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",r&&(this.templateIsValid(r)?this.changelogTemplate=r:this.logger.warn(t.colors.yellow("Invalid changelog template, using default"))),"function"==typeof s&&(this.diffFileTemplateHandler=s),"function"==typeof a&&(this.diffLineTemplateHandler=a),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return x.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return x.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===x.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){x.existsSync(e)||x.mkdirSync(e,{recursive:!0})}async unzipFile(e,t){x.rmSync(t,{force:!0,recursive:!0}),await r.extractZipSafe(e,t)}normalizeAssetFolderPath(e){const t=x.readdirSync(e);return 1===t.length&&x.lstatSync(P.join(e,t[0])).isDirectory()?this.normalizeAssetFolderPath(P.join(e,t[0])):e}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const t=e.filter((e,t,o)=>0!==e.lineType||(t>=0&&t<this.contextLines||t>o.length-(this.contextLines+1)&&t<=o.length-1||o.slice(t-this.contextLines,t+this.contextLines+1).some(e=>0!==e.lineType))).map((e,t,o)=>{if(t>0){const n=o[t-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]}).flat().map(e=>this.diffLineHTML(e)).join("");return this.diffTableTemplate(t)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:t,lineContent:o,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${r=o??"",r.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var r}diffLineHTML(e){if(this.diffLineTemplateHandler)return this.diffLineTemplateHandler(e);const{lineNumber:t}=e;return-1===t?this.diffLineSkipTemplate():this.diffLineTemplate(e)}diffFileTemplate(e,t){return this.diffFileTemplateHandler?this.diffFileTemplateHandler(e,t):`<div class="diff-file">\n <div class="diff-file-title">${e}</div>\n <div class="diff-file-content">${t}</div>\n </div>`}async generateAssetFoldersDiff(){this.logger.info(t.colors.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await S.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(te.test(e)&&(e=e.replace(te,"$1$3")),te.test(t)&&(t=t.replace(te,"$1$3")),0===e.localeCompare(t)?0:e.localeCompare(t)>0?1:-1)});return e.diffSet?.filter(e=>"equal"!==e.state||e.name1!==e.name2)||[]}async generateAssetFilesDiff(e,t){const o=new T,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let r=0;return i.map(e=>{const[t,o]=e,n=o.endsWith("\n")?o.split("\n").length-1:o.split("\n").length,i=o.split("\n").map((e,o)=>({lineContent:e,lineNumber:r+o+1,lineType:t})).slice(0,n);return-1!==t&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const t=this.pathToPosix(P.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(P.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${o}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const t=e.path1&&e.name1?P.join(e.path1,e.name1):null,o=e.path2&&e.name2?P.join(e.path2,e.name2):null,n=this.pathToPosix(P.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&t)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&o)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&t&&o){const i=this.pathToPosix(P.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(P.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await h.isBinaryFile(t)||await h.isBinaryFile(o)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(x.readFileSync(t,"utf-8"),x.readFileSync(o,"utf-8"))))}return""}async generateChangelog(){this.logger.info(t.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),o=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(t.colors.green("Writing changelog file"));const n=this.changelogTemplate.split("%FILES%");n.splice(1,0,o);const i=n.join("");x.writeFileSync(P.join(this.destinationPath,this.changelogFilename),i),this.logger.info(t.colors.green(`Changelog file written to ${P.join(this.destinationPath,this.changelogFilename)}`))}}async function ne(e){const{changelog:o,executionRoot:n,newAssetsPath:i,backupsDirPath:r,changelogDestinationPath:s,logLevel:a}=e;let l;if("string"==typeof o)l=P.resolve(n,o);else{if(!x.existsSync(r))return void t.createLogger(a).warn(t.colors.yellow("backups directory not found, skipping changelog generation"));const e=x.readdirSync(r,{withFileTypes:!0});if(!e.length)return void t.createLogger(a).warn(t.colors.yellow("no backups found, skipping changelog generation"));const o=e.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!o.length)return void t.createLogger(a).warn(t.colors.yellow("no ZIP backups found, skipping changelog generation"));const n=o.reduce((e,t)=>x.statSync(P.resolve(r,e.name)).mtimeMs>x.statSync(P.resolve(r,t.name)).mtimeMs?e:t).name;l=P.resolve(r,n)}const c=new oe({oldAssetsPath:l,newAssetsPath:i,destinationPath:s});await c.generateChangelog()}class ie{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){const{default:e}=await(import("svgtofont"));await e({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}const re=e.cac("pp-dev");re.option("-c, --config <file>","[string] use specified config file").option("--base <path>","[string] public base path (default: /)").option("-l, --logLevel <level>","[string] info | warn | error | silent").option("--clearScreen","[boolean] allow/disable clear screen when logging").option("-d, --debug [feat]","[string | boolean] show debug logs").option("-f, --filter <filter>","[string] filter debug logs").option("-m, --mode <mode>","[string] set env mode"),function(e){e.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{U(o);let s=null,a=null;const l=e?P.resolve(process.cwd(),e):process.cwd(),c=t.createLogger(o.logLevel),d=async({restart:p=!1}={})=>{let f=null;try{const{clearConfigCache:p,getConfig:g}=await Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.config);p();const{createServer:h}=await(import("vite")),m=o.mode||"development",{config:v,envDir:w}=await z({root:e,mode:m,command:"serve",configFile:o.config,logLevel:o.logLevel}),b=o.base??v.base;if(!b||"/"===b)throw new Error('base cannot be equal to "/" or empty string');if(f=await h(i.mergeConfig(v,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:R(o),customLogger:c},!0)),!f.httpServer)throw new Error("HTTP server not available");if(s){const e=s;s=null,c.info(t.colors.yellow("🛑 Stopping existing dev server...")),await e.close()}await f.listen(),s=f;const y=global.__pp_dev_start_time??!1,P=y?t.colors.dim(`ready in ${t.colors.reset(t.colors.bold(Math.ceil(n.performance.now()-y)))} ms`):"";c.info(`\n ${t.colors.green(`${t.colors.bold("PP-DEV")} v${t.VERSION}`)} ${P}\n`),s.printUrls();const x=await g(w);if(!1!==x.inspector?.enabled){const e=s.resolvedUrls?.local[0],o=e?new URL(e).origin:`http://localhost:${s.config.server.port??5173}`;c.info(`\n ${t.colors.cyan("🔍 Request Inspector")} ${t.colors.dim(o+r.INSPECTOR_PATH)}\n`)}F(s,{print:!0,customShortcuts:[...(u=c.info,W?[{key:"p",description:"start/stop the profiler",async action(){if(W)await Z(u);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{W=new e.Session,W.connect(),W.post("Profiler.enable",()=>{W?.post("Profiler.start",()=>{u("Profiler started"),t()})})})}}}]:[]),{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),a||(a=O(l,()=>d({restart:!0}),c.info))}catch(e){if(!p)return c.error(t.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),Z(c.info),void process.exit(1);f&&f!==s&&await f.close().catch(()=>{}),c.error(t.colors.red(`❌ Failed to restart dev server:\n${e.stack}`),{error:e}),c.warn(t.colors.yellow(s?"⚠️ The running dev server is kept, with its config, until the next config change":"⚠️ No dev server is running; it starts again on the next config change"))}var u};N({logger:c,shutdown:async()=>{var e;a&&(await(e=a,e.close()),a=null),s&&(await s.close(),s=null),Z(c.info)}}),await d()})}(re),function(e){e.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname; without a value, listen on all addresses").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] no effect with pp-dev next (deprecated)").option("--open [path]","[boolean | string] no effect with pp-dev next (deprecated)").option("--cors","[boolean] no effect with pp-dev next (deprecated)").option("--strictPort","[boolean] no effect with pp-dev next (deprecated)").option("--force","[boolean] no effect with pp-dev next (deprecated)").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(e,o)=>{if(U(o),!function(e=process.env){return"1"===e[K]}())return void await function(e){const{projectRoot:o,logger:n,mode:i="development",checkConfig:r=()=>Q(o,i),startServerProcess:s=Y,createWatcher:a=O,stopTimeoutMs:l=1e4,processRef:c=process}=e;let d=null,p=!1,f=!1,u=null,g=null,h=!1;return new Promise(()=>{const e=async e=>{if(u){const e=u;u=null,await e.close()}c.exit(e)},i=e=>{const o=d;return o?g||(g=new Promise(i=>{if(null!==o.exitCode||null!==o.signalCode)return void i(o.exitCode);const r=setTimeout(()=>{n.warn(t.colors.yellow(`⏰ The dev server did not stop within ${l} ms, killing it`)),o.kill("SIGKILL")},l);o.on("exit",e=>{clearTimeout(r),i(e)}),o.send({type:j,reason:e},()=>{})}).finally(()=>{g=null}),g):Promise.resolve(0)},m=()=>{const i=s();let r;const l=new Promise(e=>r=e);d=i,p=!1,i.on("message",e=>{e?.type===C&&d===i&&(p=!0,f=!0,r(),u||h||(u=a(o,v,n.info)))});let c=!1;const m=(o,s,a)=>{if(c)return;if(c=!0,r(),d===i&&(d=null),g||h)return;const l=p,u=o??1,m=a??s??`code ${u}`;p=!1,l?(n.error(t.colors.red(`❌ The dev server exited (${m})`)),e(u)):f?n.error(t.colors.red(`❌ The dev server did not start after the config change (${m}); fix the config and save it again`)):e(u)};return i.on("exit",(e,t)=>m(e,t)),i.on("error",e=>m(1,null,ee(e))),l},v=async()=>{if(!h){try{await r()}catch(e){return void n.error(t.colors.red(`❌ The pp-dev config could not be loaded, the dev server keeps running: ${ee(e)}`))}await i("a config change"),h||await m()}},w=async t=>{if(h)return;h=!0;const o=await i(t);await e(o??1)};c.on("SIGINT",()=>{w("SIGINT")}),c.on("SIGTERM",()=>{w("SIGTERM")}),c.on("SIGHUP",()=>{w("SIGHUP")}),c.on("exit",()=>{d&&null===d.exitCode&&null===d.signalCode&&d.kill("SIGKILL")}),m()})}({projectRoot:e?P.resolve(process.cwd(),e):process.cwd(),logger:t.createLogger(o.logLevel),mode:o.mode||"development"});const n=M.filter(e=>void 0!==o[e]);let i,s;n.length>0&&t.createLogger(o.logLevel).warn(t.colors.yellow(`⚠️ ${n.map(e=>`--${e}`).join(", ")} ${1===n.length?"has":"have"} no effect with pp-dev next and will be removed.`));try{({host:i,port:s}=function(e,t){let o="localhost";!0===e||""===e?o="0.0.0.0":"string"==typeof e?o=e:"number"==typeof e&&(o=String(e));const n=void 0===t?3e3:"number"==typeof t?t:"string"==typeof t&&t.trim()?Number(t):NaN;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`--port must be a port number (0-65535), got ${JSON.stringify(t)}`);return{host:o,port:n}}(o.host,o.port))}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`❌ ${e.message}`)),process.exit(1)}let l=null,p=null,f=null,u=null;const g=new Set,h=t.createLogger(o.logLevel),m=function(e=["uncaughtException"],t=process){const o=e=>t.listeners(e);let n=null,i=null;return{beforeCreate(){n=new Map(e.map(e=>[e,new Set(o(e))]))},afterCreate(){if(!n)return 0;const r=n,s=new Map(e.map(e=>[e,o(e).filter(t=>!r.get(e).has(t))]));let a=0;if(i)for(const[e,o]of i){const n=new Set(s.get(e).map(e=>e.toString()));for(const i of o)n.has(i.toString())&&(t.off(e,i),a+=1)}return i=s,n=null,a}}}(),v=async()=>{l&&"function"==typeof l.close&&await l.close(),l=null};N({logger:h,knownRejections:[X],shutdown:async()=>{u?.dispose(),u=null,f&&(await f.close(),f=null),await(async()=>{const e=p;if(e){for(const e of g)e.destroy();g.clear(),await new Promise(t=>{e.close(()=>t())}),p===e&&(p=null)}})(),await v()}}),await(async()=>{try{const{next:n,constants:w}=await a.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:b}=w,{createServer:y}=await(import("http")),S=await(import("next/dist/server/config.js")),T=S.default.default||S["module.exports"].default||S.default,L=e?P.resolve(process.cwd(),e):process.cwd();a.loadPPDevEnv(o.mode||"development",L);const E=await T(b,L);let k=E?.ppDev||{};if(0===Object.keys(k).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.config),o=await e(L);Object.keys(o).length>0?(k=o,h.info(t.colors.blue("🔧 Loaded pp-dev config from standalone config file"))):h.info(t.colors.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){h.warn(t.colors.yellow(`⚠️ Failed to load standalone pp-dev config, using defaults: ${e instanceof Error?e.message:String(e)}`))}else h.info(t.colors.blue("🔧 Loaded pp-dev config from Next.js config"));const{getPkg:D}=await Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.config),I=D(L).name;t.validatePPDevConfig(k,I);const F=t.normalizePPDevConfig(k,I),{templateName:$}=F,j=F.backendBaseURL,_=F.templateLess,N=F.v7Features,A=F.disableSSLValidation,R=F.enableProxyCache,M=F.proxyCacheTTL,H=F.personalAccessToken,q=F.miHudLess,O=F.inspectorEnabled,U=F.inspectorMaxMemory,z=F.inspectorCaptureLimit,W=F.appId,G=!0===F.allowedHosts||[...F.allowedHosts,i.toLowerCase()],Z=r.createInternalServer({allowedHosts:F.allowedHosts}),X=E?.basePath;let K="";X?K=X:(K=_?t.PATH_PAGE_PREFIX:N?t.PATH_TEMPLATE_LOCAL_PREFIX:t.PATH_TEMPLATE_PREFIX,K+=`/${$}`);const Y=function(e){const t="1"===process.env.PP_DEV_NEXT_WEBPACK||"true"===process.env.PP_DEV_NEXT_WEBPACK;if(t&&(e.webpack||e.turbopack))throw new Error("Do not combine PP_DEV_NEXT_WEBPACK with --webpack or --turbopack");if(t)return{webpack:!0};if(e.webpack&&e.turbopack)throw new Error("Use only one of --webpack or --turbopack");return e.webpack?{webpack:!0}:e.turbopack?{turbopack:!0}:{}}(o),Q=async e=>{delete process.env.TURBOPACK,await v();const t={dev:!0,customServer:!0,hostname:i,port:s,dir:L,conf:{...E,basePath:K,assetPrefix:K}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),m.beforeCreate(),l=n(t),await l.prepare(),m.afterCreate()};if(Y.webpack)await Q({webpack:!0});else if(Y.turbopack)try{await Q({turbopack:!0})}catch(e){if(!V(e))throw e;h.warn(t.colors.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await Q({webpack:!0})}else try{await Q({})}catch(e){if(!V(e))throw e;h.warn(t.colors.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await Q({webpack:!0})}if(!l)throw new Error("Next.js app failed to initialize");if(K.endsWith("/")||(K+="/"),"/"===K)throw new Error('basePath cannot be equal to "/" or equal to empty string');h.info(t.colors.green("✅ Next.js app prepared successfully")),h.info(t.colors.blue(`🔧 pp-dev plugin configured for template: ${$}`)),h.info(t.colors.blue(`🔧 Base path configured: ${K}`)),j&&(h.info(t.colors.blue(`🌐 Backend URL: ${j}`)),h.info(t.colors.blue(`🆔 Custom App ID: ${W}`)));const ee=l.getRequestHandler(),te=s,oe=i;p=y(async(e,o)=>{const n=e.headers.host;if(!t.isHostAllowed(n,G))return o.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),void o.end(t.hostNotAllowedMessage(n));try{const i=e.url||"/",s=i.split("?")[0];let a=d.parse(i,!0);if(se.length>0){const c=s.startsWith("/_next/")||s.startsWith("/__nextjs_");return void r.runMiddlewareChain(c?ae:se,e,o,()=>{l()})}async function l(){if(s.startsWith(K))a=d.parse(i,!0);else{if(s===K.replace(/\/$/,"")){const e=i.replace(s,K);return o.writeHead(302,{Location:e}),void o.end()}if(s.startsWith("/_next/")||s.startsWith("/__nextjs_"));else if("/"===s)return o.writeHead(302,{Location:K}),void o.end()}await ee(e,o,a)}l()}catch(p){h.error(`Error handling request: ${p instanceof Error?p.message:String(p)}`,{error:p instanceof Error?p:void 0}),o.statusCode=500,o.end("Internal Server Error")}});let ne=null;const ie=(e,o,n)=>{t.isHostAllowed(e.headers.host,G)?ne?ne(e,o,n):p.listeners("upgrade").every(e=>e===ie)&&o.destroy():B(o)};p.on("upgrade",ie);let re=null;const se=[],ae=[];if(!1!==O){const e=new r.RequestStore(U);r.registerInspectorRoutes(Z,e,z);const t=r.createRequestCaptureMiddleware(e,z);se.push(t)}const le=(e,t,o)=>{e.url?.startsWith("/@api/")||e.url?.startsWith(r.INSPECTOR_PATH)||e.url?.startsWith(r.VARIABLES_EDITOR_PATH)?Z(e,t,e=>r.endUnhandledInternalRequest(t,e)):o()};if(j||!1===O||(ae.push(le),se.push(le)),j){const e=new URL(j).host,o=r.createUserHostGuard();ae.unshift(o),se.unshift(o),j.startsWith("https://")&&(c.EventEmitter.defaultMaxListeners=Math.max(c.EventEmitter.defaultMaxListeners,20));const n=r.getMiAPIOptions(j,{appId:W,templateLess:_,disableSSLValidation:A,v7Features:N,personalAccessToken:H});re=new r.MiAPI(j,n);const i=r.initPPRedirect(K,$),s=(e,t,o)=>{i(e,t,o)};ae.push(s),se.push(s);const d=a.createDevPanelAssetMiddleware(K);if(ae.push(d),se.push(d),R){const e=r.resolveProxyCacheTtl(M),o={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},n=r.initProxyCache(o),i=(e,t,o)=>{n(e,t,o)};se.push(i),h.info(t.colors.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const p=r.getIndexPageRegExp(K),g=r.initLoadPPData(p,re,Object.assign({base:K,appBase:K},n,{miHudLess:q})),m=(e,t,o)=>{g(e,t,o)};se.push(m);const v={middlewares:{use:e=>e},config:{logger:console}},b=r.initProxy({devServer:v,baseURL:j,proxyIgnore:[...r.getProxyIgnore(K),"/_next","/__nextjs_","/installHook.js.map"],disableSSLValidation:A,miAPI:re,templateName:$}),y=(e,t,o)=>{b(e,t,o)};se.push(y),ae.push(le),se.push(le);const S=r.initRewriteResponse(e=>{const t=e.split("?")[0];return t.startsWith(K)&&!t.includes("/_next/")},(t,o)=>{const n=re.buildPage(t,q),i=a.injectDevPanel(n,K,{backendBaseURL:j,templateLess:_,appId:W,devPanelPosition:F.devPanelPosition,devPanelHidden:F.devPanelHidden,devPanelAutoHide:F.devPanelAutoHide});return Buffer.from(r.urlReplacer(e,o.headers.host??"",i))},{contentType:e=>e.includes("text/html")}),k=(e,t,o)=>{S(e,t,o)};se.push(k),f=new J({allowedHosts:F.allowedHosts});const D=E?.distDirRoot||(E?.distDir||".next").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),I=!0===E?.ppDevWrapped;let C=D;if(!I)try{const e=await T(w.PHASE_PRODUCTION_BUILD,L);C=e?.distDir||D}catch{}let O,V="0.0.0";try{const e=JSON.parse(x.readFileSync(P.join(L,"package.json"),"utf-8"));V="string"==typeof e.version?e.version:V,O="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const U=new r.DistService($,{root:L,backupFolder:P.resolve(L,F.syncBackupsDir),maxBackups:F.syncMaxBackups,buildTimeoutMs:F.syncBuildTimeoutMs,nextBuild:{projectRoot:L,distDir:D,buildDistDir:C,output:E?.output,configWrapped:I,packageVersion:V,packageRepositoryUrl:O}}),z={ws:f.ws,config:{clientInjectionPlugin:{v7Features:N}}};u=r.startSyncAndUsers({server:z,internalServer:Z,distService:U,miAPI:re,persistUsers:F.persistUsers,projectRoot:L,miUrl:j});const G="function"==typeof l?.getUpgradeHandler?l.getUpgradeHandler():null;ne=(e,t,o)=>{f?.handleUpgrade(e,t,o)||(G?G(e,t,o):t.destroy())},h.info(t.colors.blue(`🔧 ${se.length} pp-dev middlewares initialized`)),h.info(t.colors.blue(`🔧 ${ae.length} essential middlewares for internal routes`)),h.info(t.colors.blue(`🔧 MiAPI initialized for backend: ${j}`)),h.info(t.colors.blue(`🔧 Custom App ID: ${W}`))}p.listen(te,oe,()=>{const e="0.0.0.0"===oe||"::"===oe,o=`http://${e?"localhost":oe}:${te}`;h.info(t.colors.green(`✅ pp-dev Next.js server running at ${o}`)),h.info(t.colors.blue(`📱 Next.js app accessible at ${o}${K}`)),e&&h.info(t.colors.blue("🌐 Listening on all addresses. A page opened from another device needs this machine's address in allowedDevOrigins (next.config) for Next's HMR, as with next dev -H 0.0.0.0.")),!1!==O&&h.info(t.colors.cyan(`🔍 Request Inspector: ${o}${r.INSPECTOR_PATH}`)),h.info(t.colors.blue("🔧 Base path handling active")),p.on("connection",e=>{g.add(e),e.on("close",()=>g.delete(e))}),function(e=process){if("function"!=typeof e.send)return;e.stdout.write("",()=>e.send({type:C},()=>{}))}()})}catch(e){h.error(t.colors.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(h.error(t.colors.red("❌ Next.js Peer Dependency Error:")),h.error(t.colors.red(e.message)),h.error(t.colors.yellow("\n💡 To fix this issue:")),h.error(t.colors.blue(" 1. Install Next.js in your project:")),h.error(t.colors.white(" npm install next@^16")),h.error(t.colors.blue(" 2. Or use yarn:")),h.error(t.colors.white(" yarn add next@^16")),h.error(t.colors.blue(" 3. Or use pnpm:")),h.error(t.colors.white(" pnpm add next@^16")),h.error(t.colors.yellow("\n📖 For more information, see:")),h.error(t.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}})()})}(re),function(e){e.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,o)=>{U(o);const n=R(o),r=a.resolveBuildCliOverrides(o);try{const t=o.mode||"production",{config:s}=await z({root:e,mode:t,command:"build",configFile:o.config,logLevel:o.logLevel,buildOverrides:r}),a=i.mergeConfig(s,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},build:n},!0);if(await i.build(a),o.changelog){const t=e||process.cwd(),n=a.build?.outDir||"dist";let i="dist-zip";a.ppDevConfig&&(!1===a.ppDevConfig.distZip?i=n:"object"==typeof a.ppDevConfig.distZip&&"string"==typeof a.ppDevConfig.distZip.outDir&&(i=a.ppDevConfig.distZip.outDir)),await ne({changelog:o.changelog,executionRoot:t,newAssetsPath:P.resolve(t,n),backupsDirPath:P.resolve(t,a.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:P.resolve(t,i),logLevel:o.logLevel})}}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{Z(e=>t.createLogger(o.logLevel).info(e))}})}(re),function(e){e.command("next-build [root]","build a Next.js app for production (`next build`) and emit VERSION/BUILD-MANIFEST/zip in the same format as `pp-dev build`").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,o)=>{U(o);const n=t.createLogger(o.logLevel),i=e?P.resolve(process.cwd(),e):process.cwd(),s=a.resolveBuildCliOverrides(o);process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]="1";try{a.loadPPDevEnv(o.mode||"production",i);const{constants:e}=await a.safeNextImport(),l=await(import("next/dist/server/config.js")),c=l.default.default||l["module.exports"].default||l.default,d=await c(e.PHASE_PRODUCTION_BUILD,i);let p=d?.ppDev||{};if(0===Object.keys(p).length){const{getConfig:e}=await Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.config);p=await e(i)}const{getPkg:f}=await Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.config),u=f(i).name;t.validatePPDevConfig(p,u);const g=t.normalizePPDevConfig(p,u),h=a.applyDistZipOverride(g.distZip,s,t.createDefaultZipFileName(g.templateName)),m=a.applyVersionManifestOverride(g.versionPlugin,s),v=r.removeStaleDevTypes(i,d);v&&n.info(t.colors.dim(`[pp-dev] Removed stale dev route types: ${P.relative(i,v)}`)),n.info(t.colors.cyan("[pp-dev] Running `next build`...")),await r.runNextBuildProcess(i);const b="string"==typeof d?.distDir&&d.distDir?d.distDir:".next",y=".next"===b?"out":b,S=P.resolve(i,y);if(!x.existsSync(S)||!x.statSync(S).isDirectory())throw new Error(`Next.js build output directory not found: ${S}. "next-build" requires "output: 'export'" in next.config (static export).`);const T=JSON.parse(x.readFileSync(P.join(i,"package.json"),"utf-8"));if(!1!==m&&!1!==m.enabled&&(await w.writeBuildVersionManifest({outDir:S,packageVersion:"string"==typeof T.version?T.version:"0.0.0",versionFileTemplate:m.versionFileTemplate,packageRepositoryUrl:"string"==typeof T.repository?T.repository:T.repository?.url,enabled:m.enabled}),n.info(t.colors.green(`✅ VERSION / BUILD-MANIFEST written to ${P.relative(i,S)}`))),!1!==h){const e=P.resolve(i,h.outDir),o=t.resolveZipSourceDir(i,S,h.inDir),s=t.resolveOutputFilePath(e,h.outFileName,"ZIP output file name");x.mkdirSync(P.dirname(s),{recursive:!0});const a=await r.zipDirectoryToBuffer(o);x.writeFileSync(s,a),n.info(t.colors.green(`✅ Zip archive written to ${P.relative(i,s)}`))}if(o.changelog){const e=!1!==h?h.outDir:y;await ne({changelog:o.changelog,executionRoot:i,newAssetsPath:S,backupsDirPath:P.resolve(i,g.syncBackupsDir),changelogDestinationPath:P.resolve(i,e),logLevel:o.logLevel})}}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{Z(e=>t.createLogger(o.logLevel).info(e))}})}(re),function(e){e.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(e,o,n)=>{U(n);const{oldAssetsPath:i=e,newAssetsPath:r=o,destination:s=".",filename:a="CHANGELOG.html",logLevel:l}=n,c=process.cwd();i&&r||(t.createLogger(l).error(t.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=P.resolve(c,i),p=P.resolve(c,r),f=P.resolve(c,s),u=new oe({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await u.generateChangelog()})}(re),function(e){e.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(e,o,n)=>{U(n);const{source:i=e,destination:r=o,fontName:s="icon-font"}=n,a=process.cwd(),l=P.resolve(a,i),c=P.resolve(a,r),d=new ie({sourceDir:l,outputDir:c,fontName:s}),p=t.createLogger(n.logLevel);p.info(`Generating icon font from SVG files in ${t.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${t.colors.dim(c)}`)})}(re),function(e){e.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{U(o);try{const t=o.mode||"production",{config:n}=await z({root:e,mode:t,command:"serve",configFile:o.config,logLevel:o.logLevel}),r=await i.resolveConfig(i.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode}),"serve");await i.optimizeDeps(r,o.force,!0)}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}})}(re),function(e){e.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,o)=>{U(o);try{const t=o.mode||"production",{config:n}=await z({root:e,mode:t,command:"serve",isPreview:!0,configFile:o.config,logLevel:o.logLevel});(await i.preview(i.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode,build:{outDir:o.outDir},preview:{port:o.port,strictPort:o.strictPort,host:o.host,https:o.https,open:o.open}}))).printUrls()}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{Z(e=>t.createLogger(o.logLevel).info(e))}})}(re),function(e){e.command("migrate [config]","migrate pp-dev config from 0.x flat format to 1.0 grouped format").option("--dry-run","[boolean] print migrated config without writing any files").option("--format <format>","[string] output format: ts (default), js, json").option("--output <file>","[string] output file path (default: pp-dev.config.ts)").option("--no-backup","[boolean] skip backup of original config file").action(async(e,o)=>{const n=t.createLogger(o.logLevel),{isLegacyFlatConfig:i,isLegacyPPWatchConfig:r,isAlreadyMigrated:s,migrateLegacyFlatConfig:a,migratePPWatchConfig:l,generateConfigFileContent:c,discoverMigrateSource:d,loadPackageJsonMigrateConfig:p}=await Promise.resolve().then(()=>require("./migrate-Gi9k9cLw.js")),f=o.format??"ts",u=!1!==o.backup,g=process.cwd(),h=d(g,e);h||(n.warn(t.colors.yellow("No pp-dev or pp-watch config file found in the current directory.")),n.info(t.colors.blue('Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}, or a "pp-dev" field in package.json')),process.exit(1));const{sourceFile:m,isWatchConfig:v,isPackageJsonConfig:w}=h;n.info(t.colors.blue(`Found config: ${P.relative(g,m)}`));const{getPkg:b}=await Promise.resolve().then(()=>require("./index-Ty1d2YCg.js")).then(e=>e.config),y=b();let S,T={};try{if(/\.[cm]?ts$/i.test(m)){const e=await(import("esbuild")),{pathToFileURL:t}=await(import("url")),o=(await e.build({absWorkingDir:g,entryPoints:[m],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,n=`pp-migrate-tmp-${Date.now()}.mjs`;x.writeFileSync(n,o);try{const e=await(import(t(P.resolve(g,n)).toString()));T=e.default?.default??e.default??e}finally{x.existsSync(n)&&x.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(m)){const{pathToFileURL:e}=await(import("url")),t=await(import(e(P.resolve(g,m)).toString()));T=t.default?.default??t.default??t}else w?T=p(m):m.endsWith(".json")&&(T=JSON.parse(x.readFileSync(m,"utf-8")))}catch(e){n.error(t.colors.red(`Failed to load config file: ${e.message}`)),process.exit(1)}T&&"object"==typeof T||(n.error(t.colors.red("Config file did not export a valid object.")),process.exit(1)),s(T)?(n.info(t.colors.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):v||r(T)?(n.info(t.colors.blue("Detected pp-watch config format → migrating to 1.0")),S=l(T)):i(T)?(n.info(t.colors.blue("Detected 0.x flat config format → migrating to 1.0")),S=a(T,y.name)):(n.warn(t.colors.yellow("Could not detect config format. No known keys found.")),process.exit(1));const L=c(S,f),E=o.output??P.join(g,`pp-dev.config.${f}`);if(o.dryRun&&(n.info(t.colors.green(`\n--- Migrated config (dry-run) → ${P.relative(g,E)} ---\n`)),process.stdout.write(`${L}\n`),process.exit(0)),u&&!w&&x.existsSync(m)){const e=`${m}.bak`;x.copyFileSync(m,e),n.info(t.colors.blue(`Backed up original to: ${P.relative(g,e)}`))}x.writeFileSync(E,L,"utf-8"),n.info(t.colors.green(`✅ Migration complete → ${P.relative(g,E)}`)),w?n.info(t.colors.yellow('You can now remove the "pp-dev" field from package.json.')):m!==E&&x.existsSync(m)&&n.info(t.colors.yellow(`You can now delete the old config: ${P.relative(g,m)}`))})}(re),re.help(),re.version(t.VERSION),re.parse(),exports.stopProfiler=Z;
|
|
1
|
+
"use strict";const e=require("cac"),t=require("./auth.provider-C3O8wdGc.js"),o=require("path"),n=require("node:perf_hooks"),i=require("vite"),r=require("./internal.middleware-63EM6Z98.js"),s=require("chokidar"),a=require("./index-DnVkH9ZF.js"),l=require("fs"),c=require("node:events"),d=require("url"),p=require("ws"),f=require("node:child_process"),u=require("dir-compare"),g=require("diff-match-patch"),h=require("isbinaryfile"),m=require("os"),v=require("crypto"),w=require("./version-manifest-fusPAO4h.js");require("picocolors"),require("node:path"),require("ejs"),require("node:net"),require("axios"),require("node:http"),require("node:https"),require("http-proxy-middleware"),require("node:string_decoder"),require("zlib"),require("node:crypto"),require("process"),require("jszip"),require("node:fs"),require("node:fs/promises"),require("child_process"),require("module"),require("node:os"),require("express"),require("node:module"),require("./helpers.js"),require("fs/promises"),require("util");const b=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function y(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const o in e)t[o]=e[o];return t.default=e,Object.freeze(t)}const P=y(o),x=y(l),S=y(u),T=b(g),L=y(m),k=y(v);function E(e){return null!=e&&!1!==e}let D=null;const F=new WeakMap;function I(e,o){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;F.set(e,o);const n=t.createLogger();o.print&&n.info(t.colors.dim(t.colors.green(" ➜"))+t.colors.dim(" press ")+t.colors.bold("h")+t.colors.dim(" to show help"));const i=(o.customShortcuts??[]).filter(E).concat($);D?.(),D=null;let r=!1;const s=process.stdin.isPaused(),a=process.stdin,l=Boolean(a.isRaw),c=async o=>{if(""===o)return void function(e=process){"win32"===e.platform?e.emit("SIGINT","SIGINT"):e.kill(e.pid,"SIGINT")}();if(""===o)return void await e.close().finally(()=>process.exit(0));if(r)return;"h"===o&&n.info(["",t.colors.bold(" Shortcuts"),...i.map(e=>t.colors.dim(" press ")+t.colors.bold(e.key)+t.colors.dim(` to ${e.description}`))].join("\n"));const s=i.find(e=>e.key===o);s&&(r=!0,await s.action(e),r=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",c).setEncoding("utf8").resume();const d=e.httpServer,p=()=>{D===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),s&&process.stdin.pause(),D=null)};D=p,d.on("close",p)}const $=[{key:"r",description:"restart the server",async action(e){const t=F.get(e);await e.restart(),t&&I(e,{...t,print:!1})}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally(()=>process.exit())}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}],C="pp-dev:ready",j="pp-dev:shutdown";function N(e){return e instanceof Error?e.stack??e.message:String(e)}function _({logger:e,knownRejections:o=[],shutdown:n,shutdownTimeoutMs:i=5e3,processRef:r=process}){let s=!1,a=!1,l=0;const c=async(o,c,{repeatable:d=!0}={})=>{if((e=>{l=Math.max(l,e)})(c),s){if(d&&(e=>"SIGINT"===e||"SIGTERM"===e||"SIGHUP"===e)(o)){if(a)return void(a=!1);e.warn(t.colors.yellow(`\n⚠️ Received ${o} again, exiting without waiting for the shutdown`)),r.exit(l)}return}s=!0,a=!d,e.info(t.colors.yellow(`\n🛑 Received ${o}, shutting down gracefully...`));const p=setTimeout(()=>{e.error(t.colors.red(`⏰ Shutdown did not finish within ${i} ms, forcing exit`)),r.exit(1)},i);try{await n(),clearTimeout(p),e.info(t.colors.green("✅ Graceful shutdown completed")),r.exit(l)}catch(o){clearTimeout(p),e.error(t.colors.red(`❌ Error during graceful shutdown: ${N(o)}`)),r.exit(1)}},d=()=>{c("SIGINT",0)},p=()=>{c("SIGTERM",0)},f=()=>{c("SIGHUP",0)},u=o=>{e.error(t.colors.red(`❌ Uncaught exception: ${N(o)}`)),c("uncaughtException",1)},g=n=>{const i=o.find(e=>e.matches(n));i?e.info(t.colors.dim(i.message)):e.error(t.colors.red(`❌ Unhandled promise rejection (the server keeps running): ${N(n)}`))},h=e=>{(function(e){return"object"==typeof e&&null!==e&&e.type===j&&"string"==typeof e.reason})(e)&&c(e.reason,0,{repeatable:!1})},m=()=>{c("the end of the pp-dev process",0,{repeatable:!1})},v="function"==typeof r.send;return r.on("SIGINT",d),r.on("SIGTERM",p),r.on("SIGHUP",f),r.on("uncaughtException",u),r.on("unhandledRejection",g),v&&(r.on("message",h),r.on("disconnect",m)),()=>{r.off("SIGINT",d),r.off("SIGTERM",p),r.off("SIGHUP",f),r.off("uncaughtException",u),r.off("unhandledRejection",g),v&&(r.off("message",h),r.off("disconnect",m))}}const A=["--","c","config","base","l","logLevel","clearScreen","configLoader","profile","d","debug","f","filter","m","mode","force","w","changelog","distZip","distZipDir","distZipFilename","versionManifest","versionFileTemplate","webpack","turbopack"];function M(e){const t={...e};for(const e of A)delete t[e];return"sourcemap"in t&&(t.sourcemap="true"===t.sourcemap||"false"!==t.sourcemap&&t.sourcemap),"watch"in t&&(t.watch=t.watch?{}:void 0),t}const R=["https","open","cors","strictPort","force"];const H=[...t.PP_DEV_CONFIG_NAMES,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"];function q(e){return e instanceof Error?e.stack??e.message:String(e)}function O(e,o,n,i={}){const{debounceMs:r=500}=i,a=P.resolve(e),l=new Set(H),c=s.watch(a,{ignored:(e,t)=>!!t&&(t.isDirectory()?P.resolve(e)!==a:!l.has(P.basename(e))),depth:0,persistent:!0,ignoreInitial:!0,followSymlinks:!1});let d=null,p=!1,f=!1,u=!1;const g=()=>{d&&clearTimeout(d),d=setTimeout(()=>{(async()=>{if(d=null,!u)if(p)f=!0;else{p=!0;try{n(t.colors.yellow("🔄 Restarting dev server due to config change...")),await o()}catch(e){n(t.colors.red(`❌ Failed to restart dev server: ${q(e)}`))}finally{p=!1}f&&!u&&(f=!1,n(t.colors.blue("🔧 Config changed again during the restart")),g())}})()},r)},h=e=>o=>{n(t.colors.blue(`🔧 Config file ${e}: ${P.relative(a,o)}`)),g()};c.on("change",h("changed")),c.on("add",h("added")),c.on("unlink",h("removed")),c.on("error",e=>{n(t.colors.red(`❌ Config watcher error: ${q(e)}`))});const m=new Promise(e=>{c.once("ready",()=>{n(t.colors.blue("🔧 Config file watcher started")),e()})});return{watcher:c,ready:m,async close(){u=!0,d&&(clearTimeout(d),d=null),await c.close()}}}function V(e){if(!e||"object"!=typeof e||!("message"in e))return!1;const t=String(e.message);return/Turbopack is not supported/i.test(t)||/native bindings are not available/i.test(t)||/Only WebAssembly \(WASM\) bindings were loaded/i.test(t)}const z=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};async function U(e){const{root:t,mode:o,command:n,isPreview:r}=e,s=P.resolve(process.cwd(),t??".");a.loadPPDevEnv(o,s);const l=await i.loadConfigFromFile({mode:o,command:n,...r?{isPreview:r}:{}},e.configFile,t,e.logLevel);let c=await a.getViteConfig(e.buildOverrides,{mode:o,root:s});if(l){const e={...l.config};delete e.plugins,c=i.mergeConfig(c,e)}return{config:c,envDir:s}}let W=global.__pp_dev_profile_session,Z=0;const G=e=>{if(W)return new Promise((o,n)=>{W.post("Profiler.stop",(i,{profile:r})=>{if(i)n(i);else{const n=P.resolve(`./pp-dev-profile-${Z++}.cpuprofile`);x.writeFileSync(n,JSON.stringify(r)),e(t.colors.yellow(`CPU profile written to ${t.colors.white(t.colors.dim(n))}`)),W=void 0,o()}})})};function B(e){e.once("error",()=>e.destroy()),e.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n",()=>e.destroy())}class J{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;allowedHosts;constructor({allowedHosts:e=[]}={}){this.allowedHosts=e,this.wss=new p.WebSocketServer({noServer:!0}),this.wss.on("connection",e=>this.onConnection(e)),this.wss.on("error",e=>this.fireLifecycle("error",e)),this.ws={on:(e,t)=>{"close"!==e&&"error"!==e?this.getEventSet(e).add(t):this.getLifecycleSet(e).add(t)},off:(e,t)=>{"close"!==e&&"error"!==e?this.eventListeners.get(e)?.delete(t):this.lifecycleListeners.get(e)?.delete(t)},send:(e,t)=>{if("string"==typeof e)for(const o of this.clients.keys())this.sendToSocket(o,e,t);else{const t=JSON.stringify(e);for(const e of this.clients.keys())e.readyState===p.WebSocket.OPEN&&e.send(t)}}}}handleUpgrade(e,o,n){return(e.url??"").split("?")[0]===r.PP_DEV_HMR_WS_PATH&&(t.crossOriginReason(e,this.allowedHosts)?(B(o),!0):(this.wss.handleUpgrade(e,o,n,t=>{this.wss.emit("connection",t,e)}),!0))}async close(){this.fireLifecycle("close");for(const e of this.clients.keys())e.terminate();this.clients.clear(),await new Promise(e=>this.wss.close(()=>e()))}onConnection(e){const t={send:(t,o)=>this.sendToSocket(e,t,o),socket:e};this.clients.set(e,t),e.on("message",e=>this.onMessage(t,e)),e.on("close",()=>this.clients.delete(e)),e.on("error",()=>{})}onMessage(e,o){let n;try{n=JSON.parse(o.toString())}catch{return}if(!n||"custom"!==n.type||"string"!=typeof n.event)return;const i=this.eventListeners.get(n.event);if(i)for(const o of i)try{o(n.data,e)}catch(e){t.createLogger().error(`ws handler for "${n.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===p.WebSocket.OPEN&&e.send(JSON.stringify({type:"custom",event:t,data:o}))}fireLifecycle(e,t){for(const o of this.lifecycleListeners.get(e)??[])try{o(t)}catch{}}getEventSet(e){let t=this.eventListeners.get(e);return t||(t=new Set,this.eventListeners.set(e,t)),t}getLifecycleSet(e){let t=this.lifecycleListeners.get(e);return t||(t=new Set,this.lifecycleListeners.set(e,t)),t}}const X={matches:e=>e instanceof Error&&"Worker creator already registered"===e.message,message:"Next.js kept its Turbopack worker pool from before the restart ('Worker creator already registered')"};const K="PP_DEV_NEXT_SERVER_PROCESS";function Y(){const[,e,...t]=process.argv;if(!e)throw new Error("pp-dev next: cannot start the server process, no script in process.argv");return f.fork(e,t,{env:{...process.env,[K]:"1"},stdio:"inherit",execArgv:process.execArgv})}async function Q(e,t="development"){const[{loadPPDevEnv:o},{clearConfigCache:n,getConfig:i,getPkg:r},{validatePPDevConfig:s}]=await Promise.all([Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.env),Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.config),Promise.resolve().then(()=>require("./auth.provider-C3O8wdGc.js")).then(e=>e.ppDevConfig)]);o(t,e),n();s(await i(e),r(e).name)}function ee(e){return e instanceof Error?e.message:String(e)}const te=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class oe{oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(e){const{oldAssetsPath:o,newAssetsPath:n,destinationPath:i,changelogTemplate:r,diffFileTemplateHandler:s,diffLineTemplateHandler:a,changelogFilename:l,contextLines:c}=e;if(this.logger=t.createLogger(),!o||!n||!i)throw new Error("Previous assets path, current assets path and destination path are required");if(o===n)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(n))throw new Error(`Current assets path ${n} does not exist`);if(this.isZipFile(o)){const e=P.resolve(L.tmpdir(),k.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(n)){const e=P.resolve(L.tmpdir(),k.createHash("md5").update(n).digest("hex"));this.newAssetsPath=this.unzipFile(n,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(n))throw new Error(`Invalid current assets path ${n}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(n);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${n} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=i,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",r&&(this.templateIsValid(r)?this.changelogTemplate=r:this.logger.warn(t.colors.yellow("Invalid changelog template, using default"))),"function"==typeof s&&(this.diffFileTemplateHandler=s),"function"==typeof a&&(this.diffLineTemplateHandler=a),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return x.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return x.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===x.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){x.existsSync(e)||x.mkdirSync(e,{recursive:!0})}async unzipFile(e,t){x.rmSync(t,{force:!0,recursive:!0}),await r.extractZipSafe(e,t)}normalizeAssetFolderPath(e){const t=x.readdirSync(e);return 1===t.length&&x.lstatSync(P.join(e,t[0])).isDirectory()?this.normalizeAssetFolderPath(P.join(e,t[0])):e}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const t=e.filter((e,t,o)=>0!==e.lineType||(t>=0&&t<this.contextLines||t>o.length-(this.contextLines+1)&&t<=o.length-1||o.slice(t-this.contextLines,t+this.contextLines+1).some(e=>0!==e.lineType))).map((e,t,o)=>{if(t>0){const n=o[t-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]}).flat().map(e=>this.diffLineHTML(e)).join("");return this.diffTableTemplate(t)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:t,lineContent:o,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${r=o??"",r.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var r}diffLineHTML(e){if(this.diffLineTemplateHandler)return this.diffLineTemplateHandler(e);const{lineNumber:t}=e;return-1===t?this.diffLineSkipTemplate():this.diffLineTemplate(e)}diffFileTemplate(e,t){return this.diffFileTemplateHandler?this.diffFileTemplateHandler(e,t):`<div class="diff-file">\n <div class="diff-file-title">${e}</div>\n <div class="diff-file-content">${t}</div>\n </div>`}async generateAssetFoldersDiff(){this.logger.info(t.colors.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await S.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(te.test(e)&&(e=e.replace(te,"$1$3")),te.test(t)&&(t=t.replace(te,"$1$3")),0===e.localeCompare(t)?0:e.localeCompare(t)>0?1:-1)});return e.diffSet?.filter(e=>"equal"!==e.state||e.name1!==e.name2)||[]}async generateAssetFilesDiff(e,t){const o=new T,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let r=0;return i.map(e=>{const[t,o]=e,n=o.endsWith("\n")?o.split("\n").length-1:o.split("\n").length,i=o.split("\n").map((e,o)=>({lineContent:e,lineNumber:r+o+1,lineType:t})).slice(0,n);return-1!==t&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const t=this.pathToPosix(P.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(P.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${o}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const t=e.path1&&e.name1?P.join(e.path1,e.name1):null,o=e.path2&&e.name2?P.join(e.path2,e.name2):null,n=this.pathToPosix(P.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&t)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&o)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&t&&o){const i=this.pathToPosix(P.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(P.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await h.isBinaryFile(t)||await h.isBinaryFile(o)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(x.readFileSync(t,"utf-8"),x.readFileSync(o,"utf-8"))))}return""}async generateChangelog(){this.logger.info(t.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),o=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(t.colors.green("Writing changelog file"));const n=this.changelogTemplate.split("%FILES%");n.splice(1,0,o);const i=n.join("");x.writeFileSync(P.join(this.destinationPath,this.changelogFilename),i),this.logger.info(t.colors.green(`Changelog file written to ${P.join(this.destinationPath,this.changelogFilename)}`))}}async function ne(e){const{changelog:o,executionRoot:n,newAssetsPath:i,backupsDirPath:r,changelogDestinationPath:s,logLevel:a}=e;let l;if("string"==typeof o)l=P.resolve(n,o);else{if(!x.existsSync(r))return void t.createLogger(a).warn(t.colors.yellow("backups directory not found, skipping changelog generation"));const e=x.readdirSync(r,{withFileTypes:!0});if(!e.length)return void t.createLogger(a).warn(t.colors.yellow("no backups found, skipping changelog generation"));const o=e.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!o.length)return void t.createLogger(a).warn(t.colors.yellow("no ZIP backups found, skipping changelog generation"));const n=o.reduce((e,t)=>x.statSync(P.resolve(r,e.name)).mtimeMs>x.statSync(P.resolve(r,t.name)).mtimeMs?e:t).name;l=P.resolve(r,n)}const c=new oe({oldAssetsPath:l,newAssetsPath:i,destinationPath:s});await c.generateChangelog()}class ie{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){const{default:e}=await(import("svgtofont"));await e({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}const re=e.cac("pp-dev");re.option("-c, --config <file>","[string] use specified config file").option("--base <path>","[string] public base path (default: /)").option("-l, --logLevel <level>","[string] info | warn | error | silent").option("--clearScreen","[boolean] allow/disable clear screen when logging").option("-d, --debug [feat]","[string | boolean] show debug logs").option("-f, --filter <filter>","[string] filter debug logs").option("-m, --mode <mode>","[string] set env mode"),function(e){e.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{z(o);let s=null,a=null;const l=e?P.resolve(process.cwd(),e):process.cwd(),c=t.createLogger(o.logLevel),d=async({restart:p=!1}={})=>{let f=null;try{const{clearConfigCache:p,getConfig:g}=await Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.config);p();const{createServer:h}=await(import("vite")),m=o.mode||"development",{config:v,envDir:w}=await U({root:e,mode:m,command:"serve",configFile:o.config,logLevel:o.logLevel}),b=o.base??v.base;if(!b||"/"===b)throw new Error('base cannot be equal to "/" or empty string');if(f=await h(i.mergeConfig(v,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:M(o),customLogger:c},!0)),!f.httpServer)throw new Error("HTTP server not available");if(s){const e=s;s=null,c.info(t.colors.yellow("🛑 Stopping existing dev server...")),await e.close()}await f.listen(),s=f;const y=global.__pp_dev_start_time??!1,P=y?t.colors.dim(`ready in ${t.colors.reset(t.colors.bold(Math.ceil(n.performance.now()-y)))} ms`):"";c.info(`\n ${t.colors.green(`${t.colors.bold("PP-DEV")} v${t.VERSION}`)} ${P}\n`),s.printUrls();const x=await g(w);if(!1!==x.inspector?.enabled){const e=s.resolvedUrls?.local[0],o=e?new URL(e).origin:`http://localhost:${s.config.server.port??5173}`;c.info(`\n ${t.colors.cyan("🔍 Request Inspector")} ${t.colors.dim(o+r.INSPECTOR_PATH)}\n`)}I(s,{print:!0,customShortcuts:[...(u=c.info,W?[{key:"p",description:"start/stop the profiler",async action(){if(W)await G(u);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{W=new e.Session,W.connect(),W.post("Profiler.enable",()=>{W?.post("Profiler.start",()=>{u("Profiler started"),t()})})})}}}]:[]),{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),a||(a=O(l,()=>d({restart:!0}),c.info))}catch(e){if(!p)return c.error(t.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),G(c.info),void process.exit(1);f&&f!==s&&await f.close().catch(()=>{}),c.error(t.colors.red(`❌ Failed to restart dev server:\n${e.stack}`),{error:e}),c.warn(t.colors.yellow(s?"⚠️ The running dev server is kept, with its config, until the next config change":"⚠️ No dev server is running; it starts again on the next config change"))}var u};_({logger:c,shutdown:async()=>{var e;a&&(await(e=a,e.close()),a=null),s&&(await s.close(),s=null),G(c.info)}}),await d()})}(re),function(e){e.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname; without a value, listen on all addresses").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] no effect with pp-dev next (deprecated)").option("--open [path]","[boolean | string] no effect with pp-dev next (deprecated)").option("--cors","[boolean] no effect with pp-dev next (deprecated)").option("--strictPort","[boolean] no effect with pp-dev next (deprecated)").option("--force","[boolean] no effect with pp-dev next (deprecated)").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(e,o)=>{if(z(o),!function(e=process.env){return"1"===e[K]}())return void await function(e){const{projectRoot:o,logger:n,mode:i="development",checkConfig:r=()=>Q(o,i),startServerProcess:s=Y,createWatcher:a=O,stopTimeoutMs:l=1e4,processRef:c=process}=e;let d=null,p=!1,f=!1,u=null,g=null,h=!1;return new Promise(()=>{const e=async e=>{if(u){const e=u;u=null,await e.close()}c.exit(e)},i=e=>{const o=d;return o?g||(g=new Promise(i=>{if(null!==o.exitCode||null!==o.signalCode)return void i(o.exitCode);const r=setTimeout(()=>{n.warn(t.colors.yellow(`⏰ The dev server did not stop within ${l} ms, killing it`)),o.kill("SIGKILL")},l);o.on("exit",e=>{clearTimeout(r),i(e)}),o.send({type:j,reason:e},()=>{})}).finally(()=>{g=null}),g):Promise.resolve(0)},m=()=>{const i=s();let r;const l=new Promise(e=>r=e);d=i,p=!1,i.on("message",e=>{e?.type===C&&d===i&&(p=!0,f=!0,r(),u||h||(u=a(o,v,n.info)))});let c=!1;const m=(o,s,a)=>{if(c)return;if(c=!0,r(),d===i&&(d=null),g||h)return;const l=p,u=o??1,m=a??s??`code ${u}`;p=!1,l?(n.error(t.colors.red(`❌ The dev server exited (${m})`)),e(u)):f?n.error(t.colors.red(`❌ The dev server did not start after the config change (${m}); fix the config and save it again`)):e(u)};return i.on("exit",(e,t)=>m(e,t)),i.on("error",e=>m(1,null,ee(e))),l},v=async()=>{if(!h){try{await r()}catch(e){return void n.error(t.colors.red(`❌ The pp-dev config could not be loaded, the dev server keeps running: ${ee(e)}`))}await i("a config change"),h||await m()}},w=async t=>{if(h)return;h=!0;const o=await i(t);await e(o??1)};c.on("SIGINT",()=>{w("SIGINT")}),c.on("SIGTERM",()=>{w("SIGTERM")}),c.on("SIGHUP",()=>{w("SIGHUP")}),c.on("exit",()=>{d&&null===d.exitCode&&null===d.signalCode&&d.kill("SIGKILL")}),m()})}({projectRoot:e?P.resolve(process.cwd(),e):process.cwd(),logger:t.createLogger(o.logLevel),mode:o.mode||"development"});const n=R.filter(e=>void 0!==o[e]);let i,s;n.length>0&&t.createLogger(o.logLevel).warn(t.colors.yellow(`⚠️ ${n.map(e=>`--${e}`).join(", ")} ${1===n.length?"has":"have"} no effect with pp-dev next and will be removed.`));try{({host:i,port:s}=function(e,t){let o="localhost";!0===e||""===e?o="0.0.0.0":"string"==typeof e?o=e:"number"==typeof e&&(o=String(e));const n=void 0===t?3e3:"number"==typeof t?t:"string"==typeof t&&t.trim()?Number(t):NaN;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`--port must be a port number (0-65535), got ${JSON.stringify(t)}`);return{host:o,port:n}}(o.host,o.port))}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`❌ ${e.message}`)),process.exit(1)}let l=null,p=null,f=null,u=null;const g=new Set,h=t.createLogger(o.logLevel),m=function(e=["uncaughtException"],t=process){const o=e=>t.listeners(e);let n=null,i=null;return{beforeCreate(){n=new Map(e.map(e=>[e,new Set(o(e))]))},afterCreate(){if(!n)return 0;const r=n,s=new Map(e.map(e=>[e,o(e).filter(t=>!r.get(e).has(t))]));let a=0;if(i)for(const[e,o]of i){const n=new Set(s.get(e).map(e=>e.toString()));for(const i of o)n.has(i.toString())&&(t.off(e,i),a+=1)}return i=s,n=null,a}}}(),v=async()=>{l&&"function"==typeof l.close&&await l.close(),l=null};_({logger:h,knownRejections:[X],shutdown:async()=>{u?.dispose(),u=null,f&&(await f.close(),f=null),await(async()=>{const e=p;if(e){for(const e of g)e.destroy();g.clear(),await new Promise(t=>{e.close(()=>t())}),p===e&&(p=null)}})(),await v()}}),await(async()=>{try{const{next:n,constants:w}=await a.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:b}=w,{createServer:y}=await(import("http")),S=await(import("next/dist/server/config.js")),T=S.default.default||S["module.exports"].default||S.default,L=e?P.resolve(process.cwd(),e):process.cwd();a.loadPPDevEnv(o.mode||"development",L),a.clearWithPPDevHandoff();const k=await T(b,L),E=a.readWithPPDevHandoff();let D=k?.ppDev||E?.ppDev||{};if(0===Object.keys(D).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.config),o=await e(L);Object.keys(o).length>0?(D=o,h.info(t.colors.blue("🔧 Loaded pp-dev config from standalone config file"))):h.info(t.colors.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){h.warn(t.colors.yellow(`⚠️ Failed to load standalone pp-dev config, using defaults: ${e instanceof Error?e.message:String(e)}`))}else h.info(t.colors.blue("🔧 Loaded pp-dev config from Next.js config"));const{getPkg:F}=await Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.config),I=F(L).name;t.validatePPDevConfig(D,I);const $=t.normalizePPDevConfig(D,I),{templateName:j}=$,N=$.backendBaseURL,_=$.templateLess,A=$.v7Features,M=$.disableSSLValidation,R=$.enableProxyCache,H=$.proxyCacheTTL,q=$.personalAccessToken,O=$.miHudLess,z=$.inspectorEnabled,U=$.inspectorMaxMemory,W=$.inspectorCaptureLimit,Z=$.appId,G=!0===$.allowedHosts||[...$.allowedHosts,i.toLowerCase()],X=r.createInternalServer({allowedHosts:$.allowedHosts}),K=k?.basePath;let Y="";K?Y=K:(Y=_?t.PATH_PAGE_PREFIX:A?t.PATH_TEMPLATE_LOCAL_PREFIX:t.PATH_TEMPLATE_PREFIX,Y+=`/${j}`);const Q=function(e){const t="1"===process.env.PP_DEV_NEXT_WEBPACK||"true"===process.env.PP_DEV_NEXT_WEBPACK;if(t&&(e.webpack||e.turbopack))throw new Error("Do not combine PP_DEV_NEXT_WEBPACK with --webpack or --turbopack");if(t)return{webpack:!0};if(e.webpack&&e.turbopack)throw new Error("Use only one of --webpack or --turbopack");return e.webpack?{webpack:!0}:e.turbopack?{turbopack:!0}:{}}(o),ee=async e=>{delete process.env.TURBOPACK,await v();const t={dev:!0,customServer:!0,hostname:i,port:s,dir:L,conf:{...k,basePath:Y,assetPrefix:Y}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),m.beforeCreate(),l=n(t),await l.prepare(),m.afterCreate()};if(Q.webpack)await ee({webpack:!0});else if(Q.turbopack)try{await ee({turbopack:!0})}catch(e){if(!V(e))throw e;h.warn(t.colors.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await ee({webpack:!0})}else try{await ee({})}catch(e){if(!V(e))throw e;h.warn(t.colors.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await ee({webpack:!0})}if(!l)throw new Error("Next.js app failed to initialize");if(Y.endsWith("/")||(Y+="/"),"/"===Y)throw new Error('basePath cannot be equal to "/" or equal to empty string');h.info(t.colors.green("✅ Next.js app prepared successfully")),h.info(t.colors.blue(`🔧 pp-dev plugin configured for template: ${j}`)),h.info(t.colors.blue(`🔧 Base path configured: ${Y}`)),N&&(h.info(t.colors.blue(`🌐 Backend URL: ${N}`)),h.info(t.colors.blue(`🆔 Custom App ID: ${Z}`)));const te=l.getRequestHandler(),oe=s,ne=i;p=y(async(e,o)=>{const n=e.headers.host;if(!t.isHostAllowed(n,G))return o.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),void o.end(t.hostNotAllowedMessage(n));try{const i=e.url||"/",s=i.split("?")[0];let a=d.parse(i,!0);if(ae.length>0){const c=s.startsWith("/_next/")||s.startsWith("/__nextjs_");return void r.runMiddlewareChain(c?le:ae,e,o,()=>{l()})}async function l(){if(s.startsWith(Y))a=d.parse(i,!0);else{if(s===Y.replace(/\/$/,"")){const e=i.replace(s,Y);return o.writeHead(302,{Location:e}),void o.end()}if(s.startsWith("/_next/")||s.startsWith("/__nextjs_"));else if("/"===s)return o.writeHead(302,{Location:Y}),void o.end()}await te(e,o,a)}l()}catch(p){h.error(`Error handling request: ${p instanceof Error?p.message:String(p)}`,{error:p instanceof Error?p:void 0}),o.statusCode=500,o.end("Internal Server Error")}});let ie=null;const re=(e,o,n)=>{t.isHostAllowed(e.headers.host,G)?ie?ie(e,o,n):p.listeners("upgrade").every(e=>e===re)&&o.destroy():B(o)};p.on("upgrade",re),N?.startsWith("https://")&&(c.EventEmitter.defaultMaxListeners=Math.max(c.EventEmitter.defaultMaxListeners,20));const se=r.createMiddlewareChain({base:Y,templateName:j,internalServer:X,backendBaseURL:N,mi:{appId:Z,templateLess:_,miHudLess:O,disableSSLValidation:M,v7Features:A,personalAccessToken:q},inspector:{enabled:!1!==z,maxMemory:U,captureLimit:W},proxy:{cache:R,cacheTtl:H,ignore:["/_next","/__nextjs_","/installHook.js.map"]},devPanelAssets:!0,rewrite:(e,o)=>({predicate:e=>{const t=e.split("?")[0];return t.startsWith(Y)&&!t.includes("/_next/")},transform:(n,i)=>{const s=e.buildPage(n,O),a=t.injectDevPanel(s,Y,{backendBaseURL:N,templateLess:_,appId:Z,devPanelPosition:$.devPanelPosition,devPanelHidden:$.devPanelHidden,devPanelAutoHide:$.devPanelAutoHide});return Buffer.from(r.urlReplacer(o,i.headers.host??"",a))},contentType:e=>e.includes("text/html")})}),ae=se.rewrite?[...se.main,se.rewrite]:se.main,le=se.essential;if(null!==se.proxyCacheTtl&&h.info(t.colors.blue(`🔧 Proxy cache middleware added with TTL: ${se.proxyCacheTtl}ms`)),N&&se.mi){const e=se.mi;f=new J({allowedHosts:$.allowedHosts});const o=k?.distDirRoot||(k?.distDir||".next").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),n=!0===k?.ppDevWrapped||!0===E?.wrapped;let i=o;if(!n)try{const e=await T(w.PHASE_PRODUCTION_BUILD,L);i=e?.distDir||o}catch{}let s,a="0.0.0";try{const e=JSON.parse(x.readFileSync(P.join(L,"package.json"),"utf-8"));a="string"==typeof e.version?e.version:a,s="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const c=new r.DistService(j,{root:L,backupFolder:P.resolve(L,$.syncBackupsDir),maxBackups:$.syncMaxBackups,buildTimeoutMs:$.syncBuildTimeoutMs,nextBuild:{projectRoot:L,distDir:o,buildDistDir:i,output:k?.output,configWrapped:n,packageVersion:a,packageRepositoryUrl:s}}),d={ws:f.ws,config:{clientInjectionPlugin:{v7Features:A}}};u=r.startSyncAndUsers({server:d,internalServer:X,distService:c,miAPI:e,persistUsers:$.persistUsers,projectRoot:L,miUrl:N});const p="function"==typeof l?.getUpgradeHandler?l.getUpgradeHandler():null;ie=(e,t,o)=>{f?.handleUpgrade(e,t,o)||(p?p(e,t,o):t.destroy())},h.info(t.colors.blue(`🔧 ${ae.length} pp-dev middlewares initialized`)),h.info(t.colors.blue(`🔧 ${le.length} essential middlewares for internal routes`)),h.info(t.colors.blue(`🔧 MiAPI initialized for backend: ${N}`)),h.info(t.colors.blue(`🔧 Custom App ID: ${Z}`))}p.listen(oe,ne,()=>{const e="0.0.0.0"===ne||"::"===ne,o=`http://${e?"localhost":ne}:${oe}`;h.info(t.colors.green(`✅ pp-dev Next.js server running at ${o}`)),h.info(t.colors.blue(`📱 Next.js app accessible at ${o}${Y}`)),e&&h.info(t.colors.blue("🌐 Listening on all addresses. A page opened from another device needs this machine's address in allowedDevOrigins (next.config) for Next's HMR, as with next dev -H 0.0.0.0.")),!1!==z&&h.info(t.colors.cyan(`🔍 Request Inspector: ${o}${r.INSPECTOR_PATH}`)),h.info(t.colors.blue("🔧 Base path handling active")),p.on("connection",e=>{g.add(e),e.on("close",()=>g.delete(e))}),function(e=process){if("function"!=typeof e.send)return;e.stdout.write("",()=>e.send({type:C},()=>{}))}()})}catch(e){h.error(t.colors.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(h.error(t.colors.red("❌ Next.js Peer Dependency Error:")),h.error(t.colors.red(e.message)),h.error(t.colors.yellow("\n💡 To fix this issue:")),h.error(t.colors.blue(" 1. Install Next.js in your project:")),h.error(t.colors.white(" npm install next@^16")),h.error(t.colors.blue(" 2. Or use yarn:")),h.error(t.colors.white(" yarn add next@^16")),h.error(t.colors.blue(" 3. Or use pnpm:")),h.error(t.colors.white(" pnpm add next@^16")),h.error(t.colors.yellow("\n📖 For more information, see:")),h.error(t.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}})()})}(re),function(e){e.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,o)=>{z(o);const n=M(o),r=a.resolveBuildCliOverrides(o);try{const t=o.mode||"production",{config:s}=await U({root:e,mode:t,command:"build",configFile:o.config,logLevel:o.logLevel,buildOverrides:r}),a=i.mergeConfig(s,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},build:n},!0);if(await i.build(a),o.changelog){const t=e||process.cwd(),n=a.build?.outDir||"dist";let i="dist-zip";a.ppDevConfig&&(!1===a.ppDevConfig.distZip?i=n:"object"==typeof a.ppDevConfig.distZip&&"string"==typeof a.ppDevConfig.distZip.outDir&&(i=a.ppDevConfig.distZip.outDir)),await ne({changelog:o.changelog,executionRoot:t,newAssetsPath:P.resolve(t,n),backupsDirPath:P.resolve(t,a.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:P.resolve(t,i),logLevel:o.logLevel})}}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{G(e=>t.createLogger(o.logLevel).info(e))}})}(re),function(e){e.command("next-build [root]","build a Next.js app for production (`next build`) and emit VERSION/BUILD-MANIFEST/zip in the same format as `pp-dev build`").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,o)=>{z(o);const n=t.createLogger(o.logLevel),i=e?P.resolve(process.cwd(),e):process.cwd(),s=a.resolveBuildCliOverrides(o);process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]="1";try{a.loadPPDevEnv(o.mode||"production",i);const{constants:e}=await a.safeNextImport(),l=await(import("next/dist/server/config.js")),c=l.default.default||l["module.exports"].default||l.default,d=await c(e.PHASE_PRODUCTION_BUILD,i);let p=d?.ppDev||{};if(0===Object.keys(p).length){const{getConfig:e}=await Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.config);p=await e(i)}const{getPkg:f}=await Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.config),u=f(i).name;t.validatePPDevConfig(p,u);const g=t.normalizePPDevConfig(p,u),h=a.applyDistZipOverride(g.distZip,s,t.createDefaultZipFileName(g.templateName)),m=a.applyVersionManifestOverride(g.versionPlugin,s),v=r.removeStaleDevTypes(i,d);v&&n.info(t.colors.dim(`[pp-dev] Removed stale dev route types: ${P.relative(i,v)}`)),n.info(t.colors.cyan("[pp-dev] Running `next build`...")),await r.runNextBuildProcess(i);const b="string"==typeof d?.distDir&&d.distDir?d.distDir:".next",y=".next"===b?"out":b,S=P.resolve(i,y);if(!x.existsSync(S)||!x.statSync(S).isDirectory())throw new Error(`Next.js build output directory not found: ${S}. "next-build" requires "output: 'export'" in next.config (static export).`);const T=JSON.parse(x.readFileSync(P.join(i,"package.json"),"utf-8"));if(!1!==m&&!1!==m.enabled&&(await w.writeBuildVersionManifest({outDir:S,root:i,packageVersion:"string"==typeof T.version?T.version:"0.0.0",versionFileTemplate:m.versionFileTemplate,packageRepositoryUrl:"string"==typeof T.repository?T.repository:T.repository?.url,enabled:m.enabled}),n.info(t.colors.green(`✅ VERSION / BUILD-MANIFEST written to ${P.relative(i,S)}`))),!1!==h){const e=P.resolve(i,h.outDir),o=t.resolveZipSourceDir(i,S,h.inDir),s=t.resolveOutputFilePath(e,h.outFileName,"ZIP output file name");x.mkdirSync(P.dirname(s),{recursive:!0});const a=await r.zipDirectoryToBuffer(o);x.writeFileSync(s,a),n.info(t.colors.green(`✅ Zip archive written to ${P.relative(i,s)}`))}if(o.changelog){const e=!1!==h?h.outDir:y;await ne({changelog:o.changelog,executionRoot:i,newAssetsPath:S,backupsDirPath:P.resolve(i,g.syncBackupsDir),changelogDestinationPath:P.resolve(i,e),logLevel:o.logLevel})}}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{G(e=>t.createLogger(o.logLevel).info(e))}})}(re),function(e){e.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(e,o,n)=>{z(n);const{oldAssetsPath:i=e,newAssetsPath:r=o,destination:s=".",filename:a="CHANGELOG.html",logLevel:l}=n,c=process.cwd();i&&r||(t.createLogger(l).error(t.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=P.resolve(c,i),p=P.resolve(c,r),f=P.resolve(c,s),u=new oe({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await u.generateChangelog()})}(re),function(e){e.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(e,o,n)=>{z(n);const{source:i=e,destination:r=o,fontName:s="icon-font"}=n,a=process.cwd(),l=P.resolve(a,i),c=P.resolve(a,r),d=new ie({sourceDir:l,outputDir:c,fontName:s}),p=t.createLogger(n.logLevel);p.info(`Generating icon font from SVG files in ${t.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${t.colors.dim(c)}`)})}(re),function(e){e.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{z(o);try{const t=o.mode||"production",{config:n}=await U({root:e,mode:t,command:"serve",configFile:o.config,logLevel:o.logLevel}),r=await i.resolveConfig(i.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode}),"serve");await i.optimizeDeps(r,o.force,!0)}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}})}(re),function(e){e.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,o)=>{z(o);try{const t=o.mode||"production",{config:n}=await U({root:e,mode:t,command:"serve",isPreview:!0,configFile:o.config,logLevel:o.logLevel});(await i.preview(i.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode,build:{outDir:o.outDir},preview:{port:o.port,strictPort:o.strictPort,host:o.host,https:o.https,open:o.open}}))).printUrls()}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{G(e=>t.createLogger(o.logLevel).info(e))}})}(re),function(e){e.command("migrate [config]","migrate pp-dev config from 0.x flat format to 1.0 grouped format").option("--dry-run","[boolean] print migrated config without writing any files").option("--format <format>","[string] output format: ts (default), js, json").option("--output <file>","[string] output file path (default: pp-dev.config.ts)").option("--no-backup","[boolean] skip backup of original config file").action(async(e,o)=>{const n=t.createLogger(o.logLevel),{isLegacyFlatConfig:i,isLegacyPPWatchConfig:r,isAlreadyMigrated:s,migrateLegacyFlatConfig:a,migratePPWatchConfig:l,generateConfigFileContent:c,discoverMigrateSource:d,loadPackageJsonMigrateConfig:p}=await Promise.resolve().then(()=>require("./migrate-oVYAMhLH.js")),f=o.format??"ts",u=!1!==o.backup,g=process.cwd(),h=d(g,e);h||(n.warn(t.colors.yellow("No pp-dev or pp-watch config file found in the current directory.")),n.info(t.colors.blue('Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}, or a "pp-dev" field in package.json')),process.exit(1));const{sourceFile:m,isWatchConfig:v,isPackageJsonConfig:w}=h;n.info(t.colors.blue(`Found config: ${P.relative(g,m)}`));const{getPkg:b}=await Promise.resolve().then(()=>require("./index-DnVkH9ZF.js")).then(e=>e.config),y=b();let S,T={};try{if(/\.[cm]?ts$/i.test(m)){const e=await(import("esbuild")),{pathToFileURL:t}=await(import("url")),o=(await e.build({absWorkingDir:g,entryPoints:[m],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,n=`pp-migrate-tmp-${Date.now()}.mjs`;x.writeFileSync(n,o);try{const e=await(import(t(P.resolve(g,n)).toString()));T=e.default?.default??e.default??e}finally{x.existsSync(n)&&x.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(m)){const{pathToFileURL:e}=await(import("url")),t=await(import(e(P.resolve(g,m)).toString()));T=t.default?.default??t.default??t}else w?T=p(m):m.endsWith(".json")&&(T=JSON.parse(x.readFileSync(m,"utf-8")))}catch(e){n.error(t.colors.red(`Failed to load config file: ${e.message}`)),process.exit(1)}T&&"object"==typeof T||(n.error(t.colors.red("Config file did not export a valid object.")),process.exit(1)),s(T)?(n.info(t.colors.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):v||r(T)?(n.info(t.colors.blue("Detected pp-watch config format → migrating to 1.0")),S=l(T)):i(T)?(n.info(t.colors.blue("Detected 0.x flat config format → migrating to 1.0")),S=a(T,y.name)):(n.warn(t.colors.yellow("Could not detect config format. No known keys found.")),process.exit(1));const L=c(S,f),k=o.output??P.join(g,`pp-dev.config.${f}`);if(o.dryRun&&(n.info(t.colors.green(`\n--- Migrated config (dry-run) → ${P.relative(g,k)} ---\n`)),process.stdout.write(`${L}\n`),process.exit(0)),u&&!w&&x.existsSync(m)){const e=`${m}.bak`;x.copyFileSync(m,e),n.info(t.colors.blue(`Backed up original to: ${P.relative(g,e)}`))}x.writeFileSync(k,L,"utf-8"),n.info(t.colors.green(`✅ Migration complete → ${P.relative(g,k)}`)),w?n.info(t.colors.yellow('You can now remove the "pp-dev" field from package.json.')):m!==k&&x.existsSync(m)&&n.info(t.colors.yellow(`You can now delete the old config: ${P.relative(g,m)}`))})}(re),re.help(),re.version(t.VERSION),re.parse(),exports.stopProfiler=G;
|
|
2
2
|
//# sourceMappingURL=cli.js.map
|