@exponential_app/engine 0.0.0-stage → 0.1.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.
Files changed (85) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +54 -0
  3. package/README.md +35 -2
  4. package/dist/capabilities.js +29 -0
  5. package/dist/capabilities.js.map +9 -0
  6. package/dist/chunks/index-3nf9f7pv.js +315 -0
  7. package/dist/chunks/index-3nf9f7pv.js.map +10 -0
  8. package/dist/chunks/index-3rgr16n2.js +443 -0
  9. package/dist/chunks/index-3rgr16n2.js.map +9 -0
  10. package/dist/chunks/index-79swfbsm.js +366 -0
  11. package/dist/chunks/index-79swfbsm.js.map +10 -0
  12. package/dist/chunks/index-knntt4cb.js +259 -0
  13. package/dist/chunks/index-knntt4cb.js.map +10 -0
  14. package/dist/chunks/index-m2845dn6.js +72 -0
  15. package/dist/chunks/index-m2845dn6.js.map +10 -0
  16. package/dist/chunks/index-pqpnz4ns.js +2213 -0
  17. package/dist/chunks/index-pqpnz4ns.js.map +9 -0
  18. package/dist/chunks/index-q4zws02e.js +2301 -0
  19. package/dist/chunks/index-q4zws02e.js.map +10 -0
  20. package/dist/chunks/index-s3xjr701.js +170 -0
  21. package/dist/chunks/index-s3xjr701.js.map +10 -0
  22. package/dist/chunks/index-sk8b0dh4.js +126 -0
  23. package/dist/chunks/index-sk8b0dh4.js.map +10 -0
  24. package/dist/chunks/index-tvsykgcv.js +3015 -0
  25. package/dist/chunks/index-tvsykgcv.js.map +19 -0
  26. package/dist/chunks/index-v0m7r4y3.js +6869 -0
  27. package/dist/chunks/index-v0m7r4y3.js.map +13 -0
  28. package/dist/consent.js +24 -0
  29. package/dist/consent.js.map +9 -0
  30. package/dist/index.js +654 -0
  31. package/dist/index.js.map +12 -0
  32. package/dist/lifecycle.js +11 -0
  33. package/dist/lifecycle.js.map +9 -0
  34. package/dist/outbox.js +27 -0
  35. package/dist/outbox.js.map +9 -0
  36. package/dist/pdf.js +15 -0
  37. package/dist/pdf.js.map +9 -0
  38. package/dist/providers.js +26 -0
  39. package/dist/providers.js.map +9 -0
  40. package/dist/runner.js +24 -0
  41. package/dist/runner.js.map +9 -0
  42. package/dist/tools.js +38 -0
  43. package/dist/tools.js.map +9 -0
  44. package/dist/types/domain-contract/src/app-records.d.ts +3148 -0
  45. package/dist/types/domain-contract/src/app-share.d.ts +222 -0
  46. package/dist/types/domain-contract/src/apps.d.ts +612 -0
  47. package/dist/types/eengine/fixtures/providers.json +55 -0
  48. package/dist/types/eengine/src/broker.d.ts +80 -0
  49. package/dist/types/eengine/src/capabilities.d.ts +88 -0
  50. package/dist/types/eengine/src/consent.d.ts +50 -0
  51. package/dist/types/eengine/src/index.d.ts +12 -0
  52. package/dist/types/eengine/src/instance.d.ts +131 -0
  53. package/dist/types/eengine/src/lifecycle.d.ts +64 -0
  54. package/dist/types/eengine/src/outbox.d.ts +3 -0
  55. package/dist/types/eengine/src/pdf.d.ts +36 -0
  56. package/dist/types/eengine/src/providers.d.ts +38 -0
  57. package/dist/types/eengine/src/runner.d.ts +82 -0
  58. package/dist/types/eengine/src/stores.d.ts +125 -0
  59. package/dist/types/eengine/src/synced.d.ts +59 -0
  60. package/dist/types/eengine/src/tools.d.ts +79 -0
  61. package/dist/types/eengine/src/web/index.d.ts +20 -0
  62. package/dist/types/eengine/src/web/mcp.d.ts +27 -0
  63. package/dist/types/eengine/src/web/platform.d.ts +91 -0
  64. package/dist/types/eengine/src/web/stores.d.ts +125 -0
  65. package/dist/types/emcp/fixtures/automations.json +521 -0
  66. package/dist/types/emcp/fixtures/hub.json +498 -0
  67. package/dist/types/emcp/src/access.d.ts +55 -0
  68. package/dist/types/emcp/src/audit.d.ts +22 -0
  69. package/dist/types/emcp/src/automations.d.ts +111 -0
  70. package/dist/types/emcp/src/exposes.d.ts +242 -0
  71. package/dist/types/emcp/src/hub.d.ts +63 -0
  72. package/dist/types/emcp/src/index.d.ts +7 -0
  73. package/dist/types/emcp/src/pure.d.ts +11 -0
  74. package/dist/types/emcp/src/upstream.d.ts +288 -0
  75. package/dist/types/emcp/src/vault.d.ts +34 -0
  76. package/dist/web/index.js +791 -0
  77. package/dist/web/index.js.map +13 -0
  78. package/fixtures/bundle.json +1165 -0
  79. package/fixtures/capabilities.json +434 -0
  80. package/fixtures/consent.json +146 -0
  81. package/fixtures/lifecycle.json +125 -0
  82. package/fixtures/outbox.json +22 -0
  83. package/fixtures/providers.json +55 -0
  84. package/fixtures/runner.json +2167 -0
  85. package/package.json +92 -4
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Dennis Strähhuber
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,54 @@
1
+ Exponential
2
+ Copyright 2026 Dennis Strähhuber
3
+
4
+ This product includes software developed as part of the Exponential project,
5
+ licensed under the Apache License, Version 2.0 (see LICENSE at the repo root).
6
+
7
+ Third-party code vendored into this repository keeps its own NOTICE, next to
8
+ the vendored source:
9
+
10
+ apps/desktop/crates/ui/NOTICE
11
+ apps/desktop/crates/gpui-markdown-editor/NOTICE
12
+
13
+ This file records the attributions that travel with a distributed artifact.
14
+ It is not the per-client dependency inventory; that is generated separately.
15
+
16
+
17
+ ================================================================================
18
+ Feedback widget
19
+ ================================================================================
20
+
21
+ The feedback widget (packages/widget, emitted to
22
+ apps/web/public/widget/v1/loader.js and widget.js) is served cross-origin to
23
+ third-party websites, so its bundle redistributes the software below. Both
24
+ emitted files carry a short banner naming these packages and pointing here.
25
+
26
+ preact
27
+ Copyright (c) 2015-present Jason Miller
28
+ https://github.com/preactjs/preact
29
+ MIT License
30
+
31
+ @zumer/snapdom
32
+ Copyright (c) 2025 ZumerLab
33
+ https://github.com/zumerlab/snapdom
34
+ MIT License
35
+
36
+ Both are made available under the following terms:
37
+
38
+ Permission is hereby granted, free of charge, to any person obtaining a
39
+ copy of this software and associated documentation files (the "Software"),
40
+ to deal in the Software without restriction, including without limitation
41
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
42
+ and/or sell copies of the Software, and to permit persons to whom the
43
+ Software is furnished to do so, subject to the following conditions:
44
+
45
+ The above copyright notice and this permission notice shall be included in
46
+ all copies or substantial portions of the Software.
47
+
48
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
51
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
53
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
54
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @exponential_app/engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Engine's contract (#VAPP-259, `docs/spec/apps.md` §13.1). The Engine is the stateful runtime around genUI that runs Apps in every host: Exponential, the softcoded app, eDE, Spezl and exported apps. The Apps format and its pure logic stay in genUI's host (`@exponential_app/eui/host`, `eui-core/src/host`). Each `fixtures/*.json` is the spec (its `$comment`) plus the cases. `src/` holds the pure TypeScript reference that replays them. It is the web's twin of the Rust crate `eengine`, which replays the same fixtures.
4
+
5
+ ```ts
6
+ import { brokerDecide, consentSheet, lifecycleStep } from "@exponential_app/engine"
7
+ import fixture from "@exponential_app/engine/fixtures/capabilities.json" with { type: "json" }
8
+ ```
9
+
10
+ Inside this monorepo the workspace package is `@exp/eengine` (private, the same entries); every `eengine-v*` tag publishes it to npm (`release/prepare-npm.ts`; Node 18+, Bun, Deno). Swift and Kotlin reach the Rust crate through `eengine-ffi`: SwiftPM `ExponentialEngine`, Maven `at.exponential:engine`.
11
+
12
+ | fixture | covers |
13
+ |---|---|
14
+ | `lifecycle.json` | launch, foreground, background, terminate, `online`, deep links (`crossAppTarget`), notification taps; the effects (open, flush, sources, automations, persist, refused) |
15
+ | `consent.json` | the sheet's answer, grant writes (only the ConsentUi, only after a gesture), the Vault record, reconciling on a package load, the ask sheet and the Permissions sheet as genUI surfaces |
16
+ | `capabilities.json` | the capability catalog (scopes, `ask` vs `picker`, host-only), `<capability>__<tool>` / `<capability>.<tool>` names, the one broker for UI and agent calls, an agent's tool list, the audit row; capabilities v1 (E5): every tool's schemas, the bridge between the broker and a native provider (validation, app files, notification ids and taps) and the `print.pdf` layout, byte for byte |
17
+ | `providers.json` | the `HostConfig` (required and optional providers; no telemetry, no updates), identity kinds (local = "me"), the network policy |
18
+ | `outbox.json` | a `$ref` to `domain-contract` `app-records.json` `outbox` (O1, not copied) plus when it applies (sync provider = queue, none = write through) and the account's queue (`syncedCases`, `SyncedRecordStore`: one outbox per account over the host's `OutboxLog`) |
19
+
20
+ ## Web capabilities
21
+
22
+ `@exp/eengine/web` is the browser's host side of capabilities v1 (#VAPP-265): `webCapabilities(platform = browserPlatform(), { onTap })` answers the native providers the Engine's bridge calls, each `{ name, call(tool, args) }` returning an MCP call result that matches `capabilities.json` `nativeOutputSchema`. Every browser API sits behind the `WebPlatform` seam (tests use fakes). A capability the browser lacks is left out.
23
+
24
+ | capability | tools | browser |
25
+ |---|---|---|
26
+ | `files` | `open`, `save` | `showOpenFilePicker` / `showSaveFilePicker` when present, else a hidden `<input type=file>` (cancel = its `cancel` event) and an `<a download>` blob URL (`saved: true`) |
27
+ | `photos` | `pick`, `list`, `get` | the library is the app's OPFS `photos/` dir: `pick` = the image picker, each picked file copied in as `<lastModified>-<name>` (the id; takenAt = lastModified); `list` newest first, cursor = an offset; no OPFS = an empty library |
28
+ | `share` | `send` | `navigator.share` (files only when `canShare({files})`); absent without `navigator.share` |
29
+ | `print` | `print` | a hidden iframe on a blob URL, `contentWindow.print()`; always `printed: true` (browsers cannot tell) |
30
+ | `notifications` | `post`, `cancel` | `Notification` (asks when `default`, `denied` = `failed: notifications blocked`); `tag` = the id; a tap calls `onTap(tap)` + `window.focus()`; absent without `Notification` |
31
+
32
+ - **User activation:** pickers, the share sheet and print open only inside a user gesture. App UI must call through the broker within the click's task (no awaited round trip first); without one, the call answers `failed: …`.
33
+ - **Scheduled notifications** are page timers: one fires only if the page is still open at `at` (no service worker, nothing survives a reload).
34
+ - No permission strings: the browser prompts for notifications itself; the others need none.
35
+
36
+ Licence: Apache-2.0
@@ -0,0 +1,29 @@
1
+ import {
2
+ CAPABILITIES2,
3
+ RESERVED_CAPABILITY_NAMES2,
4
+ scopeIdValid2,
5
+ capabilityNameValid2,
6
+ capabilityDef2,
7
+ scopeDef2,
8
+ parseCapabilityCall2,
9
+ urlOrigin2,
10
+ brokerDecide2,
11
+ agentToolList2,
12
+ brokerAuditRow2
13
+ } from "./chunks/index-tvsykgcv.js";
14
+ export {
15
+ CAPABILITIES2 as CAPABILITIES,
16
+ RESERVED_CAPABILITY_NAMES2 as RESERVED_CAPABILITY_NAMES,
17
+ agentToolList2 as agentToolList,
18
+ brokerAuditRow2 as brokerAuditRow,
19
+ brokerDecide2 as brokerDecide,
20
+ capabilityDef2 as capabilityDef,
21
+ capabilityNameValid2 as capabilityNameValid,
22
+ parseCapabilityCall2 as parseCapabilityCall,
23
+ scopeDef2 as scopeDef,
24
+ scopeIdValid2 as scopeIdValid,
25
+ urlOrigin2 as urlOrigin
26
+ };
27
+
28
+ //# debugId=827572527ECDF1A764756E2164756E21
29
+ //# sourceMappingURL=capabilities.js.map
@@ -0,0 +1,9 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [
5
+ ],
6
+ "mappings": "",
7
+ "debugId": "827572527ECDF1A764756E2164756E21",
8
+ "names": []
9
+ }
@@ -0,0 +1,315 @@
1
+ import {
2
+ capabilities_default
3
+ } from "./index-3rgr16n2.js";
4
+
5
+ // packages/eengine/src/pdf.ts
6
+ var [PAGE_W, PAGE_H] = capabilities_default.pdf.page;
7
+ var MARGIN = capabilities_default.pdf.margin;
8
+ var TOP = PAGE_H - MARGIN;
9
+ var WIDTH = PAGE_W - 2 * MARGIN;
10
+ var IMAGE_MAX_H = TOP - MARGIN;
11
+ var WIDTHS = { F1: capabilities_default.pdf.widths.Helvetica, F2: capabilities_default.pdf.widths[`Helvetica-Bold`] };
12
+ var WIN_ANSI = new Map(Object.entries(capabilities_default.pdf.winAnsi).map(([cp, code]) => [Number(cp), code]));
13
+ function winAnsi(cp) {
14
+ if (cp === 9)
15
+ return 32;
16
+ if (cp >= 32 && cp <= 126 || cp >= 160 && cp <= 255)
17
+ return cp;
18
+ if (cp < 32 || cp >= 127 && cp <= 159)
19
+ return null;
20
+ return WIN_ANSI.get(cp) ?? 63;
21
+ }
22
+ var encode = (s) => [...s].map((c) => winAnsi(c.codePointAt(0))).filter((b) => b !== null);
23
+ var widthSum = (font, bytes) => bytes.reduce((sum, b) => sum + WIDTHS[font][b], 0);
24
+ var fits = (font, size, bytes) => widthSum(font, bytes) * size <= WIDTH * 1000;
25
+ function wrapLines2(text, font, size) {
26
+ const lines = [];
27
+ for (const paragraph of text.split(`
28
+ `)) {
29
+ const words = [];
30
+ let word = [];
31
+ for (const b of encode(paragraph)) {
32
+ if (b === 32) {
33
+ if (word.length)
34
+ words.push(word);
35
+ word = [];
36
+ } else
37
+ word.push(b);
38
+ }
39
+ if (word.length)
40
+ words.push(word);
41
+ if (!words.length) {
42
+ lines.push([]);
43
+ continue;
44
+ }
45
+ let line = [];
46
+ for (let w of words) {
47
+ if (line.length) {
48
+ const joined = [...line, 32, ...w];
49
+ if (fits(font, size, joined)) {
50
+ line = joined;
51
+ continue;
52
+ }
53
+ lines.push(line);
54
+ line = [];
55
+ }
56
+ while (!fits(font, size, w)) {
57
+ let n = 1;
58
+ while (n < w.length && fits(font, size, w.slice(0, n + 1)))
59
+ n++;
60
+ lines.push(w.slice(0, n));
61
+ w = w.slice(n);
62
+ }
63
+ line = w;
64
+ }
65
+ lines.push(line);
66
+ }
67
+ return lines;
68
+ }
69
+ function pdfNumber2(x) {
70
+ const r = Math.sign(x) * Math.round(Math.abs(x) * 100);
71
+ if (r === 0)
72
+ return `0`;
73
+ const abs = Math.abs(r);
74
+ const whole = Math.floor(abs / 100);
75
+ const frac = abs % 100;
76
+ const sign = r < 0 ? `-` : ``;
77
+ if (frac === 0)
78
+ return `${sign}${whole}`;
79
+ const digits = String(frac).padStart(2, `0`).replace(/0$/, ``);
80
+ return `${sign}${whole}.${digits}`;
81
+ }
82
+ function pdfString(bytes) {
83
+ let out = `(`;
84
+ for (const b of bytes) {
85
+ if (b === 40 || b === 41 || b === 92)
86
+ out += `\\${String.fromCharCode(b)}`;
87
+ else if (b >= 128)
88
+ out += `\\${b.toString(8).padStart(3, `0`)}`;
89
+ else
90
+ out += String.fromCharCode(b);
91
+ }
92
+ return `${out})`;
93
+ }
94
+ var u16 = (b, i) => b[i] << 8 | b[i + 1];
95
+ var u32 = (b, i) => (b[i] << 24 >>> 0) + (b[i + 1] << 16 | b[i + 2] << 8 | b[i + 3]);
96
+ var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
97
+ function jpegImage(b) {
98
+ let i = 2;
99
+ while (i + 4 <= b.length) {
100
+ if (b[i] !== 255)
101
+ return null;
102
+ const marker = b[i + 1];
103
+ if (marker === 255) {
104
+ i++;
105
+ continue;
106
+ }
107
+ if (marker === 1 || marker >= 208 && marker <= 216) {
108
+ i += 2;
109
+ continue;
110
+ }
111
+ if (marker === 217 || marker === 218)
112
+ return null;
113
+ const length = u16(b, i + 2);
114
+ if (length < 2)
115
+ return null;
116
+ if (marker >= 192 && marker <= 195) {
117
+ if (i + 10 > b.length)
118
+ return null;
119
+ const height = u16(b, i + 5);
120
+ const width = u16(b, i + 7);
121
+ const components = b[i + 9];
122
+ const space = components === 1 ? `DeviceGray` : components === 3 ? `DeviceRGB` : components === 4 ? `DeviceCMYK` : null;
123
+ if (!space || !width || !height)
124
+ return null;
125
+ return { width, height, dict: `/Type /XObject /Subtype /Image /Width ${width} /Height ${height} /ColorSpace /${space} /BitsPerComponent 8 /Filter /DCTDecode`, data: b };
126
+ }
127
+ i += 2 + length;
128
+ }
129
+ return null;
130
+ }
131
+ function pngImage(b) {
132
+ let i = 8;
133
+ let header = null;
134
+ const idat = [];
135
+ while (i + 8 <= b.length) {
136
+ const length = u32(b, i);
137
+ const type = String.fromCharCode(b[i + 4], b[i + 5], b[i + 6], b[i + 7]);
138
+ const data = b.subarray(i + 8, i + 8 + length);
139
+ if (data.length < length)
140
+ return null;
141
+ if (!header) {
142
+ if (type !== `IHDR` || length < 13)
143
+ return null;
144
+ const width = u32(data, 0);
145
+ const height = u32(data, 4);
146
+ const [depth, colorType, compression, filter, interlace] = data.subarray(8, 13);
147
+ if (depth !== 8 || colorType !== 0 && colorType !== 2 || compression !== 0 || filter !== 0 || interlace !== 0 || !width || !height)
148
+ return null;
149
+ header = { width, height, colors: colorType === 0 ? 1 : 3 };
150
+ } else if (type === `IDAT`)
151
+ idat.push(data);
152
+ else if (type === `IEND`)
153
+ break;
154
+ i += 12 + length;
155
+ }
156
+ if (!header || !idat.length)
157
+ return null;
158
+ const joined = new Uint8Array(idat.reduce((n, d) => n + d.length, 0));
159
+ let o = 0;
160
+ for (const d of idat) {
161
+ joined.set(d, o);
162
+ o += d.length;
163
+ }
164
+ const { width, height, colors } = header;
165
+ const space = colors === 1 ? `DeviceGray` : `DeviceRGB`;
166
+ return {
167
+ width,
168
+ height,
169
+ dict: `/Type /XObject /Subtype /Image /Width ${width} /Height ${height} /ColorSpace /${space} /BitsPerComponent 8 /Filter /FlateDecode /DecodeParms << /Predictor 15 /Colors ${colors} /BitsPerComponent 8 /Columns ${width} >>`,
170
+ data: joined
171
+ };
172
+ }
173
+ function pdfImage2(bytes) {
174
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255)
175
+ return jpegImage(bytes);
176
+ if (PNG_SIGNATURE.every((v, k) => bytes[k] === v))
177
+ return pngImage(bytes);
178
+ return null;
179
+ }
180
+ var utf16Hex = (s) => {
181
+ let out = `FEFF`;
182
+ for (let i = 0;i < s.length; i++)
183
+ out += s.charCodeAt(i).toString(16).toUpperCase().padStart(4, `0`);
184
+ return out;
185
+ };
186
+ async function renderPdf2(args, getBlob) {
187
+ const pages = [{ ops: [], images: [] }];
188
+ const images = [];
189
+ let y = TOP;
190
+ const page = () => pages[pages.length - 1];
191
+ const empty = () => y === TOP;
192
+ const newPage = () => {
193
+ pages.push({ ops: [], images: [] });
194
+ y = TOP;
195
+ };
196
+ const lines = (text, font, size, leading) => {
197
+ for (const line of wrapLines2(text, font, size)) {
198
+ if (!empty() && y - leading < MARGIN)
199
+ newPage();
200
+ if (line.length)
201
+ page().ops.push(`BT /${font} ${size} Tf ${MARGIN} ${pdfNumber2(y - size)} Td ${pdfString(line)} Tj ET`);
202
+ y -= leading;
203
+ }
204
+ };
205
+ for (const block of args.blocks) {
206
+ if (`heading` in block) {
207
+ if (!empty())
208
+ y -= 12;
209
+ lines(block.heading, `F2`, 18, 24);
210
+ y -= 4;
211
+ } else if (`text` in block) {
212
+ lines(block.text, `F1`, 11, 15);
213
+ y -= 6;
214
+ } else if (`image` in block) {
215
+ let k = images.findIndex((i) => i.id === block.image);
216
+ if (k < 0) {
217
+ const bytes = await getBlob(block.image);
218
+ if (!bytes)
219
+ return { error: `notFound: ${block.image}` };
220
+ const image = pdfImage2(bytes);
221
+ if (!image)
222
+ return { error: `unsupportedImage: ${block.image}` };
223
+ images.push({ id: block.image, image });
224
+ k = images.length - 1;
225
+ }
226
+ const { width, height } = images[k].image;
227
+ const scale = Math.min(WIDTH / width, IMAGE_MAX_H / height, 1);
228
+ const w = width * scale;
229
+ const h = height * scale;
230
+ if (!empty() && y - h < MARGIN)
231
+ newPage();
232
+ page().ops.push(`q ${pdfNumber2(w)} 0 0 ${pdfNumber2(h)} ${MARGIN} ${pdfNumber2(y - h)} cm /Im${k + 1} Do Q`);
233
+ if (!page().images.includes(k + 1))
234
+ page().images.push(k + 1);
235
+ y -= h;
236
+ if (block.caption !== undefined) {
237
+ y -= 4;
238
+ lines(block.caption, `F1`, 9, 12);
239
+ }
240
+ y -= 6;
241
+ } else if (!empty())
242
+ newPage();
243
+ }
244
+ if (pages.length > 1 && empty())
245
+ pages.pop();
246
+ const chunks = [];
247
+ let offset = 0;
248
+ const offsets = [];
249
+ const latin = (s) => Uint8Array.from(s, (c) => c.charCodeAt(0));
250
+ const push = (bytes) => {
251
+ chunks.push(bytes);
252
+ offset += bytes.length;
253
+ };
254
+ const object = (body, stream) => {
255
+ offsets.push(offset);
256
+ const n = offsets.length;
257
+ if (stream) {
258
+ push(latin(`${n} 0 obj
259
+ << ${body}${body ? ` ` : ``}/Length ${stream.length} >>
260
+ stream
261
+ `));
262
+ push(stream);
263
+ push(latin(`
264
+ endstream
265
+ endobj
266
+ `));
267
+ } else
268
+ push(latin(`${n} 0 obj
269
+ ${body}
270
+ endobj
271
+ `));
272
+ };
273
+ push(Uint8Array.from([37, 80, 68, 70, 45, 49, 46, 52, 10, 37, 226, 227, 207, 211, 10]));
274
+ const firstPage = 6 + images.length;
275
+ const kids = pages.map((_, i) => `${firstPage + 2 * i} 0 R`).join(` `);
276
+ object(`<< /Type /Catalog /Pages 2 0 R >>`);
277
+ object(`<< /Type /Pages /Kids [${kids}] /Count ${pages.length} >>`);
278
+ object(`<< /Type /Font /Subtype /Type1 /BaseFont /${capabilities_default.pdf.fonts.F1} /Encoding /WinAnsiEncoding >>`);
279
+ object(`<< /Type /Font /Subtype /Type1 /BaseFont /${capabilities_default.pdf.fonts.F2} /Encoding /WinAnsiEncoding >>`);
280
+ object(`<< /Title <${utf16Hex(args.title)}> /Producer (Exponential Engine) >>`);
281
+ for (const { image } of images)
282
+ object(image.dict, image.data);
283
+ pages.forEach((p, i) => {
284
+ const xobjects = [...p.images].sort((a, b) => a - b).map((k) => `/Im${k} ${5 + k} 0 R`);
285
+ const resources = `<< /Font << /F1 3 0 R /F2 4 0 R >>${xobjects.length ? ` /XObject << ${xobjects.join(` `)} >>` : ``} >>`;
286
+ object(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PAGE_W} ${PAGE_H}] /Resources ${resources} /Contents ${firstPage + 2 * i + 1} 0 R >>`);
287
+ object(``, latin(p.ops.join(`
288
+ `)));
289
+ });
290
+ const xref = offset;
291
+ const size = offsets.length + 1;
292
+ push(latin(`xref
293
+ 0 ${size}
294
+ 0000000000 65535 f
295
+ ${offsets.map((o) => `${String(o).padStart(10, `0`)} 00000 n
296
+ `).join(``)}`));
297
+ push(latin(`trailer
298
+ << /Size ${size} /Root 1 0 R /Info 5 0 R >>
299
+ startxref
300
+ ${xref}
301
+ %%EOF
302
+ `));
303
+ const bytes = new Uint8Array(offset);
304
+ let at = 0;
305
+ for (const c of chunks) {
306
+ bytes.set(c, at);
307
+ at += c.length;
308
+ }
309
+ return { bytes, pages: pages.length };
310
+ }
311
+
312
+ export { wrapLines2, pdfNumber2, pdfImage2, renderPdf2 };
313
+
314
+ //# debugId=434A59D2B116CFC664756E2164756E21
315
+ //# sourceMappingURL=index-3nf9f7pv.js.map