@signiphi/page-assembly 0.2.0-beta.2 → 0.2.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -14,7 +14,7 @@ import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
14
14
  import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
15
15
  import * as TooltipPrimitive from '@radix-ui/react-tooltip';
16
16
  import * as pdfjsLib from 'pdfjs-dist';
17
- import { PDFDocument } from 'pdf-lib';
17
+ import { PDFDocument, PDFTextField, PDFCheckBox, PDFDropdown, PDFRadioGroup, StandardFonts, rgb, PDFName, PDFString } from 'pdf-lib';
18
18
 
19
19
  // src/components/PageAssembler.tsx
20
20
  function cn(...inputs) {
@@ -693,6 +693,580 @@ function downloadPdf(pdfBytes, filename) {
693
693
  a.click();
694
694
  URL.revokeObjectURL(url);
695
695
  }
696
+ function getSigniphiMetadata(pdfDoc) {
697
+ try {
698
+ const infoRef = pdfDoc.context.trailerInfo.Info;
699
+ if (!infoRef) {
700
+ return null;
701
+ }
702
+ const infoObj = pdfDoc.context.lookup(infoRef);
703
+ if (!infoObj || typeof infoObj.get !== "function") {
704
+ return null;
705
+ }
706
+ const infoDict = infoObj;
707
+ const metadataObj = infoDict.get(PDFName.of("SigniphiMetadata"));
708
+ if (!metadataObj) {
709
+ return null;
710
+ }
711
+ const metadataStr = metadataObj.toString();
712
+ let jsonStr = metadataStr;
713
+ if (metadataStr.startsWith("(") && metadataStr.endsWith(")")) {
714
+ jsonStr = metadataStr.slice(1, -1);
715
+ } else if (metadataStr.startsWith("<") && metadataStr.endsWith(">")) {
716
+ jsonStr = metadataStr.slice(1, -1);
717
+ }
718
+ const metadata = JSON.parse(jsonStr);
719
+ return metadata;
720
+ } catch (error) {
721
+ console.error("Failed to load Signiphi metadata:", error);
722
+ return null;
723
+ }
724
+ }
725
+ function getBaseFieldName(encodedName) {
726
+ let baseName = encodedName;
727
+ if (baseName.includes("__SIGNER__")) {
728
+ baseName = baseName.split("__SIGNER__")[0];
729
+ }
730
+ if (baseName.includes("__LABEL__")) {
731
+ baseName = baseName.split("__LABEL__")[0];
732
+ }
733
+ if (baseName.includes("__PLACEHOLDER__")) {
734
+ baseName = baseName.split("__PLACEHOLDER__")[0];
735
+ }
736
+ return baseName;
737
+ }
738
+ function getSignerFromFieldName(encodedName) {
739
+ if (encodedName.includes("__SIGNER__")) {
740
+ const parts = encodedName.split("__SIGNER__");
741
+ if (parts[1]) {
742
+ return parts[1].split("__")[0] || parts[1];
743
+ }
744
+ }
745
+ return void 0;
746
+ }
747
+ function determineFieldType(fieldName, widgetType) {
748
+ const baseName = getBaseFieldName(fieldName);
749
+ const nameLower = baseName.toLowerCase();
750
+ if (nameLower.includes("_signature") || nameLower.includes("signature")) {
751
+ return "signature";
752
+ }
753
+ if (nameLower.includes("_initials") || nameLower.includes("initials")) {
754
+ return "initials";
755
+ }
756
+ if (nameLower.includes("_date") || nameLower.includes("date")) {
757
+ return "date";
758
+ }
759
+ if (widgetType === "checkbox" || nameLower.includes("checkbox")) {
760
+ return "checkbox";
761
+ }
762
+ if (widgetType === "radio" || nameLower.includes("radio")) {
763
+ return "radio";
764
+ }
765
+ if (widgetType === "dropdown" || widgetType === "select" || nameLower.includes("dropdown")) {
766
+ return "dropdown";
767
+ }
768
+ return "text";
769
+ }
770
+ async function extractFieldsFromPdf(pdfBytes) {
771
+ const pdfDoc = await PDFDocument.load(pdfBytes);
772
+ const fields = [];
773
+ const metadata = getSigniphiMetadata(pdfDoc);
774
+ const form = pdfDoc.getForm();
775
+ const pdfFields = form.getFields();
776
+ for (const field of pdfFields) {
777
+ const fieldName = field.getName();
778
+ const widgets = field.acroField.getWidgets();
779
+ const baseName = getBaseFieldName(fieldName);
780
+ const signerFromName = getSignerFromFieldName(fieldName);
781
+ let required = false;
782
+ let options;
783
+ let widgetType;
784
+ if (field instanceof PDFTextField) {
785
+ required = field.isRequired();
786
+ console.log(`[field-extraction] PDFTextField "${fieldName}" isRequired=${required}`);
787
+ } else if (field instanceof PDFCheckBox) {
788
+ widgetType = "checkbox";
789
+ required = field.isRequired();
790
+ console.log(`[field-extraction] PDFCheckBox "${fieldName}" isRequired=${required}`);
791
+ } else if (field instanceof PDFDropdown) {
792
+ widgetType = "dropdown";
793
+ required = field.isRequired();
794
+ options = field.getOptions();
795
+ console.log(`[field-extraction] PDFDropdown "${fieldName}" isRequired=${required}`);
796
+ } else if (field instanceof PDFRadioGroup) {
797
+ widgetType = "radio";
798
+ required = field.isRequired();
799
+ options = field.getOptions();
800
+ console.log(`[field-extraction] PDFRadioGroup "${fieldName}" isRequired=${required}`);
801
+ } else {
802
+ console.log(`[field-extraction] Unknown field type "${fieldName}" - defaulting required=false`);
803
+ }
804
+ for (const widget of widgets) {
805
+ const rect = widget.getRectangle();
806
+ const pageRef = widget.P();
807
+ let pageNumber = 1;
808
+ if (pageRef) {
809
+ const pages = pdfDoc.getPages();
810
+ for (let i = 0; i < pages.length; i++) {
811
+ if (pages[i].ref === pageRef) {
812
+ pageNumber = i + 1;
813
+ break;
814
+ }
815
+ }
816
+ }
817
+ const pageQualifiedKey = `${baseName}_p${pageNumber}`;
818
+ let fieldMetadata = metadata?.fields?.[pageQualifiedKey];
819
+ if (!fieldMetadata) {
820
+ fieldMetadata = metadata?.fields?.[fieldName];
821
+ }
822
+ if (!fieldMetadata && baseName !== fieldName) {
823
+ fieldMetadata = metadata?.fields?.[baseName];
824
+ }
825
+ let fieldRequired = required;
826
+ let fieldOptions = options;
827
+ if (fieldMetadata?.required !== void 0) {
828
+ fieldRequired = fieldMetadata.required;
829
+ }
830
+ if (fieldMetadata?.options?.length) {
831
+ fieldOptions = fieldMetadata.options;
832
+ }
833
+ const page = pdfDoc.getPage(pageNumber - 1);
834
+ const pageHeight = page.getHeight();
835
+ const extractedField = {
836
+ name: baseName,
837
+ // Use clean base name without __SIGNER__ encoding (signer stored in signer property)
838
+ type: determineFieldType(fieldName, widgetType),
839
+ // Uses base name internally
840
+ page: pageNumber,
841
+ x: rect.x,
842
+ y: pageHeight - rect.y - rect.height,
843
+ // Convert from PDF coords (bottom-left) to top-left
844
+ width: rect.width,
845
+ height: rect.height,
846
+ required: fieldRequired,
847
+ options: fieldOptions,
848
+ signer: signerFromName
849
+ // Extract signer from encoded name
850
+ };
851
+ if (fieldMetadata) {
852
+ if (fieldMetadata.fieldId) {
853
+ extractedField.fieldId = fieldMetadata.fieldId;
854
+ }
855
+ if (fieldMetadata.label) {
856
+ extractedField.label = fieldMetadata.label;
857
+ }
858
+ if (!extractedField.signer && fieldMetadata.signer) {
859
+ extractedField.signer = fieldMetadata.signer;
860
+ }
861
+ if (fieldMetadata.placeholder) {
862
+ extractedField.placeholder = fieldMetadata.placeholder;
863
+ }
864
+ }
865
+ fields.push(extractedField);
866
+ }
867
+ }
868
+ const deduplicatedFields = fields.reduce((acc, field) => {
869
+ const newBaseName = getBaseFieldName(field.name);
870
+ const existingIndex = acc.findIndex((f) => {
871
+ const existingBaseName = getBaseFieldName(f.name);
872
+ return existingBaseName === newBaseName && f.page === field.page;
873
+ });
874
+ if (existingIndex === -1) {
875
+ acc.push(field);
876
+ } else {
877
+ const existing = acc[existingIndex];
878
+ acc[existingIndex] = {
879
+ ...existing,
880
+ // Prefer non-empty values from either field
881
+ label: existing.label || field.label,
882
+ placeholder: existing.placeholder || field.placeholder,
883
+ required: existing.required || field.required,
884
+ options: existing.options?.length ? existing.options : field.options,
885
+ fieldId: existing.fieldId || field.fieldId,
886
+ // Prefer signer from the field that has it
887
+ signer: existing.signer || field.signer
888
+ };
889
+ }
890
+ return acc;
891
+ }, []);
892
+ return deduplicatedFields;
893
+ }
894
+ function setSigniphiMetadata(pdfDoc, metadata) {
895
+ try {
896
+ const infoRef = pdfDoc.context.trailerInfo.Info;
897
+ const infoObj = pdfDoc.context.lookup(infoRef);
898
+ if (!infoObj || typeof infoObj.set !== "function") {
899
+ throw new Error("Info object is not a PDFDict or does not have set method");
900
+ }
901
+ const infoDict = infoObj;
902
+ const metadataString = JSON.stringify(metadata);
903
+ infoDict.set(PDFName.of("SigniphiMetadata"), PDFString.of(metadataString));
904
+ } catch (error) {
905
+ console.error("Failed to set Signiphi metadata:", error);
906
+ throw error;
907
+ }
908
+ }
909
+ var FormFieldType = /* @__PURE__ */ ((FormFieldType2) => {
910
+ FormFieldType2["TEXT"] = "text";
911
+ FormFieldType2["SIGNATURE"] = "signature";
912
+ FormFieldType2["INITIALS"] = "initials";
913
+ FormFieldType2["DATE"] = "date";
914
+ FormFieldType2["CHECKBOX"] = "checkbox";
915
+ FormFieldType2["RADIO"] = "radio";
916
+ FormFieldType2["DROPDOWN"] = "dropdown";
917
+ FormFieldType2["TEXT_LABEL"] = "text_label";
918
+ return FormFieldType2;
919
+ })(FormFieldType || {});
920
+ function parseEncodedFieldName(encodedName) {
921
+ let baseName = encodedName;
922
+ let label;
923
+ let signer;
924
+ if (baseName.includes("__SIGNER__")) {
925
+ const parts = baseName.split("__SIGNER__");
926
+ baseName = parts[0];
927
+ signer = parts[1];
928
+ }
929
+ if (baseName.includes("__LABEL__")) {
930
+ const parts = baseName.split("__LABEL__");
931
+ baseName = parts[0];
932
+ label = parts[1];
933
+ }
934
+ if (baseName.includes("__PLACEHOLDER__")) {
935
+ const parts = baseName.split("__PLACEHOLDER__");
936
+ baseName = parts[0];
937
+ }
938
+ return { baseName, label, signer };
939
+ }
940
+ function encodeFieldNameWithSigner(fieldName, signerEmail) {
941
+ const { baseName, signer: existingSigner } = parseEncodedFieldName(fieldName);
942
+ const finalSigner = existingSigner || signerEmail;
943
+ if (!finalSigner) return baseName;
944
+ return `${baseName}__SIGNER__${finalSigner}`;
945
+ }
946
+ function encodeFieldNameWithLabelAndSigner(fieldName, label, signerEmail) {
947
+ const { baseName, label: existingLabel, signer: existingSigner } = parseEncodedFieldName(fieldName);
948
+ const finalLabel = existingLabel || label;
949
+ const finalSigner = existingSigner || signerEmail;
950
+ let name = baseName;
951
+ if (finalLabel && finalLabel.trim()) {
952
+ name = `${name}__LABEL__${finalLabel.trim()}`;
953
+ }
954
+ if (finalSigner) {
955
+ name = `${name}__SIGNER__${finalSigner}`;
956
+ }
957
+ return name;
958
+ }
959
+ async function addFormFieldsToPdf(pdfBytes, formFields, options = {}) {
960
+ const { removeExistingFields = false, drawLabels = false } = options;
961
+ const pdfDoc = await PDFDocument.load(pdfBytes);
962
+ const form = pdfDoc.getForm();
963
+ const pages = pdfDoc.getPages();
964
+ if (removeExistingFields) {
965
+ const existingFields = form.getFields();
966
+ for (const field of existingFields) {
967
+ try {
968
+ const acroField = field.acroField;
969
+ if (acroField && typeof acroField.getWidgets === "function") {
970
+ let widgets = acroField.getWidgets();
971
+ let safetyCounter = 0;
972
+ const maxIterations = widgets.length + 5;
973
+ while (widgets.length > 0 && safetyCounter < maxIterations) {
974
+ try {
975
+ acroField.removeWidget(widgets.length - 1);
976
+ widgets = acroField.getWidgets();
977
+ } catch {
978
+ break;
979
+ }
980
+ safetyCounter++;
981
+ }
982
+ }
983
+ form.removeField(field);
984
+ } catch (error) {
985
+ console.warn(`Failed to remove field ${field.getName()}:`, error);
986
+ try {
987
+ form.removeField(field);
988
+ } catch {
989
+ }
990
+ }
991
+ }
992
+ }
993
+ const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
994
+ const fieldNamePages = /* @__PURE__ */ new Map();
995
+ for (const field of formFields) {
996
+ const baseName = field.name;
997
+ if (!fieldNamePages.has(baseName)) {
998
+ fieldNamePages.set(baseName, /* @__PURE__ */ new Set());
999
+ }
1000
+ fieldNamePages.get(baseName).add(field.position.page);
1001
+ }
1002
+ const conflictingNames = /* @__PURE__ */ new Set();
1003
+ for (const [name, pages2] of fieldNamePages) {
1004
+ if (pages2.size > 1) {
1005
+ conflictingNames.add(name);
1006
+ }
1007
+ }
1008
+ for (const field of formFields) {
1009
+ const pageIndex = field.position.page - 1;
1010
+ if (pageIndex < 0 || pageIndex >= pages.length) {
1011
+ console.warn(`Field ${field.name} references page ${field.position.page} but PDF only has ${pages.length} pages`);
1012
+ continue;
1013
+ }
1014
+ const page = pages[pageIndex];
1015
+ const { height: pageHeight } = page.getSize();
1016
+ const pdfX = field.position.x;
1017
+ const pdfY = pageHeight - field.position.y - field.position.height;
1018
+ const uniqueFieldName = conflictingNames.has(field.name) ? `${field.name}_p${field.position.page}` : field.name;
1019
+ try {
1020
+ const fieldType = typeof field.type === "string" ? field.type : field.type;
1021
+ switch (fieldType) {
1022
+ case "text" /* TEXT */:
1023
+ case "text": {
1024
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1025
+ const textField = form.createTextField(encodedName);
1026
+ textField.addToPage(page, {
1027
+ x: pdfX,
1028
+ y: pdfY,
1029
+ width: field.position.width,
1030
+ height: field.position.height,
1031
+ borderColor: rgb(0.5, 0.5, 0.5),
1032
+ backgroundColor: rgb(1, 1, 1)
1033
+ });
1034
+ if (field.label && field.label.trim()) {
1035
+ textField.acroField.dict.set(PDFName.of("TU"), PDFString.of(field.label));
1036
+ if (drawLabels) {
1037
+ const fontSize = Math.min(10, field.position.height * 0.4);
1038
+ const labelY = pdfY + field.position.height + 5;
1039
+ page.drawText(field.label, { x: pdfX, y: labelY, size: fontSize, font, color: rgb(0, 0, 0) });
1040
+ }
1041
+ }
1042
+ if (field.defaultValue && field.defaultValue.trim()) {
1043
+ textField.setText(field.defaultValue);
1044
+ }
1045
+ if (field.fontSize && field.fontSize >= 8 && field.fontSize <= 72) {
1046
+ try {
1047
+ textField.setFontSize(field.fontSize);
1048
+ } catch {
1049
+ }
1050
+ }
1051
+ if (field.multiline) {
1052
+ try {
1053
+ textField.enableMultiline();
1054
+ } catch {
1055
+ }
1056
+ }
1057
+ if (field.maxLength && field.maxLength > 0) {
1058
+ try {
1059
+ textField.setMaxLength(field.maxLength);
1060
+ } catch {
1061
+ }
1062
+ }
1063
+ if (field.required) {
1064
+ textField.enableRequired();
1065
+ }
1066
+ break;
1067
+ }
1068
+ case "checkbox" /* CHECKBOX */:
1069
+ case "checkbox": {
1070
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1071
+ const checkBox = form.createCheckBox(encodedName);
1072
+ checkBox.addToPage(page, {
1073
+ x: pdfX,
1074
+ y: pdfY,
1075
+ width: field.position.width,
1076
+ height: field.position.height,
1077
+ borderColor: rgb(0.5, 0.5, 0.5),
1078
+ backgroundColor: rgb(1, 1, 1)
1079
+ });
1080
+ if (field.defaultValue === "true" || field.defaultValue === "checked") {
1081
+ checkBox.check();
1082
+ }
1083
+ if (field.required) {
1084
+ checkBox.enableRequired();
1085
+ }
1086
+ if (field.label && field.label.trim()) {
1087
+ try {
1088
+ checkBox.acroField.dict.set(PDFName.of("TU"), PDFString.of(field.label));
1089
+ } catch {
1090
+ }
1091
+ if (drawLabels) {
1092
+ const fontSize = Math.min(12, field.position.height * 0.6);
1093
+ const labelX = pdfX + field.position.width + 5;
1094
+ const labelY = pdfY + (field.position.height - fontSize) / 2;
1095
+ page.drawText(field.label, { x: labelX, y: labelY, size: fontSize, font, color: rgb(0, 0, 0) });
1096
+ }
1097
+ }
1098
+ break;
1099
+ }
1100
+ case "signature" /* SIGNATURE */:
1101
+ case "signature": {
1102
+ const baseWithSuffix = field.name.endsWith("_signature") ? field.name : `${field.name}_signature`;
1103
+ const finalName = conflictingNames.has(field.name) ? `${baseWithSuffix}_p${field.position.page}` : baseWithSuffix;
1104
+ const encodedName = encodeFieldNameWithLabelAndSigner(finalName, field.label, field.assignedSignerEmail);
1105
+ const sigField = form.createTextField(encodedName);
1106
+ sigField.addToPage(page, {
1107
+ x: pdfX,
1108
+ y: pdfY,
1109
+ width: field.position.width,
1110
+ height: field.position.height,
1111
+ borderColor: rgb(0, 0, 1),
1112
+ backgroundColor: rgb(0.9, 0.9, 1)
1113
+ });
1114
+ if (field.label && field.label.trim()) {
1115
+ sigField.acroField.dict.set(PDFName.of("TU"), PDFString.of(field.label));
1116
+ }
1117
+ sigField.enableReadOnly();
1118
+ if (field.required) {
1119
+ sigField.enableRequired();
1120
+ }
1121
+ break;
1122
+ }
1123
+ case "initials" /* INITIALS */:
1124
+ case "initials": {
1125
+ const baseWithSuffix = field.name.endsWith("_initials") ? field.name : `${field.name}_initials`;
1126
+ const finalName = conflictingNames.has(field.name) ? `${baseWithSuffix}_p${field.position.page}` : baseWithSuffix;
1127
+ const encodedName = encodeFieldNameWithLabelAndSigner(finalName, field.label, field.assignedSignerEmail);
1128
+ const initField = form.createTextField(encodedName);
1129
+ initField.addToPage(page, {
1130
+ x: pdfX,
1131
+ y: pdfY,
1132
+ width: field.position.width,
1133
+ height: field.position.height,
1134
+ borderColor: rgb(0.5, 0, 0.5),
1135
+ backgroundColor: rgb(1, 0.95, 1)
1136
+ });
1137
+ if (field.label && field.label.trim()) {
1138
+ initField.acroField.dict.set(PDFName.of("TU"), PDFString.of(field.label));
1139
+ }
1140
+ initField.enableReadOnly();
1141
+ if (field.required) {
1142
+ initField.enableRequired();
1143
+ }
1144
+ break;
1145
+ }
1146
+ case "date" /* DATE */:
1147
+ case "date": {
1148
+ const baseWithSuffix = field.name.endsWith("_date") ? field.name : `${field.name}_date`;
1149
+ const finalName = conflictingNames.has(field.name) ? `${baseWithSuffix}_p${field.position.page}` : baseWithSuffix;
1150
+ const encodedName = encodeFieldNameWithLabelAndSigner(finalName, field.label, field.assignedSignerEmail);
1151
+ const dateField = form.createTextField(encodedName);
1152
+ dateField.addToPage(page, {
1153
+ x: pdfX,
1154
+ y: pdfY,
1155
+ width: field.position.width,
1156
+ height: field.position.height,
1157
+ borderColor: rgb(0, 0.5, 0),
1158
+ backgroundColor: rgb(0.95, 1, 0.95)
1159
+ });
1160
+ if (field.label && field.label.trim()) {
1161
+ dateField.acroField.dict.set(PDFName.of("TU"), PDFString.of(field.label));
1162
+ }
1163
+ if (field.required) {
1164
+ dateField.enableRequired();
1165
+ }
1166
+ break;
1167
+ }
1168
+ case "dropdown" /* DROPDOWN */:
1169
+ case "dropdown": {
1170
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1171
+ const dropdown = form.createDropdown(encodedName);
1172
+ dropdown.addToPage(page, {
1173
+ x: pdfX,
1174
+ y: pdfY,
1175
+ width: field.position.width,
1176
+ height: field.position.height,
1177
+ borderColor: rgb(0.5, 0.5, 0.5),
1178
+ backgroundColor: rgb(1, 1, 1)
1179
+ });
1180
+ if (field.options && field.options.length > 0) {
1181
+ dropdown.addOptions(field.options);
1182
+ if (field.defaultValue && field.options.includes(field.defaultValue)) {
1183
+ dropdown.select(field.defaultValue);
1184
+ }
1185
+ }
1186
+ if (field.label && field.label.trim()) {
1187
+ try {
1188
+ dropdown.acroField.dict.set(PDFName.of("TU"), PDFString.of(field.label));
1189
+ } catch {
1190
+ }
1191
+ if (drawLabels) {
1192
+ const fontSize = Math.min(10, field.position.height * 0.4);
1193
+ const labelY = pdfY + field.position.height + 5;
1194
+ page.drawText(field.label, { x: pdfX, y: labelY, size: fontSize, font, color: rgb(0, 0, 0) });
1195
+ }
1196
+ }
1197
+ if (field.required) {
1198
+ dropdown.enableRequired();
1199
+ }
1200
+ break;
1201
+ }
1202
+ case "radio" /* RADIO */:
1203
+ case "radio": {
1204
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1205
+ const radioGroup = form.createRadioGroup(encodedName);
1206
+ if (field.options && field.options.length > 0) {
1207
+ const optionHeight = Math.min(20, field.position.height / field.options.length);
1208
+ const spacing = field.position.height / field.options.length;
1209
+ field.options.forEach((option, index) => {
1210
+ const optionY = pdfY + field.position.height - (index + 1) * spacing + (spacing - optionHeight) / 2;
1211
+ radioGroup.addOptionToPage(option, page, {
1212
+ x: pdfX,
1213
+ y: optionY,
1214
+ width: optionHeight,
1215
+ height: optionHeight,
1216
+ borderColor: rgb(0.5, 0.5, 0.5),
1217
+ backgroundColor: rgb(1, 1, 1)
1218
+ });
1219
+ if (drawLabels) {
1220
+ const labelX = pdfX + optionHeight + 5;
1221
+ const labelY = optionY + optionHeight / 4;
1222
+ page.drawText(option, { x: labelX, y: labelY, size: 10, font, color: rgb(0, 0, 0) });
1223
+ }
1224
+ });
1225
+ if (field.defaultValue && field.options.includes(field.defaultValue)) {
1226
+ radioGroup.select(field.defaultValue);
1227
+ }
1228
+ }
1229
+ if (field.label && field.label.trim()) {
1230
+ try {
1231
+ radioGroup.acroField.dict.set(PDFName.of("TU"), PDFString.of(field.label));
1232
+ } catch {
1233
+ }
1234
+ if (drawLabels) {
1235
+ const fontSize = 10;
1236
+ const labelY = pdfY + field.position.height + 5;
1237
+ page.drawText(field.label, { x: pdfX, y: labelY, size: fontSize, font, color: rgb(0, 0, 0) });
1238
+ }
1239
+ }
1240
+ if (field.required) {
1241
+ radioGroup.enableRequired();
1242
+ }
1243
+ break;
1244
+ }
1245
+ default:
1246
+ console.warn(`Unknown field type: ${fieldType} for field ${field.name}`);
1247
+ }
1248
+ } catch (error) {
1249
+ console.error(`Error adding field ${field.name}:`, error);
1250
+ }
1251
+ }
1252
+ return await pdfDoc.save();
1253
+ }
1254
+ function mapFieldPositionsAfterAssembly(fields, pageMapping) {
1255
+ return fields.map((field) => {
1256
+ const mappingKey = String(field.position.page - 1);
1257
+ const newPageNumber = pageMapping.get(mappingKey);
1258
+ if (newPageNumber !== void 0) {
1259
+ return {
1260
+ ...field,
1261
+ position: { ...field.position, page: newPageNumber }
1262
+ };
1263
+ }
1264
+ return field;
1265
+ }).filter((field) => {
1266
+ const mappingKey = String(field.position.page - 1);
1267
+ return pageMapping.has(mappingKey) || pageMapping.size === 0;
1268
+ });
1269
+ }
696
1270
  var isMultiSelectModifier = (event) => {
697
1271
  return event.ctrlKey || event.metaKey;
698
1272
  };
@@ -1325,6 +1899,7 @@ var PageAssembler = forwardRef(
1325
1899
  const processedInitialPdfRef = useRef(null);
1326
1900
  const isDraggingPage = useRef(false);
1327
1901
  const onChangeRef = useRef(onChange);
1902
+ const originalBytesCache = useRef(/* @__PURE__ */ new Map());
1328
1903
  const summary = useMemo(() => ({
1329
1904
  totalFiles: state.files.length,
1330
1905
  totalPages: state.files.reduce((sum, file) => sum + file.pages.length, 0)
@@ -1394,6 +1969,7 @@ var PageAssembler = forwardRef(
1394
1969
  originalFileId: fileId
1395
1970
  }))
1396
1971
  };
1972
+ originalBytesCache.current.set(fileId, originalBytes);
1397
1973
  dispatch({ type: "ADD_FILE", payload: file });
1398
1974
  } catch (error) {
1399
1975
  console.error("Error processing initial PDF:", error);
@@ -1446,6 +2022,7 @@ var PageAssembler = forwardRef(
1446
2022
  const arrayBuffer = await file.arrayBuffer();
1447
2023
  const pdfBytes = new Uint8Array(arrayBuffer);
1448
2024
  fileInfo.originalBytes = new Uint8Array(pdfBytes);
2025
+ originalBytesCache.current.set(fileInfo.id, fileInfo.originalBytes);
1449
2026
  const defensiveCopy = new Uint8Array(pdfBytes);
1450
2027
  const pages = await pdfToImages(defensiveCopy, { hideFormFields: true });
1451
2028
  fileInfo.pages = pages.map((page, index) => ({
@@ -1462,6 +2039,7 @@ var PageAssembler = forwardRef(
1462
2039
  const arrayBuffer = await file.arrayBuffer();
1463
2040
  const imageBytes = new Uint8Array(arrayBuffer);
1464
2041
  fileInfo.originalBytes = new Uint8Array(imageBytes);
2042
+ originalBytesCache.current.set(fileInfo.id, fileInfo.originalBytes);
1465
2043
  const thumbUrl = URL.createObjectURL(file);
1466
2044
  const img = new Image();
1467
2045
  const dimensions = await new Promise((resolve) => {
@@ -1589,21 +2167,205 @@ var PageAssembler = forwardRef(
1589
2167
  setIsLoading(true);
1590
2168
  setProcessingStatus("Assembling PDF...");
1591
2169
  try {
1592
- const { PDFDocument: PDFDocument2 } = await import('pdf-lib');
1593
- const combinedDoc = await PDFDocument2.create();
2170
+ const { PDFDocument: PDFDocument4, PDFName: PDFName3, PDFString: PDFString3 } = await import('pdf-lib');
1594
2171
  const loadedPdfs = /* @__PURE__ */ new Map();
1595
2172
  const fileMap = /* @__PURE__ */ new Map();
2173
+ const pdfFiles = state.files.filter((f) => f.type === "pdf" && f.originalBytes?.length > 0);
2174
+ const imageFiles = state.files.filter((f) => f.type === "image");
2175
+ const isSinglePdfScenario = pdfFiles.length === 1 && imageFiles.length === 0;
1596
2176
  for (const file of state.files) {
1597
2177
  fileMap.set(file.id, file);
1598
2178
  if (file.type === "pdf" && file.originalBytes && file.originalBytes.length > 0) {
1599
2179
  try {
1600
- const sourcePdf = await PDFDocument2.load(file.originalBytes);
2180
+ const sourcePdf = await PDFDocument4.load(file.originalBytes);
1601
2181
  loadedPdfs.set(file.id, sourcePdf);
1602
2182
  } catch (error) {
1603
2183
  console.error(`Error loading PDF for file ${file.id}:`, error);
1604
2184
  }
1605
2185
  }
1606
2186
  }
2187
+ const referencedFileIds = /* @__PURE__ */ new Set();
2188
+ for (const file of state.files) {
2189
+ for (const page of file.pages) {
2190
+ const originalFileId = page.originalFileId || file.id;
2191
+ if (!loadedPdfs.has(originalFileId)) {
2192
+ referencedFileIds.add(originalFileId);
2193
+ }
2194
+ }
2195
+ }
2196
+ for (const fileId of referencedFileIds) {
2197
+ const cachedBytes = originalBytesCache.current.get(fileId);
2198
+ if (cachedBytes && cachedBytes.length > 0) {
2199
+ try {
2200
+ console.log(`[PageAssembler] Loading PDF from cache for deleted file ${fileId}`);
2201
+ const sourcePdf = await PDFDocument4.load(cachedBytes);
2202
+ loadedPdfs.set(fileId, sourcePdf);
2203
+ } catch (error) {
2204
+ console.error(`Error loading cached PDF for file ${fileId}:`, error);
2205
+ }
2206
+ }
2207
+ }
2208
+ console.log("[PageAssembler] Checking single PDF scenario:", {
2209
+ isSinglePdfScenario,
2210
+ pdfFilesCount: pdfFiles.length,
2211
+ imageFilesCount: imageFiles.length
2212
+ });
2213
+ if (isSinglePdfScenario && pdfFiles[0]) {
2214
+ const sourceFile = pdfFiles[0];
2215
+ const sourcePdf = loadedPdfs.get(sourceFile.id);
2216
+ console.log("[PageAssembler] Single PDF check:", {
2217
+ sourcePdfLoaded: !!sourcePdf,
2218
+ pagesCount: sourceFile.pages.length,
2219
+ originalBytesLength: sourceFile.originalBytes?.length
2220
+ });
2221
+ if (sourcePdf) {
2222
+ const desiredPageIndices = sourceFile.pages.map((p) => p.srcIndex);
2223
+ const originalPageCount = sourcePdf.getPageCount();
2224
+ const allPagesFromSameFile = sourceFile.pages.every(
2225
+ (p) => (p.originalFileId || sourceFile.id) === sourceFile.id
2226
+ );
2227
+ const isOriginalOrder = desiredPageIndices.length === originalPageCount && desiredPageIndices.every((idx, i) => idx === i);
2228
+ console.log("[PageAssembler] Original bytes check:", {
2229
+ allPagesFromSameFile,
2230
+ isOriginalOrder,
2231
+ desiredPageIndices,
2232
+ originalPageCount
2233
+ });
2234
+ if (allPagesFromSameFile && isOriginalOrder) {
2235
+ console.log("[PageAssembler] \u2705 Returning ORIGINAL bytes (form fields preserved)");
2236
+ const arrayBuffer2 = sourceFile.originalBytes.buffer.slice(
2237
+ sourceFile.originalBytes.byteOffset,
2238
+ sourceFile.originalBytes.byteOffset + sourceFile.originalBytes.byteLength
2239
+ );
2240
+ const blob2 = new Blob([arrayBuffer2], { type: "application/pdf" });
2241
+ return blob2;
2242
+ } else {
2243
+ console.log("[PageAssembler] \u26A0\uFE0F Pages modified, will use copyPages (form fields may be lost)");
2244
+ }
2245
+ }
2246
+ }
2247
+ console.log("[PageAssembler] Starting multi-PDF assembly with field preservation");
2248
+ const allExtractedFields = [];
2249
+ const mergedMetadata = {
2250
+ version: "1.0",
2251
+ fields: {},
2252
+ fieldIdIndex: {}
2253
+ };
2254
+ const filePageUsage = /* @__PURE__ */ new Map();
2255
+ for (const file of state.files) {
2256
+ for (const page of file.pages) {
2257
+ const originalFileId = page.originalFileId || file.id;
2258
+ if (!filePageUsage.has(originalFileId)) {
2259
+ filePageUsage.set(originalFileId, /* @__PURE__ */ new Map());
2260
+ }
2261
+ const pageUsage = filePageUsage.get(originalFileId);
2262
+ if (!pageUsage.has(page.srcIndex)) {
2263
+ pageUsage.set(page.srcIndex, []);
2264
+ }
2265
+ pageUsage.get(page.srcIndex).push(page);
2266
+ }
2267
+ }
2268
+ let combinedPageIndex = 0;
2269
+ const pageIdToNewPageNumber = /* @__PURE__ */ new Map();
2270
+ for (const file of state.files) {
2271
+ for (const page of file.pages) {
2272
+ combinedPageIndex++;
2273
+ pageIdToNewPageNumber.set(page.id, combinedPageIndex);
2274
+ }
2275
+ }
2276
+ console.log("[PageAssembler] Page mapping:", Object.fromEntries(pageIdToNewPageNumber));
2277
+ const extractAndMapFields = async (fileId, fileName, pdfBytes2, sourcePdf) => {
2278
+ let sourceMetadata = null;
2279
+ if (sourcePdf) {
2280
+ try {
2281
+ const sourceInfoRef = sourcePdf.context.trailerInfo.Info;
2282
+ if (sourceInfoRef) {
2283
+ const sourceInfoDict = sourcePdf.context.lookup(sourceInfoRef);
2284
+ if (sourceInfoDict && typeof sourceInfoDict.get === "function") {
2285
+ const metadataObj = sourceInfoDict.get(PDFName3.of("SigniphiMetadata"));
2286
+ if (metadataObj) {
2287
+ const metadataStr = metadataObj.toString();
2288
+ let jsonStr = metadataStr;
2289
+ if (metadataStr.startsWith("(") && metadataStr.endsWith(")")) {
2290
+ jsonStr = metadataStr.slice(1, -1);
2291
+ }
2292
+ sourceMetadata = JSON.parse(jsonStr);
2293
+ }
2294
+ }
2295
+ }
2296
+ } catch (metadataError) {
2297
+ console.warn(`Could not read metadata from PDF ${fileName}:`, metadataError);
2298
+ }
2299
+ }
2300
+ console.log(`[PageAssembler] Extracting fields from "${fileName}"`);
2301
+ const extractedFields = await extractFieldsFromPdf(pdfBytes2);
2302
+ console.log(`[PageAssembler] Found ${extractedFields.length} fields in "${fileName}"`);
2303
+ const pageUsageForFile = filePageUsage.get(fileId) || /* @__PURE__ */ new Map();
2304
+ for (const field of extractedFields) {
2305
+ const originalPage = field.page;
2306
+ const srcIndex = originalPage - 1;
2307
+ const pageInstances = pageUsageForFile.get(srcIndex) || [];
2308
+ for (const pageInstance of pageInstances) {
2309
+ const newPageNumber = pageIdToNewPageNumber.get(pageInstance.id);
2310
+ if (newPageNumber !== void 0) {
2311
+ const trackedField = {
2312
+ name: field.name,
2313
+ type: field.type,
2314
+ position: {
2315
+ x: field.x,
2316
+ y: field.y,
2317
+ width: field.width,
2318
+ height: field.height,
2319
+ page: newPageNumber
2320
+ // Updated to new page number
2321
+ },
2322
+ pageId: pageInstance.id,
2323
+ originalFileId: fileId,
2324
+ label: field.label,
2325
+ required: field.required,
2326
+ options: field.options,
2327
+ placeholder: field.placeholder,
2328
+ fieldId: field.fieldId,
2329
+ assignedSignerEmail: field.signer
2330
+ };
2331
+ allExtractedFields.push(trackedField);
2332
+ console.log(`[PageAssembler] Mapped field "${field.name}" from page ${originalPage} to page ${newPageNumber}`);
2333
+ const metadataKey = `${field.name}_p${newPageNumber}`;
2334
+ if (sourceMetadata?.fields?.[field.name]) {
2335
+ mergedMetadata.fields[metadataKey] = sourceMetadata.fields[field.name];
2336
+ }
2337
+ if (sourceMetadata?.fieldIdIndex?.[field.name]) {
2338
+ mergedMetadata.fieldIdIndex[metadataKey] = sourceMetadata.fieldIdIndex[field.name];
2339
+ }
2340
+ }
2341
+ }
2342
+ }
2343
+ };
2344
+ const processedFileIds = /* @__PURE__ */ new Set();
2345
+ for (const file of state.files) {
2346
+ if (file.type !== "pdf" || !file.originalBytes || file.originalBytes.length === 0) continue;
2347
+ try {
2348
+ await extractAndMapFields(file.id, file.name, file.originalBytes, loadedPdfs.get(file.id));
2349
+ processedFileIds.add(file.id);
2350
+ } catch (extractError) {
2351
+ console.error(`Error extracting fields from ${file.name}:`, extractError);
2352
+ }
2353
+ }
2354
+ for (const fileId of referencedFileIds) {
2355
+ if (processedFileIds.has(fileId)) continue;
2356
+ const cachedBytes = originalBytesCache.current.get(fileId);
2357
+ if (cachedBytes && cachedBytes.length > 0) {
2358
+ try {
2359
+ console.log(`[PageAssembler] Extracting fields from cached file ${fileId}`);
2360
+ await extractAndMapFields(fileId, `Cached file ${fileId}`, cachedBytes, loadedPdfs.get(fileId));
2361
+ } catch (extractError) {
2362
+ console.error(`Error extracting fields from cached file ${fileId}:`, extractError);
2363
+ }
2364
+ }
2365
+ }
2366
+ console.log(`[PageAssembler] Total extracted fields: ${allExtractedFields.length}`);
2367
+ console.log(`[PageAssembler] Field names:`, allExtractedFields.map((f) => `${f.name} (page ${f.position.page})`));
2368
+ const combinedDoc = await PDFDocument4.create();
1607
2369
  for (const file of state.files) {
1608
2370
  if (file.pages.length === 0) continue;
1609
2371
  for (const page of file.pages) {
@@ -1623,7 +2385,17 @@ var PageAssembler = forwardRef(
1623
2385
  if (page.srcIndex >= 0 && page.srcIndex < sourcePageCount) {
1624
2386
  try {
1625
2387
  const copiedPages = await combinedDoc.copyPages(sourcePdf, [page.srcIndex]);
1626
- copiedPages.forEach((copiedPage) => combinedDoc.addPage(copiedPage));
2388
+ copiedPages.forEach((copiedPage) => {
2389
+ try {
2390
+ const annotsRef = copiedPage.node.get(PDFName3.of("Annots"));
2391
+ if (annotsRef) {
2392
+ copiedPage.node.delete(PDFName3.of("Annots"));
2393
+ }
2394
+ } catch (annotError) {
2395
+ console.warn("Could not remove annotations from copied page:", annotError);
2396
+ }
2397
+ combinedDoc.addPage(copiedPage);
2398
+ });
1627
2399
  } catch (copyError) {
1628
2400
  console.error(`Error copying page ${page.srcIndex}:`, copyError);
1629
2401
  throw new Error(`Failed to copy page: ${copyError instanceof Error ? copyError.message : String(copyError)}`);
@@ -1632,7 +2404,7 @@ var PageAssembler = forwardRef(
1632
2404
  } else if (sourceFile.type === "image" && sourceFile.originalFile) {
1633
2405
  try {
1634
2406
  const imagePdfBytes = await imageToPdf(sourceFile.originalFile);
1635
- const imagePdf = await PDFDocument2.load(imagePdfBytes);
2407
+ const imagePdf = await PDFDocument4.load(imagePdfBytes);
1636
2408
  const copiedPages = await combinedDoc.copyPages(imagePdf, [0]);
1637
2409
  copiedPages.forEach((copiedPage) => combinedDoc.addPage(copiedPage));
1638
2410
  } catch (imageError) {
@@ -1642,7 +2414,46 @@ var PageAssembler = forwardRef(
1642
2414
  }
1643
2415
  }
1644
2416
  }
1645
- const pdfBytes = await combinedDoc.save();
2417
+ if (Object.keys(mergedMetadata.fields).length > 0) {
2418
+ try {
2419
+ const newInfoRef = combinedDoc.context.trailerInfo.Info;
2420
+ if (newInfoRef) {
2421
+ const newInfoDict = combinedDoc.context.lookup(newInfoRef);
2422
+ if (newInfoDict && typeof newInfoDict.set === "function") {
2423
+ newInfoDict.set(
2424
+ PDFName3.of("SigniphiMetadata"),
2425
+ PDFString3.of(JSON.stringify(mergedMetadata))
2426
+ );
2427
+ }
2428
+ }
2429
+ } catch (metadataError) {
2430
+ console.warn("Could not write merged metadata:", metadataError);
2431
+ }
2432
+ }
2433
+ let pdfBytes = await combinedDoc.save();
2434
+ if (allExtractedFields.length > 0) {
2435
+ console.log(`[PageAssembler] Re-adding ${allExtractedFields.length} fields to combined document`);
2436
+ const fieldsForPdf = allExtractedFields.map((field) => ({
2437
+ name: field.name,
2438
+ type: field.type,
2439
+ position: field.position,
2440
+ label: field.label,
2441
+ required: field.required,
2442
+ options: field.options,
2443
+ placeholder: field.placeholder,
2444
+ assignedSignerEmail: field.assignedSignerEmail
2445
+ }));
2446
+ try {
2447
+ pdfBytes = await addFormFieldsToPdf(pdfBytes, fieldsForPdf, {
2448
+ removeExistingFields: true,
2449
+ // Remove any orphaned field references
2450
+ drawLabels: false
2451
+ });
2452
+ console.log("[PageAssembler] \u2705 Successfully re-added form fields to combined PDF");
2453
+ } catch (addFieldsError) {
2454
+ console.error("[PageAssembler] Error re-adding fields:", addFieldsError);
2455
+ }
2456
+ }
1646
2457
  const arrayBuffer = pdfBytes.buffer.slice(pdfBytes.byteOffset, pdfBytes.byteOffset + pdfBytes.byteLength);
1647
2458
  const blob = new Blob([arrayBuffer], { type: "application/pdf" });
1648
2459
  return blob;
@@ -1833,6 +2644,6 @@ function debounce(func, wait) {
1833
2644
  }
1834
2645
  var PageAssembler_default = PageAssembler;
1835
2646
 
1836
- export { Button, PageAssembler, createPdfBlobUrl, PageAssembler_default as default, downloadPdf, imageToPdf, pdfToImages };
2647
+ export { Button, FormFieldType, PageAssembler, addFormFieldsToPdf, createPdfBlobUrl, PageAssembler_default as default, downloadPdf, extractFieldsFromPdf, getSigniphiMetadata, imageToPdf, mapFieldPositionsAfterAssembly, pdfToImages, setSigniphiMetadata };
1837
2648
  //# sourceMappingURL=index.mjs.map
1838
2649
  //# sourceMappingURL=index.mjs.map