@pao-at-office/reports-web 1.0.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,22 +1,22 @@
1
- # Reports.Web License / 使用許諾
2
-
3
- Copyright (c) Pao@Office. All rights reserved.
4
-
5
- This package is part of **Reports.Web**, a commercial product of Pao@Office.
6
- Use of this package is governed by the Reports.Web End User License Agreement:
7
-
8
- - 使用許諾(正式な条件): https://www.pao.ac/reports.web/manual/index.html#16
9
- - 製品サイト: https://www.pao.ac/reports.web/
10
- - ご購入・お見積もり: https://www.pao.ac/reports.web/buy.html
11
-
12
- ## 要点 / Summary
13
-
14
- - **体験版 / Trial** — 出力される帳票には赤い「SAMPLE」の印が付きます。購入前の評価に、無償でお使いいただけます。
15
- Output carries a red "SAMPLE" mark. You may evaluate it free of charge before purchase.
16
- - **製品版 / Product** — ご購入時に納品するライセンスファイルを Reports.Web エンジンに設定すると、「SAMPLE」の印が消えます。
17
- Configure the license file delivered on purchase in the Reports.Web engine to remove the mark.
18
- - **ライセンスの数え方 / Licensing** — 開発用パソコン 1 台につき 1 開発ライセンスです。運用専用のサーバーやエンドユーザーのパソコンには不要です(ランタイムライセンスフリー)。
19
- One development license per development PC. Production servers and end-user PCs need no license (royalty-free runtime).
20
-
21
- 上記の要点と使用許諾が異なる場合は、使用許諾が優先します。
22
- If this summary and the license agreement differ, the license agreement prevails.
1
+ # Reports.Web License / 使用許諾
2
+
3
+ Copyright (c) Pao@Office. All rights reserved.
4
+
5
+ This package is part of **Reports.Web**, a commercial product of Pao@Office.
6
+ Use of this package is governed by the Reports.Web End User License Agreement:
7
+
8
+ - 使用許諾(正式な条件、共通マニュアル第16章): https://www.pao.ac/reports.web/manual/Reports-Web-Guide.pdf
9
+ - 製品サイト: https://www.pao.ac/reports.web/
10
+ - ご購入・お見積もり: https://www.pao.ac/reports.web/buy.html
11
+
12
+ ## 要点 / Summary
13
+
14
+ - **体験版 / Trial** — 出力される帳票には赤い「SAMPLE」の印が付きます。購入前の評価に、無償でお使いいただけます。
15
+ Output carries a red "SAMPLE" mark. You may evaluate it free of charge before purchase.
16
+ - **製品版 / Product** — ご購入時に納品するライセンスファイルを Reports.Web エンジンに設定すると、「SAMPLE」の印が消えます。
17
+ Configure the license file delivered on purchase in the Reports.Web engine to remove the mark.
18
+ - **ライセンスの数え方 / Licensing** — 開発用パソコン 1 台につき 1 開発ライセンスです。運用専用のサーバーやエンドユーザーのパソコンには不要です(ランタイムライセンスフリー)。
19
+ One development license per development PC. Production servers and end-user PCs need no license (royalty-free runtime).
20
+
21
+ 上記の要点と使用許諾が異なる場合は、使用許諾が優先します。
22
+ If this summary and the license agreement differ, the license agreement prevails.
package/README.md CHANGED
@@ -1,92 +1,123 @@
1
- # @pao-at-office/reports-web
2
-
3
- **Reports.Web for Node.js** — 帳票定義(`.prepdj`)に値を入れて印刷データ(PREPEJ)を作り、Reports.Web エンジン(C++ WebAssembly)で PDF にします。請求書・見積書・納品書・宛名ラベル・名刺など、日本の業務帳票向けです。
4
-
5
- Build print data (PREPEJ) from a report definition (`.prepdj`) and render it to PDF with the Reports.Web engine (C++ WebAssembly). Designed for Japanese business forms: invoices, estimates, delivery slips, address labels, business cards.
6
-
7
- - 製品サイト / Product: https://www.pao.ac/reports.web/
8
- - デモのソース / Demo source: https://github.com/ReportsWeb/wasm-node
9
- - オンラインデモ / Live demo: https://www.pao.ac/demo/reports.web/samples/node/
10
-
11
- ## しくみ / How it works
12
-
13
- ```
14
- your Node.js app ──(PREPEJ JSON)──▶ Reports.Web engine (Docker: ghcr.io/reportsweb/engine) ──▶ PDF
15
- ▲
16
- report definition (.prepdj) designed in the browser designer
17
- ```
18
-
19
- 帳票のデザインは、ブラウザで動くデザイナーで作ります。アプリは値を入れて印刷データを作り、エンジンに送るだけです。描画はすべてエンジンが行います。
20
-
21
- ## インストール / Install
22
-
23
- ```sh
24
- npm install @pao-at-office/reports-web
25
- docker run -d -p 3107:3107 ghcr.io/reportsweb/engine:1.0.0
26
- ```
27
-
28
- Node.js 18 以降。エンジンは Docker イメージで動きます。
29
- Requires Node.js 18+. The engine runs as a Docker image.
30
-
31
- ## 使い方 / Quick start
32
-
33
- ```js
34
- import { readFile, writeFile } from "node:fs/promises";
35
- import { PrintData, ReportsWebEngine } from "@pao-at-office/reports-web";
36
-
37
- const definition = JSON.parse(await readFile("report.prepdj", "utf8"));
38
-
39
- const printData = new PrintData()
40
- .setDefinition(definition)
41
- .pageStart()
42
- .setValue("Message", "Node.jsから、あっという間に帳票出力")
43
- .pageEnd();
44
-
45
- const engine = new ReportsWebEngine({ url: "http://127.0.0.1:3107" });
46
- await writeFile("report.pdf", await engine.renderPdf(printData));
47
- ```
48
-
49
- ## API
50
-
51
- ### `PrintData`
52
-
53
- | メソッド / Method | 内容 / Description |
54
- |---|---|
55
- | `setDefinition(definition)` | 帳票定義(`.prepdj` の内容)を設定 / Set the report definition |
56
- | `pageStart(definition?)` / `pageEnd()` | ページの開始と終了。ページごとに別の定義も使えます / Begin and end a page (optionally with its own definition) |
57
- | `setValue(name, value, index?, drawing?)` | 文字などの値を入れる / Set a value |
58
- | `setRepeatedValue(name, value, x, y)` | 繰り返し(明細行など)の値 / Value for a repeated object |
59
- | `setImage(name, source)` / `setBarcode(name, code)` | 画像・バーコード / Image and barcode |
60
- | `changeAttributes(name, values)` | 色・位置などの属性を変える / Change attributes |
61
- | `toObject()` / `toJson()` / `save(path)` | 印刷データ(PREPEJ)として取り出す・保存する / Get or save the PREPEJ |
62
-
63
- ### `ReportsWebEngine`
64
-
65
- | メソッド / Method | 内容 / Description |
66
- |---|---|
67
- | `new ReportsWebEngine({ url, timeoutMs, maxBytes })` | 既定の URL は `REPORTS_ENGINE_URL`、なければ `http://127.0.0.1:3107` |
68
- | `renderPdf(printData)` | PDF の `Buffer` を返します / Returns the PDF as a `Buffer` |
69
- | `health()` | エンジンの状態 / Engine status |
70
-
71
- エラーは `ReportsWebEngineError`(`status` に HTTP ステータス)で返ります。
72
- Errors are thrown as `ReportsWebEngineError` with the HTTP `status`.
73
-
74
- ## 体験版と製品版 / Trial and product
75
-
76
- このパッケージとエンジンのイメージは体験版です。出力には赤い「SAMPLE」の印が付きます。ご購入後に納品するライセンスファイルをエンジンに設定すると、印が消えます。
77
-
78
- The package and the engine image are trial builds: output carries a red "SAMPLE" mark. Mount the license file delivered on purchase to remove it:
79
-
80
- ```sh
81
- docker run -d -p 3107:3107 -v /path/to/reports-web.license:/app/reports-web.license:ro ghcr.io/reportsweb/engine:1.0.0
82
- ```
83
-
84
- 開発用パソコン 1 台につき 1 ライセンス、運用環境はランタイムライセンスフリーです。詳しくは [LICENSE.md](LICENSE.md) と [使用許諾](https://www.pao.ac/reports.web/manual/index.html#16) をご覧ください。
85
-
86
- ## 他の言語 / Other languages
87
-
88
- Reports.Web は同じ帳票定義と印刷データを、PHP・Java・.NET・Go・Ruby・Rust・Node.js から使えます。Pure Java・Pure Python・WPF 版もあります。
89
- https://github.com/ReportsWeb
90
-
91
- ---
92
- Pao@Office — https://www.pao.ac/ — info@pao.ac
1
+ # @pao-at-office/reports-web
2
+
3
+ **Reports.Web for Node.js** — 帳票定義(`.prepdj`)に値を入れて印刷データ(PREPEJ)を作り、Reports.Web エンジン(C++ WebAssembly)で PDF にします。請求書・見積書・納品書・宛名ラベル・名刺など、日本の業務帳票向けです。
4
+
5
+ Build print data (PREPEJ) from a report definition (`.prepdj`) and render it to PDF with the Reports.Web engine (C++ WebAssembly). Designed for Japanese business forms: invoices, estimates, delivery slips, address labels, business cards.
6
+
7
+ - 製品サイト / Product: https://www.pao.ac/reports.web/
8
+ - デモのソース / Demo source: https://github.com/ReportsWeb/wasm-node
9
+ - オンラインデモ / Live demo: https://www.pao.ac/demo/reports.web/samples/node/
10
+
11
+ ## しくみ / How it works
12
+
13
+ ```
14
+ your Node.js app ──(PREPEJ JSON)──▶ Reports.Web engine (Docker: ghcr.io/reportsweb/engine) ──▶ PDF
15
+ ▲
16
+ report definition (.prepdj) designed in the browser designer
17
+ ```
18
+
19
+ 帳票のデザインは、ブラウザで動くデザイナーで作ります。アプリは値を入れて印刷データを作り、エンジンに送るだけです。描画はすべてエンジンが行います。
20
+
21
+ ## インストール / Install
22
+
23
+ ```sh
24
+ npm install @pao-at-office/reports-web@1.3.1
25
+ docker run -d -p 3107:3107 ghcr.io/reportsweb/engine:1.3.1
26
+ ```
27
+
28
+ Node.js 18 以降。エンジンは Docker イメージで動きます。
29
+ Requires Node.js 18+. The engine runs as a Docker image.
30
+
31
+ ## 使い方 / Quick start
32
+
33
+ ```js
34
+ import { readFile, writeFile } from "node:fs/promises";
35
+ import { PrintData, ReportsWebEngine } from "@pao-at-office/reports-web";
36
+
37
+ const definition = JSON.parse(await readFile("report.prepdj", "utf8"));
38
+
39
+ const printData = new PrintData()
40
+ .setDefinition(definition)
41
+ .pageStart()
42
+ .setValue("Message", "Node.jsから、あっという間に帳票出力")
43
+ .pageEnd();
44
+
45
+ const engine = new ReportsWebEngine({ url: "http://127.0.0.1:3107" });
46
+ await writeFile("report.pdf", await engine.renderPdf(printData));
47
+ ```
48
+
49
+ ## API
50
+
51
+ ### `PrintData`
52
+
53
+ | メソッド / Method | 内容 / Description |
54
+ |---|---|
55
+ | `setDefinition(definition)` | 帳票定義(`.prepdj` の内容)を設定 / Set the report definition |
56
+ | `pageStart(definition?)` / `pageEnd()` | ページの開始と終了。ページごとに別の定義も使えます / Begin and end a page (optionally with its own definition) |
57
+ | `setValue(name, value, index?, drawing?)` | 文字などの値を入れる / Set a value |
58
+ | `setRepeatedValue(name, value, x, y)` | 繰り返し(明細行など)の値 / Value for a repeated object |
59
+ | `setImage(name, source)` / `setBarcode(name, code)` | 画像・バーコード / Image and barcode |
60
+ | `changeAttributes(name, values)` | 色・位置などの属性を変える / Change attributes |
61
+ | `toObject()` / `toJson()` / `save(path)` | 印刷データ(PREPEJ)として取り出す・保存する / Get or save the PREPEJ |
62
+
63
+ ### `ReportsWebEngine`
64
+
65
+ | メソッド / Method | 内容 / Description |
66
+ |---|---|
67
+ | `new ReportsWebEngine({ url, timeoutMs, maxBytes })` | 既定の URL は `REPORTS_ENGINE_URL`、なければ `http://127.0.0.1:3107` |
68
+ | `renderPdf(printData)` | PDF の `Buffer` を返します / Returns the PDF as a `Buffer` |
69
+ | `health()` | エンジンの状態 / Engine status |
70
+
71
+ エラーは `ReportsWebEngineError`(`status` に HTTP ステータス)で返ります。
72
+ Errors are thrown as `ReportsWebEngineError` with the HTTP `status`.
73
+
74
+ ## 体験版と製品版 / Trial and product
75
+
76
+ このパッケージとエンジンのイメージは体験版です。出力には赤い「SAMPLE」の印が付きます。ご購入後に納品するライセンスファイルをエンジンに設定すると、印が消えます。
77
+
78
+ The package and the engine image are trial builds: output carries a red "SAMPLE" mark. Mount the license file delivered on purchase to remove it:
79
+
80
+ ```sh
81
+ docker run -d -p 3107:3107 -v /path/to/reports-web.license:/app/reports-web.license:ro ghcr.io/reportsweb/engine:1.3.1
82
+ ```
83
+
84
+ 開発用パソコン 1 台につき 1 ライセンス、運用環境はランタイムライセンスフリーです。詳しくは [LICENSE.md](LICENSE.md) と [使用許諾(共通マニュアル第16章)](https://www.pao.ac/reports.web/manual/Reports-Web-Guide.pdf) をご覧ください。
85
+
86
+ ## 他の言語 / Other languages
87
+
88
+ Reports.Web は同じ帳票定義と印刷データを、PHP・Java・.NET・Go・Ruby・Rust・Node.js から使えます。Pure Java・Pure Python・WPF 版もあります。
89
+ https://github.com/ReportsWeb
90
+
91
+ ## デザインの検査とエンジンの知らせ
92
+
93
+ デザインを描く前に、共通の検査で書き間違いを確認できます(この API を含むビルドが必要です)。検査は入力を書き換えません。
94
+
95
+ ```sh
96
+ npx @pao-at-office/reports-web validate invoice.prepdj
97
+ # check も同じ命令です。error があれば終了コード 1、warning だけなら 0。
98
+ ```
99
+
100
+ ```js
101
+ import { validateDesign, ReportsWebEngine } from '@pao-at-office/reports-web';
102
+ const diagnostics = validateDesign(definition);
103
+ for (const d of diagnostics) console.log(d.severity, d.path, d.message, d.fix);
104
+ const { pdf, warnings } = await new ReportsWebEngine().renderPdfWithWarnings(printData);
105
+ for (const w of warnings) console.log(w.objectName, w.message);
106
+ ```
107
+
108
+ `validateDesign` は `{ severity, code, path, message, fix, suggestion? }[]` を返します。`path` は `Objects[3].Width` のような JSON の位置です。同じ検査をエンジンの `POST /validate` に .prepdj の JSON を送って呼べます。応答は `{ diagnostics: [...] }`(HTTP 200)です。
109
+
110
+ `renderPdfWithWarnings` は `{ pdf: Buffer, warnings: EngineWarning[] }` を返します。通知は `x-reports-image-diagnostics` の内容です。通知がなければ空の配列、通知が壊れていれば例外です。従来の `renderPdf` はこれまでどおり PDF の `Buffer` を返します。検査は既存の描画に新しい拒否条件を加えません。
111
+
112
+ ## PDF を PNG で確かめる
113
+
114
+ ```sh
115
+ npx @pao-at-office/reports-web preview design.prepdj data.json -o out.png --dpi 96
116
+ ```
117
+
118
+ `data.json` は省略できます。部品名と値のオブジェクトを指定し、値の配列は繰り返し番号順、外側の配列はページ順です。複数ページは `out-p1.png` のように保存します。接続先は `REPORTS_ENGINE_URL` です。この命令を含むエンジンが必要です。
119
+
120
+ `await engine.renderPreview(printData, { dpi: 96 })` は `{ pages: [{ widthMm, heightMm, png: Buffer }], pageCount, dpi, warnings }` を返します。サーバーが PDF を作ってから画像にします。既定96dpi、36〜300dpi、1ページ1600万・合計3200万画素、Base64の合計24MiBまでです。外部URLの画像は取得せず、知らせを返します。画像は埋め込んでください。
121
+
122
+ ---
123
+ Pao@Office — https://www.pao.ac/ — info@pao.ac
@@ -17,6 +17,7 @@ export declare class PrintData {
17
17
  drawObject(n: string, i?: number, type?: string | null): this;
18
18
  changeAttributes(n: string, values: Record<string, Scalar>, i?: number): this;
19
19
  changeRepeatedAttributes(n: string, values: Record<string, Scalar>, i?: number, x?: number, y?: number, type?: string | null): this;
20
+ private requireObject;
20
21
  private resolveType;
21
22
  pageEnd(): this;
22
23
  toObject(): JsonObject;
package/dist/PrintData.js CHANGED
@@ -1,14 +1,15 @@
1
- import { writeFile, rename, unlink } from "node:fs/promises";
1
+ import { writeFile, rename, unlink, stat, open } from "node:fs/promises";
2
+ import { constants } from "node:fs";
2
3
  import { randomUUID } from "node:crypto";
3
4
  const copy = (v) => structuredClone(v);
4
5
  const name = (v) => {
5
6
  if (typeof v !== "string" || !v.trim())
6
- throw new Error("Name is required");
7
+ throw new Error("名前を指定してください。");
7
8
  return v.trim();
8
9
  };
9
10
  const index = (v) => {
10
11
  if (!Number.isSafeInteger(v) || v < 0)
11
- throw new Error("Index must be a non-negative integer");
12
+ throw new Error("物体・繰返しのインデックスには0以上の整数を指定してください。");
12
13
  return v;
13
14
  };
14
15
  const scalar = (v) => {
@@ -16,9 +17,34 @@ const scalar = (v) => {
16
17
  return null;
17
18
  if (!["string", "number", "boolean"].includes(typeof v) ||
18
19
  (typeof v === "number" && !Number.isFinite(v)))
19
- throw new Error("A finite scalar is required");
20
+ throw new Error("値は文字列・有限の数値・真偽値・nullのいずれかで指定してください。");
20
21
  return String(v);
21
22
  };
23
+ async function requireWritable(path) {
24
+ let info;
25
+ try {
26
+ info = await stat(path);
27
+ }
28
+ catch (error) {
29
+ if (error.code === 'ENOENT')
30
+ return;
31
+ throw error;
32
+ }
33
+ if (!info.isFile())
34
+ return;
35
+ const message = "読み取り専用のため保存できません。別名で保存してください。";
36
+ if ((info.mode & 0o222) === 0)
37
+ throw new Error(message);
38
+ try {
39
+ const probe = await open(path, constants.O_WRONLY);
40
+ await probe.close();
41
+ }
42
+ catch (error) {
43
+ if (['EACCES', 'EPERM'].includes(error.code ?? ''))
44
+ throw new Error(message, { cause: error });
45
+ throw error;
46
+ }
47
+ }
22
48
  export class PrintData {
23
49
  definition = null;
24
50
  pages = [];
@@ -33,12 +59,12 @@ export class PrintData {
33
59
  d.version === 1 &&
34
60
  Array.isArray(d.pages) &&
35
61
  d.pages.length)))
36
- throw new Error("Invalid report definition");
62
+ throw new Error("帳票定義の形式が不正です。");
37
63
  }
38
64
  setDefinition(d) {
39
65
  PrintData.assertDefinition(d);
40
66
  if (this.page)
41
- throw new Error("Finish the current page first");
67
+ throw new Error("現在のページを終了してください。");
42
68
  if (this.definition)
43
69
  for (const p of this.pages)
44
70
  if (!p.Definition)
@@ -48,11 +74,11 @@ export class PrintData {
48
74
  }
49
75
  pageStart(d = null) {
50
76
  if (this.page)
51
- throw new Error("Call pageEnd first");
77
+ throw new Error("次のページを開始する前にpageEndで現在のページを終了してください。");
52
78
  if (d)
53
79
  PrintData.assertDefinition(d);
54
80
  if (!this.definition)
55
- throw new Error("Set definition first");
81
+ throw new Error("先に帳票定義を設定してください。");
56
82
  this.page = {
57
83
  Index: this.pages.length + 1,
58
84
  Definition: copy(d),
@@ -63,10 +89,11 @@ export class PrintData {
63
89
  }
64
90
  current() {
65
91
  if (!this.page)
66
- throw new Error("Call pageStart first");
92
+ throw new Error("先にページを開始してください。");
67
93
  return this.page;
68
94
  }
69
95
  value(n, v, i, drawing, type, x, y) {
96
+ this.requireObject(n);
70
97
  const item = {
71
98
  Name: name(n),
72
99
  Type: this.resolveType(n, type),
@@ -103,8 +130,9 @@ export class PrintData {
103
130
  return this.changeRepeatedAttributes(n, values, i);
104
131
  }
105
132
  changeRepeatedAttributes(n, values, i = 0, x, y, type = null) {
133
+ this.requireObject(n);
106
134
  if ((x === undefined) !== (y === undefined))
107
- throw new Error("Both repeat indexes required");
135
+ throw new Error("繰返し座標のxとyを両方指定してください。");
108
136
  const item = {
109
137
  Name: name(n),
110
138
  Type: this.resolveType(n, type),
@@ -113,7 +141,7 @@ export class PrintData {
113
141
  };
114
142
  for (const [k, v] of Object.entries(values)) {
115
143
  if (v === null)
116
- throw new Error("Attributes cannot be null");
144
+ throw new Error("属性値にnullは指定できません。");
117
145
  item.Values[k] = scalar(v);
118
146
  }
119
147
  if (x !== undefined && y !== undefined) {
@@ -123,6 +151,13 @@ export class PrintData {
123
151
  this.current().DynamicAttributes.push(item);
124
152
  return this;
125
153
  }
154
+ // V1-03:Reports.net の Write と同じく、帳票に無い名前はその場で断る(以前は黙って受け、あとで送った PDF 全体が失敗した)。
155
+ requireObject(n) {
156
+ const d = this.current().Definition ?? this.definition;
157
+ const objects = [...(d.Objects ?? []), ...(d.pages ?? []).flatMap((p) => p.objects ?? [])];
158
+ if (!objects.some((o) => (o.Name ?? o.name) === name(n)))
159
+ throw new Error(`帳票にオブジェクト「${n}」がありません。`);
160
+ }
126
161
  // 型省略時は当該ページの定義を参照する。明示指定はそのまま保持する。
127
162
  resolveType(n, explicit) {
128
163
  if (explicit !== null)
@@ -148,7 +183,7 @@ export class PrintData {
148
183
  }
149
184
  toObject() {
150
185
  if (this.page || !this.definition || !this.pages.length)
151
- throw new Error("Definition and completed pages required");
186
+ throw new Error("帳票定義と終了したページが必要です。");
152
187
  return copy({
153
188
  Format: "Reports.net PrintData",
154
189
  Version: "1.0",
@@ -160,9 +195,11 @@ export class PrintData {
160
195
  return JSON.stringify(this.toObject(), null, pretty ? 2 : undefined) + "\n";
161
196
  }
162
197
  async save(path) {
198
+ await requireWritable(path);
163
199
  const temp = path + "." + randomUUID() + ".tmp";
164
200
  try {
165
201
  await writeFile(temp, this.toJson(), { flag: "wx" });
202
+ await requireWritable(path);
166
203
  await rename(temp, path);
167
204
  }
168
205
  finally {
@@ -4,13 +4,39 @@ export interface ReportsWebEngineOptions {
4
4
  url?: string;
5
5
  /** Request timeout in milliseconds. Default: 90000 */
6
6
  timeoutMs?: number;
7
- /** Largest PDF accepted from the engine in bytes. Default: 32 MiB */
7
+ /** Largest PDF or preview JSON accepted from the engine in bytes. Default: 32 MiB */
8
8
  maxBytes?: number;
9
9
  }
10
10
  export interface RenderPdfOptions {
11
11
  /** Spill large PDF images to temporary storage on the engine (X-Reports-Swap-Pdf-Image). */
12
12
  swapPdfImage?: boolean;
13
13
  }
14
+ /** エンジンが応答の見出しで返す知らせ。将来追加される項目も保持する。 */
15
+ export interface EngineWarning {
16
+ objectName: string;
17
+ reason: string;
18
+ message: string;
19
+ pageNumber?: number;
20
+ source?: string;
21
+ [key: string]: unknown;
22
+ }
23
+ export interface RenderPdfResult {
24
+ pdf: Buffer;
25
+ warnings: EngineWarning[];
26
+ }
27
+ export interface RenderPreviewOptions extends RenderPdfOptions {
28
+ dpi?: number;
29
+ }
30
+ export interface RenderPreviewResult {
31
+ pages: {
32
+ widthMm: number;
33
+ heightMm: number;
34
+ png: Buffer;
35
+ }[];
36
+ pageCount: number;
37
+ dpi: number;
38
+ warnings: EngineWarning[];
39
+ }
14
40
  /** Error returned by the Reports.Web engine (status is the HTTP status, or undefined for transport errors). */
15
41
  export declare class ReportsWebEngineError extends Error {
16
42
  readonly status?: number | undefined;
@@ -32,5 +58,10 @@ export declare class ReportsWebEngine {
32
58
  }>;
33
59
  /** Render PREPEJ print data (PrintData, its object form, or JSON text) to a PDF. */
34
60
  renderPdf(data: PrintData | JsonObject | string, options?: RenderPdfOptions): Promise<Buffer>;
61
+ /** PDF と、読み替えた値・描けなかったバーコードなどの知らせを返す。 */
62
+ renderPdfWithWarnings(data: PrintData | JsonObject | string, options?: RenderPdfOptions): Promise<RenderPdfResult>;
63
+ /** PDF から作った各ページの PNG とエンジンの知らせ。既定96dpi。 */
64
+ renderPreview(data: PrintData | JsonObject | string, options?: RenderPreviewOptions): Promise<RenderPreviewResult>;
65
+ private render;
35
66
  private request;
36
67
  }
@@ -32,6 +32,60 @@ export class ReportsWebEngine {
32
32
  }
33
33
  /** Render PREPEJ print data (PrintData, its object form, or JSON text) to a PDF. */
34
34
  async renderPdf(data, options = {}) {
35
+ return (await this.render(data, options, false)).pdf;
36
+ }
37
+ /** PDF と、読み替えた値・描けなかったバーコードなどの知らせを返す。 */
38
+ async renderPdfWithWarnings(data, options = {}) {
39
+ return this.render(data, options, true);
40
+ }
41
+ /** PDF から作った各ページの PNG とエンジンの知らせ。既定96dpi。 */
42
+ async renderPreview(data, options = {}) {
43
+ if (options.dpi !== undefined && (!Number.isFinite(options.dpi) || options.dpi < 36 || options.dpi > 300))
44
+ throw new ReportsWebEngineError('DPI は36〜300の数で指定してください。');
45
+ const payload = typeof data === 'string' ? data : JSON.stringify(data instanceof PrintData ? data.toObject() : data);
46
+ if (Buffer.byteLength(payload) > DEFAULT_MAX)
47
+ throw new ReportsWebEngineError('Print data exceeds 32 MiB.');
48
+ const headers = { 'Content-Type': 'application/json' };
49
+ if (options.dpi !== undefined)
50
+ headers['X-Reports-Preview-Dpi'] = String(options.dpi);
51
+ if (options.swapPdfImage !== undefined)
52
+ headers['X-Reports-Swap-Pdf-Image'] = String(options.swapPdfImage);
53
+ const response = await this.request('/render/preview', { method: 'POST', headers, body: payload });
54
+ if (!response.body)
55
+ throw new ReportsWebEngineError('PNG の応答が空です。', response.status);
56
+ const chunks = [];
57
+ let size = 0;
58
+ for await (const chunk of response.body) {
59
+ size += chunk.length;
60
+ if (size > this.maxBytes)
61
+ throw new ReportsWebEngineError(`PNG response exceeds ${this.maxBytes} bytes.`);
62
+ chunks.push(Buffer.from(chunk));
63
+ }
64
+ let value;
65
+ try {
66
+ value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
67
+ }
68
+ catch {
69
+ throw new ReportsWebEngineError('PNG の応答を JSON として読めません。', response.status);
70
+ }
71
+ if (!response.ok)
72
+ throw new ReportsWebEngineError(`PNG を作れません(HTTP ${response.status}): ${String(value?.error ?? '')}`, response.status);
73
+ if (!value || typeof value !== 'object' || !Array.isArray(value.pages) || value.pages.length !== value.pageCount || !value.pages.length ||
74
+ !Number.isFinite(value.dpi) || value.dpi < 36 || value.dpi > 300 || !Array.isArray(value.warnings) ||
75
+ !value.warnings.every((w) => w && typeof w.objectName === 'string' && typeof w.reason === 'string' && typeof w.message === 'string'))
76
+ throw new ReportsWebEngineError('PNG の応答の項目が不正です。');
77
+ const pages = value.pages.map((page) => {
78
+ if (!page || !Number.isFinite(page.widthMm) || page.widthMm <= 0 || !Number.isFinite(page.heightMm) || page.heightMm <= 0 ||
79
+ typeof page.png !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(page.png) || page.png.length % 4)
80
+ throw new ReportsWebEngineError('PNG のページ情報が不正です。');
81
+ const png = Buffer.from(page.png, 'base64');
82
+ if (!png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
83
+ throw new ReportsWebEngineError('応答の画像が PNG ではありません。');
84
+ return { widthMm: page.widthMm, heightMm: page.heightMm, png };
85
+ });
86
+ return { pages, pageCount: value.pageCount, dpi: value.dpi, warnings: value.warnings };
87
+ }
88
+ async render(data, options, includeWarnings) {
35
89
  const payload = typeof data === "string" ? data : JSON.stringify(data instanceof PrintData ? data.toObject() : data);
36
90
  if (Buffer.byteLength(payload) > DEFAULT_MAX)
37
91
  throw new ReportsWebEngineError("Print data exceeds 32 MiB.");
@@ -61,7 +115,20 @@ export class ReportsWebEngine {
61
115
  const pdf = Buffer.concat(chunks);
62
116
  if (pdf.subarray(0, 5).toString("latin1") !== "%PDF-")
63
117
  throw new ReportsWebEngineError("Engine response is not a PDF.");
64
- return pdf;
118
+ let warnings = [];
119
+ const header = response.headers.get('x-reports-image-diagnostics');
120
+ if (includeWarnings && header) {
121
+ try {
122
+ const value = JSON.parse(decodeURIComponent(header));
123
+ if (!Array.isArray(value) || !value.every(w => w && typeof w === 'object' && typeof w.objectName === 'string' && typeof w.reason === 'string' && typeof w.message === 'string'))
124
+ throw new Error();
125
+ warnings = value;
126
+ }
127
+ catch {
128
+ throw new ReportsWebEngineError('エンジンの知らせを読み取れません。');
129
+ }
130
+ }
131
+ return { pdf, warnings };
65
132
  }
66
133
  async request(path, init) {
67
134
  try {
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { extname } from 'node:path';
4
+ import { PrintData } from './PrintData.js';
5
+ import { ReportsWebEngine } from './ReportsWebEngine.js';
6
+ import { validateDesign } from './designLint.js';
7
+ const [command, file, ...extra] = process.argv.slice(2);
8
+ if (command === 'preview' && file) {
9
+ try {
10
+ let dataFile, output, dpi;
11
+ for (let i = 0; i < extra.length; i++) {
12
+ const arg = extra[i];
13
+ if (arg === '-o' || arg === '--output') {
14
+ if (output || !extra[i + 1] || extra[i + 1].startsWith('-'))
15
+ throw new Error('-o の後に PNG の保存先を指定してください。');
16
+ output = extra[++i];
17
+ }
18
+ else if (arg === '--dpi') {
19
+ if (dpi !== undefined || !extra[i + 1])
20
+ throw new Error('--dpi の後に解像度を指定してください。');
21
+ dpi = Number(extra[++i]);
22
+ }
23
+ else if (!arg.startsWith('-') && !dataFile)
24
+ dataFile = arg;
25
+ else
26
+ throw new Error(`使えない引数です: ${arg}`);
27
+ }
28
+ if (!output || extname(output).toLowerCase() !== '.png')
29
+ throw new Error('-o out.png を指定してください。');
30
+ const jsonFile = async (path) => JSON.parse((await readFile(path, 'utf8')).replace(/^\uFEFF/, ''));
31
+ const pd = new PrintData().setDefinition(await jsonFile(file));
32
+ const values = dataFile ? await jsonFile(dataFile) : {};
33
+ // 名前→値。内側の配列は繰返し番号順、外側の配列はページごと。
34
+ const pages = Array.isArray(values) ? values : [values];
35
+ if (!pages.length)
36
+ throw new Error('ページのデータが空です。');
37
+ for (const page of pages) {
38
+ if (!page || typeof page !== 'object' || Array.isArray(page))
39
+ throw new Error('データは名前と値の JSON オブジェクトで指定してください。');
40
+ pd.pageStart();
41
+ for (const [name, value] of Object.entries(page)) {
42
+ if (Array.isArray(value))
43
+ value.forEach((v, i) => pd.setValue(name, v, i));
44
+ else
45
+ pd.setValue(name, value);
46
+ }
47
+ pd.pageEnd();
48
+ }
49
+ const result = await new ReportsWebEngine().renderPreview(pd, { dpi });
50
+ const prefix = output.slice(0, -4);
51
+ for (const [i, page] of result.pages.entries()) {
52
+ const path = result.pages.length === 1 ? output : `${prefix}-p${i + 1}.png`;
53
+ await writeFile(path, page.png);
54
+ console.log(`${path} ${page.widthMm.toFixed(2)}×${page.heightMm.toFixed(2)}mm`);
55
+ }
56
+ for (const warning of result.warnings)
57
+ console.error(`${warning.objectName}: ${warning.message}`);
58
+ }
59
+ catch (error) {
60
+ console.error(error instanceof Error ? error.message : String(error));
61
+ process.exitCode = 1;
62
+ }
63
+ }
64
+ else if (!['validate', 'check'].includes(command ?? '') || !file || extra.length) {
65
+ console.error('使い方: npx @pao-at-office/reports-web validate file.prepdj(check も可) / preview design.prepdj [data.json] -o out.png [--dpi 96]');
66
+ process.exitCode = 1;
67
+ }
68
+ else {
69
+ try {
70
+ const text = (await readFile(file, 'utf8')).replace(/^\uFEFF/, '');
71
+ let value;
72
+ try {
73
+ value = JSON.parse(text);
74
+ }
75
+ catch {
76
+ throw new Error('JSON を読み取れません。引用符・カンマなどを確認してください。');
77
+ }
78
+ const diagnostics = validateDesign(value);
79
+ for (const d of diagnostics)
80
+ console.log(`${d.severity === 'error' ? 'エラー' : '注意'} ${d.path}: ${d.message} ${d.fix}`);
81
+ const errors = diagnostics.filter(d => d.severity === 'error').length;
82
+ console.log(`エラー ${errors} 件、注意 ${diagnostics.length - errors} 件`);
83
+ process.exitCode = errors ? 1 : 0;
84
+ }
85
+ catch (error) {
86
+ console.error(`検査できません: ${error instanceof Error ? error.message : String(error)}`);
87
+ process.exitCode = 1;
88
+ }
89
+ }