@zhama/tego-plugin-sdk 1.36.1 → 1.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -3
- package/agent/RULES.md +123 -0
- package/agent/guides/access.md +39 -0
- package/agent/guides/backend.md +76 -0
- package/agent/guides/claw.md +18 -0
- package/agent/guides/desktop-web.md +48 -0
- package/agent/guides/frontend.md +83 -0
- package/agent/guides/host-api-versions.md +34 -0
- package/agent/guides/i18n.md +17 -0
- package/agent/guides/manifest.md +26 -0
- package/agent/guides/migrations.md +17 -0
- package/agent/guides/storage.md +18 -0
- package/agent/guides/testing.md +17 -0
- package/agent/guides/ui.md +22 -0
- package/agent/reference/plugin-sdk-api.md +561 -0
- package/bin/tego-plugin-pack.mjs +1 -1
- package/bin/tego-plugin.mjs +4 -2
- package/dist/chunk-2NTAWYCG.js +1 -0
- package/dist/chunk-2P6UEAPV.cjs +1 -0
- package/dist/chunk-45Y4CR4R.cjs +1 -0
- package/dist/{chunk-THMWRUAT.cjs → chunk-4LKRXDYY.cjs} +13 -12
- package/dist/{chunk-7XHF3YSK.js → chunk-56QOZQTY.js} +1 -1
- package/dist/{chunk-C2OCOPZQ.cjs → chunk-6HNG5OZI.cjs} +1 -1
- package/dist/chunk-DEGQDJF6.js +1 -0
- package/dist/chunk-EIVA5BR6.js +1 -0
- package/dist/chunk-FCYAAOHC.js +20 -0
- package/dist/chunk-HZ4YWRYX.cjs +5 -0
- package/dist/chunk-I5Z3ECC4.js +5 -0
- package/dist/chunk-INCA3GFW.js +1 -0
- package/dist/chunk-IVJECPGG.js +1 -0
- package/dist/chunk-MWMGJJ74.cjs +1 -0
- package/dist/chunk-N4SXZZPY.cjs +1 -0
- package/dist/chunk-SKNPNPJP.cjs +1 -0
- package/dist/dev.cjs +358 -0
- package/dist/dev.d.cts +144 -0
- package/dist/dev.d.ts +144 -0
- package/dist/dev.js +358 -0
- package/dist/doctor.cjs +8 -0
- package/dist/doctor.d.cts +62 -0
- package/dist/doctor.d.ts +62 -0
- package/dist/doctor.js +8 -0
- package/dist/frontend.d.cts +33 -1
- package/dist/frontend.d.ts +33 -1
- package/dist/hono.cjs +1 -0
- package/dist/hono.d.cts +84 -0
- package/dist/hono.d.ts +84 -0
- package/dist/hono.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/index.js +1 -1
- package/dist/{manifest-types-DQARCQJt.d.cts → manifest-types-CUTNfJTa.d.cts} +1 -1
- package/dist/{manifest-types-DQARCQJt.d.ts → manifest-types-CUTNfJTa.d.ts} +1 -1
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.d.cts +55 -2
- package/dist/manifest.d.ts +55 -2
- package/dist/manifest.js +1 -1
- package/dist/migrations-sync.cjs +1 -0
- package/dist/migrations-sync.d.cts +20 -0
- package/dist/migrations-sync.d.ts +20 -0
- package/dist/migrations-sync.js +1 -0
- package/dist/pack.cjs +1 -1
- package/dist/pack.d.cts +8 -2
- package/dist/pack.d.ts +8 -2
- package/dist/pack.js +1 -1
- package/dist/publish.cjs +1 -1
- package/dist/publish.d.cts +1 -1
- package/dist/publish.d.ts +1 -1
- package/dist/publish.js +1 -1
- package/dist/react.cjs +1 -0
- package/dist/react.d.cts +101 -0
- package/dist/react.d.ts +101 -0
- package/dist/react.js +1 -0
- package/dist/scaffold.cjs +672 -17
- package/dist/scaffold.d.cts +42 -18
- package/dist/scaffold.d.ts +42 -18
- package/dist/scaffold.js +674 -19
- package/dist/server-runtime.cjs +1 -1
- package/dist/server-runtime.d.cts +27 -2
- package/dist/server-runtime.d.ts +27 -2
- package/dist/server-runtime.js +1 -1
- package/dist/testing.cjs +6 -2
- package/dist/testing.d.cts +19 -1
- package/dist/testing.d.ts +19 -1
- package/dist/testing.js +6 -2
- package/dist/verify-FF2RD2MV.cjs +1 -0
- package/dist/verify-W7ZTUCO4.js +1 -0
- package/dist/vite.cjs +1 -1
- package/dist/vite.d.cts +27 -1
- package/dist/vite.d.ts +27 -1
- package/dist/vite.js +1 -1
- package/package.json +37 -3
- package/dist/chunk-3KUOBGJN.js +0 -19
- package/dist/chunk-3WA3M347.cjs +0 -1
- package/dist/chunk-5CU33JVY.js +0 -1
- package/dist/chunk-7K37PVGV.js +0 -5
- package/dist/chunk-BTHXQWHT.js +0 -1
- package/dist/chunk-ROFUQLOZ.cjs +0 -1
- package/dist/chunk-W7C357A6.cjs +0 -5
package/dist/dev.d.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { P as PluginNavEntry } from './manifest-types-CUTNfJTa.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The two shells a plugin page runs in, as the local preview imitates them.
|
|
6
|
+
*
|
|
7
|
+
* - `web`: the platform's nginx CSP (`docker/ai-studio/nginx.conf`) — the page
|
|
8
|
+
* may connect to the platform only. Its per-request nonce is left out: Vite's
|
|
9
|
+
* dev scripts cannot carry one, and what the nonce guards (injected inline
|
|
10
|
+
* scripts, `eval`) is refused here the same way.
|
|
11
|
+
* - `desktop`: the Tauri app's CSP (`apps/ai-studio/src-tauri/tauri.conf.json`)
|
|
12
|
+
* — no `eval`/`new Function`, no `blob:` scripts — and its protocol proxy,
|
|
13
|
+
* which buffers every `ctx.api` response whole, refuses one over 100 MB, and
|
|
14
|
+
* strips `accept-encoding`.
|
|
15
|
+
*
|
|
16
|
+
* Both report violations to the preview, which prints them, so a dependency
|
|
17
|
+
* that compiles strings or a call to a third-party URL shows up while
|
|
18
|
+
* developing instead of after release.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
type PreviewTarget = 'web' | 'desktop';
|
|
22
|
+
/** The machine-readable line tools watch for (`TEGO_DEV_CSP {"target",…}`). */
|
|
23
|
+
declare const CSP_REPORT_PREFIX = "TEGO_DEV_CSP ";
|
|
24
|
+
declare const PREVIEW_CSP: Record<PreviewTarget, string>;
|
|
25
|
+
/** `?target=` wins, then the cookie the shell's switch sets, then the default. */
|
|
26
|
+
declare function targetOf(req: Pick<IncomingMessage, 'url' | 'headers'>, fallback: PreviewTarget): PreviewTarget;
|
|
27
|
+
interface CspViolation {
|
|
28
|
+
directive: string;
|
|
29
|
+
blocked: string;
|
|
30
|
+
source?: string;
|
|
31
|
+
line?: number;
|
|
32
|
+
}
|
|
33
|
+
/** A browser's `application/csp-report` body; `undefined` when it is not one. */
|
|
34
|
+
declare function parseCspReport(body: string): CspViolation | undefined;
|
|
35
|
+
|
|
36
|
+
/** `tego_dev_<id>` with every character Postgres would need quoted folded to `_`. */
|
|
37
|
+
declare function devSchemaName(pluginId: string): string;
|
|
38
|
+
/**
|
|
39
|
+
* The database URL the backend gets: the developer's, with the schema pinned
|
|
40
|
+
* as the only `search_path` entry (percent-encoded by hand, as the host does:
|
|
41
|
+
* libpq reads a `+` literally).
|
|
42
|
+
*/
|
|
43
|
+
declare function devDatabaseUrl(databaseUrl: string, schema: string): string;
|
|
44
|
+
/** Applies the files not yet in the ledger, in name order; returns their names. */
|
|
45
|
+
declare function applyDevMigrations(options: {
|
|
46
|
+
databaseUrl: string;
|
|
47
|
+
schema: string;
|
|
48
|
+
migrationsDir: string;
|
|
49
|
+
tenantId: string;
|
|
50
|
+
}): Promise<string[]>;
|
|
51
|
+
|
|
52
|
+
/** Who the preview shell says is calling; sent by the shell on every API request. */
|
|
53
|
+
declare const DEV_USER_HEADER = "x-tego-dev-user-id";
|
|
54
|
+
declare const DEV_ROLES_HEADER = "x-tego-dev-roles";
|
|
55
|
+
declare const DEV_TENANT_ID = "dev-tenant";
|
|
56
|
+
interface DevCaller {
|
|
57
|
+
userId: string;
|
|
58
|
+
roles: string[];
|
|
59
|
+
}
|
|
60
|
+
/** The caller the shell named, falling back to the default dev user; never throws. */
|
|
61
|
+
declare function devCallerOf(headers: Record<string, string | string[] | undefined>): DevCaller;
|
|
62
|
+
/**
|
|
63
|
+
* Request headers for the backend: the browser's, minus anything that could
|
|
64
|
+
* pass for identity (cookies, authorization, every `x-tego-*`), plus the
|
|
65
|
+
* signed context `serveBackend` verifies.
|
|
66
|
+
*/
|
|
67
|
+
declare function gatewayHeaders(incoming: Record<string, string | string[] | undefined>, caller: DevCaller, key: string, nowMs?: number): Record<string, string>;
|
|
68
|
+
|
|
69
|
+
interface FakeHostOptions {
|
|
70
|
+
token: string;
|
|
71
|
+
storageDir: string;
|
|
72
|
+
/** Backend config values, defaults applied. */
|
|
73
|
+
config: () => Record<string, unknown>;
|
|
74
|
+
/** The preview's origin, for signed URLs. */
|
|
75
|
+
origin: () => string;
|
|
76
|
+
/** Users the preview has made calls as, with the roles they had. */
|
|
77
|
+
users: () => ReadonlyMap<string, string[]>;
|
|
78
|
+
log(line: string): void;
|
|
79
|
+
}
|
|
80
|
+
/** A storage key as a file below the storage dir; refuses `..` and absolute keys. */
|
|
81
|
+
declare function storagePath(storageDir: string, key: string): string;
|
|
82
|
+
/** Handles a request below {@link FAKE_HOST_PREFIX} or {@link FAKE_FILES_PREFIX}. */
|
|
83
|
+
declare function handleFakeHost(req: IncomingMessage, res: ServerResponse, options: FakeHostOptions): Promise<void>;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The page the local preview serves: a small stand-in for the shell's plugin
|
|
87
|
+
* page, written into the plugin's `.tego-dev/shell/` on every start.
|
|
88
|
+
*
|
|
89
|
+
* Written into the plugin rather than served from this package so that its
|
|
90
|
+
* imports (`react`, `@tego/ui`, `react-i18next`) resolve to the plugin's own
|
|
91
|
+
* installed copies — the same single instances the plugin's code imports, as
|
|
92
|
+
* in the shell, where they are shared rather than bundled twice.
|
|
93
|
+
*
|
|
94
|
+
* It mounts the plugin's source entry with a `PluginHostContext` built the
|
|
95
|
+
* way the shell builds one: `basePath` `/p/<id>`, history-backed routing,
|
|
96
|
+
* `ctx.api` at `/api/v1/tego-os/plugin-api/<id>/*`, the frontend config's
|
|
97
|
+
* defaults. What only the platform has (`ai`, `office`, live events) is
|
|
98
|
+
* absent or inert. The top bar switches page, language, theme and the user
|
|
99
|
+
* the API calls are made as.
|
|
100
|
+
*/
|
|
101
|
+
|
|
102
|
+
interface ShellOptions {
|
|
103
|
+
pluginId: string;
|
|
104
|
+
displayName: string;
|
|
105
|
+
nav: PluginNavEntry[];
|
|
106
|
+
config: Record<string, unknown>;
|
|
107
|
+
/** Import specifier of the plugin's source entry, relative to the shell dir; none without a frontend. */
|
|
108
|
+
entry?: string | undefined;
|
|
109
|
+
/** Locales the plugin ships (`en.json` → `en`). */
|
|
110
|
+
locales: string[];
|
|
111
|
+
/** The shell imitated when the page has not chosen one. */
|
|
112
|
+
defaultTarget?: 'web' | 'desktop';
|
|
113
|
+
}
|
|
114
|
+
interface ShellFile {
|
|
115
|
+
path: string;
|
|
116
|
+
contents: string;
|
|
117
|
+
}
|
|
118
|
+
declare function shellFiles(options: ShellOptions): ShellFile[];
|
|
119
|
+
|
|
120
|
+
/** First port tried; the next free one is taken when it is busy. */
|
|
121
|
+
declare const DEFAULT_DEV_PORT = 5280;
|
|
122
|
+
/** The line tools (Tego Studio) wait for; the JSON after it is `{ "url" }`. */
|
|
123
|
+
declare const DEV_READY_PREFIX = "TEGO_DEV_READY ";
|
|
124
|
+
declare const DEV_DIR = ".tego-dev";
|
|
125
|
+
interface DevServerOptions {
|
|
126
|
+
/** The plugin folder (holding tego.plugin.json). */
|
|
127
|
+
root: string;
|
|
128
|
+
/** 0 for any free port; defaults to {@link DEFAULT_DEV_PORT} or the next free one. */
|
|
129
|
+
port?: number;
|
|
130
|
+
host?: string;
|
|
131
|
+
/** Run the backend part (needs `databaseUrl`); default true. */
|
|
132
|
+
backend?: boolean;
|
|
133
|
+
/** Which shell to imitate by default (CSP, network proxy); the page can switch. Default `web`. */
|
|
134
|
+
target?: PreviewTarget;
|
|
135
|
+
databaseUrl?: string;
|
|
136
|
+
log?(line: string): void;
|
|
137
|
+
}
|
|
138
|
+
interface DevServer {
|
|
139
|
+
url: string;
|
|
140
|
+
close(): Promise<void>;
|
|
141
|
+
}
|
|
142
|
+
declare function startDevServer(options: DevServerOptions): Promise<DevServer>;
|
|
143
|
+
|
|
144
|
+
export { CSP_REPORT_PREFIX, type CspViolation, DEFAULT_DEV_PORT, DEV_DIR, DEV_READY_PREFIX, DEV_ROLES_HEADER, DEV_TENANT_ID, DEV_USER_HEADER, type DevServer, type DevServerOptions, PREVIEW_CSP, type PreviewTarget, applyDevMigrations, devCallerOf, devDatabaseUrl, devSchemaName, gatewayHeaders, handleFakeHost, parseCspReport, shellFiles, startDevServer, storagePath, targetOf };
|
package/dist/dev.js
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
var Me=Object.defineProperty;var s=(e,t)=>Me(e,"name",{value:t,configurable:!0});import{signPluginContext as Fe}from"./chunk-WLTASJF6.js";import{readManifest as Ke,readPluginLocales as Je,buildPluginBackend as ze}from"./chunk-FCYAAOHC.js";import"./chunk-I5Z3ECC4.js";import{applyConfigDefaults as fe}from"./chunk-DEGQDJF6.js";import"./chunk-EIVA5BR6.js";import"./chunk-2NTAWYCG.js";import{resolvePluginParts as We}from"./chunk-IVJECPGG.js";import"./chunk-INCA3GFW.js";import"./chunk-56QOZQTY.js";import{PLUGIN_CONTEXT_HEADERS as L}from"./chunk-QKSPPMVN.js";import"./chunk-VMCGDDGP.js";import"./chunk-SNUCO2MK.js";import{randomUUID as qe,randomBytes as pe,createHash as Xe}from"crypto";import{existsSync as K,realpathSync as Ye,watch as Qe}from"fs";import{readdir as Ze,readFile as J,mkdir as ee,copyFile as ge,rm as te,writeFile as ne,stat as et}from"fs/promises";import{createServer as tt,request as nt}from"http";import{createRequire as rt}from"module";import{join as w,resolve as x,isAbsolute as at,sep as he,dirname as O,relative as me}from"path";import{spawn as ot}from"child_process";import{createServer as st}from"net";var re="x-tego-dev-user-id",ae="x-tego-dev-roles",C="dev-tenant",ve="00000000-0000-4000-8000-000000000001";function we(e){const t=s(r=>(Array.isArray(r)?r[0]:r)?.trim()??"","single"),n=t(e[re])||ve;let a=[];try{const r=JSON.parse(t(e[ae])||"[]");Array.isArray(r)&&(a=r.filter(i=>typeof i=="string"))}catch{}return{userId:n,roles:a}}s(we,"devCallerOf");function ye(e,t,n,a=Date.now()){const r={};for(const[o,l]of Object.entries(e)){const d=o.toLowerCase();l===void 0||d.startsWith("x-tego-")||d==="cookie"||d==="authorization"||d==="host"||d==="connection"||(r[d]=Array.isArray(l)?l.join(", "):l)}const i=JSON.stringify(t.roles),u=String(a);return r[L.userId]=t.userId,r[L.tenantId]=C,r[L.roles]=i,r[L.issuedAt]=u,r[L.signature]=Fe({userId:t.userId,tenantId:C,rolesHeader:i,avatarId:"",issuedAt:u},n),r}s(ye,"gatewayHeaders");var it="tego_dev_migrations";function Se(e){return`tego_dev_${e.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`.slice(0,63)}s(Se,"devSchemaName");function be(e,t){const n=new URL(e);n.searchParams.delete("options");const a=n.search.replace(/^\?/,"");return n.search=`?${a?`${a}&`:""}options=${encodeURIComponent(`-c search_path=${t}`)}`,n.toString()}s(be,"devDatabaseUrl");async function ct(e){let t;try{t=await import("pg")}catch(r){throw new Error(`The local backend needs the "pg" driver; add it to the plugin's dependencies.`,{cause:r})}const n=t.default?.Client??t.Client;if(!n)throw new Error('The "pg" module has no Client constructor.');const a=new n({connectionString:e});try{await a.connect()}catch(r){throw new Error(`Cannot connect to DATABASE_URL (${oe(e)}): ${r instanceof Error?r.message:String(r)}`,{cause:r})}return a}s(ct,"connect");function oe(e){try{const t=new URL(e);return t.password&&(t.password="***"),t.toString()}catch{return"<unparseable DATABASE_URL>"}}s(oe,"redactUrl");var Ee=s(e=>`"${e.replace(/"/g,'""')}"`,"quote");async function ke(e){const t=await Ze(e.migrationsDir).then(i=>i.filter(u=>u.endsWith(".sql")).sort(),i=>{if(i.code==="ENOENT")return[];throw i}),n=await ct(e.databaseUrl),a=Ee(e.schema),r=`${a}.${Ee(it)}`;try{await n.query(`CREATE SCHEMA IF NOT EXISTS ${a}`),await n.query(`CREATE TABLE IF NOT EXISTS ${r} (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`);const i=new Set((await n.query(`SELECT name FROM ${r}`)).rows.map(o=>String(o.name))),u=[];for(const o of t){if(i.has(o))continue;const l=await J(w(e.migrationsDir,o),"utf8");await n.query("BEGIN");try{await n.query(`SET LOCAL search_path TO ${a}`),await n.query("SELECT set_config('app.tenant_id', $1, true)",[e.tenantId]),await n.query(l),await n.query(`INSERT INTO ${r} (name) VALUES ($1)`,[o]),await n.query("COMMIT")}catch(d){throw await n.query("ROLLBACK").catch(()=>{}),new Error(`Migration ${o} failed: ${d instanceof Error?d.message:String(d)}`,{cause:d})}u.push(o)}return u}finally{await n.end().catch(()=>{})}}s(ke,"applyDevMigrations");var lt=250,ut=5e3;function dt(){return new Promise((e,t)=>{const n=st();n.once("error",t),n.listen(0,"127.0.0.1",()=>{const a=n.address(),r=typeof a=="object"&&a?a.port:0;n.close(()=>e(r))})})}s(dt,"freePort");function Te(e){return!e||e.exitCode!==null||e.signalCode!==null?Promise.resolve():new Promise(t=>{const n=setTimeout(()=>{e.kill("SIGKILL"),t()},ut);e.once("exit",()=>{clearTimeout(n),t()}),e.kill("SIGTERM")})}s(Te,"stopChild");async function ft(e){const{part:t,log:n}=e;if(t.runtime==="python")throw new Error("The local preview runs TypeScript backends only; a python backend runs through the platform.");const a=await dt(),r=Se(e.pluginId),i=x(e.root,t.migrationsDirPath),u=w(e.outDir,t.entryPath),o={...process.env,NODE_ENV:"development",TEGO_PLUGIN_ID:e.pluginId,TEGO_PLUGIN_VERSION:e.version,TEGO_PLUGIN_INSTALL_ID:"dev-install",TEGO_TENANT_ID:C,TEGO_PLUGIN_PORT:String(a),TEGO_PLUGIN_HEALTH_PATH:t.healthPath,TEGO_PLUGIN_HOST_API_URL:e.hostApiUrl,TEGO_PLUGIN_HOST_API_TOKEN:e.hostApiToken,TEGO_PLUGIN_GATEWAY_KEY:e.gatewayKey,DATABASE_URL:be(e.databaseUrl,r)};let l=null,d=!1;async function p(){await te(e.outDir,{recursive:!0,force:!0}),await ze(t,{root:e.root,outDir:e.outDir});const h=await ke({databaseUrl:e.databaseUrl,schema:r,migrationsDir:i,tenantId:C});for(const E of h)n(`[backend] applied migration ${E}`)}s(p,"build");function y(){const h=ot(process.execPath,[u],{env:o,stdio:["ignore","pipe","pipe"]});l=h,h.stdout?.on("data",E=>process.stdout.write(E)),h.stderr?.on("data",E=>process.stderr.write(E)),h.on("exit",E=>{l===h&&!d&&(l=null,n(`[backend] exited (code ${E??"null"}); it starts again on the next save`))})}s(y,"start"),await p(),y(),n(`[backend] ${e.pluginId} on 127.0.0.1:${a}, schema ${r} in ${oe(e.databaseUrl)}`);let b=null,v=null,R=!1;const H=s(async()=>{if(v){R=!0;return}v=(async()=>{try{await p();const h=l;l=null,await Te(h),d||(y(),n("[backend] rebuilt and restarted"))}catch(h){n(`[backend] rebuild failed, the previous build keeps running: ${h instanceof Error?h.message:String(h)}`)}})(),await v,v=null,R&&!d&&(R=!1,await H())},"rebuild"),V=[];for(const h of[t.dir,"shared"]){const E=x(e.root,h);K(E)&&V.push(Qe(E,{recursive:!0},(P,I)=>{I&&/(^|[\\/])(node_modules|dist)([\\/]|$)/.test(String(I))||(b&&clearTimeout(b),b=setTimeout(()=>void H(),lt))}))}return{port:a,schema:r,async close(){d=!0,b&&clearTimeout(b);for(const h of V)h.close();await v,await Te(l)}}}s(ft,"startDevBackend");var se="/__tego/host",ie="/__tego/files",pt=1024*1024;async function ce(e,t=1/0){const n=[];let a=0;for await(const r of e){if(a+=r.length,a>t)throw Object.assign(new Error("body too large"),{status:413});n.push(r)}return Buffer.concat(n)}s(ce,"readBody");function g(e,t,n){if(n===void 0){e.writeHead(t),e.end();return}e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))}s(g,"send");function le(e,t){const n=x(e),a=x(n,t);if(!t||at(t)||!a.startsWith(n+he))throw Object.assign(new Error(`invalid storage key ${JSON.stringify(t)}`),{status:400});return a}s(le,"storagePath");var U=s(e=>`${e}.tego-meta.json`,"metaOf");async function B(e){const t=await et(e).catch(()=>null);if(!t?.isFile())return null;const n=await J(U(e),"utf8").then(a=>JSON.parse(a),()=>({}));return{size:t.size,contentType:n.contentType??null,versionTag:Xe("sha1").update(`${t.size}:${t.mtimeMs}`).digest("hex")}}s(B,"head");async function Ie(e,t,n){await ee(O(e),{recursive:!0}),await ne(e,t),await ne(U(e),JSON.stringify({contentType:n??null}))}s(Ie,"put");async function xe(e,t,n){const a=new URL(e.url??"/","http://preview.local");try{if(a.pathname.startsWith(ie)){const o=le(n.storageDir,a.searchParams.get("key")??""),l=await B(o);if(!l)return g(t,404);t.writeHead(200,{"content-type":l.contentType??"application/octet-stream"}),t.end(await J(o));return}if(e.headers.authorization!==`Bearer ${n.token}`)return g(t,401,{error:"bad host API token"});const r=a.pathname.slice(se.length)||"/",i=s(async()=>JSON.parse((await ce(e,pt)).toString("utf8")||"{}"),"json"),u=s(o=>le(n.storageDir,String(o??"")),"keyFile");switch(r){case"/config":return g(t,200,{data:{values:n.config()}});case"/log":{const{level:o,message:l,fields:d}=await i();return n.log(`[backend ${String(o??"info")}] ${String(l??"")}${d?` ${JSON.stringify(d)}`:""}`),g(t,200,{data:{}})}case"/events":{const{name:o,payload:l}=await i();return n.log(`[event] ${String(o)} ${JSON.stringify(l??null)}`),g(t,200,{data:{}})}case"/notifications":return n.log(`[notification] ${JSON.stringify(await i())}`),g(t,200,{data:{id:qe()}});case"/directory/identity":{const{userId:o}=await i(),l=n.users().get(String(o));return g(t,200,{data:{active:!!l,roleNames:l??[],memberships:[],checkedAt:new Date().toISOString()}})}case"/directory/list":{const{kind:o,search:l,ids:d}=await i(),p=typeof l=="string"?l.toLowerCase():"",y=Array.isArray(d)?new Set(d.map(String)):void 0,b=o==="users"?[...n.users().keys()].filter(v=>(!y||y.has(v))&&v.toLowerCase().includes(p)).map(v=>({id:v,displayName:v,active:!0})):[];return g(t,200,{data:{items:b,hasMore:!1}})}case"/directory/match":{const{userId:o,principals:l}=await i(),d=Array.isArray(l)?l:[];return g(t,200,{data:{active:n.users().has(String(o)),matched:d.flatMap((p,y)=>p.kind==="user"&&p.id===o?[y]:[]),checkedAt:new Date().toISOString()}})}case"/directory/validate":{const{principals:o}=await i(),l=Array.isArray(o)?o:[],d=n.users();return g(t,200,{data:{invalid:l.flatMap((p,y)=>p.kind==="user"&&d.has(String(p.id))?[]:[y])}})}case"/storage/get":case"/storage/stream":{const o=u(a.searchParams.get("key"));if(e.method==="POST"&&r==="/storage/stream")return await Ie(o,await ce(e),e.headers["content-type"]),g(t,200,{data:{}});const l=await B(o);if(!l)return g(t,404);let d=await J(o);const p=Number(a.searchParams.get("bytes"));Number.isFinite(p)&&p>0&&(d=d.subarray(0,p)),t.writeHead(200,{"content-type":l.contentType??"application/octet-stream"}),t.end(d);return}case"/storage/put":return await Ie(u(a.searchParams.get("key")),await ce(e),e.headers["content-type"]),g(t,200,{data:{}});case"/storage/head":{const o=await B(u((await i()).key));return o?g(t,200,{data:o}):g(t,404)}case"/storage/delete":{const o=u((await i()).key);return await te(o,{force:!0}),await te(U(o),{force:!0}),g(t,200,{data:{}})}case"/storage/copy":{const{sourceKey:o,destinationKey:l}=await i(),d=u(o),p=u(l);return await B(d)?(await ee(O(p),{recursive:!0}),await ge(d,p),await ge(U(d),U(p)).catch(()=>{}),g(t,200,{data:await B(p)})):g(t,404)}case"/storage/signed-url":{const{key:o}=await i();u(o);const l=`${ie}?key=${encodeURIComponent(String(o))}`;return g(t,200,{data:{url:`${n.origin()}${l}`,path:l}})}default:return n.log(`[host] ${r} is not available in local preview`),g(t,501,{error:{code:"not_available_in_preview",message:`${r} is not available in local preview`}})}}catch(r){const i=r.status??500;g(t,i,{error:{message:r instanceof Error?r.message:String(r)}})}}s(xe,"handleFakeHost");var _e="@tego/plugin-sdk",gt=JSON.stringify(_e),ht=JSON.stringify(`${_e}/frontend`);function Pe(e){return[{path:"index.html",contents:vt(e)},{path:"main.tsx",contents:St(e)},{path:"shell.css",contents:wt},{path:"plugin-surface.tsx",contents:yt}]}s(Pe,"shellFiles");var mt=s(e=>e.replace(/[&<>"]/g,t=>({"&":"&","<":"<",">":">",'"':"""})[t]),"escapeHtml");function vt({displayName:e}){return`<!doctype html>
|
|
2
|
+
<html lang="en" class="h-full">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>${mt(e)} \xB7 local preview</title>
|
|
7
|
+
</head>
|
|
8
|
+
<body class="h-full">
|
|
9
|
+
<div id="tego-dev-bar"></div>
|
|
10
|
+
<div id="tego-dev-plugin"></div>
|
|
11
|
+
<script type="module" src="/main.tsx"><\/script>
|
|
12
|
+
</body>
|
|
13
|
+
</html>
|
|
14
|
+
`}s(vt,"indexHtml");var wt=`@tailwind base;
|
|
15
|
+
@tailwind components;
|
|
16
|
+
@tailwind utilities;
|
|
17
|
+
|
|
18
|
+
html,
|
|
19
|
+
body {
|
|
20
|
+
height: 100%;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
body {
|
|
24
|
+
display: flex;
|
|
25
|
+
flex-direction: column;
|
|
26
|
+
@apply bg-background text-foreground antialiased;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
#tego-dev-plugin {
|
|
30
|
+
flex: 1;
|
|
31
|
+
min-height: 0;
|
|
32
|
+
overflow: auto;
|
|
33
|
+
}
|
|
34
|
+
`,yt=`import type { ReactNode } from 'react';
|
|
35
|
+
|
|
36
|
+
function Unavailable(): ReactNode {
|
|
37
|
+
return (
|
|
38
|
+
<div className='flex h-full items-center justify-center p-6 text-sm text-muted-foreground'>
|
|
39
|
+
Chat is not available in local preview.
|
|
40
|
+
</div>
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const ChatSurface = Unavailable;
|
|
45
|
+
export const ChatPanel = Unavailable;
|
|
46
|
+
export function useTopic() {
|
|
47
|
+
return { topic: undefined, topics: [], loading: false };
|
|
48
|
+
}
|
|
49
|
+
`;function St(e){const t=JSON.stringify({pluginId:e.pluginId,displayName:e.displayName,nav:e.nav.map(a=>({key:a.key,labelKey:a.labelKey,path:a.path??"/"})),config:e.config,locales:e.locales,defaultTarget:e.defaultTarget??"web",userHeader:re,rolesHeader:ae,defaultUser:ve},null,2),n=e.entry?`import plugin from ${JSON.stringify(e.entry)};`:"const plugin = undefined;";return`// Generated by \`tego-plugin dev\` on every start; edits here are overwritten.
|
|
50
|
+
import '@tego/ui/styles/tokens.css';
|
|
51
|
+
import './shell.css';
|
|
52
|
+
|
|
53
|
+
import { pluginI18nNamespace } from ${gt};
|
|
54
|
+
import type { PluginFrontendModule, PluginHostContext, PluginRoute } from ${ht};
|
|
55
|
+
import {
|
|
56
|
+
Button,
|
|
57
|
+
Input,
|
|
58
|
+
Select,
|
|
59
|
+
SelectContent,
|
|
60
|
+
SelectItem,
|
|
61
|
+
SelectTrigger,
|
|
62
|
+
SelectValue,
|
|
63
|
+
Toaster,
|
|
64
|
+
TooltipProvider,
|
|
65
|
+
} from '@tego/ui';
|
|
66
|
+
import i18next from 'i18next';
|
|
67
|
+
import { useState, useSyncExternalStore } from 'react';
|
|
68
|
+
import { createRoot } from 'react-dom/client';
|
|
69
|
+
import { initReactI18next } from 'react-i18next';
|
|
70
|
+
|
|
71
|
+
${n}
|
|
72
|
+
|
|
73
|
+
const DEV = ${t};
|
|
74
|
+
const TARGET: 'web' | 'desktop' = /(?:^|;\\s*)tego-dev-target=desktop(?:;|$)/.test(document.cookie)
|
|
75
|
+
? 'desktop'
|
|
76
|
+
: /(?:^|;\\s*)tego-dev-target=web(?:;|$)/.test(document.cookie)
|
|
77
|
+
? 'web'
|
|
78
|
+
: DEV.defaultTarget;
|
|
79
|
+
const BASE = '/p/' + DEV.pluginId;
|
|
80
|
+
const NAMESPACE = pluginI18nNamespace(DEV.pluginId);
|
|
81
|
+
|
|
82
|
+
function stored(key: string, fallback: string): string {
|
|
83
|
+
try {
|
|
84
|
+
return localStorage.getItem('tegoDev.' + key) ?? fallback;
|
|
85
|
+
} catch {
|
|
86
|
+
return fallback;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function store(key: string, value: string): void {
|
|
90
|
+
try {
|
|
91
|
+
localStorage.setItem('tegoDev.' + key, value);
|
|
92
|
+
} catch {
|
|
93
|
+
// storage blocked: the choice lasts until the next reload
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const user = {
|
|
98
|
+
userId: stored('userId', DEV.defaultUser),
|
|
99
|
+
roles: stored('roles', '').split(',').map(role => role.trim()).filter(Boolean),
|
|
100
|
+
};
|
|
101
|
+
const language = DEV.locales.includes(stored('lang', 'zh-CN')) ? stored('lang', 'zh-CN') : (DEV.locales[0] ?? 'en');
|
|
102
|
+
if (stored('theme', 'light') === 'dark') document.documentElement.classList.add('dark');
|
|
103
|
+
|
|
104
|
+
async function loadLocale(tag: string): Promise<void> {
|
|
105
|
+
if (i18next.hasResourceBundle(tag, NAMESPACE)) return;
|
|
106
|
+
const response = await fetch('/i18n/' + tag + '.json');
|
|
107
|
+
if (response.ok) i18next.addResourceBundle(tag, NAMESPACE, await response.json(), true, true);
|
|
108
|
+
}
|
|
109
|
+
await i18next.use(initReactI18next).init({
|
|
110
|
+
lng: language,
|
|
111
|
+
fallbackLng: false,
|
|
112
|
+
ns: [NAMESPACE],
|
|
113
|
+
defaultNS: NAMESPACE,
|
|
114
|
+
resources: {},
|
|
115
|
+
interpolation: { escapeValue: false },
|
|
116
|
+
});
|
|
117
|
+
await loadLocale(language);
|
|
118
|
+
|
|
119
|
+
const listeners = new Set<() => void>();
|
|
120
|
+
function readRoute(): PluginRoute {
|
|
121
|
+
const path = location.pathname.slice(BASE.length) || '/';
|
|
122
|
+
return { path: path.startsWith('/') ? path : '/' + path, search: location.search };
|
|
123
|
+
}
|
|
124
|
+
let route = readRoute();
|
|
125
|
+
function routeChanged(): void {
|
|
126
|
+
const next = readRoute();
|
|
127
|
+
if (next.path === route.path && next.search === route.search) return;
|
|
128
|
+
route = next;
|
|
129
|
+
for (const listener of listeners) listener();
|
|
130
|
+
}
|
|
131
|
+
addEventListener('popstate', routeChanged);
|
|
132
|
+
if (!location.pathname.startsWith(BASE)) history.replaceState(null, '', BASE + '/');
|
|
133
|
+
|
|
134
|
+
function navigate(to: string): void {
|
|
135
|
+
history.pushState(null, '', to.startsWith('/p/') ? to : BASE + (to.startsWith('/') ? to : '/' + to));
|
|
136
|
+
routeChanged();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const api: PluginHostContext['api'] = {
|
|
140
|
+
request: (path, init = {}) =>
|
|
141
|
+
fetch('/api/v1/tego-os/plugin-api/' + DEV.pluginId + (path.startsWith('/') ? path : '/' + path), {
|
|
142
|
+
...init,
|
|
143
|
+
headers: {
|
|
144
|
+
...(init.headers as Record<string, string> | undefined),
|
|
145
|
+
[DEV.userHeader]: user.userId,
|
|
146
|
+
[DEV.rolesHeader]: JSON.stringify(user.roles),
|
|
147
|
+
},
|
|
148
|
+
}),
|
|
149
|
+
async json<T>(path: string, init?: RequestInit): Promise<T> {
|
|
150
|
+
const response = await api.request(path, init);
|
|
151
|
+
if (!response.ok) throw new Error((init?.method ?? 'GET') + ' ' + path + ': ' + response.status);
|
|
152
|
+
return (await response.json()) as T;
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const navKeys = DEV.nav.map(entry => entry.key);
|
|
157
|
+
const context: PluginHostContext = {
|
|
158
|
+
pluginId: DEV.pluginId,
|
|
159
|
+
layout: { collapseSidebar: () => () => {} },
|
|
160
|
+
basePath: BASE,
|
|
161
|
+
publicPagesUrl: location.origin + '/public/' + DEV.pluginId + '/',
|
|
162
|
+
hostUrl: path => new URL(path, location.origin).toString(),
|
|
163
|
+
user: { userId: user.userId, tenantId: 'dev-tenant', roles: user.roles, displayName: user.userId },
|
|
164
|
+
api,
|
|
165
|
+
route: {
|
|
166
|
+
current: () => route,
|
|
167
|
+
subscribe: listener => {
|
|
168
|
+
listeners.add(listener);
|
|
169
|
+
return () => listeners.delete(listener);
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
events: { subscribe: () => () => {}, connected: () => false, subscribeStatus: () => () => {} },
|
|
173
|
+
config: DEV.config,
|
|
174
|
+
navigate,
|
|
175
|
+
can: navKey => navKeys.includes(navKey),
|
|
176
|
+
// Host API 1.37, as the shells provide it: the preview prints what a plugin
|
|
177
|
+
// asked for, then does the browser equivalent.
|
|
178
|
+
platform: TARGET,
|
|
179
|
+
openExternal: async url => {
|
|
180
|
+
if (!/^https?:\\/\\//i.test(url)) throw new Error('openExternal takes an http(s) URL');
|
|
181
|
+
console.info('[preview] openExternal', url);
|
|
182
|
+
window.open(url, '_blank', 'noopener');
|
|
183
|
+
},
|
|
184
|
+
download: async request => {
|
|
185
|
+
const anchor = document.createElement('a');
|
|
186
|
+
let revoke: string | undefined;
|
|
187
|
+
if ('blob' in request) {
|
|
188
|
+
revoke = URL.createObjectURL(request.blob);
|
|
189
|
+
anchor.href = revoke;
|
|
190
|
+
anchor.download = request.fileName;
|
|
191
|
+
} else {
|
|
192
|
+
if (!request.path.startsWith('/')) throw new Error('download takes a root-relative host path');
|
|
193
|
+
anchor.href = context.hostUrl(request.path);
|
|
194
|
+
if (request.fileName) anchor.download = request.fileName;
|
|
195
|
+
}
|
|
196
|
+
console.info('[preview] download', 'blob' in request ? request.fileName : request.path);
|
|
197
|
+
document.body.append(anchor);
|
|
198
|
+
anchor.click();
|
|
199
|
+
anchor.remove();
|
|
200
|
+
if (revoke) setTimeout(() => URL.revokeObjectURL(revoke), 30_000);
|
|
201
|
+
},
|
|
202
|
+
copyText: async text => {
|
|
203
|
+
try {
|
|
204
|
+
await navigator.clipboard.writeText(text);
|
|
205
|
+
return true;
|
|
206
|
+
} catch {
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
// What the imitated shell's CSP refused on this page (the server prints them too).
|
|
213
|
+
const violations: string[] = [];
|
|
214
|
+
const violationListeners = new Set<() => void>();
|
|
215
|
+
document.addEventListener('securitypolicyviolation', event => {
|
|
216
|
+
violations.push(event.effectiveDirective + ': ' + (event.blockedURI || 'inline'));
|
|
217
|
+
for (const listener of violationListeners) listener();
|
|
218
|
+
});
|
|
219
|
+
function useViolations(): number {
|
|
220
|
+
return useSyncExternalStore(
|
|
221
|
+
listener => {
|
|
222
|
+
violationListeners.add(listener);
|
|
223
|
+
return () => violationListeners.delete(listener);
|
|
224
|
+
},
|
|
225
|
+
() => violations.length
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function useRoute(): PluginRoute {
|
|
230
|
+
return useSyncExternalStore(context.route.subscribe, context.route.current);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function DevBar() {
|
|
234
|
+
const current = useRoute();
|
|
235
|
+
const [lang, setLang] = useState(language);
|
|
236
|
+
const [dark, setDark] = useState(document.documentElement.classList.contains('dark'));
|
|
237
|
+
const [userId, setUserId] = useState(user.userId);
|
|
238
|
+
const [roles, setRoles] = useState(user.roles.join(', '));
|
|
239
|
+
const blocked = useViolations();
|
|
240
|
+
const switchTarget = (next: 'web' | 'desktop') => {
|
|
241
|
+
const url = new URL(location.href);
|
|
242
|
+
url.searchParams.set('target', next);
|
|
243
|
+
location.assign(url.toString());
|
|
244
|
+
};
|
|
245
|
+
const switchUser = () => {
|
|
246
|
+
store('userId', userId.trim() || DEV.defaultUser);
|
|
247
|
+
store('roles', roles);
|
|
248
|
+
location.reload();
|
|
249
|
+
};
|
|
250
|
+
return (
|
|
251
|
+
<div className='flex shrink-0 items-center gap-2 border-b border-border bg-card px-3 py-2 text-sm'>
|
|
252
|
+
<span className='shrink-0 font-medium'>{DEV.displayName}</span>
|
|
253
|
+
<span className='shrink-0 rounded-control bg-sunken px-1.5 py-0.5 font-mono text-xs text-muted-foreground'>preview</span>
|
|
254
|
+
<nav className='flex min-w-0 flex-1 items-center gap-1 overflow-x-auto'>
|
|
255
|
+
{DEV.nav.map(entry => (
|
|
256
|
+
<Button
|
|
257
|
+
key={entry.key}
|
|
258
|
+
size='sm'
|
|
259
|
+
variant={current.path === entry.path ? 'secondary' : 'ghost'}
|
|
260
|
+
onClick={() => navigate(entry.path)}
|
|
261
|
+
>
|
|
262
|
+
{i18next.t(entry.labelKey, { ns: NAMESPACE, lng: lang })}
|
|
263
|
+
</Button>
|
|
264
|
+
))}
|
|
265
|
+
</nav>
|
|
266
|
+
<Select
|
|
267
|
+
value={lang}
|
|
268
|
+
onValueChange={async next => {
|
|
269
|
+
await loadLocale(next);
|
|
270
|
+
await i18next.changeLanguage(next);
|
|
271
|
+
store('lang', next);
|
|
272
|
+
setLang(next);
|
|
273
|
+
}}
|
|
274
|
+
>
|
|
275
|
+
<SelectTrigger className='h-8 w-28' aria-label='Language'>
|
|
276
|
+
<SelectValue />
|
|
277
|
+
</SelectTrigger>
|
|
278
|
+
<SelectContent>
|
|
279
|
+
{DEV.locales.map(tag => (
|
|
280
|
+
<SelectItem key={tag} value={tag}>
|
|
281
|
+
{tag}
|
|
282
|
+
</SelectItem>
|
|
283
|
+
))}
|
|
284
|
+
</SelectContent>
|
|
285
|
+
</Select>
|
|
286
|
+
<div className='flex shrink-0 items-center rounded-control border border-border p-0.5' role='group' aria-label='Shell'>
|
|
287
|
+
{(['web', 'desktop'] as const).map(target => (
|
|
288
|
+
<Button
|
|
289
|
+
key={target}
|
|
290
|
+
size='sm'
|
|
291
|
+
variant={TARGET === target ? 'secondary' : 'ghost'}
|
|
292
|
+
aria-pressed={TARGET === target}
|
|
293
|
+
onClick={() => TARGET !== target && switchTarget(target)}
|
|
294
|
+
>
|
|
295
|
+
{target === 'web' ? 'Web' : 'Desktop'}
|
|
296
|
+
</Button>
|
|
297
|
+
))}
|
|
298
|
+
</div>
|
|
299
|
+
{blocked > 0 && (
|
|
300
|
+
<span
|
|
301
|
+
className='shrink-0 rounded-control bg-destructive-soft px-1.5 py-0.5 text-xs text-destructive'
|
|
302
|
+
title={violations.join('\\n')}
|
|
303
|
+
>
|
|
304
|
+
CSP blocked {blocked}
|
|
305
|
+
</span>
|
|
306
|
+
)}
|
|
307
|
+
<Button
|
|
308
|
+
size='sm'
|
|
309
|
+
variant='ghost'
|
|
310
|
+
onClick={() => {
|
|
311
|
+
document.documentElement.classList.toggle('dark', !dark);
|
|
312
|
+
store('theme', dark ? 'light' : 'dark');
|
|
313
|
+
setDark(!dark);
|
|
314
|
+
}}
|
|
315
|
+
>
|
|
316
|
+
{dark ? 'Light' : 'Dark'}
|
|
317
|
+
</Button>
|
|
318
|
+
<form
|
|
319
|
+
className='flex shrink-0 items-center gap-1'
|
|
320
|
+
onSubmit={event => {
|
|
321
|
+
event.preventDefault();
|
|
322
|
+
switchUser();
|
|
323
|
+
}}
|
|
324
|
+
>
|
|
325
|
+
<Input className='h-8 w-32' aria-label='User id' value={userId} onChange={event => setUserId(event.target.value)} />
|
|
326
|
+
<Input
|
|
327
|
+
className='h-8 w-36'
|
|
328
|
+
aria-label='Roles, comma-separated'
|
|
329
|
+
placeholder='roles'
|
|
330
|
+
value={roles}
|
|
331
|
+
onChange={event => setRoles(event.target.value)}
|
|
332
|
+
/>
|
|
333
|
+
<Button size='sm' variant='outline' type='submit'>
|
|
334
|
+
Sign in as
|
|
335
|
+
</Button>
|
|
336
|
+
</form>
|
|
337
|
+
</div>
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
createRoot(document.getElementById('tego-dev-bar')!).render(
|
|
342
|
+
<TooltipProvider>
|
|
343
|
+
<DevBar />
|
|
344
|
+
<Toaster />
|
|
345
|
+
</TooltipProvider>
|
|
346
|
+
);
|
|
347
|
+
|
|
348
|
+
const mountPoint = document.getElementById('tego-dev-plugin')!;
|
|
349
|
+
const frontend = plugin as PluginFrontendModule | undefined;
|
|
350
|
+
if (frontend) {
|
|
351
|
+
frontend.mount(mountPoint, context);
|
|
352
|
+
} else {
|
|
353
|
+
mountPoint.innerHTML =
|
|
354
|
+
'<p style="padding:24px">This plugin has no frontend part; its API is served at /api/v1/tego-os/plugin-api/' +
|
|
355
|
+
DEV.pluginId +
|
|
356
|
+
'/</p>';
|
|
357
|
+
}
|
|
358
|
+
`}s(St,"mainTsx");var Ae="/__tego/csp-report",$e="TEGO_DEV_CSP ",bt="tego-dev-target",Et=100*1024*1024,De=["default-src 'self'","object-src 'none'","base-uri 'self'"],Ne={web:[...De,"script-src 'self' 'wasm-unsafe-eval'","style-src 'self' 'unsafe-inline'","img-src 'self' data: blob: https:","font-src 'self' data:","connect-src 'self' wss: ws:","frame-src 'self'","worker-src 'self' blob:"].join("; "),desktop:[...De,"script-src 'self' 'wasm-unsafe-eval'","style-src 'self' 'unsafe-inline' https:","img-src 'self' data: blob: http: https:","font-src 'self' data: blob: https:","media-src 'self' data: blob:","worker-src 'self' blob:","connect-src 'self' http: https: ws: wss:","frame-src 'self'"].join("; ")};function ue(e){return e==="web"||e==="desktop"}s(ue,"isPreviewTarget");function Re(e,t){const n=new URL(e.url??"/","http://preview.local").searchParams.get("target");if(ue(n))return n;const a=/(?:^|;\s*)tego-dev-target=(web|desktop)(?:;|$)/.exec(String(e.headers.cookie??""))?.[1];return ue(a)?a:t}s(Re,"targetOf");function Le(e){try{const t=JSON.parse(e)["csp-report"];if(!t)return;const n=String(t["effective-directive"]??t["violated-directive"]??""),a=String(t["blocked-uri"]??"");if(!n)return;const r=typeof t["source-file"]=="string"?t["source-file"]:void 0,i=typeof t["line-number"]=="number"?t["line-number"]:void 0;return{directive:n,blocked:a,...r?{source:r}:{},...i?{line:i}:{}}}catch{return}}s(Le,"parseCspReport");var Oe=5280,kt=20,Ce="TEGO_DEV_READY ",Ue=".tego-dev",Tt="/api/v1/tego-os/plugin-api/";function It(e){const{displayName:t}=e;return typeof t=="string"?t:t.en??t["zh-CN"]??Object.values(t)[0]??e.id}s(It,"displayNameOf");function de(e,t){for(let n=x(e);;n=O(n)){const a=w(n,"node_modules",...t.split("/"));if(K(w(a,"package.json")))return Ye(a);if(O(n)===n)return}}s(de,"packageDir");function N(e,t,n){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))}s(N,"sendJson");function xt(e,t,n){return new Promise((a,r)=>{const i=s(o=>{e.off("listening",u),r(o)},"onError"),u=s(()=>{e.off("error",i);const o=e.address();a(typeof o=="object"&&o?o.port:t)},"onListening");e.once("error",i),e.once("listening",u),e.listen(t,n)})}s(xt,"listen");async function _t(e,t){const n=rt(w(e,"vite.config.ts"));let a,r;try{a=n("@tego/ui/tailwind-preset"),r=O(n.resolve("@tego/ui"))}catch(u){throw new Error(`The preview cannot load @tego/ui's Tailwind preset from ${e}: ${u instanceof Error?u.message:String(u)}. Install the plugin's dependencies.`,{cause:u})}const i=(await import("tailwindcss")).default;return i({presets:[a],content:[w(r,"**/*.{js,cjs}"),w(t,"*.tsx")]})}s(_t,"shellTailwind");function Pt(e,t,n){return{postcssPlugin:"tego-dev-stylesheets",async Once(a,r){const i=a.source?.input.file,u=i&&x(i)===e?[t]:n;if(u.length===0)return;const o=await r.postcss(u).process(a,{from:i});r.result.messages.push(...o.messages)}}}s(Pt,"perStylesheet");function At(e){return Array.isArray(e)?e.flat(1/0).map(t=>{if(!t||typeof t!="object")return t;const{buildStart:n}=t;return typeof n!="function"?t:{...t,buildStart(...a){const r=new Proxy(this,{get(i,u){if(u==="emitFile")return()=>"";const o=Reflect.get(i,u);return typeof o=="function"?o.bind(i):o}});return n.apply(r,a)}}}):e}s(At,"servePlugins");async function $t(e){const t=x(e.root),n=e.log??(c=>console.log(c)),a=await Ke(t),r=We(a),i=w(t,Ue),u=w(i,"shell"),o=pe(32).toString("hex"),l=pe(24).toString("hex");let d="";const p=new Map;let y,b={};const v=r.frontend?x(t,r.frontend.dir):t,{loadConfigFromFile:R,createServer:H,mergeConfig:V}=await import("vite");if(r.frontend){const c=w(v,"vite.config.ts");K(c)&&(b=(await R({command:"serve",mode:"development"},c,t))?.config??{});const f=b.build?.rollupOptions?.input,S=x(t,typeof f=="string"?f:`${r.frontend.dir}/src/index.tsx`);if(!K(S))throw new Error(`The frontend entry ${me(t,S)} does not exist.`);y=me(u,S).split(he).join("/"),y.startsWith(".")||(y=`./${y}`)}const h=s(()=>r.frontend?Je(t,a,r.frontend.i18nDirPath):Promise.resolve(new Map),"localeFiles"),E=[...(await h()).keys()].map(c=>c.replace(/\.json$/,""));await ee(u,{recursive:!0});for(const c of Pe({pluginId:a.id,displayName:It(a),nav:r.frontend?.nav??[],config:r.frontend?.config?fe(r.frontend.config.schema,{}):{},entry:y,locales:E,defaultTarget:e.target??"web"}))await ne(w(u,c.path),c.contents);let P,I;const Be=s(()=>r.backend?.config?fe(r.backend.config.schema,{}):{},"backendConfig"),j=tt((c,f)=>void He(c,f));async function He(c,f){const S=(c.url??"/").split("?")[0],_=Re(c,e.target??"web");try{if(S==="/favicon.ico"){f.writeHead(204),f.end();return}if(S===Ae){const m=await new Promise(F=>{let D="";c.setEncoding("utf8"),c.on("data",A=>D+=A),c.on("end",()=>F(D))}),T=Le(m);T&&(n(`[csp:${_}] blocked ${T.blocked||"(inline)"} by ${T.directive}${T.source?` in ${T.source}${T.line?`:${T.line}`:""}`:""}`),n(`${$e}${JSON.stringify({target:_,...T})}`)),f.writeHead(204),f.end();return}if(S.startsWith(se)||S.startsWith(ie)){await xe(c,f,{token:l,storageDir:w(i,"storage"),config:Be,origin:s(()=>d,"origin"),users:s(()=>p,"users"),log:n});return}const k=/^\/i18n\/([A-Za-z-]+)\.json$/.exec(S);if(k){const m=(await h()).get(`${k[1]}.json`);if(m===void 0)return N(f,404,{error:`no ${k[1]}.json`});f.writeHead(200,{"content-type":"application/json"}),f.end(m);return}const $=`${Tt}${a.id}`;if(S===$||S.startsWith(`${$}/`)){Ve(c,f,(c.url??"/").slice($.length)||"/",_);return}if(String(c.headers.accept??"").includes("text/html")){f.setHeader("Content-Security-Policy",`${Ne[_]}; report-uri ${Ae}`);const m=new URL(c.url??"/","http://preview.local").searchParams.get("target");ue(m)&&f.setHeader("Set-Cookie",`${bt}=${m}; Path=/; SameSite=Lax`)}W.middlewares(c,f,()=>N(f,404,{error:`${S} not found`}))}catch(k){N(f,500,{error:k instanceof Error?k.message:String(k)})}}s(He,"route");function Ve(c,f,S,_){if(!P){N(f,503,{error:I??"The plugin has no backend part."});return}const k=we(c.headers);p.set(k.userId,k.roles);const $=nt({host:"127.0.0.1",port:P.port,method:c.method,path:S,headers:{...ye(c.headers,k,o),..._==="desktop"?{"accept-encoding":"identity"}:{}}},m=>{if(_!=="desktop"){f.writeHead(m.statusCode??502,m.headers),m.pipe(f);return}const T=[];let F=0,D=!1;m.on("data",A=>{if(!D){if(F+=A.length,F>Et){D=!0,m.destroy(),n(`[desktop] ${c.method} ${S}: response over 100 MB refused (413)`),N(f,413,{error:"Response over 100 MB: the desktop app refuses it. Serve large files through storage paths."});return}T.push(A)}}),m.on("end",()=>{if(D)return;const A=Buffer.concat(T),Z={...m.headers};delete Z["transfer-encoding"],Z["content-length"]=String(A.length),f.writeHead(m.statusCode??502,Z),f.end(A)})});$.on("error",m=>{f.headersSent?f.destroy():N(f,502,{error:`The backend is not answering (${m.message}); see the terminal.`})}),c.pipe($)}s(Ve,"proxy");const je=w(u,"shell.css"),Ge=(()=>{const c=b.css?.postcss;return c&&typeof c=="object"?c.plugins??[]:[]})(),G=(()=>{const c=de(v,"react-i18next");return(c&&de(c,"i18next"))??de(v,"i18next")})(),{css:Dt,mode:Nt,build:Rt,...z}=b;z.plugins=At(z.plugins);const W=await H(V(z,{configFile:!1,root:u,mode:"development",appType:"spa",clearScreen:!1,logLevel:"info",esbuild:{jsx:"automatic",jsxDev:!1},css:{postcss:{plugins:[Pt(je,await _t(v,u),Ge)]}},resolve:{alias:[{find:"@tego/chat/plugin-surface",replacement:w(u,"plugin-surface.tsx")},...G?[{find:/^i18next$/,replacement:G}]:[]]},server:{middlewareMode:!0,hmr:{server:j},fs:{allow:[t,u,...G?[G]:[]]}},optimizeDeps:{entries:[w(u,"index.html")]}})),M=e.host??"127.0.0.1";let q;const X=e.port??Oe;for(let c=0;q===void 0;c++)try{q=await xt(j,X===0?0:X+c,M)}catch(f){if(f.code!=="EADDRINUSE"||X===0||c>=kt)throw await W.close(),f}const Y=M==="0.0.0.0"||M==="::"?"127.0.0.1":M;if(d=`http://${Y.includes(":")?`[${Y}]`:Y}:${q}`,!r.backend)I="The plugin has no backend part.";else if(e.backend===!1)I="The backend is off (--no-backend).";else if(!e.databaseUrl)I="The backend needs a PostgreSQL: start the preview with DATABASE_URL=postgres://\u2026 (each plugin gets its own schema).";else try{P=await ft({root:t,pluginId:a.id,version:a.version,part:r.backend,databaseUrl:e.databaseUrl,outDir:w(i,"backend"),hostApiUrl:`${d}${se}`,hostApiToken:l,gatewayKey:o,log:n})}catch(c){I=`The backend did not start: ${c instanceof Error?c.message:String(c)}`}I&&r.backend&&n(`[backend] ${I}`);const Q=`${d}/p/${a.id}/`;return n(`${a.id} ${a.version}: local preview at ${Q}`),e.databaseUrl&&P&&n(` database ${oe(e.databaseUrl)}, schema ${P.schema}`),n(`${Ce}${JSON.stringify({url:Q})}`),{url:Q,async close(){await P?.close(),await W.close(),j.closeAllConnections(),await new Promise(c=>j.close(()=>c()))}}}s($t,"startDevServer");export{$e as CSP_REPORT_PREFIX,Oe as DEFAULT_DEV_PORT,Ue as DEV_DIR,Ce as DEV_READY_PREFIX,ae as DEV_ROLES_HEADER,C as DEV_TENANT_ID,re as DEV_USER_HEADER,Ne as PREVIEW_CSP,ke as applyDevMigrations,we as devCallerOf,be as devDatabaseUrl,Se as devSchemaName,ye as gatewayHeaders,xe as handleFakeHost,Le as parseCspReport,Pe as shellFiles,$t as startDevServer,le as storagePath,Re as targetOf};
|
package/dist/doctor.cjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";var A=Object.defineProperty;var d=(e,t)=>A(e,"name",{value:t,configurable:!0});var chunkSKNPNPJP_cjs=require("./chunk-SKNPNPJP.cjs"),chunk45Y4CR4R_cjs=require("./chunk-45Y4CR4R.cjs"),chunk2P6UEAPV_cjs=require("./chunk-2P6UEAPV.cjs"),chunkN4SXZZPY_cjs=require("./chunk-N4SXZZPY.cjs"),chunk6HNG5OZI_cjs=require("./chunk-6HNG5OZI.cjs");require("./chunk-AJY7ZHXK.cjs"),require("./chunk-OP64Y4IN.cjs");var child_process=require("child_process"),promises=require("fs/promises"),path=require("path"),COLOR_ALLOW_MARKER="ui-colors-allow",PALETTE="slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose",UTILITY="bg|text|border(?:-[trblxyse])?|ring(?:-offset)?|from|via|to|fill|stroke|outline|divide|placeholder|caret|accent|decoration|shadow",COLOR_PATTERNS=[new RegExp(`(?<![\\w-])(?:${UTILITY})-(?:(?:${PALETTE})-(?:50|[1-9]00|950)|white|black)(?:\\/\\d{1,3})?(?![\\w-])`,"g"),/-\[(?:#[0-9a-fA-F]{3,8}|(?:rgba?|hsla?)\(\s*\d+)/g,/(?<![a-zA-Z0-9[-])(?:rgba?|hsla?)\(\s*\d+/g],QUOTED_HEX=/['"`]#[0-9a-fA-F]{3,8}['"`]/g,CSS_HEX=/(?<![\w&-])#[0-9a-fA-F]{3,8}(?![\w-])/g,DARK_VARIANT=/(?<![\w-])dark:(?=\S)/g,DARK_SELECTOR=/\.dark(?![\w-])/g;function stripComments(e){return e.replace(/(^|[\s{(,;])\/\*[\s\S]*?\*\//g,(t,r)=>r+t.slice(r.length).replace(/[^\n]/g," ")).replace(/(^|\s)\/\/.*$/gm,(t,r)=>r)}d(stripComments,"stripComments");function allowedLines(e){const t=new Set;return e.forEach((r,s)=>{r.includes(COLOR_ALLOW_MARKER)&&(t.add(s),/^\s*(?:\/\/|\/\*|\*|\{\/\*)/.test(r)&&t.add(s+1))}),t}d(allowedLines,"allowedLines");function findColorIssues(e,t){const r=t===".css",s=allowedLines(e.split(`
|
|
2
|
+
`)),c=stripComments(e).split(`
|
|
3
|
+
`),i=[...COLOR_PATTERNS,r?CSS_HEX:QUOTED_HEX],o=r?[DARK_VARIANT,DARK_SELECTOR]:[DARK_VARIANT],h=[];return c.forEach((f,n)=>{if(s.has(n))return;const u=[];for(const[a,l]of[["color",i],["dark",o]])for(const w of l)for(const k of f.matchAll(w))u.push({kind:a,match:k[0],at:k.index??0});u.sort((a,l)=>a.kind.localeCompare(l.kind)||a.at-l.at).forEach(({kind:a,match:l})=>h.push({line:n+1,kind:a,match:l}))}),h}d(findColorIssues,"findColorIssues");var rule=d((e,t,r,s)=>({id:e,severity:t,guide:r,title:s}),"rule"),DOCTOR_RULES=[rule("TP-MAN-001","error","manifest.md","tego.plugin.json is valid"),rule("TP-MAN-002","error","host-api-versions.md","hostApiRange admits every host capability the code uses"),rule("TP-PKG-001","error","manifest.md","SDK packages come from npm aliases or workspace links, never a plain @tego/* name"),rule("TP-PKG-002","warning","testing.md","package.json has the lint, type-check, test and build gates"),rule("TP-CLAW-002","warning","claw.md","Each claw skill's frontmatter name matches its folder"),rule("TP-DESK-001","error","desktop-web.md","No eval or new Function (the desktop CSP refuses them)"),rule("TP-DESK-002","error","desktop-web.md","No addresses built from location.origin (tauri://localhost on desktop)"),rule("TP-DESK-003","error","desktop-web.md","External links open with ctx.openExternal, not window.open"),rule("TP-DESK-004","error","desktop-web.md","Files are saved with ctx.download, not <a download> or a.download"),rule("TP-DESK-005","warning","desktop-web.md","No streamed responses or EventSource from the frontend (the desktop proxy buffers; use ctx.events)"),rule("TP-DESK-006","warning","desktop-web.md","Clipboard writes go through ctx.copyText"),rule("TP-WEB-001","error","desktop-web.md","The frontend calls no third-party URL (the web CSP blocks it); call the backend, which declares egress"),rule("TP-WEB-002","error","desktop-web.md","No remote or injected scripts; everything ships in the bundle"),rule("TP-UI-001","error","ui.md","Colors come from token classes: no hex, rgb(), palette classes or dark: overrides"),rule("TP-UI-002","error","ui.md","No direct @radix-ui/* imports; use @tego/ui"),rule("TP-UI-003","error","ui.md","The plugin's root element carries its scope class (.<pluginId>) when it compiles its own Tailwind"),rule("TP-UI-004","error","frontend.md","The frontend has its own error boundary"),rule("TP-I18N-001","error","i18n.md","All ten locales, with the same keys as zh-CN, and every nav label defined"),rule("TP-I18N-002","error","i18n.md","Every locale value keeps the {{placeholders}} of zh-CN and is not empty"),rule("TP-I18N-003","error","i18n.md","Every literal t('\u2026') key exists in zh-CN"),rule("TP-I18N-004","warning","i18n.md","Current terminology: \u6570\u5B57\u5458\u5DE5 / Employee, never \u6570\u5B57\u5206\u8EAB / digital avatar"),rule("TP-BE-001","error","backend.md","Identity comes from the verified ctx, never from the raw x-tego-plugin-* headers"),rule("TP-BE-002","error","access.md","No host role names in business code; ask the access engine"),rule("TP-BE-003","error","migrations.md","Migrations are <ordinal>_<name>.sql with unique ordinals"),rule("TP-BE-004","error","migrations.md","Committed migrations are never edited or deleted"),rule("TP-BE-005","warning","backend.md","Backend errors are logged through host.log, not console"),rule("TP-ACC-001","error","access.md","With an access catalog, a test asserts every route has a policy (assertRouteCoverage)"),rule("TP-ACC-002","error","access.md","With an access catalog, start() reconciles it (reconcile(host))"),rule("TP-TEST-001","warning","testing.md","The plugin has tests")],BY_ID=new Map(DOCTOR_RULES.map(e=>[e.id,e]));function doctorRule(e){return BY_ID.get(e)}d(doctorRule,"doctorRule");var VERSIONED_CAPABILITIES=[{pattern:/\.openExternal\s*\(/,since:"1.37.0",name:"ctx.openExternal"},{pattern:/\.copyText\s*\(/,since:"1.37.0",name:"ctx.copyText"},{pattern:/\b(?:ctx|host|context)\.download\s*\(/,since:"1.37.0",name:"ctx.download"},{pattern:/\b(?:ctx|host|context)\.platform\b/,since:"1.37.0",name:"ctx.platform"}],SOURCE_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".css"]),SKIP_DIRS=new Set(["node_modules","dist","build",".tego-dev",".turbo",".drizzle","__fixtures__","coverage"]),TEST_FILE=/\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|[\\/])test[\\/]|(?:^|[\\/])test-[\w-]+\.[cm]?[jt]s$|-double\.[cm]?[jt]s$|\.d\.ts$/,IGNORE_MARKER=/tego-doctor-ignore\s+([A-Z0-9-]+(?:\s*,\s*[A-Z0-9-]+)*)/,PLACEHOLDER=/\{\{\s*([\w.-]+)\s*\}\}/g,REQUIRED_SCRIPTS=["lint","type-check","test","build"];function toPosix(e){return e.split(path.sep).join("/")}d(toPosix,"toPosix");async function walk(e,t,r){let s;try{s=await promises.readdir(path.join(e,t),{withFileTypes:!0})}catch{return}for(const c of s){const i=t?`${t}/${c.name}`:c.name;c.isDirectory()?!SKIP_DIRS.has(c.name)&&!c.name.startsWith(".")&&await walk(e,i,r):SOURCE_EXTENSIONS.has(path.extname(c.name))&&r.push(i)}}d(walk,"walk");function folderReader(e){return{async list(t){try{return(await promises.readdir(path.join(e,t),{withFileTypes:!0})).filter(s=>s.isFile()).map(s=>s.name)}catch{return[]}},readText:d(t=>promises.readFile(path.join(e,t),"utf8").catch(()=>null),"readText")}}d(folderReader,"folderReader");function runGit(e,t){return new Promise(r=>{child_process.execFile("git",["-C",e,...t],{maxBuffer:8*1024*1024},(s,c)=>r(s?null:c))})}d(runGit,"runGit");function ignoredLines(e){const t=new Map;return e.split(`
|
|
4
|
+
`).forEach((r,s)=>{const c=IGNORE_MARKER.exec(r);if(!c?.[1])return;const i=new Set(c[1].split(",").map(h=>h.trim())),o=d(h=>t.set(h,new Set([...t.get(h)??[],...i])),"add");o(s),/^\s*(?:\/\/|\/\*|\*|\{\/\*)/.test(r)&&o(s+1)}),t}d(ignoredLines,"ignoredLines");var Findings=class{static{d(this,"Findings")}list=[];add(e,t,r={}){const{severity:s,guide:c}=doctorRule(e);this.list.push({rule:e,severity:s,message:t,guide:c,...r})}};function eachMatch(e,t,r,s){const c=ignoredLines(e.text);e.code.split(`
|
|
5
|
+
`).forEach((i,o)=>{if(c.get(o)?.has(t))return;const h=r.exec(i);h&&s(o+1,h[0])})}d(eachMatch,"eachMatch");function partOf(e,t){const r=d(s=>!!s&&(e===s||e.startsWith(`${s}/`)),"inside");return r(t.frontend?.dir)||r(t.publicFrontend?.dir)?"frontend":r(t.backend?.dir)?"backend":r(t.claw?.dir)?"claw":r("shared")?"shared":"other"}d(partOf,"partOf");async function readJson(e){try{return JSON.parse(await promises.readFile(e,"utf8"))}catch{return}}d(readJson,"readJson");function checkPackageJson(e,t){if(!t)return;for(const c of["dependencies","devDependencies","peerDependencies"]){const i=t[c];if(!(!i||typeof i!="object"))for(const[o,h]of Object.entries(i))!o.startsWith("@tego/")||typeof h!="string"||/^(?:npm:@zhama\/tego-|workspace:|file:|link:|portal:)/.test(h)||e.add("TP-PKG-001",`${c}.${o} is "${h}": on npm @tego/* belongs to another project. Install it as "npm:@zhama/tego-${o.slice(6)}@^<sdk version>".`,{file:"package.json"})}const r=t.scripts??{},s=REQUIRED_SCRIPTS.filter(c=>typeof r[c]!="string");s.length>0&&e.add("TP-PKG-002",`package.json has no ${s.map(c=>`"${c}"`).join(", ")} script; the platform's gates are lint, type-check, test and build.`,{file:"package.json"})}d(checkPackageJson,"checkPackageJson");async function checkLocales(e,t,r,s,c){const i=s.frontend;if(!i)return;const{bundles:o,errors:h}=await chunk45Y4CR4R_cjs.verifyFrontendLocales(folderReader(t),i);for(const p of h)e.add("TP-I18N-001",p,{file:i.i18nDirPath});const f=o.get("zh-CN");if(!f)return;const n=d((p,m="",P=new Map)=>{if(typeof p!="object"||p===null||Array.isArray(p))return P.set(m,p),P;for(const[b,T]of Object.entries(p))n(T,m?`${m}.${b}`:b,P);return P},"leaves"),u=d(p=>new Set(typeof p=="string"?[...p.matchAll(PLACEHOLDER)].map(m=>m[1]):[]),"placeholders"),a=n(f);for(const[p,m]of o){const P=`${i.i18nDirPath}/${p}.json`;let b=0;for(const[T,g]of n(m)){if(b>=10)break;if(typeof g=="string"&&g.trim()===""){e.add("TP-I18N-002",`"${T}" is empty in ${p}.json.`,{file:P}),b++;continue}if(p==="zh-CN"||!a.has(T))continue;const v=u(a.get(T)),y=u(g),x=[...v].filter(E=>!y.has(E)),S=[...y].filter(E=>!v.has(E));(x.length||S.length)&&(e.add("TP-I18N-002",`"${T}" in ${p}.json has placeholders {${[...y].join(", ")}} but zh-CN has {${[...v].join(", ")}}.`,{file:P}),b++)}for(const[T,g]of n(m))if(typeof g=="string"&&/数字分身|digital avatar/i.test(g)){e.add("TP-I18N-004",`"${T}" in ${p}.json says "${/数字分身/.test(g)?"\u6570\u5B57\u5206\u8EAB":"digital avatar"}"; the platform calls them \u6570\u5B57\u5458\u5DE5 / Employee ({{avatarTerm}}).`,{file:P});break}}const l=chunk45Y4CR4R_cjs.flattenLocaleKeys(f),w=new Set(Object.keys(f)),k=d(p=>l.has(p)||["_one","_other","_zero","_few","_many","_two"].some(m=>l.has(p+m))||[...l].some(m=>m.startsWith(`${p}.`)),"exists");for(const p of c){if(p.part!=="frontend"||p.test)continue;const m=ignoredLines(p.text);p.code.split(`
|
|
6
|
+
`).forEach((P,b)=>{if(!m.get(b)?.has("TP-I18N-003"))for(const T of P.matchAll(/\bt\(\s*['"]([A-Za-z0-9_.-]+)['"]/g)){const g=T[1],v=g.split(".")[0];!g.includes(".")||!w.has(v)||k(g)||e.add("TP-I18N-003",`t('${g}') has no entry in zh-CN.json (namespace ${chunkN4SXZZPY_cjs.pluginI18nNamespace(r.id)}).`,{file:p.path,line:b+1})}})}}d(checkLocales,"checkLocales");async function checkMigrations(e,t,r){const s=r.backend;if(!s)return;const{errors:c}=await chunk45Y4CR4R_cjs.verifyMigrationNames(folderReader(t),s.migrationsDirPath);for(const h of c)e.add("TP-BE-003",h,{file:s.migrationsDirPath});const i=await runGit(t,["diff","--name-status","HEAD","--",s.migrationsDirPath]);if(!i)return;const o=(await runGit(t,["rev-parse","--show-prefix"]))?.trim()??"";for(const h of i.split(`
|
|
7
|
+
`)){const[f,n]=h.split(" ");if(!n||f!=="M"&&f!=="D")continue;const u=n.startsWith(o)?n.slice(o.length):n;e.add("TP-BE-004",`${u} is a committed migration and was ${f==="M"?"edited":"deleted"}; an install may have applied it already. Revert it and add a new migration instead.`,{file:u})}}d(checkMigrations,"checkMigrations");async function checkClaw(e,t,r){const s=r.claw;if(!s)return;const c=path.join(t,s.dir,"skills");let i=[];try{i=(await promises.readdir(c,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return}for(const o of i){const h=await promises.readFile(path.join(c,o,"SKILL.md"),"utf8").catch(()=>null),f=`${s.dir}/skills/${o}/SKILL.md`,n=h?/^---[\s\S]*?^name:\s*["']?([^"'\n]+)["']?\s*$/m.exec(h)?.[1]?.trim():void 0;n!==o&&e.add("TP-CLAW-002",h?`${f} declares name "${n??"(none)"}"; it must equal the folder name "${o}".`:`${s.dir}/skills/${o} has no SKILL.md.`,{file:f})}}d(checkClaw,"checkClaw");function checkSources(e,t,r,s,c,i){const o=t.hostApiRange&&chunk6HNG5OZI_cjs.isValidHostApiRange(t.hostApiRange)?chunk6HNG5OZI_cjs.hostApiRangeMinimum(t.hostApiRange):void 0,h=d(n=>{if(!o)return!1;const[u,a,l]=o.split(".").map(Number),[w,k,p]=n.split(".").map(Number);return u!==w?u<w:a!==k?a<k:l<p},"below");for(const n of s){if(!c(n)||n.test)continue;const u=d(a=>({file:n.path,line:a}),"at");if(n.part==="frontend"){if(n.path.endsWith(".css")||n.path.endsWith(".tsx")||n.path.endsWith(".ts")){const a=ignoredLines(n.text);for(const l of findColorIssues(n.text,path.extname(n.path)))a.get(l.line-1)?.has("TP-UI-001")||e.add("TP-UI-001",l.kind==="dark"?`"${l.match}" is a hand-written dark override; tokens already carry both themes.`:`"${l.match}" is a literal color; use a token class (bg-card, text-muted-foreground, bg-primary\u2026).`,u(l.line))}eachMatch(n,"TP-DESK-001",/\beval\s*\(|\bnew\s+Function\s*\(/,a=>e.add("TP-DESK-001","eval / new Function: the desktop app's CSP (script-src 'self') refuses code compiled from strings.",u(a))),eachMatch(n,"TP-DESK-002",/\b(?:window\.|document\.)?location\.origin\b/,a=>e.add("TP-DESK-002","location.origin is tauri://localhost in the desktop app; build host addresses with ctx.hostUrl(path) and share links from ctx.publicPagesUrl.",u(a))),eachMatch(n,"TP-DESK-003",/\bwindow\.open\s*\(/,a=>e.add("TP-DESK-003","window.open does not reliably open links in the desktop app; use ctx.openExternal(url) (hostApiRange ^1.37.0), or ctx.download for a file.",u(a))),eachMatch(n,"TP-DESK-004",/\.download\s*=(?!=)|<a\b[^>]*\sdownload(?:[\s=>]|$)/,a=>e.add("TP-DESK-004","An <a download> save is not handled by the desktop app; use ctx.download({ path | blob, fileName }) (hostApiRange ^1.37.0).",u(a))),eachMatch(n,"TP-DESK-005",/\bnew\s+EventSource\s*\(|\.body\s*(?:\?\.|!\.|\.)\s*getReader\s*\(/,a=>e.add("TP-DESK-005","The desktop app buffers ctx.api responses whole (and caps them at 100 MB), so streams arrive at the end; subscribe to ctx.events for pushed updates.",u(a))),eachMatch(n,"TP-DESK-006",/\bnavigator\.clipboard\./,a=>e.add("TP-DESK-006","navigator.clipboard is not available in every shell; use ctx.copyText(text) (hostApiRange ^1.37.0).",u(a))),eachMatch(n,"TP-WEB-001",/\bfetch\s*\(\s*['"`]https?:\/\//,a=>e.add("TP-WEB-001","The web app's CSP allows connections to the platform only; call your backend through ctx.api and let it reach the service (declare it in parts.backend.egress).",u(a))),eachMatch(n,"TP-WEB-002",/\bimport\s*\(\s*['"`]https?:|createElement\(\s*['"]script['"]\s*\)|<script\b[^>]*\bsrc=/,a=>e.add("TP-WEB-002","Remote or injected scripts are refused by both shells' CSP; bundle the code.",u(a))),eachMatch(n,"TP-UI-002",/from\s+['"]@radix-ui\//,a=>e.add("TP-UI-002","Import the @tego/ui wrapper instead of @radix-ui/* (the shell shares @tego/ui; a second Radix copy breaks focus and portals).",u(a)));for(const a of VERSIONED_CAPABILITIES){if(!h(a.since))continue;const l=a.name.split(".").pop();new RegExp(`\\.${l}\\s*(?:\\)|\\?(?!\\.)|&&)`).test(n.code)||eachMatch(n,"TP-MAN-002",a.pattern,w=>e.add("TP-MAN-002",`${a.name} needs host API ${a.since}, but hostApiRange is "${t.hostApiRange}"; raise it to ^${a.since}.`,u(w)))}}n.part==="backend"&&(eachMatch(n,"TP-BE-001",/\bheaders?\s*(?:\.get)?\(\s*['"]x-tego-plugin-(?:user-id|tenant-id|roles|avatar-id|delegation)['"]|\bheaders\s*\[\s*['"]x-tego-plugin-(?:user-id|tenant-id|roles|avatar-id|delegation)['"]/i,a=>e.add("TP-BE-001","Take the caller from the verified ctx (ctx.userId, ctx.tenantId, ctx.roles) that serveBackend hands you; the raw x-tego-plugin-* headers are unverified here.",u(a))),eachMatch(n,"TP-BE-005",/\bconsole\.(?:error|warn)\s*\(/,a=>e.add("TP-BE-005","Log through host.log so the message reaches the platform's logs; console output from a plugin container is not collected.",u(a)))),n.part!=="other"&&eachMatch(n,"TP-BE-002",/\b(?:roles|roleNames)\s*\??\.\s*(?:includes|indexOf)\(\s*['"`](?:admin|owner|super_?admin|tenant_?admin|member|manager)['"`]/i,a=>e.add("TP-BE-002","Do not decide by host role names; declare permissions in the access catalog (hostRoleBindings) and ask the engine (authorize / useAccess).",u(a)))}const f=s.filter(n=>n.part==="frontend"&&!n.test);if(r.frontend&&f.length>0&&(f.some(n=>/getDerivedStateFromError|componentDidCatch|PluginErrorBoundary/.test(n.code))||e.add("TP-UI-004","No error boundary in the frontend: the shell's boundary cannot see into your React root, so a render error leaves a blank page. Wrap the root in PluginErrorBoundary (@tego/plugin-sdk/react) or your own.",{file:r.frontend.dir}),i?.includes("tegoPluginTailwind"))){const n=new RegExp(`(?:className|class)=\\{?\\s*(?:cn\\()?\\s*['"\`][^'"\`]*(?<![\\w-])${t.id.replace(/[.]/g,"\\.")}(?![\\w-])`);f.some(u=>n.test(u.code))||e.add("TP-UI-003",`tegoPluginTailwind scopes every utility under .${t.id}, but no element carries className="${t.id}": none of the plugin's own classes will apply. Put it on the root element (and on portalled content, or use tegoPluginScopeRoot).`,{file:r.frontend.dir})}}d(checkSources,"checkSources");function checkAccessAndTests(e,t,r,s){const c=s.filter(o=>o.test);if(c.length===0&&e.add("TP-TEST-001","The plugin has no *.test.ts files; backend routes and pure frontend logic need tests (createTestPluginHost for SQL)."),!t.access||!r.backend)return;c.some(o=>o.text.includes("assertRouteCoverage"))||e.add("TP-ACC-001","The manifest declares an access catalog but no test calls assertRouteCoverage(app): a route without a policy would be open to everyone who can open the plugin.",{file:r.backend.dir}),s.filter(o=>(o.part==="backend"||o.part==="shared")&&!o.test).some(o=>/\breconcile\s*\(/.test(o.code))||e.add("TP-ACC-002","The manifest declares an access catalog but start() never calls reconcile(host): built-in roles and catalog changes never reach the database.",{file:r.backend.dir})}d(checkAccessAndTests,"checkAccessAndTests");async function runDoctor(e){const t=e.root;await promises.stat(path.join(t,"tego.plugin.json")).catch(()=>{throw new Error(`No tego.plugin.json in ${t}; run doctor in the plugin folder.`)});const r=new Findings;let s;try{s=JSON.parse(await promises.readFile(path.join(t,"tego.plugin.json"),"utf8"))}catch(l){return r.add("TP-MAN-001",`tego.plugin.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`,{file:"tego.plugin.json"}),summarize(r,void 0)}const c=chunkSKNPNPJP_cjs.parseTegoPluginManifest(s);if(!c.ok||!c.manifest){for(const l of c.errors)r.add("TP-MAN-001",l,{file:"tego.plugin.json"});return summarize(r,s.id)}const i=c.manifest,o=chunk2P6UEAPV_cjs.resolvePluginParts(i),h=[];await walk(t,"",h);const f=await Promise.all(h.map(async l=>{const w=await promises.readFile(path.join(t,l),"utf8");return{path:l,part:partOf(l,o),text:w,code:stripComments(w),test:TEST_FILE.test(l)}})),n=e.files?.map(l=>toPosix(path.relative(t,path.join(t,l)))),u=d(l=>!n||n.includes(l.path),"scanned"),a=o.frontend?await promises.readFile(path.join(t,o.frontend.dir,"vite.config.ts"),"utf8").catch(()=>null):null;return checkPackageJson(r,await readJson(path.join(t,"package.json"))),await checkLocales(r,t,i,o,f.filter(u)),await checkMigrations(r,t,o),await checkClaw(r,t,o),checkSources(r,i,o,f,u,a),checkAccessAndTests(r,i,o,f),summarize(r,i.id)}d(runDoctor,"runDoctor");function summarize(e,t){const r={errors:e.list.filter(i=>i.severity==="error").length,warnings:e.list.filter(i=>i.severity==="warning").length},s=new Map(DOCTOR_RULES.map((i,o)=>[i.id,o])),c=[...e.list].sort((i,o)=>(i.severity===o.severity?0:i.severity==="error"?-1:1)||(s.get(i.rule)??0)-(s.get(o.rule)??0)||(i.file??"").localeCompare(o.file??"")||(i.line??0)-(o.line??0));return{...t?{pluginId:t}:{},findings:c,...r}}d(summarize,"summarize");var UPLOAD_BLOCKING_RULES=["TP-MAN-001","TP-I18N-001","TP-BE-003"];function formatDoctorReport(e){const t=e.findings.map(r=>{const s=r.file?`${r.file}${r.line?`:${r.line}`:""} `:"";return`${r.severity==="error"?"\u2716":"\u26A0"} ${r.rule} ${s}${r.message}`});return t.push(e.findings.length===0?"\u2705 doctor: no problems":`${e.errors} error(s), ${e.warnings} warning(s). Each rule is explained in node_modules/@tego/plugin-sdk/agent/RULES.md.`),t.join(`
|
|
8
|
+
`)}d(formatDoctorReport,"formatDoctorReport"),exports.DOCTOR_RULES=DOCTOR_RULES,exports.UPLOAD_BLOCKING_RULES=UPLOAD_BLOCKING_RULES,exports.doctorRule=doctorRule,exports.findColorIssues=findColorIssues,exports.formatDoctorReport=formatDoctorReport,exports.runDoctor=runDoctor;
|