@my-life-buddies/cli-refinewidget 0.0.0-stage → 0.37.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ // 注入隔离的 Widget 文档;只允许向宿主发送固定方法,不提供身份、Token 或网络代理。
2
+ ((render) => {
3
+ let counter = 0, closed = false, gesture = 0, callback = null, running = false, changePending = false, scheduled = false;
4
+ // The script runs before the page's own head. Install layout observers once its DOM exists.
5
+ let viewport = { keyboardOpen: false, safeAreaTop: 0, fixedHeight: 0 };
6
+ let layoutMounted = false;
7
+ function applyViewport() {
8
+ if (!layoutMounted) return;
9
+ const root = document.documentElement;
10
+ root.toggleAttribute('data-dada-keyboard-open', viewport.keyboardOpen);
11
+ for (const [property, value] of [['--dada-safe-area-top', viewport.safeAreaTop], ['--dada-fixed-height', viewport.fixedHeight]]) {
12
+ const length = value + 'px';
13
+ if (root.style.getPropertyValue(property) !== length) root.style.setProperty(property, length);
14
+ }
15
+ }
16
+ function mountLayout() {
17
+ layoutMounted = true;
18
+ const root = document.documentElement;
19
+ const style = document.createElement('style');
20
+ style.textContent = `
21
+ html[data-dada-layout="fix"] { overflow-y: hidden !important; }
22
+ html[data-dada-layout="fix"][data-dada-keyboard-open] { overflow-y: auto !important; }
23
+ html[data-dada-layout="fix"][data-dada-keyboard-open] body { overflow-y: visible !important; }
24
+ `;
25
+ document.head.prepend(style);
26
+ applyViewport();
27
+
28
+ const words = (document.querySelector('meta[name="dada-widget-layout" i]')?.content || '').toLowerCase().split(/\s+/u);
29
+ const layoutMode = words.includes('fix') ? 'fix' : 'scroll';
30
+ const immersive = words.includes('immersive');
31
+ root.dataset.dadaLayout = layoutMode;
32
+ let frame = 0, last = '', nestedScroll = false;
33
+ let backgroundColor = '', missingColor = false;
34
+ // iOS samples the composed page background once at load, including :root and dark mode.
35
+ const sample = document.createElement('canvas');
36
+ sample.width = sample.height = 1;
37
+ const ctx = sample.getContext('2d', {willReadFrequently: true});
38
+ if (ctx) {
39
+ for (const element of [root, document.body]) {
40
+ if (!element) continue;
41
+ ctx.fillStyle = getComputedStyle(element).backgroundColor;
42
+ ctx.fillRect(0, 0, 1, 1);
43
+ }
44
+ missingColor = ctx.getImageData(0, 0, 1, 1).data[3] === 0;
45
+ ctx.globalCompositeOperation = 'destination-over';
46
+ ctx.fillStyle = '#ffffff'; // DadaColors.canvas in the iOS host.
47
+ ctx.fillRect(0, 0, 1, 1);
48
+ const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data;
49
+ backgroundColor = `rgb(${r}, ${g}, ${b})`;
50
+ }
51
+ function report() {
52
+ frame = 0;
53
+ const scrollY = Math.max(0, document.scrollingElement?.scrollTop || 0);
54
+ const diagnostics = [];
55
+ if (missingColor) diagnostics.push('请在 html 或 body 声明页面的纯色背景。');
56
+ if (layoutMode === 'scroll' && nestedScroll) diagnostics.push('当前滑动发生在局部容器,请检查整页纵向阅读能否带动聊天。');
57
+ const data = {channel: 'buddy-widget-layout', render, layoutMode, immersive, backgroundColor, scrollY, diagnostics};
58
+ const key = JSON.stringify(data);
59
+ if (key !== last) { last = key; parent.postMessage(data, '*'); }
60
+ }
61
+ function schedule() {
62
+ if (!frame && !closed) frame = window.requestAnimationFrame(report);
63
+ }
64
+ document.addEventListener('scroll', event => {
65
+ const target = event.target;
66
+ if (target === document || target === document.scrollingElement) nestedScroll = false;
67
+ else if (target instanceof Element && target.clientHeight > 0 && target.scrollHeight > target.clientHeight && target.scrollTop > 0) nestedScroll = true;
68
+ schedule();
69
+ }, {capture: true, passive: true});
70
+ report();
71
+ }
72
+ const choiceInputs = new Set(['button', 'checkbox', 'color', 'date', 'datetime-local', 'file', 'hidden', 'image', 'month', 'radio', 'range', 'reset', 'submit', 'time', 'week']);
73
+ document.addEventListener('mousedown', event => {
74
+ // Preserve the chat keyboard on passive canvas/board taps. Native pickers and focusable
75
+ // controls still receive their default action (and prohibited text fields report on focus).
76
+ if (viewport.keyboardOpen && event.target instanceof Element &&
77
+ !event.target.closest('input, select, textarea, [contenteditable], button, a[href], [tabindex], label')) event.preventDefault();
78
+ }, true);
79
+ document.addEventListener('focusin', event => {
80
+ const target = event.composedPath()[0];
81
+ if (!(target instanceof HTMLElement) || target.matches(':disabled') || target.readOnly) return;
82
+ if (target.isContentEditable || target.tagName === 'TEXTAREA' || (target.tagName === 'INPUT' && !choiceInputs.has(target.type))) {
83
+ target.blur();
84
+ parent.postMessage({channel: 'buddy-widget-input-blocked', render}, '*');
85
+ }
86
+ }, true);
87
+ async function changed() {
88
+ if(closed || !callback)return;
89
+ if(running){changePending=true;return;}
90
+ running=true;
91
+ try{do{changePending=false;try{await callback();}catch{}}while(changePending&&callback&&!closed);}finally{running=false;}
92
+ }
93
+ function scheduleChange(){if(scheduled)return;scheduled=true;setTimeout(()=>{scheduled=false;void changed();},0);}
94
+ const pending = new Map();
95
+ const writes = new Set(['submitAction','retryAction','notifyBuddy','records.create','records.update','records.delete']);
96
+ let untrackedWrite = false;
97
+ const unknown = () => Object.assign(new Error('操作结果待核对,请关闭后重新打开查看最新数据'),
98
+ {code:'WIDGET_BRIDGE_RESULT_UNKNOWN',httpStatus:503,status:503,resultState:'unknown',retry:'none'});
99
+ function publicError(error) {
100
+ const result = Object.assign(new Error(error.message || '操作未完成'), {code:error.code,status:error.status});
101
+ for(const [field, values] of [['resultState',['not_submitted','rejected','unknown']],['retry',['none','refresh_then_new_action','query_then_same_action']]])
102
+ if(values.includes(error[field]))result[field]=error[field];
103
+ if(Number.isInteger(error.httpStatus))result.httpStatus=error.httpStatus;
104
+ const handle=error.operation?.operationId?error.operation:error;
105
+ if(typeof handle.operationId==='string'&&/^op_[A-Za-z0-9_-]{8,128}$/.test(handle.operationId)) {
106
+ result.operation={operationId:handle.operationId};result.operationId=handle.operationId;
107
+ if(typeof handle.clientMessageId==='string'&&/^[A-Za-z0-9_-]{8,128}$/.test(handle.clientMessageId))result.clientMessageId=result.operation.clientMessageId=handle.clientMessageId;
108
+ }
109
+ return result;
110
+ }
111
+ document.addEventListener('click', event => { if (event.isTrusted) gesture = Date.now(); }, true);
112
+ function request(method, params = {}) {
113
+ if (closed) return Promise.reject(new Error('小挂件已关闭'));
114
+ if (untrackedWrite && writes.has(method))return Promise.reject(unknown());
115
+ const requestId = `${render}-${++counter}`;
116
+ return new Promise((resolve, reject) => {
117
+ const timer = setTimeout(() => { pending.delete(requestId); if(writes.has(method)){untrackedWrite=true;reject(unknown());}else reject(new Error('读取等待超时,请稍后重试')); }, 90000);
118
+ pending.set(requestId, {resolve, reject, timer, method});
119
+ try { parent.postMessage({channel:'buddy-widget-bridge', render, requestId, method, params}, '*'); }
120
+ catch { pending.delete(requestId);clearTimeout(timer);reject(Object.assign(new Error('小挂件请求参数无法传递'),
121
+ {code:'WIDGET_INVALID_ARGUMENT',httpStatus:400,status:400,resultState:'not_submitted',retry:'none'})); }
122
+ });
123
+ }
124
+ window.addEventListener('message', event => {
125
+ const data = event.data;
126
+ if (closed || event.source !== parent || data?.render !== render) return;
127
+ if (data.channel === 'buddy-widget-viewport') {
128
+ if (typeof data.keyboardOpen === 'boolean' && Number.isFinite(data.safeAreaTop) && data.safeAreaTop >= 0 &&
129
+ Number.isFinite(data.fixedHeight) && data.fixedHeight >= 0) {
130
+ const restoreFixedPage = viewport.keyboardOpen && !data.keyboardOpen;
131
+ viewport = {keyboardOpen: data.keyboardOpen, safeAreaTop: data.safeAreaTop, fixedHeight: data.fixedHeight};
132
+ applyViewport();
133
+ if (restoreFixedPage && layoutMounted && document.documentElement.dataset.dadaLayout === 'fix') {
134
+ document.scrollingElement.scrollTop = 0;
135
+ }
136
+ }
137
+ return;
138
+ }
139
+ if (data.channel !== 'buddy-widget-reply') return;
140
+ if(data.change===true){scheduleChange();return;}
141
+ const call = pending.get(data.requestId); if (!call) return;
142
+ pending.delete(data.requestId); clearTimeout(call.timer);
143
+ if (data.error) {
144
+ const error=publicError(data.error);
145
+ if(writes.has(call.method)&&error.resultState==='unknown'&&!error.operation)untrackedWrite=true;
146
+ call.reject(error);
147
+ }
148
+ else {call.resolve(data.value);if(['records.create','records.update','records.delete','submitAction','retryAction','refresh'].includes(call.method))scheduleChange();}
149
+ });
150
+ const records = Object.freeze({
151
+ list: module => request('records.list', {module}).then(value => value.records),
152
+ get: (module, recordId) => request('records.get', {module, recordId}).then(value => value.record),
153
+ create: (module, data) => request('records.create', {module, data}),
154
+ update: (module, recordId, data, options = {}) => request('records.update', {module, recordId, data, expectedRevision:options.expectedRevision}),
155
+ delete: (module, recordId, options = {}) => request('records.delete', {module, recordId, expectedRevision:options.expectedRevision}),
156
+ });
157
+ const media = Object.freeze({
158
+ url: mediaId => request('media.url', {mediaId}).then(value => value.url),
159
+ pickAndUpload: () => {
160
+ if (Date.now() - gesture > 1000) return Promise.reject(new Error('请点击按钮后选择图片'));
161
+ gesture = 0; return request('media.pickAndUpload');
162
+ },
163
+ });
164
+ Object.defineProperty(window, 'dadaWidget', { value: Object.freeze({version:2, records, media,
165
+ getInfo:()=>request('getInfo'), getTitle:()=>request('getTitle'), getOpenTarget:()=>request('getOpenTarget'),
166
+ getContext:()=>request('getContext'), getCapabilities:()=>request('getCapabilities'),
167
+ refresh:(options={})=>request('refresh',options), notifyBuddy:()=>request('notifyBuddy'),
168
+ submitAction:input=>request('submitAction',input), getActionStatus:handle=>request('getActionStatus',handle), retryAction:handle=>request('retryAction',handle),
169
+ onChange:handler=>{if(typeof handler!=='function')throw new TypeError('onChange requires a function');callback=handler;},
170
+ close: async () => { await request('close'); closed = true; },
171
+ }), configurable:false, writable:false });
172
+ window.addEventListener('load', () => {
173
+ parent.postMessage({channel:'buddy-widget-document', render, state:'ready'}, '*');
174
+ mountLayout();
175
+ }, {once:true});
176
+ })(__WIDGET_RENDER__);
@@ -0,0 +1,212 @@
1
+ // <define:__BUDDY_CLI_LANE_BUILD__>
2
+ var define_BUDDY_CLI_LANE_BUILD_default = { schemaVersion: 1, id: "refinewidgetstyles", origin: "https://buddies-refinewidgetstyles.devops.sl.sit.xiaohongshu.com", command: "buddy-cli-refinewidget", runtimePackage: "@my-life-buddies/buddy-runtime-refinewidget", runtimeTag: "dev", runtimePrerelease: "dev", avatarPackage: "@my-life-buddies/avatar-creator-skill", creatorPackage: "@my-life-buddies/buddy-creator-skill", skillTag: "latest", skillPrerelease: "stable", sourceVersion: "0.37.0-dev.1", distribution: "npm", packageName: "@my-life-buddies/cli-refinewidget", version: "0.37.0-dev.1", validationScope: "mac-config-only" };
3
+
4
+ // packages/cli-core/src/dev/runtime-preflight.ts
5
+ import { parentPort, workerData } from "node:worker_threads";
6
+
7
+ // packages/cli-core/src/config/data-access.ts
8
+ import { lstat, readFile } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ var DATA_ACCESS_FILENAME = "data-access.json";
11
+ function parseDataAccessRequirements(source) {
12
+ if (source === void 0) return [];
13
+ const invalid = (reason) => {
14
+ throw new Error(`${DATA_ACCESS_FILENAME}\uFF1A${reason}`);
15
+ };
16
+ let value;
17
+ try {
18
+ value = JSON.parse(source.replace(/^\uFEFF/u, ""));
19
+ } catch {
20
+ return invalid("\u4E0D\u662F\u6709\u6548 JSON");
21
+ }
22
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => key !== "requirements") || !Array.isArray(value.requirements) || value.requirements.length > 32) {
23
+ return invalid("\u5FC5\u987B\u662F\u4EC5\u5305\u542B requirements \u6570\u7EC4\u7684\u5BF9\u8C61\uFF0C\u6700\u591A\u58F0\u660E 32 \u9879");
24
+ }
25
+ const seen = /* @__PURE__ */ new Set();
26
+ return value.requirements.map((item, index) => {
27
+ if (!item || typeof item !== "object" || Array.isArray(item) || Object.keys(item).some((key) => key !== "id" && key !== "purpose") || !("id" in item) || typeof item.id !== "string" || !item.id.trim() || !("purpose" in item) || typeof item.purpose !== "string" || !item.purpose.trim() || item.purpose.trim().length > 200) {
28
+ return invalid(`requirements[${index}] \u5FC5\u987B\u5305\u542B\u975E\u7A7A id \u548C 1\u2013200 \u5B57\u7684 purpose`);
29
+ }
30
+ const id = item.id.trim(), purpose = item.purpose.trim();
31
+ if (seen.has(id)) return invalid(`\u6570\u636E\u96C6\u4E0D\u80FD\u91CD\u590D\u58F0\u660E\uFF1A${id}`);
32
+ seen.add(id);
33
+ return { id, purpose };
34
+ });
35
+ }
36
+ async function readDataAccessRequirements(projectRoot2) {
37
+ const path = join(projectRoot2, DATA_ACCESS_FILENAME);
38
+ try {
39
+ if (!(await lstat(path)).isFile()) throw new Error(`${DATA_ACCESS_FILENAME} \u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6`);
40
+ return parseDataAccessRequirements(await readFile(path, "utf8"));
41
+ } catch (cause) {
42
+ if (cause.code === "ENOENT") return [];
43
+ throw cause;
44
+ }
45
+ }
46
+
47
+ // packages/cli-core/src/config/runtime-catalog.ts
48
+ import { readFile as readFile2, realpath } from "node:fs/promises";
49
+ import { createRequire } from "node:module";
50
+ import { resolve } from "node:path";
51
+ import { pathToFileURL } from "node:url";
52
+
53
+ // packages/cli-core/src/build-target.ts
54
+ var LANE_BUILD = typeof define_BUDDY_CLI_LANE_BUILD_default === "undefined" ? void 0 : Object.freeze(define_BUDDY_CLI_LANE_BUILD_default);
55
+ var CLI_COMMAND_NAME = LANE_BUILD?.command ?? "buddy-cli-sit";
56
+ var CLI_PACKAGE_NAME = LANE_BUILD?.packageName ?? "@my-life-buddies/cli";
57
+ var CLI_AUTO_UPDATE_AVAILABLE = !LANE_BUILD || LANE_BUILD.distribution === "npm";
58
+ var CLI_WINDOWS_SETUP_AVAILABLE = !LANE_BUILD || LANE_BUILD.distribution === "npm" && LANE_BUILD.validationScope === "windows-candidate";
59
+ var CLI_MAC_SETUP_AVAILABLE = !LANE_BUILD || LANE_BUILD.distribution === "npm" && LANE_BUILD.validationScope === "windows-candidate";
60
+ var CLI_MAC_INSTALL_COMMAND = `npx --yes --registry=https://registry.npmjs.org/ --@my-life-buddies:registry=https://registry.npmjs.org/ --package=${CLI_PACKAGE_NAME}@dev ${CLI_COMMAND_NAME} setup`;
61
+ var CLI_WINDOWS_INSTALL_COMMAND = `cmd /d /c "npx --yes --registry=https://registry.npmjs.org/ --@my-life-buddies:registry=https://registry.npmjs.org/ --package=${CLI_PACKAGE_NAME}@dev ${CLI_COMMAND_NAME} setup"`;
62
+ var PLATFORM_ORIGIN = LANE_BUILD?.origin ?? "https://buddies.sit.dots.chat";
63
+ var RUNTIME_PACKAGE_NAME = LANE_BUILD?.runtimePackage ?? "@my-life-buddies/buddy-runtime";
64
+ var RUNTIME_DIST_TAG = LANE_BUILD?.runtimeTag ?? "dev";
65
+ var RUNTIME_SOURCE_LABEL = LANE_BUILD ? `${RUNTIME_PACKAGE_NAME} \u7684 npm ${RUNTIME_DIST_TAG}` : "npm dev";
66
+ var AVATAR_PACKAGE_NAME = LANE_BUILD?.avatarPackage ?? "@my-life-buddies/avatar-creator-skill";
67
+ var CREATOR_PACKAGE_NAME = LANE_BUILD?.creatorPackage ?? "@my-life-buddies/buddy-creator-skill";
68
+ var SKILL_DIST_TAG = LANE_BUILD?.skillTag ?? "latest";
69
+ var SKILL_VERSION_POLICY = LANE_BUILD?.skillPrerelease ?? "stable";
70
+ var CREATOR_SOURCE_LABEL = LANE_BUILD ? `${CREATOR_PACKAGE_NAME} \u7684\u516C\u5171 npm ${SKILL_DIST_TAG}` : "\u516C\u5171 npm latest";
71
+ var CLI_UPDATE_GUIDANCE = CLI_AUTO_UPDATE_AVAILABLE ? `\u6B63\u5E38\u547D\u4EE4\u5148\u8054\u7F51\u68C0\u67E5 ${CLI_PACKAGE_NAME} \u7684 dev \u7248\u672C\uFF0C\u65E7\u7248\u81EA\u52A8\u66F4\u65B0\u540E\u7EE7\u7EED\u6267\u884C\uFF1B\u5931\u8D25\u65F6\u505C\u6B62\u3002\u5E2E\u52A9\u3001--version \u548C dev stop \u79BB\u7EBF\u53EF\u7528\u3002\u53EF\u7528 ${CLI_COMMAND_NAME} update --check \u68C0\u67E5\u7248\u672C\uFF0C\u6216 ${CLI_COMMAND_NAME} update \u5355\u72EC\u66F4\u65B0\u3002` : "\u672C\u5730\u6CF3\u9053\u6D4B\u8BD5\u5236\u54C1\u5DF2\u7981\u7528\u81EA\u52A8\u66F4\u65B0\u3001update \u548C setup\uFF1B\u66F4\u6362\u7248\u672C\u987B\u91CD\u65B0\u5B89\u88C5\u540C\u6CF3\u9053\u6D4B\u8BD5\u5236\u54C1\u3002";
72
+
73
+ // packages/cli-core/src/config/runtime-dependency.ts
74
+ var BUDDY_RUNTIME_PACKAGE = "@my-life-buddies/buddy-runtime";
75
+ function isExactRuntimeVersion(value) {
76
+ return typeof value === "string" && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?$/u.test(value);
77
+ }
78
+ function isSelectedRuntimeVersion(value) {
79
+ return isExactRuntimeVersion(value) && (!LANE_BUILD || new RegExp(`^\\d+\\.\\d+\\.\\d+-${LANE_BUILD.runtimePrerelease}\\.\\d+$`, "u").test(value));
80
+ }
81
+ function assertInstalledRuntimeIdentity(pkg, expected) {
82
+ if (!LANE_BUILD) {
83
+ assertRuntimeHostCompatibility(pkg);
84
+ return;
85
+ }
86
+ const manifest = pkg;
87
+ if (!manifest || manifest.name !== RUNTIME_PACKAGE_NAME || !isSelectedRuntimeVersion(manifest.version) || expected !== void 0 && manifest.version !== expected) {
88
+ throw new Error(`Runtime \u5236\u54C1\u8EAB\u4EFD\u4E0D\u5339\u914D\uFF0C\u8981\u6C42 ${RUNTIME_PACKAGE_NAME}${expected ? `@${expected}` : " \u7684\u51C6\u786E\u7248\u672C"}`);
89
+ }
90
+ assertRuntimeHostCompatibility(pkg);
91
+ }
92
+ function runtimeDependencyVersion(pkg) {
93
+ if (typeof pkg !== "object" || pkg === null || !("dependencies" in pkg)) return void 0;
94
+ const dependencies = pkg.dependencies;
95
+ if (typeof dependencies !== "object" || dependencies === null || !(BUDDY_RUNTIME_PACKAGE in dependencies)) return void 0;
96
+ const declared = dependencies[BUDDY_RUNTIME_PACKAGE];
97
+ const prefix = `npm:${RUNTIME_PACKAGE_NAME}@`;
98
+ const version = LANE_BUILD ? typeof declared === "string" && declared.startsWith(prefix) ? declared.slice(prefix.length) : void 0 : declared;
99
+ return isSelectedRuntimeVersion(version) ? version : void 0;
100
+ }
101
+ function assertRuntimeHostCompatibility(pkg, platform = process.platform) {
102
+ if (platform !== "win32") return;
103
+ const capability = pkg?.buddyRuntime?.windowsCompatibility;
104
+ if (capability !== 1) throw new Error("\u6B64 Runtime \u5236\u54C1\u5C1A\u672A\u58F0\u660E Windows \u517C\u5BB9\u3002\u8BF7\u5B89\u88C5\u5DF2\u53D1\u5E03\u7684 Windows \u517C\u5BB9 Runtime\uFF0C\u5E76\u540C\u6B65\u5DE5\u7A0B\u4F9D\u8D56\u548C\u9501\u6587\u4EF6\uFF1B\u4E0D\u4F1A\u6539\u5199\u5DF2\u6709\u5DE5\u7A0B\u3002");
105
+ }
106
+
107
+ // packages/cli-core/src/config/runtime-catalog.ts
108
+ async function loadRuntime(projectRoot2) {
109
+ const packagePath = resolve(projectRoot2, "package.json");
110
+ const expected = runtimeDependencyVersion(JSON.parse((await readFile2(packagePath, "utf8")).replace(/^\uFEFF/u, "")));
111
+ if (!expected) throw new Error(`package.json \u5FC5\u987B\u58F0\u660E ${BUDDY_RUNTIME_PACKAGE} \u7684\u51C6\u786E\u7248\u672C`);
112
+ const projectRequire = createRequire(packagePath);
113
+ let runtimePath;
114
+ try {
115
+ const installedPath = await realpath(resolve(projectRoot2, "node_modules", BUDDY_RUNTIME_PACKAGE, "package.json"));
116
+ if (await realpath(projectRequire.resolve(`${BUDDY_RUNTIME_PACKAGE}/package.json`)) !== installedPath) {
117
+ throw new Error("Runtime \u5FC5\u987B\u5B89\u88C5\u5728\u5F53\u524D\u5DE5\u7A0B\u4E2D");
118
+ }
119
+ const installed = JSON.parse((await readFile2(installedPath, "utf8")).replace(/^\uFEFF/u, ""));
120
+ assertInstalledRuntimeIdentity(installed, expected);
121
+ if (installed.version !== expected) throw new Error(`\u5DF2\u5B89\u88C5 ${installed.version}\uFF0C\u5DE5\u7A0B\u8981\u6C42 ${expected}`);
122
+ runtimePath = projectRequire.resolve(BUDDY_RUNTIME_PACKAGE);
123
+ } catch (cause) {
124
+ throw new Error(`\u5DE5\u7A0B\u7684 Runtime \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5\uFF0C\u8BF7\u6309\u9501\u6587\u4EF6\u5B89\u88C5\u4F9D\u8D56\uFF1A${cause instanceof Error ? cause.message : String(cause)}`);
125
+ }
126
+ const runtime = await import(pathToFileURL(runtimePath).href);
127
+ return { runtime, runtimeVersion: expected, runtimePath };
128
+ }
129
+ async function readRuntimeDataCatalog(projectRoot2) {
130
+ const { runtime, runtimeVersion: expected } = await loadRuntime(projectRoot2);
131
+ const catalog = runtime.DATA_ACCESS_CAPABILITIES;
132
+ if (!Array.isArray(catalog)) {
133
+ throw new Error(`\u5DE5\u7A0B\u7684 Runtime ${expected} \u672A\u5BFC\u51FA DATA_ACCESS_CAPABILITIES\uFF0C\u8BF7\u4F7F\u7528\u5305\u542B\u6570\u636E\u76EE\u5F55\u7684\u65B0 Runtime \u5305\u3002`);
134
+ }
135
+ const seen = /* @__PURE__ */ new Set();
136
+ const datasets = catalog.map((value) => {
137
+ if (!value || typeof value !== "object") throw new Error("Runtime \u6570\u636E\u76EE\u5F55\u683C\u5F0F\u65E0\u6548");
138
+ const item = value;
139
+ if (typeof item.id !== "string" || !item.id.trim() || seen.has(item.id) || typeof item.title !== "string" || !item.title.trim() || typeof item.source !== "string" || !item.source.trim() || !Number.isSafeInteger(item.schemaVersion) || item.schemaVersion < 1) {
140
+ throw new Error("Runtime \u6570\u636E\u76EE\u5F55\u683C\u5F0F\u65E0\u6548\u6216\u5305\u542B\u91CD\u590D ID");
141
+ }
142
+ seen.add(item.id);
143
+ return Object.freeze({ id: item.id, title: item.title, source: item.source, schemaVersion: item.schemaVersion });
144
+ });
145
+ return Object.freeze({ runtimeVersion: expected, datasets: Object.freeze(datasets) });
146
+ }
147
+ async function validateRuntimeDatasets(projectRoot2, requirements = []) {
148
+ const catalog = await readRuntimeDataCatalog(projectRoot2);
149
+ const ids = new Set(catalog.datasets.map((item) => item.id));
150
+ for (const [index, item] of requirements.entries()) {
151
+ if (!ids.has(item.id)) throw new Error(`data-access.json/requirements/${index}/id\uFF1A\u5DE5\u7A0B Runtime ${catalog.runtimeVersion} \u4E0D\u652F\u6301 ${item.id}`);
152
+ }
153
+ }
154
+
155
+ // packages/cli-core/src/config/image-templates.ts
156
+ import { lstat as lstat2, readdir, open, realpath as realpath2 } from "node:fs/promises";
157
+ import { constants } from "node:fs";
158
+ import { join as join2 } from "node:path";
159
+ async function captureImageTemplates(projectRoot2) {
160
+ projectRoot2 = await realpath2(projectRoot2);
161
+ const files = {};
162
+ let total = 0, count = 0, visited = 0;
163
+ async function walk(relative) {
164
+ if (++visited > 1024 || relative.split("/").length > 16) throw new Error("\u56FE\u7247\u6A21\u677F\u76EE\u5F55\u6570\u91CF\u6216\u5C42\u7EA7\u8D85\u9650");
165
+ const p = join2(projectRoot2, relative), stat = await lstat2(p);
166
+ if (stat.isSymbolicLink()) throw new Error("\u56FE\u7247\u6A21\u677F\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5");
167
+ if (stat.isDirectory()) {
168
+ for (const entry of await readdir(p)) {
169
+ if (entry.startsWith(".")) throw new Error("\u56FE\u7247\u6A21\u677F\u4E0D\u5141\u8BB8\u9690\u85CF\u8D44\u6E90");
170
+ await walk(`${relative}/${entry}`);
171
+ }
172
+ return;
173
+ }
174
+ const fileLimit = relative.endsWith(".ttf") ? 16 * 1024 * 1024 : 2 * 1024 * 1024;
175
+ if (!stat.isFile() || stat.size > fileLimit || ++count > 464 || (total += stat.size) > 64 * 1024 * 1024) throw new Error("\u56FE\u7247\u6A21\u677F\u8D44\u6E90\u8D85\u9650");
176
+ if (await realpath2(p) !== p) throw new Error("\u56FE\u7247\u6A21\u677F\u8D44\u6E90\u8DEF\u5F84\u53D1\u751F\u53D8\u5316");
177
+ const fd = await open(p, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
178
+ try {
179
+ const current = await fd.stat();
180
+ if (current.ino !== stat.ino || current.dev !== stat.dev || !current.isFile()) throw new Error("\u6A21\u677F\u8D44\u6E90\u8BFB\u53D6\u65F6\u53D1\u751F\u53D8\u5316");
181
+ const b = await fd.readFile();
182
+ if (b.length !== stat.size || await realpath2(p) !== p) throw new Error("\u8BFB\u53D6\u65F6\u6A21\u677F\u6587\u4EF6\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5");
183
+ files[relative] = b;
184
+ } finally {
185
+ await fd.close();
186
+ }
187
+ }
188
+ try {
189
+ await lstat2(join2(projectRoot2, "image-templates"));
190
+ } catch (e) {
191
+ if (e.code === "ENOENT") return files;
192
+ throw e;
193
+ }
194
+ await walk("image-templates");
195
+ return files;
196
+ }
197
+ async function validateRuntimeImageTemplates(projectRoot2, snapshot) {
198
+ const files = snapshot ?? await captureImageTemplates(projectRoot2);
199
+ if (!Object.keys(files).length) return [];
200
+ const { runtime, runtimeVersion } = await loadRuntime(projectRoot2);
201
+ if (typeof runtime.inspectImageTemplates !== "function") throw new Error(`\u5DE5\u7A0B Runtime ${runtimeVersion} \u5C1A\u672A\u63D0\u4F9B\u56FE\u7247\u6A21\u677F\u6821\u9A8C\u5668\uFF1B\u8BF7\u7B49\u5F85\u5E73\u53F0\u53D1\u5E03\u5305\u542B\u8BE5\u80FD\u529B\u7684 Runtime\uFF0C\u4E0D\u8981\u7ED5\u8FC7\u7248\u672C\u68C0\u67E5`);
202
+ const result = runtime.inspectImageTemplates(files);
203
+ if (!Array.isArray(result) || result.length > 8 || result.some((v) => !v || typeof v.id !== "string" || typeof v.version !== "string" || !/^[a-f0-9]{64}$/.test(v.revision))) throw new Error("Runtime \u8FD4\u56DE\u7684\u6A21\u677F\u6E05\u5355\u4E0D\u5408\u6CD5");
204
+ return result;
205
+ }
206
+
207
+ // packages/cli-core/src/dev/runtime-preflight.ts
208
+ var projectRoot = workerData;
209
+ await validateRuntimeDatasets(projectRoot, await readDataAccessRequirements(projectRoot));
210
+ await validateRuntimeImageTemplates(projectRoot);
211
+ parentPort.postMessage("validated");
212
+ //# sourceMappingURL=runtime-preflight.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["<define:__BUDDY_CLI_LANE_BUILD__>", "../../../../../.codex/worktrees/widget-style-cli/cli/packages/cli-core/src/dev/runtime-preflight.ts", "../../../../../.codex/worktrees/widget-style-cli/cli/packages/cli-core/src/config/data-access.ts", "../../../../../.codex/worktrees/widget-style-cli/cli/packages/cli-core/src/config/runtime-catalog.ts", "../../../../../.codex/worktrees/widget-style-cli/cli/packages/cli-core/src/build-target.ts", "../../../../../.codex/worktrees/widget-style-cli/cli/packages/cli-core/src/config/runtime-dependency.ts", "../../../../../.codex/worktrees/widget-style-cli/cli/packages/cli-core/src/config/image-templates.ts"],
4
+ "sourcesContent": ["{\"schemaVersion\":1,\"id\":\"refinewidgetstyles\",\"origin\":\"https://buddies-refinewidgetstyles.devops.sl.sit.xiaohongshu.com\",\"command\":\"buddy-cli-refinewidget\",\"runtimePackage\":\"@my-life-buddies/buddy-runtime-refinewidget\",\"runtimeTag\":\"dev\",\"runtimePrerelease\":\"dev\",\"avatarPackage\":\"@my-life-buddies/avatar-creator-skill\",\"creatorPackage\":\"@my-life-buddies/buddy-creator-skill\",\"skillTag\":\"latest\",\"skillPrerelease\":\"stable\",\"sourceVersion\":\"0.37.0-dev.1\",\"distribution\":\"npm\",\"packageName\":\"@my-life-buddies/cli-refinewidget\",\"version\":\"0.37.0-dev.1\",\"validationScope\":\"mac-config-only\"}", "import { parentPort, workerData } from \"node:worker_threads\";\nimport { readDataAccessRequirements } from \"../config/data-access.js\";\nimport { validateRuntimeDatasets } from \"../config/runtime-catalog.js\";\nimport { validateRuntimeImageTemplates } from \"../config/image-templates.js\";\n\nconst projectRoot: string = workerData;\nawait validateRuntimeDatasets(projectRoot, await readDataAccessRequirements(projectRoot));\nawait validateRuntimeImageTemplates(projectRoot);\nparentPort!.postMessage(\"validated\");\n", "import { lstat, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport const DATA_ACCESS_FILENAME = \"data-access.json\";\nexport interface BuddyDatasetRequirement { id: string; purpose: string }\n\n/** Match Runtime 0.17's file contract. Capability IDs are checked against the installed SDK. */\nexport function parseDataAccessRequirements(source: string | undefined): BuddyDatasetRequirement[] {\n if (source === undefined) return [];\n const invalid = (reason: string): never => { throw new Error(`${DATA_ACCESS_FILENAME}\uFF1A${reason}`); };\n let value;\n try { value = JSON.parse(source.replace(/^\\uFEFF/u, \"\")); } catch { return invalid(\"\u4E0D\u662F\u6709\u6548 JSON\"); }\n if (!value || typeof value !== \"object\" || Array.isArray(value)\n || Object.keys(value).some(key => key !== \"requirements\")\n || !Array.isArray(value.requirements) || value.requirements.length > 32) {\n return invalid(\"\u5FC5\u987B\u662F\u4EC5\u5305\u542B requirements \u6570\u7EC4\u7684\u5BF9\u8C61\uFF0C\u6700\u591A\u58F0\u660E 32 \u9879\");\n }\n const seen = new Set<string>();\n return value.requirements.map((item: unknown, index: number) => {\n if (!item || typeof item !== \"object\" || Array.isArray(item)\n || Object.keys(item).some(key => key !== \"id\" && key !== \"purpose\")\n || !(\"id\" in item) || typeof item.id !== \"string\" || !item.id.trim()\n || !(\"purpose\" in item) || typeof item.purpose !== \"string\"\n || !item.purpose.trim() || item.purpose.trim().length > 200) {\n return invalid(`requirements[${index}] \u5FC5\u987B\u5305\u542B\u975E\u7A7A id \u548C 1\u2013200 \u5B57\u7684 purpose`);\n }\n const id = item.id.trim(), purpose = item.purpose.trim();\n if (seen.has(id)) return invalid(`\u6570\u636E\u96C6\u4E0D\u80FD\u91CD\u590D\u58F0\u660E\uFF1A${id}`);\n seen.add(id);\n return { id, purpose };\n });\n}\n\nexport async function readDataAccessRequirements(projectRoot: string): Promise<BuddyDatasetRequirement[]> {\n const path = join(projectRoot, DATA_ACCESS_FILENAME);\n try {\n if (!(await lstat(path)).isFile()) throw new Error(`${DATA_ACCESS_FILENAME} \u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6`);\n return parseDataAccessRequirements(await readFile(path, \"utf8\"));\n } catch (cause) {\n // Runtime deliberately uploads [] for a missing file to clear old declarations.\n if ((cause as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw cause;\n }\n}\n", "import { readFile, realpath } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { assertInstalledRuntimeIdentity, BUDDY_RUNTIME_PACKAGE, runtimeDependencyVersion } from \"./runtime-dependency.js\";\nimport type { BuddyDatasetRequirement } from \"./data-access.js\";\n\nexport interface RuntimeDataCapability {\n readonly id: string;\n readonly title: string;\n readonly source: string;\n readonly schemaVersion: number;\n}\n\n/** Load the project's SDK export, never the CLI's dependency tree or an HTTP catalog. */\nexport async function loadRuntime(projectRoot: string) {\n const packagePath = resolve(projectRoot, \"package.json\");\n const expected = runtimeDependencyVersion(JSON.parse((await readFile(packagePath, \"utf8\")).replace(/^\\uFEFF/u, \"\")));\n if (!expected) throw new Error(`package.json \u5FC5\u987B\u58F0\u660E ${BUDDY_RUNTIME_PACKAGE} \u7684\u51C6\u786E\u7248\u672C`);\n const projectRequire = createRequire(packagePath);\n let runtimePath: string;\n try {\n const installedPath = await realpath(resolve(projectRoot, \"node_modules\", BUDDY_RUNTIME_PACKAGE, \"package.json\"));\n if (await realpath(projectRequire.resolve(`${BUDDY_RUNTIME_PACKAGE}/package.json`)) !== installedPath) {\n throw new Error(\"Runtime \u5FC5\u987B\u5B89\u88C5\u5728\u5F53\u524D\u5DE5\u7A0B\u4E2D\");\n }\n const installed = JSON.parse((await readFile(installedPath, \"utf8\")).replace(/^\\uFEFF/u, \"\"));\n assertInstalledRuntimeIdentity(installed, expected);\n if (installed.version !== expected) throw new Error(`\u5DF2\u5B89\u88C5 ${installed.version}\uFF0C\u5DE5\u7A0B\u8981\u6C42 ${expected}`);\n runtimePath = projectRequire.resolve(BUDDY_RUNTIME_PACKAGE);\n } catch (cause) {\n throw new Error(`\u5DE5\u7A0B\u7684 Runtime \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5\uFF0C\u8BF7\u6309\u9501\u6587\u4EF6\u5B89\u88C5\u4F9D\u8D56\uFF1A${cause instanceof Error ? cause.message : String(cause)}`);\n }\n const runtime = await import(pathToFileURL(runtimePath).href);\n return { runtime, runtimeVersion: expected, runtimePath };\n}\n\nexport async function readRuntimeDataCatalog(projectRoot: string): Promise<{\n readonly runtimeVersion: string;\n readonly datasets: readonly RuntimeDataCapability[];\n}> {\n const { runtime, runtimeVersion: expected } = await loadRuntime(projectRoot);\n const catalog: unknown = runtime.DATA_ACCESS_CAPABILITIES;\n if (!Array.isArray(catalog)) {\n throw new Error(`\u5DE5\u7A0B\u7684 Runtime ${expected} \u672A\u5BFC\u51FA DATA_ACCESS_CAPABILITIES\uFF0C\u8BF7\u4F7F\u7528\u5305\u542B\u6570\u636E\u76EE\u5F55\u7684\u65B0 Runtime \u5305\u3002`);\n }\n const seen = new Set<string>();\n const datasets = catalog.map((value: unknown): RuntimeDataCapability => {\n if (!value || typeof value !== \"object\") throw new Error(\"Runtime \u6570\u636E\u76EE\u5F55\u683C\u5F0F\u65E0\u6548\");\n const item = value as Record<string, unknown>;\n if (typeof item.id !== \"string\" || !item.id.trim() || seen.has(item.id)\n || typeof item.title !== \"string\" || !item.title.trim()\n || typeof item.source !== \"string\" || !item.source.trim()\n || !Number.isSafeInteger(item.schemaVersion) || (item.schemaVersion as number) < 1) {\n throw new Error(\"Runtime \u6570\u636E\u76EE\u5F55\u683C\u5F0F\u65E0\u6548\u6216\u5305\u542B\u91CD\u590D ID\");\n }\n seen.add(item.id);\n return Object.freeze({ id: item.id, title: item.title, source: item.source, schemaVersion: item.schemaVersion as number });\n });\n return Object.freeze({ runtimeVersion: expected, datasets: Object.freeze(datasets) });\n}\n\nexport async function readRuntimeModelCatalog(projectRoot: string): Promise<{\n readonly runtimeVersion: string;\n readonly models: readonly string[];\n}> {\n const { runtime, runtimeVersion, runtimePath } = await loadRuntime(projectRoot);\n let models: unknown = runtime.MODEL_IDS;\n if (models === undefined) {\n // Published 0.11/0.12 packages expose this enum in dist/model.js only.\n // Prefer the public export when available; never substitute a CLI enum.\n try { models = (await import(new URL(\"./model.js\", pathToFileURL(runtimePath)).href)).MODEL_IDS; }\n catch (cause) { throw new Error(`Runtime ${runtimeVersion} \u7684\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u8BFB\u53D6\uFF1A${cause instanceof Error ? cause.message : String(cause)}`); }\n }\n if (!Array.isArray(models) || models.length === 0\n || models.some(id => typeof id !== \"string\" || !id.trim()) || new Set(models).size !== models.length) {\n throw new Error(`Runtime ${runtimeVersion} \u7684 MODEL_IDS \u7F3A\u5931\u6216\u683C\u5F0F\u65E0\u6548`);\n }\n return Object.freeze({ runtimeVersion, models: Object.freeze([...models]) });\n}\n\nexport async function validateRuntimeModel(projectRoot: string, model: string | undefined): Promise<void> {\n if (model === undefined) return;\n const catalog = await readRuntimeModelCatalog(projectRoot);\n if (!catalog.models.includes(model)) throw new Error(`/model\uFF1A\u5DE5\u7A0B Runtime ${catalog.runtimeVersion} \u4E0D\u652F\u6301 ${model}\uFF1B\u53EF\u9009 ${catalog.models.join(\"\u3001\")}`);\n}\n\nexport async function validateRuntimeDatasets(\n projectRoot: string,\n requirements: readonly BuddyDatasetRequirement[] = [],\n): Promise<void> {\n const catalog = await readRuntimeDataCatalog(projectRoot);\n const ids = new Set(catalog.datasets.map(item => item.id));\n for (const [index, item] of requirements.entries()) {\n if (!ids.has(item.id)) throw new Error(`data-access.json/requirements/${index}/id\uFF1A\u5DE5\u7A0B Runtime ${catalog.runtimeVersion} \u4E0D\u652F\u6301 ${item.id}`);\n }\n}\n", "/** Replaced only by the local lane builder. Runtime environment variables cannot select a target. */\nexport interface LaneBuild {\n readonly schemaVersion: 1;\n readonly id: string;\n readonly origin: string;\n readonly command: string;\n readonly distribution: \"local\" | \"npm\";\n readonly packageName: string;\n readonly runtimePackage: string;\n readonly runtimeTag: \"dev\";\n readonly runtimePrerelease: string;\n readonly avatarPackage: string;\n readonly creatorPackage: string;\n readonly skillTag: \"dev\" | \"latest\";\n readonly skillPrerelease: \"dev\" | \"stable\";\n readonly sourceVersion: string;\n readonly version: string;\n readonly validationScope: \"mac-config-only\" | \"windows-candidate\";\n}\ndeclare const __BUDDY_CLI_LANE_BUILD__: LaneBuild | undefined;\n\nexport const LANE_BUILD: Readonly<LaneBuild> | undefined = typeof __BUDDY_CLI_LANE_BUILD__ === \"undefined\"\n ? undefined : Object.freeze(__BUDDY_CLI_LANE_BUILD__);\nexport const CLI_COMMAND_NAME = LANE_BUILD?.command ?? \"buddy-cli-sit\";\nexport const CLI_PACKAGE_NAME = LANE_BUILD?.packageName ?? \"@my-life-buddies/cli\";\nexport const CLI_AUTO_UPDATE_AVAILABLE = !LANE_BUILD || LANE_BUILD.distribution === \"npm\";\nexport const CLI_WINDOWS_SETUP_AVAILABLE = !LANE_BUILD\n || (LANE_BUILD.distribution === \"npm\" && LANE_BUILD.validationScope === \"windows-candidate\");\nexport const CLI_MAC_SETUP_AVAILABLE = !LANE_BUILD\n || (LANE_BUILD.distribution === \"npm\" && LANE_BUILD.validationScope === \"windows-candidate\");\nexport const CLI_MAC_INSTALL_COMMAND = `npx --yes --registry=https://registry.npmjs.org/ --@my-life-buddies:registry=https://registry.npmjs.org/ --package=${CLI_PACKAGE_NAME}@dev ${CLI_COMMAND_NAME} setup`;\n// CMD runs npm's native shim even when pasted into PowerShell with Restricted policy.\n// No interpolated user paths or shell-specific environment assignments at this boundary.\nexport const CLI_WINDOWS_INSTALL_COMMAND = `cmd /d /c \"npx --yes --registry=https://registry.npmjs.org/ --@my-life-buddies:registry=https://registry.npmjs.org/ --package=${CLI_PACKAGE_NAME}@dev ${CLI_COMMAND_NAME} setup\"`;\nexport const PLATFORM_ORIGIN = LANE_BUILD?.origin ?? \"https://buddies.sit.dots.chat\";\nexport const RUNTIME_PACKAGE_NAME = LANE_BUILD?.runtimePackage ?? \"@my-life-buddies/buddy-runtime\";\nexport const RUNTIME_DIST_TAG = LANE_BUILD?.runtimeTag ?? \"dev\";\nexport const RUNTIME_SOURCE_LABEL = LANE_BUILD ? `${RUNTIME_PACKAGE_NAME} \u7684 npm ${RUNTIME_DIST_TAG}` : \"npm dev\";\nexport const AVATAR_PACKAGE_NAME = LANE_BUILD?.avatarPackage ?? \"@my-life-buddies/avatar-creator-skill\";\nexport const CREATOR_PACKAGE_NAME = LANE_BUILD?.creatorPackage ?? \"@my-life-buddies/buddy-creator-skill\";\nexport const SKILL_DIST_TAG = LANE_BUILD?.skillTag ?? \"latest\";\nexport const SKILL_VERSION_POLICY = LANE_BUILD?.skillPrerelease ?? \"stable\";\nexport const CREATOR_SOURCE_LABEL = LANE_BUILD ? `${CREATOR_PACKAGE_NAME} \u7684\u516C\u5171 npm ${SKILL_DIST_TAG}` : \"\u516C\u5171 npm latest\";\nexport const CLI_UPDATE_GUIDANCE = CLI_AUTO_UPDATE_AVAILABLE\n ? `\u6B63\u5E38\u547D\u4EE4\u5148\u8054\u7F51\u68C0\u67E5 ${CLI_PACKAGE_NAME} \u7684 dev \u7248\u672C\uFF0C\u65E7\u7248\u81EA\u52A8\u66F4\u65B0\u540E\u7EE7\u7EED\u6267\u884C\uFF1B\u5931\u8D25\u65F6\u505C\u6B62\u3002\u5E2E\u52A9\u3001--version \u548C dev stop \u79BB\u7EBF\u53EF\u7528\u3002\u53EF\u7528 ${CLI_COMMAND_NAME} update --check \u68C0\u67E5\u7248\u672C\uFF0C\u6216 ${CLI_COMMAND_NAME} update \u5355\u72EC\u66F4\u65B0\u3002`\n : \"\u672C\u5730\u6CF3\u9053\u6D4B\u8BD5\u5236\u54C1\u5DF2\u7981\u7528\u81EA\u52A8\u66F4\u65B0\u3001update \u548C setup\uFF1B\u66F4\u6362\u7248\u672C\u987B\u91CD\u65B0\u5B89\u88C5\u540C\u6CF3\u9053\u6D4B\u8BD5\u5236\u54C1\u3002\";\n\n/** A copied executable or mixed install must not silently acquire a different target identity. */\nexport function assertBuildManifest(manifest: { name?: unknown; version?: unknown; private?: unknown; bin?: unknown; buddyCliLane?: unknown; os?: unknown }, platform: NodeJS.Platform = process.platform, version = LANE_BUILD?.version): void {\n if (!LANE_BUILD) {\n if (manifest.buddyCliLane !== undefined) throw new Error(\"\u6CF3\u9053\u5236\u54C1\u4E0E\u6267\u884C\u5165\u53E3\u4E0D\u5339\u914D\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u5B8C\u6574\u6D4B\u8BD5\u5236\u54C1\u3002\");\n return;\n }\n // An npm update may change the version, but must retain the executable's target identity.\n const expected = LANE_BUILD.distribution === \"npm\" ? { ...LANE_BUILD, version, sourceVersion: version } : LANE_BUILD;\n const actual = manifest.buddyCliLane;\n if (!actual || typeof actual !== \"object\" || Array.isArray(actual)\n || Object.keys(actual).length !== Object.keys(LANE_BUILD).length\n || Object.entries(expected).some(([key, value]) => (actual as Record<string, unknown>)[key] !== value)\n || manifest.name !== CLI_PACKAGE_NAME || manifest.version !== expected.version\n || (LANE_BUILD.distribution === \"local\" ? manifest.private !== true : manifest.private !== undefined)\n || !manifest.bin || typeof manifest.bin !== \"object\"\n || Object.keys(manifest.bin).length !== 1\n || (manifest.bin as Record<string, unknown>)[LANE_BUILD.command] !== \"dist/bin/buddy.js\") {\n throw new Error(\"\u6CF3\u9053\u5236\u54C1\u6807\u8BC6\u3001\u7248\u672C\u6216\u5165\u53E3\u4E0D\u5339\u914D\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u5B8C\u6574\u6D4B\u8BD5\u5236\u54C1\uFF1B\u4E0D\u4F1A\u5207\u56DE\u516C\u5171 SIT\u3002\");\n }\n if (LANE_BUILD.validationScope === \"mac-config-only\" && platform !== \"darwin\") {\n throw new Error(\"\u6B64\u6CF3\u9053\u5236\u54C1\u4EC5\u652F\u6301 macOS\uFF08mac-config-only\uFF09\uFF1B\u7F3A\u5C11 Windows \u539F\u751F\u5236\u54C1\uFF0C\u5F3A\u5236\u5B89\u88C5\u4E5F\u4E0D\u80FD\u4F5C\u4E3A Windows \u5019\u9009\u8FD0\u884C\u3002\");\n }\n if (LANE_BUILD.distribution === \"npm\" && LANE_BUILD.validationScope === \"mac-config-only\"\n && JSON.stringify(manifest.os) !== JSON.stringify([\"darwin\"])) throw new Error(\"macOS \u6CF3\u9053 npm \u5236\u54C1\u7684 os \u5FC5\u987B\u4EC5\u4E3A darwin\u3002\");\n if (LANE_BUILD.distribution === \"npm\" && LANE_BUILD.validationScope === \"windows-candidate\"\n && JSON.stringify(manifest.os) !== JSON.stringify([\"darwin\", \"win32\"])) throw new Error(\"\u53CC\u5E73\u53F0\u6CF3\u9053 npm \u5236\u54C1\u7684 os \u5FC5\u987B\u4E3A darwin\u3001win32\u3002\");\n}\n", "import { LANE_BUILD, RUNTIME_PACKAGE_NAME } from \"../build-target.js\";\n/** Stable source import and node_modules key; a lane uses an npm alias at this key. */\nexport const BUDDY_RUNTIME_PACKAGE = \"@my-life-buddies/buddy-runtime\";\n\nexport function isExactRuntimeVersion(value: unknown): value is string {\n return typeof value === \"string\" && /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*)?$/u.test(value);\n}\n\nexport function isSelectedRuntimeVersion(value: unknown): value is string {\n return isExactRuntimeVersion(value) && (!LANE_BUILD\n || new RegExp(`^\\\\d+\\\\.\\\\d+\\\\.\\\\d+-${LANE_BUILD.runtimePrerelease}\\\\.\\\\d+$`, \"u\").test(value));\n}\n\nexport function runtimeDependencySpecifier(version: string): string {\n if (!isSelectedRuntimeVersion(version)) throw new Error(\"Runtime \u7248\u672C\u4E0D\u5C5E\u4E8E\u6B64 CLI \u7ED1\u5B9A\u7684\u5206\u53D1\u6E20\u9053\");\n return LANE_BUILD ? `npm:${RUNTIME_PACKAGE_NAME}@${version}` : version;\n}\n\nexport function runtimeInstallArgument(version: string): string {\n return `${BUDDY_RUNTIME_PACKAGE}@${runtimeDependencySpecifier(version)}`;\n}\n\nexport function assertInstalledRuntimeIdentity(pkg: unknown, expected?: string): void {\n // Preserve the public channel's existing version checks. A lane additionally\n // requires the aliased distribution identity before loading any SDK exports.\n if (!LANE_BUILD) { assertRuntimeHostCompatibility(pkg); return; }\n const manifest = pkg as { name?: unknown; version?: unknown } | null;\n if (!manifest || manifest.name !== RUNTIME_PACKAGE_NAME || !isSelectedRuntimeVersion(manifest.version)\n || (expected !== undefined && manifest.version !== expected)) {\n throw new Error(`Runtime \u5236\u54C1\u8EAB\u4EFD\u4E0D\u5339\u914D\uFF0C\u8981\u6C42 ${RUNTIME_PACKAGE_NAME}${expected ? `@${expected}` : \" \u7684\u51C6\u786E\u7248\u672C\"}`);\n }\n assertRuntimeHostCompatibility(pkg);\n}\n\n/** Each project records an exact Runtime release; its lockfile fixes transitive dependencies. */\nexport function runtimeDependencyVersion(pkg: unknown): string | undefined {\n if (typeof pkg !== \"object\" || pkg === null || !(\"dependencies\" in pkg)) return undefined;\n const dependencies = pkg.dependencies;\n if (typeof dependencies !== \"object\" || dependencies === null || !(BUDDY_RUNTIME_PACKAGE in dependencies)) return undefined;\n const declared = dependencies[BUDDY_RUNTIME_PACKAGE];\n const prefix = `npm:${RUNTIME_PACKAGE_NAME}@`;\n const version = LANE_BUILD\n ? typeof declared === \"string\" && declared.startsWith(prefix) ? declared.slice(prefix.length) : undefined\n : declared;\n return isSelectedRuntimeVersion(version) ? version : undefined;\n}\n\n/** Runtime 0.16 moved identity from StartOptions to environment variables. */\nexport function runtimeUsesEnvironmentIdentity(pkg: unknown): boolean {\n const version = runtimeDependencyVersion(pkg);\n if (!version) return false;\n const [major, minor] = version.split(\".\").map(Number);\n return major! > 0 || minor! >= 16;\n}\n\n/** A version string alone cannot distinguish an old, non-Windows-compatible artifact. */\nexport function assertRuntimeHostCompatibility(pkg: unknown, platform = process.platform): void {\n if (platform !== \"win32\") return;\n const capability = (pkg as { buddyRuntime?: { windowsCompatibility?: unknown } } | null)?.buddyRuntime?.windowsCompatibility;\n if (capability !== 1) throw new Error(\"\u6B64 Runtime \u5236\u54C1\u5C1A\u672A\u58F0\u660E Windows \u517C\u5BB9\u3002\u8BF7\u5B89\u88C5\u5DF2\u53D1\u5E03\u7684 Windows \u517C\u5BB9 Runtime\uFF0C\u5E76\u540C\u6B65\u5DE5\u7A0B\u4F9D\u8D56\u548C\u9501\u6587\u4EF6\uFF1B\u4E0D\u4F1A\u6539\u5199\u5DF2\u6709\u5DE5\u7A0B\u3002\");\n}\n", "// \u7BA1\uFF1A\u4F7F\u7528\u5F53\u524D\u5DE5\u7A0B\u51C6\u786E Runtime \u7684\u516C\u5F00\u6821\u9A8C\u5668\u9884\u68C0\u56FE\u7247\u6A21\u677F\u5FEB\u7167\uFF1B\u4E0D\u6267\u884C\u642D\u5B50\u5DE5\u5382\uFF0C\u4E0D\u7EF4\u62A4\u7B2C\u4E8C\u4EFD\u6A21\u677F\u534F\u8BAE\u3002\nimport { lstat, readdir, open, realpath } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { join } from 'node:path';\nimport { loadRuntime } from './runtime-catalog.js';\nexport interface TemplateManifest { id: string; version: string; revision: string; files: string[]; assetBytes: number; variants: string[]; engine?: 'html-v1' }\nexport async function captureImageTemplates(projectRoot: string): Promise<Record<string, Uint8Array>> {\n projectRoot = await realpath(projectRoot);\n const files: Record<string, Uint8Array> = {}; let total = 0, count = 0, visited = 0;\n async function walk(relative: string): Promise<void> {\n if (++visited > 1024 || relative.split('/').length > 16) throw new Error('\u56FE\u7247\u6A21\u677F\u76EE\u5F55\u6570\u91CF\u6216\u5C42\u7EA7\u8D85\u9650');\n const p = join(projectRoot, relative), stat = await lstat(p);\n if (stat.isSymbolicLink()) throw new Error('\u56FE\u7247\u6A21\u677F\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5');\n if (stat.isDirectory()) { for (const entry of await readdir(p)) { if (entry.startsWith('.')) throw new Error('\u56FE\u7247\u6A21\u677F\u4E0D\u5141\u8BB8\u9690\u85CF\u8D44\u6E90'); await walk(`${relative}/${entry}`); } return; }\n // \u4EC5\u9759\u6001\u5B57\u4F53\u5019\u9009\u6587\u4EF6\u53EF\u8FBE 16 MiB\uFF0C\u662F\u5426\u53EF\u7528\u4ECD\u7531\u5DE5\u7A0B\u51C6\u786E Runtime \u7684\u534F\u8BAE\u6821\u9A8C\uFF0C\u4E0D\u590D\u5236\u534F\u8BAE\u3002\n const fileLimit = relative.endsWith('.ttf') ? 16 * 1024 * 1024 : 2 * 1024 * 1024;\n if (!stat.isFile() || stat.size > fileLimit || ++count > 464 || (total += stat.size) > 64 * 1024 * 1024) throw new Error('\u56FE\u7247\u6A21\u677F\u8D44\u6E90\u8D85\u9650');\n if (await realpath(p) !== p) throw new Error('\u56FE\u7247\u6A21\u677F\u8D44\u6E90\u8DEF\u5F84\u53D1\u751F\u53D8\u5316');\n const fd = await open(p, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n try { const current = await fd.stat(); if (current.ino !== stat.ino || current.dev !== stat.dev || !current.isFile()) throw new Error('\u6A21\u677F\u8D44\u6E90\u8BFB\u53D6\u65F6\u53D1\u751F\u53D8\u5316'); const b = await fd.readFile(); if (b.length !== stat.size || await realpath(p) !== p) throw new Error('\u8BFB\u53D6\u65F6\u6A21\u677F\u6587\u4EF6\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5'); files[relative] = b; } finally { await fd.close(); }\n }\n try { await lstat(join(projectRoot, 'image-templates')); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'ENOENT') return files; throw e; }\n await walk('image-templates'); return files;\n}\nexport async function validateRuntimeImageTemplates(projectRoot: string, snapshot?: Readonly<Record<string, Uint8Array>>): Promise<TemplateManifest[]> {\n const files = snapshot ?? await captureImageTemplates(projectRoot);\n if (!Object.keys(files).length) return [];\n const { runtime, runtimeVersion } = await loadRuntime(projectRoot);\n if (typeof runtime.inspectImageTemplates !== 'function') throw new Error(`\u5DE5\u7A0B Runtime ${runtimeVersion} \u5C1A\u672A\u63D0\u4F9B\u56FE\u7247\u6A21\u677F\u6821\u9A8C\u5668\uFF1B\u8BF7\u7B49\u5F85\u5E73\u53F0\u53D1\u5E03\u5305\u542B\u8BE5\u80FD\u529B\u7684 Runtime\uFF0C\u4E0D\u8981\u7ED5\u8FC7\u7248\u672C\u68C0\u67E5`);\n const result: unknown = runtime.inspectImageTemplates(files);\n if (!Array.isArray(result) || result.length > 8 || result.some(v => !v || typeof v.id !== 'string' || typeof v.version !== 'string' || !/^[a-f0-9]{64}$/.test(v.revision))) throw new Error('Runtime \u8FD4\u56DE\u7684\u6A21\u677F\u6E05\u5355\u4E0D\u5408\u6CD5');\n return result as TemplateManifest[];\n}\n"],
5
+ "mappings": ";AAAA,4CAAC,eAAgB,GAAE,IAAK,sBAAqB,QAAS,oEAAmE,SAAU,0BAAyB,gBAAiB,+CAA8C,YAAa,OAAM,mBAAoB,OAAM,eAAgB,yCAAwC,gBAAiB,wCAAuC,UAAW,UAAS,iBAAkB,UAAS,eAAgB,gBAAe,cAAe,OAAM,aAAc,qCAAoC,SAAU,gBAAe,iBAAkB,kBAAiB;;;ACAzkB,SAAS,YAAY,kBAAkB;;;ACAvC,SAAS,OAAO,gBAAgB;AAChC,SAAS,YAAY;AAEd,IAAM,uBAAuB;AAI7B,SAAS,4BAA4B,QAAuD;AACjG,MAAI,WAAW,OAAW,QAAO,CAAC;AAClC,QAAM,UAAU,CAAC,WAA0B;AAAE,UAAM,IAAI,MAAM,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,QAAM,KAAK,iBAAiB;AAAG,SAAO;AACvC;AACA,eAAsB,8BAA8BA,cAAqB,UAA8E;AACtJ,QAAM,QAAQ,YAAY,MAAM,sBAAsBA,YAAW;AACjE,MAAI,CAAC,OAAO,KAAK,KAAK,EAAE,OAAQ,QAAO,CAAC;AACxC,QAAM,EAAE,SAAS,eAAe,IAAI,MAAM,YAAYA,YAAW;AACjE,MAAI,OAAO,QAAQ,0BAA0B,WAAY,OAAM,IAAI,MAAM,wBAAc,cAAc,uNAA6C;AAClJ,QAAM,SAAkB,QAAQ,sBAAsB,KAAK;AAC3D,MAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,OAAO,SAAS,KAAK,OAAO,KAAK,OAAK,CAAC,KAAK,OAAO,EAAE,OAAO,YAAY,OAAO,EAAE,YAAY,YAAY,CAAC,iBAAiB,KAAK,EAAE,QAAQ,CAAC,EAAG,OAAM,IAAI,MAAM,sEAAoB;AAChN,SAAO;AACR;;;AL3BA,IAAM,cAAsB;AAC5B,MAAM,wBAAwB,aAAa,MAAM,2BAA2B,WAAW,CAAC;AACxF,MAAM,8BAA8B,WAAW;AAC/C,WAAY,YAAY,WAAW;",
6
+ "names": ["projectRoot", "readFile", "projectRoot", "readFile", "projectRoot", "lstat", "realpath", "join", "projectRoot", "realpath", "join", "lstat"]
7
+ }
@@ -0,0 +1,107 @@
1
+ // npm links bins before postinstall (including global installs, npm exec/npx,
2
+ // upgrades and rebuilds). Keep its CMD/Git Bash launchers; remove only this
3
+ // package's PowerShell shim so the same bare command works under Restricted.
4
+ // No dependency on the CLI bundle, npm internals, shell or execution policy.
5
+ const { lstat, readFile, realpath, unlink } = require('node:fs/promises');
6
+ const { basename, dirname, isAbsolute, join, resolve, sep } = require('node:path');
7
+
8
+ const IDENTITIES = {
9
+ '@my-life-buddies/cli': ['buddy-cli', 'buddy-cli-sit', 'buddy-cli-windowscompat'],
10
+ '@my-life-buddies/cli-windowscompat': ['buddy-cli-windowscompat'],
11
+ };
12
+
13
+ async function optionalStat(path) {
14
+ try { return await lstat(path); } catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
15
+ }
16
+
17
+ function shimDirectories(packageRoot, env) {
18
+ const paths = new Set();
19
+ // Scoped packages, including nested npm and npx caches.
20
+ const modules = dirname(dirname(packageRoot));
21
+ if (basename(modules).toLowerCase() === 'node_modules') {
22
+ paths.add(join(modules, '.bin'));
23
+ paths.add(dirname(modules)); // Windows global prefix (not prefix/bin).
24
+ }
25
+ // npm link/workspaces can execute the hook at the real source path.
26
+ if (env.npm_config_prefix && isAbsolute(env.npm_config_prefix)) paths.add(resolve(env.npm_config_prefix));
27
+ if (env.npm_config_local_prefix && isAbsolute(env.npm_config_local_prefix)) paths.add(join(env.npm_config_local_prefix, 'node_modules', '.bin'));
28
+ return [...paths];
29
+ }
30
+
31
+ async function pointsTo(contents, directory, expression, target) {
32
+ const matches = [...contents.matchAll(expression)];
33
+ if (!matches.length) return false;
34
+ for (const match of matches) {
35
+ // npm uses forward slashes in ps1 and backslashes in cmd, on every host.
36
+ const path = resolve(directory, match[1].replace(/[\\/]/gu, sep));
37
+ let actual;
38
+ try { actual = await realpath(path); } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
39
+ if (actual.toLowerCase() !== target.toLowerCase()) return false;
40
+ }
41
+ return true;
42
+ }
43
+
44
+ async function isSourceWorkspace(packageRoot, manifest) {
45
+ const root = resolve(packageRoot, '../..');
46
+ if (resolve(packageRoot) !== join(root, 'apps', 'cli') || manifest.name !== '@my-life-buddies/cli') return false;
47
+ let workspace;
48
+ try { workspace = JSON.parse(await readFile(join(root, 'package.json'), 'utf8')); }
49
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
50
+ return workspace.name === '@buddy/cli-workspace' && workspace.private === true
51
+ && Array.isArray(workspace.workspaces) && workspace.workspaces.includes('apps/cli')
52
+ && (await optionalStat(join(packageRoot, 'src/bin/buddy.ts')))?.isFile()
53
+ && (await optionalStat(join(root, 'scripts/build-cli-package.mjs')))?.isFile();
54
+ }
55
+
56
+ async function configureWindowsBin({ packageRoot = resolve(__dirname, '..'), platform = process.platform, env = process.env } = {}) {
57
+ if (platform !== 'win32') return [];
58
+ const manifest = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));
59
+ const bins = Object.entries(manifest.bin ?? {});
60
+ if (bins.length !== 1 || !IDENTITIES[manifest.name]?.includes(bins[0][0]) || bins[0][1] !== 'dist/bin/buddy.js') {
61
+ throw new Error('Refusing Windows launcher cleanup for an unknown CLI package/bin identity');
62
+ }
63
+ const [command, entry] = bins[0];
64
+ let target;
65
+ try { target = await realpath(join(packageRoot, entry)); }
66
+ catch (error) {
67
+ // A clean checkout runs workspace postinstall during npm ci, before build.
68
+ // Published/staged packages have a different layout and must contain the bin.
69
+ if (error.code === 'ENOENT' && await isSourceWorkspace(packageRoot, manifest)) return [];
70
+ throw error;
71
+ }
72
+ const removed = [];
73
+ for (const directory of shimDirectories(packageRoot, env)) {
74
+ const ps1 = join(directory, `${command}.ps1`);
75
+ const stat = await optionalStat(ps1);
76
+ if (!stat) continue;
77
+ const cmd = join(directory, `${command}.cmd`);
78
+ const cmdStat = await optionalStat(cmd);
79
+ const ownCmd = cmdStat?.isFile() && cmdStat.nlink === 1
80
+ && await pointsTo(await readFile(cmd, 'utf8'), directory, /"%(?:~dp0|dp0%)\\([^"\r\n]+)"\s+%\*/gu, target);
81
+ // Never follow a file link or remove a shared inode, even in our bin name.
82
+ if (!stat.isFile() || stat.nlink !== 1) {
83
+ if (ownCmd) throw new Error(`Cannot configure ${command}: PowerShell launcher is a link or shared file; it was not changed`);
84
+ continue;
85
+ }
86
+ const content = await readFile(ps1, 'utf8');
87
+ const ownPs1 = (content.startsWith('#!/usr/bin/env pwsh\n') || content.startsWith('#!/usr/bin/env pwsh\r\n'))
88
+ && await pointsTo(content, directory, /"\$basedir\/([^"\r\n]+)"\s+\$args/gu, target);
89
+ if (!ownPs1) {
90
+ if (ownCmd) throw new Error(`Cannot configure ${command}: PowerShell launcher is not this package's npm shim; it was not changed`);
91
+ continue;
92
+ }
93
+ if (!ownCmd) {
94
+ throw new Error(`Cannot configure ${command}: npm CMD launcher is missing or belongs to another package. Reinstall with npm lifecycle scripts and bin links enabled.`);
95
+ }
96
+ const current = await lstat(ps1);
97
+ if (!current.isFile() || current.nlink !== 1 || current.dev !== stat.dev || current.ino !== stat.ino || current.size !== stat.size || current.mtimeMs !== stat.mtimeMs) {
98
+ throw new Error(`Cannot configure ${command}: launcher changed during installation`);
99
+ }
100
+ await unlink(ps1);
101
+ removed.push(ps1);
102
+ }
103
+ return removed;
104
+ }
105
+
106
+ module.exports = { configureWindowsBin };
107
+ if (require.main === module) configureWindowsBin().catch(error => { console.error(error.message); process.exitCode = 1; });