@joplo-app/server 0.2.1 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/build.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Project } from '@joplo-app/core';
2
2
  import type { BuildOptions, BuildResult } from './contract.js';
3
3
  import type { DistWeb } from './web-assets.js';
4
- /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级与镜头属于演示,保留(D43)。 */
4
+ /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头与 featureIds 顺序属于演示,保留(D43 / D61)。 */
5
5
  export declare function publishPayload(project: Project, home: string | null): {
6
6
  project: Record<string, unknown>;
7
7
  home: string | null;
package/dist/build.js CHANGED
@@ -7,6 +7,8 @@
7
7
  * 3. 后处理:IR 内联到 index.html;入口脚本内联为 <script type="module">、去掉 crossorigin,
8
8
  * 这样直接双击 index.html(file://)也能离线运行。产物是普通静态目录,可 `wrangler deploy --assets` 或任何静态托管发布。
9
9
  *
10
+ * `review: true`(评审版,D63)时第 1 步用 compile 的 review 模式:含所有功能的所有方案,同样去掉创作侧信息;其余步骤相同。
11
+ *
10
12
  * 目标目录非空且没有 overwrite 时拒绝写入;永远不清空项目目录本身或它的上级目录。
11
13
  *
12
14
  * 从 npm 安装时(web-assets.ts 的 dist 形态)第 2 步不编译界面源码:复制 @joplo-app/web 预构建的发布站,
@@ -17,13 +19,14 @@ import os from 'node:os';
17
19
  import path from 'node:path';
18
20
  import tailwindcss from '@tailwindcss/vite';
19
21
  import { build as viteBuild, createServer } from 'vite';
20
- import { JoploError } from '@joplo-app/core';
22
+ import { JoploError, orderedFeatures } from '@joplo-app/core';
21
23
  import { compileProject } from "./project.js";
22
24
  import { joploProjectPlugin, kitAliases, locateWebAssets, realProjectDir } from "./vite-shared.js";
23
- /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级与镜头属于演示,保留(D43)。 */
25
+ import { subsetSiteFonts } from "./site-fonts.js";
26
+ /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头与 featureIds 顺序属于演示,保留(D43 / D61)。 */
24
27
  export function publishPayload(project, home) {
25
28
  const { rules: _r, cases: _c, issues: _i, ...rest } = project;
26
- const features = Object.fromEntries(Object.entries(project.features).map(([id, f]) => [id, { id: f.id, name: f.name, goal: f.goal, optionIds: f.optionIds, pick: f.pick }]));
29
+ const features = Object.fromEntries(orderedFeatures(project).map(f => [f.id, { id: f.id, name: f.name, goal: f.goal, optionIds: f.optionIds, pick: f.pick }]));
27
30
  const options = Object.fromEntries(Object.entries(project.options).map(([id, o]) => [id, { id: o.id, featureId: o.featureId, key: o.key, name: o.name, idea: o.idea, routes: o.routes, coverage: {}, layers: o.layers ?? {} }]));
28
31
  const scenarios = Object.fromEntries(Object.entries(project.scenarios).map(([id, s]) => {
29
32
  const { caseIds: _ci, ...sr } = s;
@@ -91,7 +94,7 @@ export async function buildSite(opts) {
91
94
  if (nonEmpty && fs.existsSync(path.join(outDir, 'joplo.config.ts')))
92
95
  throw new JoploError('USAGE', `Output directory appears to be a Joplo project (contains joplo.config.ts); refusing to clear: ${outDir}`);
93
96
  const web = locateWebAssets();
94
- // 1. 编译(publish)
97
+ // 1. 编译(publish;评审版用 review)
95
98
  const loader = await createServer({
96
99
  configFile: false,
97
100
  envDir: false,
@@ -105,7 +108,7 @@ export async function buildSite(opts) {
105
108
  });
106
109
  let compiled;
107
110
  try {
108
- compiled = await compileProject(loader, projectDir, 'publish');
111
+ compiled = await compileProject(loader, projectDir, opts.review === true ? 'review' : 'publish');
109
112
  }
110
113
  finally {
111
114
  await loader.close();
@@ -133,6 +136,8 @@ export async function buildSite(opts) {
133
136
  for (const rel of inlined)
134
137
  fs.rmSync(path.join(staging, rel));
135
138
  fs.writeFileSync(path.join(staging, 'index.html'), html.replace(/<title>[^<]*<\/title>/i, () => `<title>${escapeHtml(project.name)} · Joplo</title>`));
139
+ // D59: scan every staged text artifact, then retain only font subsets its content needs.
140
+ subsetSiteFonts(staging, web);
136
141
  // 4. 写入目标目录
137
142
  if (fs.existsSync(outDir))
138
143
  fs.rmSync(outDir, { recursive: true, force: true });
@@ -25,6 +25,11 @@ export type BuildOptions = {
25
25
  outDir?: string;
26
26
  /** 目标目录非空时,必须显式允许才清空重建。 */
27
27
  overwrite?: boolean;
28
+ /**
29
+ * 评审版(D63,`joplo share --review`):含所有功能的所有方案(compile 的 review 模式),创作侧信息与普通发布一样去掉。
30
+ * 缺省 false:只含选定方案,与原来完全一致。
31
+ */
32
+ review?: boolean;
28
33
  };
29
34
  /** 静态发布站:只含选定方案(compile 的 publish 模式),离线可打开,可直接 `wrangler deploy`。 */
30
35
  export type BuildResult = {
@@ -0,0 +1,10 @@
1
+ /** D59: pure font subsetting policy; uncertain CSS always survives. */
2
+ export declare function parseUnicodeRange(spec: string): [number, number][] | null;
3
+ export declare function rangeIntersects(spec: string, points: ReadonlySet<number>): boolean;
4
+ /** Include both literal text and encodings left by JS/JSON, CSS content and HTML. */
5
+ export declare function collectCodepoints(text: string): Set<number>;
6
+ export declare function pruneFontCss(css: string, points: ReadonlySet<number>): {
7
+ css: string;
8
+ keptFiles: string[];
9
+ removedFiles: string[];
10
+ };
@@ -0,0 +1,130 @@
1
+ /** D59: pure font subsetting policy; uncertain CSS always survives. */
2
+ export function parseUnicodeRange(spec) {
3
+ const out = [];
4
+ for (const part of spec.split(',')) {
5
+ const m = /^U\+([0-9a-f]{1,6})(?:-([0-9a-f]{1,6}))?$|^U\+([0-9a-f]*\?+)$/i.exec(part.trim());
6
+ if (!m)
7
+ return null;
8
+ if (m[3] && m[3].length > 6)
9
+ return null;
10
+ const lo = Number.parseInt(m[3] ? m[3].replaceAll('?', '0') : m[1], 16);
11
+ const hi = Number.parseInt(m[3] ? m[3].replaceAll('?', 'f') : m[2] ?? m[1], 16);
12
+ if (lo > hi || hi > 0x10ffff)
13
+ return null;
14
+ out.push([lo, hi]);
15
+ }
16
+ return out;
17
+ }
18
+ export function rangeIntersects(spec, points) {
19
+ const ranges = parseUnicodeRange(spec);
20
+ return ranges === null || ranges.some(([lo, hi]) => { for (const cp of points)
21
+ if (cp >= lo && cp <= hi)
22
+ return true; return false; });
23
+ }
24
+ /** Include both literal text and encodings left by JS/JSON, CSS content and HTML. */
25
+ export function collectCodepoints(text) {
26
+ const points = new Set();
27
+ const add = (s) => { for (const c of s)
28
+ points.add(c.codePointAt(0)); };
29
+ add(text);
30
+ add(text.replace(/\\u\{([\da-f]{1,6})\}|\\u([\da-f]{4})|\\x([\da-f]{2})/gi, (raw, astral, unit, byte) => {
31
+ const cp = Number.parseInt(astral ?? unit ?? byte, 16);
32
+ return cp <= 0x10ffff ? String.fromCodePoint(cp) : raw;
33
+ }));
34
+ for (const m of text.matchAll(/\\([\da-f]{1,6})(?:\s)?|&#(?:x([\da-f]+)|(\d+));?/gi)) {
35
+ const cp = Number.parseInt(m[1] ?? m[2] ?? m[3], m[3] ? 10 : 16);
36
+ if (cp <= 0x10ffff)
37
+ points.add(cp);
38
+ }
39
+ return points;
40
+ }
41
+ /** Token boundaries ignore strings/comments, including braces in quoted font names. */
42
+ function faceSpans(css) {
43
+ const spans = [];
44
+ let start = -1, depth = 0, quote = '';
45
+ for (let i = 0; i < css.length; i++) {
46
+ const c = css[i];
47
+ if (quote) {
48
+ if (c === '\\')
49
+ i++;
50
+ else if (c === quote)
51
+ quote = '';
52
+ continue;
53
+ }
54
+ if (c === '/' && css[i + 1] === '*') {
55
+ const end = css.indexOf('*/', i + 2);
56
+ if (end < 0)
57
+ break;
58
+ i = end + 1;
59
+ continue;
60
+ }
61
+ if (c === '"' || c === "'") {
62
+ quote = c;
63
+ continue;
64
+ }
65
+ if (start < 0 && c === '@') {
66
+ const match = /^@font-face\s*\{/i.exec(css.slice(i));
67
+ if (match) {
68
+ start = i;
69
+ depth = 1;
70
+ i += match[0].length - 1;
71
+ }
72
+ }
73
+ else if (start >= 0) {
74
+ if (c === '{')
75
+ depth++;
76
+ if (c === '}' && --depth === 0) {
77
+ spans.push([start, i + 1]);
78
+ start = -1;
79
+ }
80
+ }
81
+ }
82
+ return spans;
83
+ }
84
+ /** Read descriptors only at declaration boundaries, never inside strings or url(). */
85
+ function unicodeRange(rule) {
86
+ const body = rule.slice(rule.indexOf('{') + 1, -1).replace(/\/\*[\s\S]*?\*\//g, '');
87
+ const ranges = [];
88
+ let start = 0, quote = '', depth = 0;
89
+ for (let i = 0; i <= body.length; i++) {
90
+ const c = body[i];
91
+ if (quote) {
92
+ if (c === '\\')
93
+ i++;
94
+ else if (c === quote)
95
+ quote = '';
96
+ continue;
97
+ }
98
+ if (c === '"' || c === "'") {
99
+ quote = c;
100
+ continue;
101
+ }
102
+ if (c === '{' || c === '}')
103
+ return null;
104
+ if (c === '(')
105
+ depth++;
106
+ if (c === ')')
107
+ depth--;
108
+ if (depth === 0 && (c === ';' || i === body.length)) {
109
+ const descriptor = /^\s*unicode-range\s*:\s*(.*?)\s*$/i.exec(body.slice(start, i));
110
+ if (descriptor)
111
+ ranges.push(descriptor[1]);
112
+ start = i + 1;
113
+ }
114
+ }
115
+ return ranges.length === 1 ? ranges[0] : null;
116
+ }
117
+ export function pruneFontCss(css, points) {
118
+ const kept = new Set(), removed = new Set();
119
+ let output = '', cursor = 0;
120
+ for (const [start, end] of faceSpans(css)) {
121
+ const rule = css.slice(start, end);
122
+ const range = unicodeRange(rule);
123
+ const keep = range === null || rangeIntersects(range, points);
124
+ for (const m of rule.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^\s)]+))\s*\)/gi))
125
+ (keep ? kept : removed).add(m[1] ?? m[2] ?? m[3]);
126
+ output += css.slice(cursor, start) + (keep ? rule : '');
127
+ cursor = end;
128
+ }
129
+ return { css: output + css.slice(cursor), keptFiles: [...kept].sort(), removedFiles: [...removed].filter((f) => !kept.has(f)).sort() };
130
+ }
@@ -70,10 +70,10 @@
70
70
  }
71
71
 
72
72
  // 4. 字体
73
- // 主题用到手写字体时(--jp-font 含 Excalifont)检查它们已加载
74
- if (/Excalifont|Xiaolai/.test(getComputedStyle(stage).fontFamily)) {
75
- const text = stage.innerText || '中文';
76
- if (!document.fonts.check('16px "Joplo Excalifont"', text) || !document.fonts.check('16px "Joplo Xiaolai"', text)) warnings.push('Fonts not loaded: Hand-drawn fonts (Excalifont / Xiaolai) are not ready; the screenshot may use fallback fonts');
73
+ // Check the selected stack, including author themes and system fallbacks.
74
+ const family = getComputedStyle(stage).fontFamily;
75
+ if (!document.fonts.check(`16px ${family}`, stage.innerText || 'Aa')) {
76
+ warnings.push('Fonts not loaded: The selected font is not ready; the screenshot may use fallback fonts');
77
77
  }
78
78
  const failed = Array.from(document.fonts).filter((f) => f.status === 'error');
79
79
  if (failed.length) warnings.push(`Fonts not loaded: ${failed.length} font files failed to load (${failed[0].family})`);
package/dist/project.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Diagnostic, type Project } from '@joplo-app/core';
1
+ import { type CompileMode, type Diagnostic, type Project } from '@joplo-app/core';
2
2
  import { discoverFiles } from '@joplo-app/core/node';
3
3
  import type { ViteDevServer } from 'vite';
4
4
  export type CompileOutcome = {
@@ -8,7 +8,7 @@ export type CompileOutcome = {
8
8
  /** joplo.config 的 home(看板与发布站的首页路径)。 */
9
9
  home: string | null;
10
10
  };
11
- export declare function compileProject(server: ViteDevServer, projectDir: string, mode: 'dev' | 'publish'): Promise<CompileOutcome>;
11
+ export declare function compileProject(server: ViteDevServer, projectDir: string, mode: CompileMode): Promise<CompileOutcome>;
12
12
  /** 让项目源文件在下次载入时重新转译、重新求值。 */
13
13
  export declare function invalidateProjectModules(server: ViteDevServer, projectDir: string): void;
14
14
  export { discoverFiles };
@@ -0,0 +1,3 @@
1
+ import type { WebAssets } from './web-assets.js';
2
+ /** Runs after IR/JS inlining and author CSS compilation in both source and dist mode. */
3
+ export declare function subsetSiteFonts(staging: string, web: WebAssets): void;
@@ -0,0 +1,64 @@
1
+ import fs from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { collectCodepoints, pruneFontCss } from "./font-subsets.js";
5
+ function files(dir) {
6
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? files(path.join(dir, e.name)) : [path.join(dir, e.name)]);
7
+ }
8
+ /** Runs after IR/JS inlining and author CSS compilation in both source and dist mode. */
9
+ export function subsetSiteFonts(staging, web) {
10
+ const all = files(staging);
11
+ const points = new Set();
12
+ const decoder = new TextDecoder('utf-8', { fatal: true });
13
+ for (const file of all) {
14
+ let text;
15
+ try {
16
+ text = decoder.decode(fs.readFileSync(file));
17
+ }
18
+ catch {
19
+ continue;
20
+ }
21
+ if (text.includes('\0'))
22
+ continue;
23
+ for (const cp of collectCodepoints(text))
24
+ points.add(cp);
25
+ }
26
+ const retained = new Set();
27
+ const renamed = new Map();
28
+ let cssText = '';
29
+ for (const file of all.filter((f) => f.endsWith('.css'))) {
30
+ const original = fs.readFileSync(file, 'utf8');
31
+ const result = pruneFontCss(original, points);
32
+ if (result.css !== original) {
33
+ const hash = createHash('sha256').update(result.css).digest('hex').slice(0, 12);
34
+ const target = file.slice(0, -4) + `-font-${hash}.css`;
35
+ fs.writeFileSync(target, result.css);
36
+ fs.rmSync(file);
37
+ renamed.set(file, target);
38
+ }
39
+ cssText += result.css;
40
+ // Also preserve URLs in unfamiliar/unclosed rules that the conservative parser left untouched.
41
+ for (const m of result.css.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^\s)]+))\s*\)/gi)) {
42
+ retained.add(path.resolve(path.dirname(file), m[1] ?? m[2] ?? m[3]));
43
+ }
44
+ }
45
+ // The original Vite hash predates pruning. A fresh URL prevents stale CSS from requesting deleted subsets.
46
+ for (const file of all.filter((f) => f.endsWith('.html'))) {
47
+ const html = fs.readFileSync(file, 'utf8').replace(/(<link\b[^>]*?\bhref=["'])([^"']+)(["'])/gi, (raw, before, url, after) => {
48
+ const target = renamed.get(path.resolve(path.dirname(file), url));
49
+ return target ? `${before}./${path.relative(path.dirname(file), target).split(path.sep).join('/')}${after}` : raw;
50
+ });
51
+ fs.writeFileSync(file, html);
52
+ }
53
+ // Resolve all stylesheets together: a file shared by two rules or CSS assets must survive.
54
+ for (const file of all)
55
+ if (file.endsWith('.woff2') && !retained.has(file))
56
+ fs.rmSync(file);
57
+ const licenses = web.mode === 'source' ? path.join(web.webDir, 'src/fonts') : path.join(web.webDir, 'dist/fonts');
58
+ for (const [family, license] of [['Joplo Excalifont', 'OFL.txt'], ['Joplo Marker Gothic', 'OFL-MarkerGothic.txt']]) {
59
+ if (!cssText.includes(family))
60
+ continue;
61
+ fs.mkdirSync(path.join(staging, 'fonts'), { recursive: true });
62
+ fs.copyFileSync(path.join(licenses, license), path.join(staging, 'fonts', license));
63
+ }
64
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.2.1",
3
+ "version": "0.2.4",
4
4
  "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.2.1",
19
- "@joplo-app/kit": "0.2.1",
20
- "@joplo-app/web": "0.2.1",
18
+ "@joplo-app/core": "0.2.4",
19
+ "@joplo-app/kit": "0.2.4",
20
+ "@joplo-app/web": "0.2.4",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "tailwindcss": "4.3.4",
23
23
  "vite": "8.3.5",