@x12i/reportic-api 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,1154 @@
1
+ // packages/reportic-api/openapi.json
2
+ var openapi_default = {
3
+ openapi: "3.1.0",
4
+ info: {
5
+ title: "Reportic API",
6
+ version: "0.2.0",
7
+ description: "Shared Reportic engine for template discovery, validation, previews, report generation, and private local jobs. Bearer authentication is required when a token is configured; remote binds require a token."
8
+ },
9
+ servers: [
10
+ {
11
+ url: "http://127.0.0.1:4173"
12
+ }
13
+ ],
14
+ security: [
15
+ {
16
+ bearerAuth: []
17
+ }
18
+ ],
19
+ paths: {
20
+ "/v1/components": {
21
+ get: {
22
+ summary: "List component schemas and target capabilities",
23
+ responses: {
24
+ "200": {
25
+ description: "Success",
26
+ content: {
27
+ "application/json": {
28
+ schema: {
29
+ type: "object"
30
+ }
31
+ }
32
+ }
33
+ },
34
+ "401": {
35
+ description: "Bearer authentication is required."
36
+ },
37
+ "422": {
38
+ description: "Invalid inputs or rendering failure.",
39
+ content: {
40
+ "application/json": {
41
+ schema: {
42
+ $ref: "#/components/schemas/Failure"
43
+ }
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }
49
+ },
50
+ "/v1/components/{type}": {
51
+ get: {
52
+ summary: "Get one component definition",
53
+ parameters: [
54
+ {
55
+ name: "type",
56
+ in: "path",
57
+ required: true,
58
+ schema: {
59
+ type: "string"
60
+ }
61
+ }
62
+ ],
63
+ responses: {
64
+ "200": {
65
+ description: "Success",
66
+ content: {
67
+ "application/json": {
68
+ schema: {
69
+ type: "object"
70
+ }
71
+ }
72
+ }
73
+ },
74
+ "401": {
75
+ description: "Bearer authentication is required."
76
+ },
77
+ "422": {
78
+ description: "Invalid inputs or rendering failure.",
79
+ content: {
80
+ "application/json": {
81
+ schema: {
82
+ $ref: "#/components/schemas/Failure"
83
+ }
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+ },
90
+ "/v1/templates/inspect": {
91
+ post: {
92
+ summary: "Inspect a template",
93
+ requestBody: {
94
+ required: true,
95
+ content: {
96
+ "application/json": {
97
+ schema: {
98
+ $ref: "#/components/schemas/ReportRequest"
99
+ }
100
+ }
101
+ }
102
+ },
103
+ responses: {
104
+ "200": {
105
+ description: "Success",
106
+ content: {
107
+ "application/json": {
108
+ schema: {
109
+ type: "object"
110
+ }
111
+ }
112
+ }
113
+ },
114
+ "401": {
115
+ description: "Bearer authentication is required."
116
+ },
117
+ "422": {
118
+ description: "Invalid inputs or rendering failure.",
119
+ content: {
120
+ "application/json": {
121
+ schema: {
122
+ $ref: "#/components/schemas/Failure"
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ }
129
+ },
130
+ "/v1/templates/validate": {
131
+ post: {
132
+ summary: "Validate template authoring syntax",
133
+ requestBody: {
134
+ required: true,
135
+ content: {
136
+ "application/json": {
137
+ schema: {
138
+ $ref: "#/components/schemas/ReportRequest"
139
+ }
140
+ }
141
+ }
142
+ },
143
+ responses: {
144
+ "200": {
145
+ description: "Success",
146
+ content: {
147
+ "application/json": {
148
+ schema: {
149
+ $ref: "#/components/schemas/Validation"
150
+ }
151
+ }
152
+ }
153
+ },
154
+ "401": {
155
+ description: "Bearer authentication is required."
156
+ },
157
+ "422": {
158
+ description: "Invalid inputs or rendering failure.",
159
+ content: {
160
+ "application/json": {
161
+ schema: {
162
+ $ref: "#/components/schemas/Failure"
163
+ }
164
+ }
165
+ }
166
+ }
167
+ }
168
+ }
169
+ },
170
+ "/v1/reports/validate": {
171
+ post: {
172
+ summary: "Validate a report without creating an artifact",
173
+ requestBody: {
174
+ required: true,
175
+ content: {
176
+ "application/json": {
177
+ schema: {
178
+ $ref: "#/components/schemas/ReportRequest"
179
+ }
180
+ }
181
+ }
182
+ },
183
+ responses: {
184
+ "200": {
185
+ description: "Success",
186
+ content: {
187
+ "application/json": {
188
+ schema: {
189
+ $ref: "#/components/schemas/Validation"
190
+ }
191
+ }
192
+ }
193
+ },
194
+ "401": {
195
+ description: "Bearer authentication is required."
196
+ },
197
+ "422": {
198
+ description: "Invalid inputs or rendering failure.",
199
+ content: {
200
+ "application/json": {
201
+ schema: {
202
+ $ref: "#/components/schemas/Failure"
203
+ }
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ },
210
+ "/v1/reports/preview": {
211
+ post: {
212
+ summary: "Create a self-contained HTML preview",
213
+ requestBody: {
214
+ required: true,
215
+ content: {
216
+ "application/json": {
217
+ schema: {
218
+ $ref: "#/components/schemas/ReportRequest"
219
+ }
220
+ }
221
+ }
222
+ },
223
+ responses: {
224
+ "200": {
225
+ description: "Success",
226
+ content: {
227
+ "application/json": {
228
+ schema: {
229
+ type: "object"
230
+ }
231
+ }
232
+ }
233
+ },
234
+ "401": {
235
+ description: "Bearer authentication is required."
236
+ },
237
+ "422": {
238
+ description: "Invalid inputs or rendering failure.",
239
+ content: {
240
+ "application/json": {
241
+ schema: {
242
+ $ref: "#/components/schemas/Failure"
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+ },
250
+ "/v1/reports/generate": {
251
+ post: {
252
+ summary: "Generate a report; PDF is the default",
253
+ requestBody: {
254
+ required: true,
255
+ content: {
256
+ "application/json": {
257
+ schema: {
258
+ $ref: "#/components/schemas/ReportRequest"
259
+ }
260
+ }
261
+ }
262
+ },
263
+ responses: {
264
+ "200": {
265
+ description: "Verified report bytes or ZIP bundle.",
266
+ content: {
267
+ "application/octet-stream": {
268
+ schema: {
269
+ type: "string",
270
+ format: "binary"
271
+ }
272
+ },
273
+ "application/pdf": {
274
+ schema: {
275
+ type: "string",
276
+ format: "binary"
277
+ }
278
+ }
279
+ }
280
+ },
281
+ "406": {
282
+ description: "Accept mismatch or companion assets require the bundle endpoint."
283
+ },
284
+ "422": {
285
+ description: "Report failed.",
286
+ content: {
287
+ "application/json": {
288
+ schema: {
289
+ $ref: "#/components/schemas/Failure"
290
+ }
291
+ }
292
+ }
293
+ }
294
+ }
295
+ }
296
+ },
297
+ "/v1/report-jobs": {
298
+ post: {
299
+ summary: "Submit a private background report job",
300
+ requestBody: {
301
+ required: true,
302
+ content: {
303
+ "application/json": {
304
+ schema: {
305
+ $ref: "#/components/schemas/ReportRequest"
306
+ }
307
+ }
308
+ }
309
+ },
310
+ responses: {
311
+ "202": {
312
+ description: "Success",
313
+ content: {
314
+ "application/json": {
315
+ schema: {
316
+ $ref: "#/components/schemas/Job"
317
+ }
318
+ }
319
+ }
320
+ },
321
+ "401": {
322
+ description: "Bearer authentication is required."
323
+ },
324
+ "409": {
325
+ description: "Idempotency key reused with different inputs."
326
+ },
327
+ "422": {
328
+ description: "Invalid inputs or rendering failure.",
329
+ content: {
330
+ "application/json": {
331
+ schema: {
332
+ $ref: "#/components/schemas/Failure"
333
+ }
334
+ }
335
+ }
336
+ }
337
+ },
338
+ parameters: [
339
+ {
340
+ in: "header",
341
+ name: "Idempotency-Key",
342
+ schema: {
343
+ type: "string"
344
+ }
345
+ }
346
+ ]
347
+ }
348
+ },
349
+ "/v1/report-jobs/{id}": {
350
+ get: {
351
+ summary: "Read job state and artifact metadata",
352
+ parameters: [
353
+ {
354
+ name: "id",
355
+ in: "path",
356
+ required: true,
357
+ schema: {
358
+ type: "string",
359
+ format: "uuid"
360
+ }
361
+ }
362
+ ],
363
+ responses: {
364
+ "200": {
365
+ description: "Success",
366
+ content: {
367
+ "application/json": {
368
+ schema: {
369
+ $ref: "#/components/schemas/Job"
370
+ }
371
+ }
372
+ }
373
+ },
374
+ "401": {
375
+ description: "Bearer authentication is required."
376
+ },
377
+ "422": {
378
+ description: "Invalid inputs or rendering failure.",
379
+ content: {
380
+ "application/json": {
381
+ schema: {
382
+ $ref: "#/components/schemas/Failure"
383
+ }
384
+ }
385
+ }
386
+ }
387
+ }
388
+ },
389
+ delete: {
390
+ summary: "Cancel a pending or running job",
391
+ parameters: [
392
+ {
393
+ name: "id",
394
+ in: "path",
395
+ required: true,
396
+ schema: {
397
+ type: "string",
398
+ format: "uuid"
399
+ }
400
+ }
401
+ ],
402
+ responses: {
403
+ "200": {
404
+ description: "Success",
405
+ content: {
406
+ "application/json": {
407
+ schema: {
408
+ $ref: "#/components/schemas/Job"
409
+ }
410
+ }
411
+ }
412
+ },
413
+ "401": {
414
+ description: "Bearer authentication is required."
415
+ },
416
+ "422": {
417
+ description: "Invalid inputs or rendering failure.",
418
+ content: {
419
+ "application/json": {
420
+ schema: {
421
+ $ref: "#/components/schemas/Failure"
422
+ }
423
+ }
424
+ }
425
+ }
426
+ }
427
+ }
428
+ },
429
+ "/v1/report-jobs/{id}/artifact": {
430
+ get: {
431
+ summary: "Download a verified primary artifact",
432
+ parameters: [
433
+ {
434
+ name: "id",
435
+ in: "path",
436
+ required: true,
437
+ schema: {
438
+ type: "string",
439
+ format: "uuid"
440
+ }
441
+ }
442
+ ],
443
+ responses: {
444
+ "200": {
445
+ description: "Verified report bytes or ZIP bundle.",
446
+ content: {
447
+ "application/octet-stream": {
448
+ schema: {
449
+ type: "string",
450
+ format: "binary"
451
+ }
452
+ },
453
+ "application/pdf": {
454
+ schema: {
455
+ type: "string",
456
+ format: "binary"
457
+ }
458
+ }
459
+ }
460
+ },
461
+ "406": {
462
+ description: "Accept mismatch or companion assets require the bundle endpoint."
463
+ },
464
+ "422": {
465
+ description: "Report failed.",
466
+ content: {
467
+ "application/json": {
468
+ schema: {
469
+ $ref: "#/components/schemas/Failure"
470
+ }
471
+ }
472
+ }
473
+ }
474
+ }
475
+ }
476
+ },
477
+ "/v1/report-jobs/{id}/bundle": {
478
+ get: {
479
+ summary: "Download a ZIP including companion assets",
480
+ parameters: [
481
+ {
482
+ name: "id",
483
+ in: "path",
484
+ required: true,
485
+ schema: {
486
+ type: "string",
487
+ format: "uuid"
488
+ }
489
+ }
490
+ ],
491
+ responses: {
492
+ "200": {
493
+ description: "Verified report bytes or ZIP bundle.",
494
+ content: {
495
+ "application/octet-stream": {
496
+ schema: {
497
+ type: "string",
498
+ format: "binary"
499
+ }
500
+ },
501
+ "application/pdf": {
502
+ schema: {
503
+ type: "string",
504
+ format: "binary"
505
+ }
506
+ }
507
+ }
508
+ },
509
+ "406": {
510
+ description: "Accept mismatch or companion assets require the bundle endpoint."
511
+ },
512
+ "422": {
513
+ description: "Report failed.",
514
+ content: {
515
+ "application/json": {
516
+ schema: {
517
+ $ref: "#/components/schemas/Failure"
518
+ }
519
+ }
520
+ }
521
+ }
522
+ }
523
+ }
524
+ }
525
+ },
526
+ components: {
527
+ securitySchemes: {
528
+ bearerAuth: {
529
+ type: "http",
530
+ scheme: "bearer"
531
+ }
532
+ },
533
+ schemas: {
534
+ Diagnostic: {
535
+ type: "object",
536
+ required: [
537
+ "code",
538
+ "severity",
539
+ "phase",
540
+ "message"
541
+ ],
542
+ properties: {
543
+ code: {
544
+ type: "string"
545
+ },
546
+ severity: {
547
+ enum: [
548
+ "error",
549
+ "warning",
550
+ "info"
551
+ ]
552
+ },
553
+ phase: {
554
+ enum: [
555
+ "parse",
556
+ "input",
557
+ "prepare",
558
+ "render"
559
+ ]
560
+ },
561
+ message: {
562
+ type: "string"
563
+ },
564
+ elementId: {
565
+ type: "string"
566
+ },
567
+ bindingPath: {
568
+ type: "string"
569
+ },
570
+ line: {
571
+ type: "integer"
572
+ },
573
+ column: {
574
+ type: "integer"
575
+ },
576
+ format: {
577
+ type: "string"
578
+ }
579
+ }
580
+ },
581
+ Validation: {
582
+ type: "object",
583
+ required: [
584
+ "valid",
585
+ "diagnostics"
586
+ ],
587
+ properties: {
588
+ valid: {
589
+ type: "boolean"
590
+ },
591
+ diagnostics: {
592
+ type: "array",
593
+ items: {
594
+ $ref: "#/components/schemas/Diagnostic"
595
+ }
596
+ }
597
+ }
598
+ },
599
+ Failure: {
600
+ type: "object",
601
+ properties: {
602
+ error: {
603
+ type: "string"
604
+ },
605
+ diagnostics: {
606
+ type: "array",
607
+ items: {
608
+ $ref: "#/components/schemas/Diagnostic"
609
+ }
610
+ }
611
+ }
612
+ },
613
+ Job: {
614
+ type: "object",
615
+ properties: {
616
+ id: {
617
+ type: "string",
618
+ format: "uuid"
619
+ },
620
+ state: {
621
+ enum: [
622
+ "queued",
623
+ "running",
624
+ "succeeded",
625
+ "failed",
626
+ "cancelled",
627
+ "expired"
628
+ ]
629
+ },
630
+ createdAt: {
631
+ type: "string",
632
+ format: "date-time"
633
+ },
634
+ expiresAt: {
635
+ type: "string",
636
+ format: "date-time"
637
+ },
638
+ diagnostics: {
639
+ type: "array",
640
+ items: {
641
+ $ref: "#/components/schemas/Diagnostic"
642
+ }
643
+ },
644
+ artifact: {
645
+ type: "object",
646
+ properties: {
647
+ filename: {
648
+ type: "string"
649
+ },
650
+ mediaType: {
651
+ type: "string"
652
+ },
653
+ bytes: {
654
+ type: "integer"
655
+ },
656
+ url: {
657
+ type: "string"
658
+ },
659
+ bundleUrl: {
660
+ type: "string"
661
+ }
662
+ }
663
+ }
664
+ }
665
+ },
666
+ ReportRequest: {
667
+ type: "object",
668
+ required: [
669
+ "template"
670
+ ],
671
+ additionalProperties: false,
672
+ properties: {
673
+ template: {
674
+ type: "string",
675
+ maxLength: 1e6
676
+ },
677
+ dataSets: {
678
+ type: "array",
679
+ default: [],
680
+ items: {
681
+ type: "object",
682
+ required: [
683
+ "name",
684
+ "data"
685
+ ],
686
+ properties: {
687
+ name: {
688
+ type: "string",
689
+ pattern: "^[A-Za-z_][A-Za-z0-9_]*$"
690
+ },
691
+ data: {
692
+ type: "object"
693
+ }
694
+ }
695
+ }
696
+ },
697
+ variables: {
698
+ type: "object",
699
+ default: {}
700
+ },
701
+ format: {
702
+ enum: [
703
+ "pdf",
704
+ "pptx",
705
+ "docx",
706
+ "html",
707
+ "markdown"
708
+ ],
709
+ default: "pdf"
710
+ },
711
+ theme: {
712
+ type: "object"
713
+ },
714
+ css: {
715
+ type: "string"
716
+ },
717
+ assets: {
718
+ type: "object",
719
+ additionalProperties: {
720
+ type: "object",
721
+ required: [
722
+ "base64",
723
+ "mediaType"
724
+ ],
725
+ properties: {
726
+ base64: {
727
+ type: "string",
728
+ contentEncoding: "base64"
729
+ },
730
+ mediaType: {
731
+ enum: [
732
+ "image/png",
733
+ "image/jpeg",
734
+ "image/webp",
735
+ "image/svg+xml"
736
+ ]
737
+ }
738
+ }
739
+ }
740
+ },
741
+ html: {
742
+ type: "object",
743
+ properties: {
744
+ assetMode: {
745
+ enum: [
746
+ "embedded",
747
+ "bundled"
748
+ ]
749
+ }
750
+ }
751
+ },
752
+ pdf: {
753
+ type: "object",
754
+ properties: {
755
+ size: {
756
+ enum: [
757
+ "A4",
758
+ "Letter"
759
+ ]
760
+ },
761
+ landscape: {
762
+ type: "boolean"
763
+ },
764
+ pageNumbers: {
765
+ type: "boolean"
766
+ },
767
+ preferCSSPageSize: {
768
+ type: "boolean"
769
+ }
770
+ }
771
+ },
772
+ pptx: {
773
+ type: "object",
774
+ properties: {
775
+ editability: {
776
+ enum: [
777
+ "normal",
778
+ "strict"
779
+ ]
780
+ },
781
+ layout: {
782
+ enum: [
783
+ "wide",
784
+ "standard"
785
+ ]
786
+ }
787
+ }
788
+ },
789
+ docx: {
790
+ type: "object"
791
+ },
792
+ diagramMode: {
793
+ enum: [
794
+ "portable",
795
+ "mermaid"
796
+ ]
797
+ },
798
+ strictStyles: {
799
+ type: "boolean"
800
+ }
801
+ }
802
+ }
803
+ }
804
+ }
805
+ };
806
+
807
+ // packages/reportic-api/src/index.ts
808
+ import express2 from "express";
809
+ import { timingSafeEqual, randomUUID, createHash } from "crypto";
810
+ import { inspectTemplate, validateReport, validateTemplate, generateReport, listComponents, getComponent, ReporticError } from "@x12i/reportic";
811
+
812
+ // packages/reportic-api/src/dataset-routes.ts
813
+ import express from "express";
814
+ import { parseAuthoringYaml } from "@x12i/reportic-core/authoring";
815
+ import { importOpenApiOperations } from "@x12i/reportic-adapter-api";
816
+ import { checkJson, datasetError, DatasetError, DatasetExecutionError } from "@x12i/reportic-datasets";
817
+ import { CatalogError } from "@x12i/reportic-catalog";
818
+ function createDatasetRouter(datasets, identity) {
819
+ const router = express.Router();
820
+ router.use(express.json({ limit: "4mb" }));
821
+ router.use(async (request, response, next) => {
822
+ try {
823
+ const principal = await identity.authenticate(request);
824
+ if (principal?.id && principal.workspaceId && Array.isArray(principal.agentIds) && Array.isArray(principal.actions)) {
825
+ request.principal = principal;
826
+ response.setHeader("Cache-Control", "no-store");
827
+ return next();
828
+ }
829
+ } catch {
830
+ }
831
+ response.status(401).json({ error: "AUTHENTICATION_REQUIRED", message: "An authorized workspace identity is required." });
832
+ });
833
+ router.use(createDatasetRoutes(datasets));
834
+ router.use((error, _request, response, next) => {
835
+ if (response.headersSent) return next(error);
836
+ if (error instanceof CatalogError) return response.status(error.status).json({ error: error.code, message: error.message, ...error.details });
837
+ if (error instanceof DatasetError) return response.status(error.status).json({
838
+ error: error.diagnostic.code,
839
+ message: error.message,
840
+ diagnostics: [error.diagnostic],
841
+ ...error instanceof DatasetExecutionError ? { metadata: error.metadata } : {}
842
+ });
843
+ return response.status(422).json({ error: "DATASET_REQUEST_FAILED", message: "The dataset request could not be processed." });
844
+ });
845
+ return router;
846
+ }
847
+ function createDatasetRoutes(datasets) {
848
+ const router = express.Router();
849
+ const agent = "/agents/:agentId";
850
+ const source = agent + "/sources";
851
+ const plan = agent + "/datasets/:datasetId/plan";
852
+ const runs = agent + "/datasets/:datasetId/runs";
853
+ const actor = (request) => request.principal;
854
+ const parameter = (request, name) => String(request.params[name]);
855
+ const agentId = (request) => parameter(request, "agentId");
856
+ const datasetId = (request) => parameter(request, "datasetId");
857
+ const runId = (request) => parameter(request, "runId");
858
+ const route = (handler) => (request, response, next) => {
859
+ void handler(request, response).catch(next);
860
+ };
861
+ function duringRequest(request, response) {
862
+ const controller = new AbortController();
863
+ request.on("aborted", () => controller.abort());
864
+ response.on("close", () => {
865
+ if (!response.writableEnded) controller.abort();
866
+ });
867
+ return controller.signal;
868
+ }
869
+ router.get(source, route(async (req, res) => res.json(await datasets.inspectSource(actor(req), agentId(req)))));
870
+ router.post(source, route(async (req, res) => res.status(201).json(await datasets.approveSource(actor(req), agentId(req), req.body))));
871
+ router.post(source + "/openapi", route(async (req, res) => {
872
+ await datasets.catalog.authorize(actor(req), agentId(req), "sources.manage");
873
+ if (typeof req.body.document !== "string" || Buffer.byteLength(req.body.document) > 1e6) throw datasetError("INVALID_OPENAPI", "plan", "Import an OpenAPI document under 1 MB.");
874
+ let document;
875
+ try {
876
+ document = parseAuthoringYaml(req.body.document).toJS({ maxAliasCount: 0 });
877
+ } catch {
878
+ throw datasetError("INVALID_OPENAPI", "plan", "Fix the JSON or YAML document before importing.");
879
+ }
880
+ checkJson(document, 1e6);
881
+ return res.json({ operations: importOpenApiOperations(document) });
882
+ }));
883
+ router.post(source + "/:sourceId/status", route(async (req, res) => res.json(
884
+ await datasets.setSourceStatus(actor(req), agentId(req), parameter(req, "sourceId"), req.body.status, req.body.expectedRevision)
885
+ )));
886
+ router.post(source + "/:sourceRef/test-connection", route(async (req, res) => res.json(
887
+ await datasets.testConnection(actor(req), agentId(req), parameter(req, "sourceRef"), duringRequest(req, res))
888
+ )));
889
+ router.get(plan, route(async (req, res) => res.json(await datasets.getPlan(actor(req), agentId(req), datasetId(req)))));
890
+ router.put(plan, route(async (req, res) => res.json(
891
+ await datasets.saveDraft(actor(req), agentId(req), datasetId(req), req.body.sourceText, req.body.expectedRevision)
892
+ )));
893
+ router.post(plan + "/validate", route(async (req, res) => res.json(
894
+ await datasets.validateDatasetPlan(actor(req), agentId(req), datasetId(req), req.body.sourceText)
895
+ )));
896
+ router.post(plan + "/test", route(async (req, res) => res.json(
897
+ await datasets.testDatasetPlan(actor(req), agentId(req), datasetId(req), req.body, duringRequest(req, res))
898
+ )));
899
+ router.get(plan + "/fixtures", route(async (req, res) => res.json(await datasets.listResponseFixtures(actor(req), agentId(req), datasetId(req)))));
900
+ router.post(plan + "/fixtures", route(async (req, res) => res.status(201).json(
901
+ await datasets.saveResponseFixture(actor(req), agentId(req), datasetId(req), req.body)
902
+ )));
903
+ router.get(plan + "/fixtures/:fixtureId", route(async (req, res) => res.json(
904
+ await datasets.getResponseFixture(actor(req), agentId(req), datasetId(req), parameter(req, "fixtureId"))
905
+ )));
906
+ router.post(plan + "/publish", route(async (req, res) => res.status(201).json(
907
+ await datasets.publishDatasetPlan(actor(req), agentId(req), datasetId(req), req.body)
908
+ )));
909
+ router.post(plan + "/activate", route(async (req, res) => res.json(
910
+ await datasets.activatePlan(actor(req), agentId(req), datasetId(req), req.body.revision, req.body.expectedDatasetRevision)
911
+ )));
912
+ router.get(plan + "/versions/:revision/source", route(async (req, res) => {
913
+ const result = await datasets.getPlan(actor(req), agentId(req), datasetId(req));
914
+ const version = result.plan?.versions.find((item) => item.revision === Number(parameter(req, "revision")));
915
+ if (!version) return res.status(404).json({ error: "RESOURCE_UNAVAILABLE", message: "The plan revision is unavailable." });
916
+ return res.type("text/yaml").attachment(result.dataset.name + ".plan-v" + version.revision + ".yaml").send(version.sourceText);
917
+ }));
918
+ router.get(runs, route(async (req, res) => res.json(await datasets.listRuns(actor(req), agentId(req), datasetId(req)))));
919
+ router.post(runs, route(async (req, res) => res.status(202).json(
920
+ await datasets.submitRun(actor(req), agentId(req), datasetId(req), req.body, req.header("Idempotency-Key"))
921
+ )));
922
+ router.get(runs + "/:runId", route(async (req, res) => res.json(await datasets.getRun(actor(req), agentId(req), datasetId(req), runId(req)))));
923
+ router.delete(runs + "/:runId", route(async (req, res) => res.json(await datasets.cancelRun(actor(req), agentId(req), datasetId(req), runId(req)))));
924
+ router.get(runs + "/:runId/result", route(async (req, res) => {
925
+ const result = await datasets.getResult(actor(req), agentId(req), datasetId(req), runId(req));
926
+ if (req.query.download === "true") res.attachment("dataset-" + runId(req) + ".json");
927
+ return res.json(result);
928
+ }));
929
+ router.post(runs + "/:runId/fixture", route(async (req, res) => res.status(201).json(
930
+ await datasets.resultFixture(actor(req), agentId(req), datasetId(req), runId(req), req.body)
931
+ )));
932
+ router.post(agent + "/templates/:templateId/acquire", route(async (req, res) => res.json(
933
+ await datasets.acquireReportData(actor(req), agentId(req), parameter(req, "templateId"), req.body, duringRequest(req, res))
934
+ )));
935
+ return router;
936
+ }
937
+
938
+ // packages/reportic-api/src/index.ts
939
+ function createReporticRouter(config = {}) {
940
+ const router = express2.Router();
941
+ router.get("/openapi.json", (_req, res) => res.json(openapi_default));
942
+ const jobs = /* @__PURE__ */ new Map();
943
+ const idempotency = /* @__PURE__ */ new Map();
944
+ let active = 0;
945
+ router.use(express2.json({ limit: "12mb" }));
946
+ router.use((req, res, next) => {
947
+ if (config.token) {
948
+ const value = (req.headers.authorization ?? "").replace(/^Bearer /, "");
949
+ const a = Buffer.from(value), b = Buffer.from(config.token);
950
+ if (a.length !== b.length || !timingSafeEqual(a, b)) {
951
+ res.status(401).json({ error: "UNAUTHORIZED", message: "A valid bearer token is required." });
952
+ return;
953
+ }
954
+ }
955
+ req.owner = config.token ? "authenticated" : "local";
956
+ res.setHeader("Cache-Control", "no-store");
957
+ next();
958
+ });
959
+ function input(req) {
960
+ const b = req.body;
961
+ if (!b || typeof b.template !== "string" || b.dataSets !== void 0 && !Array.isArray(b.dataSets) || b.variables !== void 0 && (!b.variables || typeof b.variables !== "object" || Array.isArray(b.variables))) throw new ReporticError([{ code: "INVALID_REQUEST", severity: "error", phase: "input", message: "Provide template text, a dataSets array, and a variables object." }]);
962
+ const allowed = ["template", "dataSets", "variables", "format", "theme", "css", "assets", "html", "pdf", "pptx", "docx", "diagramMode", "strictStyles"];
963
+ for (const key of Object.keys(b)) if (!allowed.includes(key)) throw new ReporticError([{ code: "INVALID_REQUEST_OPTION", severity: "error", phase: "input", message: `Request option "${key}" is not accepted.` }]);
964
+ const assets = {};
965
+ if (b.assets) {
966
+ for (const [key, a] of Object.entries(b.assets)) {
967
+ if (typeof a.base64 !== "string" || typeof a.mediaType !== "string") throw new Error("Invalid asset payload.");
968
+ assets[key] = { bytes: Buffer.from(a.base64, "base64"), mediaType: a.mediaType };
969
+ }
970
+ }
971
+ const options = { ...config.trustedOptions, registry: config.registry ?? config.trustedOptions?.registry, format: b.format, theme: b.theme, css: b.css, assets: { ...config.trustedOptions?.assets, ...assets }, html: b.html ? { assetMode: b.html.assetMode } : void 0, pdf: b.pdf ? { ...config.trustedOptions?.pdf, size: b.pdf.size, landscape: b.pdf.landscape, pageNumbers: b.pdf.pageNumbers, preferCSSPageSize: b.pdf.preferCSSPageSize } : config.trustedOptions?.pdf, pptx: b.pptx ? { editability: b.pptx.editability, layout: b.pptx.layout } : void 0, docx: b.docx ? { landscape: b.docx.landscape, margin: b.docx.margin, header: b.docx.header, footer: b.docx.footer } : void 0, diagramMode: b.diagramMode, strictStyles: b.strictStyles };
972
+ return { template: b.template, dataSets: b.dataSets ?? [], variables: b.variables ?? {}, options };
973
+ }
974
+ const send = (res, r) => {
975
+ res.setHeader("Content-Type", r.mediaType);
976
+ res.setHeader("Content-Disposition", `attachment; filename="${r.filename}"`);
977
+ res.setHeader("X-Reportic-Diagnostics", encodeURIComponent(JSON.stringify(r.diagnostics)));
978
+ if (r.assets.length) {
979
+ res.status(406).json({ error: "BUNDLE_REQUIRED", message: "This export contains companion assets. Use a report job with /bundle, or select self-contained HTML." });
980
+ return;
981
+ }
982
+ res.send(Buffer.from(r.bytes));
983
+ };
984
+ const publicJob = (j) => ({ id: j.id, state: j.state, createdAt: j.createdAt, expiresAt: j.expiresAt, diagnostics: j.diagnostics, ...j.result ? { artifact: { filename: j.result.filename, mediaType: j.result.mediaType, bytes: j.result.bytes.length, url: `/v1/report-jobs/${j.id}/artifact`, bundleUrl: `/v1/report-jobs/${j.id}/bundle` } } : {} });
985
+ function prune() {
986
+ const now = Date.now();
987
+ for (const [id, j] of jobs) {
988
+ if (new Date(j.expiresAt).getTime() < now) {
989
+ j.controller.abort();
990
+ j.result = void 0;
991
+ j.state = "expired";
992
+ if (now - new Date(j.expiresAt).getTime() > 6e4 || jobs.size >= (config.maxJobs ?? 100)) jobs.delete(id);
993
+ }
994
+ }
995
+ for (const [k, v] of idempotency) if (!jobs.has(v.id)) idempotency.delete(k);
996
+ }
997
+ function find(req, res) {
998
+ prune();
999
+ const job = jobs.get(String(req.params.id));
1000
+ if (!job || job.owner !== req.owner) {
1001
+ res.status(404).json({ error: "JOB_NOT_FOUND" });
1002
+ return;
1003
+ }
1004
+ return job;
1005
+ }
1006
+ router.get("/components", (req, res) => res.json(listComponents({ format: req.query.format, editability: req.query.editability }, config.registry)));
1007
+ router.get("/components/:type", (req, res) => {
1008
+ const component = getComponent(String(req.params.type), config.registry);
1009
+ component ? res.json(component) : res.status(404).json({ error: "COMPONENT_NOT_FOUND" });
1010
+ });
1011
+ router.post("/templates/inspect", (req, res) => res.json(inspectTemplate(req.body?.template)));
1012
+ router.post("/templates/validate", async (req, res) => res.json(await validateTemplate(req.body?.template, { registry: config.registry })));
1013
+ router.post("/reports/validate", async (req, res) => {
1014
+ const i = input(req);
1015
+ res.json(await validateReport(i.template, i.dataSets, i.variables, i.options));
1016
+ });
1017
+ router.post("/reports/preview", async (req, res) => {
1018
+ const i = input(req);
1019
+ const result = await generateReport(i.template, i.dataSets, i.variables, { ...i.options, format: "html", html: { assetMode: "embedded" } });
1020
+ res.json({ html: Buffer.from(result.bytes).toString(), diagnostics: result.diagnostics, metadata: result.metadata });
1021
+ });
1022
+ router.post("/reports/generate", async (req, res) => {
1023
+ if (active >= (config.concurrency ?? 2)) {
1024
+ res.setHeader("Retry-After", "2");
1025
+ res.status(429).json({ error: "CAPACITY_EXCEEDED" });
1026
+ return;
1027
+ }
1028
+ const i = input(req);
1029
+ const accept = req.headers.accept;
1030
+ if (accept && !accept.includes("*/*") && !accept.includes("application/octet-stream")) {
1031
+ const expected = { pdf: "application/pdf", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", html: "text/html", markdown: "text/markdown" };
1032
+ if (!accept.includes(expected[i.options.format ?? "pdf"])) {
1033
+ res.status(406).json({ error: "ACCEPT_MISMATCH" });
1034
+ return;
1035
+ }
1036
+ }
1037
+ active++;
1038
+ try {
1039
+ const result = await generateReport(i.template, i.dataSets, i.variables, i.options);
1040
+ send(res, result);
1041
+ } finally {
1042
+ active--;
1043
+ }
1044
+ });
1045
+ router.post("/report-jobs", async (req, res) => {
1046
+ prune();
1047
+ const i = input(req);
1048
+ const key = req.headers["idempotency-key"];
1049
+ const hash = createHash("sha256").update(JSON.stringify(req.body)).digest("hex");
1050
+ const scopedKey = typeof key === "string" ? `${req.owner}:${key}` : void 0;
1051
+ if (scopedKey && idempotency.has(scopedKey)) {
1052
+ const existing = idempotency.get(scopedKey);
1053
+ if (existing.hash !== hash) {
1054
+ res.status(409).json({ error: "IDEMPOTENCY_CONFLICT" });
1055
+ return;
1056
+ }
1057
+ res.json(publicJob(jobs.get(existing.id)));
1058
+ return;
1059
+ }
1060
+ if (jobs.size >= (config.maxJobs ?? 100)) {
1061
+ res.status(429).json({ error: "JOB_LIMIT" });
1062
+ return;
1063
+ }
1064
+ const job = { id: randomUUID(), owner: req.owner, state: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString(), expiresAt: new Date(Date.now() + (config.ttlMs ?? 36e5)).toISOString(), diagnostics: [], controller: new AbortController() };
1065
+ jobs.set(job.id, job);
1066
+ if (scopedKey) idempotency.set(scopedKey, { hash, id: job.id });
1067
+ res.status(202).json(publicJob(job));
1068
+ const execute = async () => {
1069
+ if (job.state !== "queued") return;
1070
+ if (active >= (config.concurrency ?? 2)) {
1071
+ const timer = setTimeout(() => void execute(), 150);
1072
+ timer.unref();
1073
+ return;
1074
+ }
1075
+ active++;
1076
+ job.state = "running";
1077
+ try {
1078
+ const result = await generateReport(i.template, i.dataSets, i.variables, { ...i.options, signal: job.controller.signal });
1079
+ if (job.state === "running") {
1080
+ job.result = result;
1081
+ job.diagnostics = result.diagnostics;
1082
+ job.state = "succeeded";
1083
+ }
1084
+ } catch (e) {
1085
+ if (!job.controller.signal.aborted) {
1086
+ job.state = "failed";
1087
+ job.diagnostics = e instanceof ReporticError ? e.diagnostics : [{ code: "RENDER_FAILED", severity: "error", phase: "render", message: "Report job failed." }];
1088
+ }
1089
+ } finally {
1090
+ active--;
1091
+ }
1092
+ };
1093
+ void execute();
1094
+ });
1095
+ router.get("/report-jobs/:id", (req, res) => {
1096
+ const job = find(req, res);
1097
+ if (job) res.json(publicJob(job));
1098
+ });
1099
+ router.get("/report-jobs/:id/artifact", (req, res) => {
1100
+ const j = find(req, res);
1101
+ if (!j) return;
1102
+ if (!j.result) {
1103
+ res.status(j.state === "expired" ? 410 : 409).json({ error: "ARTIFACT_UNAVAILABLE", state: j.state });
1104
+ return;
1105
+ }
1106
+ send(res, j.result);
1107
+ });
1108
+ router.get("/report-jobs/:id/bundle", async (req, res) => {
1109
+ const j = find(req, res);
1110
+ if (!j) return;
1111
+ if (!j.result) {
1112
+ res.status(409).json({ error: "ARTIFACT_UNAVAILABLE" });
1113
+ return;
1114
+ }
1115
+ const { default: JSZip } = await import("jszip");
1116
+ const zip = new JSZip();
1117
+ zip.file(j.result.filename, j.result.bytes);
1118
+ for (const asset of j.result.assets) zip.file(asset.path, asset.bytes);
1119
+ res.type("application/zip").attachment(j.result.filename + ".zip").send(await zip.generateAsync({ type: "nodebuffer" }));
1120
+ });
1121
+ router.delete("/report-jobs/:id", (req, res) => {
1122
+ const j = find(req, res);
1123
+ if (j) {
1124
+ if (j.state === "queued" || j.state === "running") {
1125
+ j.controller.abort();
1126
+ j.state = "cancelled";
1127
+ }
1128
+ res.json(publicJob(j));
1129
+ }
1130
+ });
1131
+ router.use((error, req, res, next) => {
1132
+ if (res.headersSent) {
1133
+ next(error);
1134
+ return;
1135
+ }
1136
+ const diagnostics = error instanceof ReporticError ? error.diagnostics : [{ code: error.type === "entity.too.large" ? "REQUEST_TOO_LARGE" : "INVALID_REQUEST", severity: "error", phase: "input", message: "Request could not be processed." }];
1137
+ res.status(422).json({ error: "REPORT_FAILED", diagnostics });
1138
+ });
1139
+ return router;
1140
+ }
1141
+ function createReporticApp(options = {}) {
1142
+ const app = express2();
1143
+ app.disable("x-powered-by");
1144
+ app.use("/v1", createReporticRouter(options));
1145
+ app.get("/health", (_req, res) => res.json({ status: "ok", version: "0.2.0" }));
1146
+ return app;
1147
+ }
1148
+ export {
1149
+ createDatasetRouter,
1150
+ createDatasetRoutes,
1151
+ createReporticApp,
1152
+ createReporticRouter
1153
+ };
1154
+ //# sourceMappingURL=index.js.map