@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.js CHANGED
@@ -722,6 +722,580 @@ function downloadPdf(pdfBytes, filename) {
722
722
  a.click();
723
723
  URL.revokeObjectURL(url);
724
724
  }
725
+ function getSigniphiMetadata(pdfDoc) {
726
+ try {
727
+ const infoRef = pdfDoc.context.trailerInfo.Info;
728
+ if (!infoRef) {
729
+ return null;
730
+ }
731
+ const infoObj = pdfDoc.context.lookup(infoRef);
732
+ if (!infoObj || typeof infoObj.get !== "function") {
733
+ return null;
734
+ }
735
+ const infoDict = infoObj;
736
+ const metadataObj = infoDict.get(pdfLib.PDFName.of("SigniphiMetadata"));
737
+ if (!metadataObj) {
738
+ return null;
739
+ }
740
+ const metadataStr = metadataObj.toString();
741
+ let jsonStr = metadataStr;
742
+ if (metadataStr.startsWith("(") && metadataStr.endsWith(")")) {
743
+ jsonStr = metadataStr.slice(1, -1);
744
+ } else if (metadataStr.startsWith("<") && metadataStr.endsWith(">")) {
745
+ jsonStr = metadataStr.slice(1, -1);
746
+ }
747
+ const metadata = JSON.parse(jsonStr);
748
+ return metadata;
749
+ } catch (error) {
750
+ console.error("Failed to load Signiphi metadata:", error);
751
+ return null;
752
+ }
753
+ }
754
+ function getBaseFieldName(encodedName) {
755
+ let baseName = encodedName;
756
+ if (baseName.includes("__SIGNER__")) {
757
+ baseName = baseName.split("__SIGNER__")[0];
758
+ }
759
+ if (baseName.includes("__LABEL__")) {
760
+ baseName = baseName.split("__LABEL__")[0];
761
+ }
762
+ if (baseName.includes("__PLACEHOLDER__")) {
763
+ baseName = baseName.split("__PLACEHOLDER__")[0];
764
+ }
765
+ return baseName;
766
+ }
767
+ function getSignerFromFieldName(encodedName) {
768
+ if (encodedName.includes("__SIGNER__")) {
769
+ const parts = encodedName.split("__SIGNER__");
770
+ if (parts[1]) {
771
+ return parts[1].split("__")[0] || parts[1];
772
+ }
773
+ }
774
+ return void 0;
775
+ }
776
+ function determineFieldType(fieldName, widgetType) {
777
+ const baseName = getBaseFieldName(fieldName);
778
+ const nameLower = baseName.toLowerCase();
779
+ if (nameLower.includes("_signature") || nameLower.includes("signature")) {
780
+ return "signature";
781
+ }
782
+ if (nameLower.includes("_initials") || nameLower.includes("initials")) {
783
+ return "initials";
784
+ }
785
+ if (nameLower.includes("_date") || nameLower.includes("date")) {
786
+ return "date";
787
+ }
788
+ if (widgetType === "checkbox" || nameLower.includes("checkbox")) {
789
+ return "checkbox";
790
+ }
791
+ if (widgetType === "radio" || nameLower.includes("radio")) {
792
+ return "radio";
793
+ }
794
+ if (widgetType === "dropdown" || widgetType === "select" || nameLower.includes("dropdown")) {
795
+ return "dropdown";
796
+ }
797
+ return "text";
798
+ }
799
+ async function extractFieldsFromPdf(pdfBytes) {
800
+ const pdfDoc = await pdfLib.PDFDocument.load(pdfBytes);
801
+ const fields = [];
802
+ const metadata = getSigniphiMetadata(pdfDoc);
803
+ const form = pdfDoc.getForm();
804
+ const pdfFields = form.getFields();
805
+ for (const field of pdfFields) {
806
+ const fieldName = field.getName();
807
+ const widgets = field.acroField.getWidgets();
808
+ const baseName = getBaseFieldName(fieldName);
809
+ const signerFromName = getSignerFromFieldName(fieldName);
810
+ let required = false;
811
+ let options;
812
+ let widgetType;
813
+ if (field instanceof pdfLib.PDFTextField) {
814
+ required = field.isRequired();
815
+ console.log(`[field-extraction] PDFTextField "${fieldName}" isRequired=${required}`);
816
+ } else if (field instanceof pdfLib.PDFCheckBox) {
817
+ widgetType = "checkbox";
818
+ required = field.isRequired();
819
+ console.log(`[field-extraction] PDFCheckBox "${fieldName}" isRequired=${required}`);
820
+ } else if (field instanceof pdfLib.PDFDropdown) {
821
+ widgetType = "dropdown";
822
+ required = field.isRequired();
823
+ options = field.getOptions();
824
+ console.log(`[field-extraction] PDFDropdown "${fieldName}" isRequired=${required}`);
825
+ } else if (field instanceof pdfLib.PDFRadioGroup) {
826
+ widgetType = "radio";
827
+ required = field.isRequired();
828
+ options = field.getOptions();
829
+ console.log(`[field-extraction] PDFRadioGroup "${fieldName}" isRequired=${required}`);
830
+ } else {
831
+ console.log(`[field-extraction] Unknown field type "${fieldName}" - defaulting required=false`);
832
+ }
833
+ for (const widget of widgets) {
834
+ const rect = widget.getRectangle();
835
+ const pageRef = widget.P();
836
+ let pageNumber = 1;
837
+ if (pageRef) {
838
+ const pages = pdfDoc.getPages();
839
+ for (let i = 0; i < pages.length; i++) {
840
+ if (pages[i].ref === pageRef) {
841
+ pageNumber = i + 1;
842
+ break;
843
+ }
844
+ }
845
+ }
846
+ const pageQualifiedKey = `${baseName}_p${pageNumber}`;
847
+ let fieldMetadata = metadata?.fields?.[pageQualifiedKey];
848
+ if (!fieldMetadata) {
849
+ fieldMetadata = metadata?.fields?.[fieldName];
850
+ }
851
+ if (!fieldMetadata && baseName !== fieldName) {
852
+ fieldMetadata = metadata?.fields?.[baseName];
853
+ }
854
+ let fieldRequired = required;
855
+ let fieldOptions = options;
856
+ if (fieldMetadata?.required !== void 0) {
857
+ fieldRequired = fieldMetadata.required;
858
+ }
859
+ if (fieldMetadata?.options?.length) {
860
+ fieldOptions = fieldMetadata.options;
861
+ }
862
+ const page = pdfDoc.getPage(pageNumber - 1);
863
+ const pageHeight = page.getHeight();
864
+ const extractedField = {
865
+ name: baseName,
866
+ // Use clean base name without __SIGNER__ encoding (signer stored in signer property)
867
+ type: determineFieldType(fieldName, widgetType),
868
+ // Uses base name internally
869
+ page: pageNumber,
870
+ x: rect.x,
871
+ y: pageHeight - rect.y - rect.height,
872
+ // Convert from PDF coords (bottom-left) to top-left
873
+ width: rect.width,
874
+ height: rect.height,
875
+ required: fieldRequired,
876
+ options: fieldOptions,
877
+ signer: signerFromName
878
+ // Extract signer from encoded name
879
+ };
880
+ if (fieldMetadata) {
881
+ if (fieldMetadata.fieldId) {
882
+ extractedField.fieldId = fieldMetadata.fieldId;
883
+ }
884
+ if (fieldMetadata.label) {
885
+ extractedField.label = fieldMetadata.label;
886
+ }
887
+ if (!extractedField.signer && fieldMetadata.signer) {
888
+ extractedField.signer = fieldMetadata.signer;
889
+ }
890
+ if (fieldMetadata.placeholder) {
891
+ extractedField.placeholder = fieldMetadata.placeholder;
892
+ }
893
+ }
894
+ fields.push(extractedField);
895
+ }
896
+ }
897
+ const deduplicatedFields = fields.reduce((acc, field) => {
898
+ const newBaseName = getBaseFieldName(field.name);
899
+ const existingIndex = acc.findIndex((f) => {
900
+ const existingBaseName = getBaseFieldName(f.name);
901
+ return existingBaseName === newBaseName && f.page === field.page;
902
+ });
903
+ if (existingIndex === -1) {
904
+ acc.push(field);
905
+ } else {
906
+ const existing = acc[existingIndex];
907
+ acc[existingIndex] = {
908
+ ...existing,
909
+ // Prefer non-empty values from either field
910
+ label: existing.label || field.label,
911
+ placeholder: existing.placeholder || field.placeholder,
912
+ required: existing.required || field.required,
913
+ options: existing.options?.length ? existing.options : field.options,
914
+ fieldId: existing.fieldId || field.fieldId,
915
+ // Prefer signer from the field that has it
916
+ signer: existing.signer || field.signer
917
+ };
918
+ }
919
+ return acc;
920
+ }, []);
921
+ return deduplicatedFields;
922
+ }
923
+ function setSigniphiMetadata(pdfDoc, metadata) {
924
+ try {
925
+ const infoRef = pdfDoc.context.trailerInfo.Info;
926
+ const infoObj = pdfDoc.context.lookup(infoRef);
927
+ if (!infoObj || typeof infoObj.set !== "function") {
928
+ throw new Error("Info object is not a PDFDict or does not have set method");
929
+ }
930
+ const infoDict = infoObj;
931
+ const metadataString = JSON.stringify(metadata);
932
+ infoDict.set(pdfLib.PDFName.of("SigniphiMetadata"), pdfLib.PDFString.of(metadataString));
933
+ } catch (error) {
934
+ console.error("Failed to set Signiphi metadata:", error);
935
+ throw error;
936
+ }
937
+ }
938
+ var FormFieldType = /* @__PURE__ */ ((FormFieldType2) => {
939
+ FormFieldType2["TEXT"] = "text";
940
+ FormFieldType2["SIGNATURE"] = "signature";
941
+ FormFieldType2["INITIALS"] = "initials";
942
+ FormFieldType2["DATE"] = "date";
943
+ FormFieldType2["CHECKBOX"] = "checkbox";
944
+ FormFieldType2["RADIO"] = "radio";
945
+ FormFieldType2["DROPDOWN"] = "dropdown";
946
+ FormFieldType2["TEXT_LABEL"] = "text_label";
947
+ return FormFieldType2;
948
+ })(FormFieldType || {});
949
+ function parseEncodedFieldName(encodedName) {
950
+ let baseName = encodedName;
951
+ let label;
952
+ let signer;
953
+ if (baseName.includes("__SIGNER__")) {
954
+ const parts = baseName.split("__SIGNER__");
955
+ baseName = parts[0];
956
+ signer = parts[1];
957
+ }
958
+ if (baseName.includes("__LABEL__")) {
959
+ const parts = baseName.split("__LABEL__");
960
+ baseName = parts[0];
961
+ label = parts[1];
962
+ }
963
+ if (baseName.includes("__PLACEHOLDER__")) {
964
+ const parts = baseName.split("__PLACEHOLDER__");
965
+ baseName = parts[0];
966
+ }
967
+ return { baseName, label, signer };
968
+ }
969
+ function encodeFieldNameWithSigner(fieldName, signerEmail) {
970
+ const { baseName, signer: existingSigner } = parseEncodedFieldName(fieldName);
971
+ const finalSigner = existingSigner || signerEmail;
972
+ if (!finalSigner) return baseName;
973
+ return `${baseName}__SIGNER__${finalSigner}`;
974
+ }
975
+ function encodeFieldNameWithLabelAndSigner(fieldName, label, signerEmail) {
976
+ const { baseName, label: existingLabel, signer: existingSigner } = parseEncodedFieldName(fieldName);
977
+ const finalLabel = existingLabel || label;
978
+ const finalSigner = existingSigner || signerEmail;
979
+ let name = baseName;
980
+ if (finalLabel && finalLabel.trim()) {
981
+ name = `${name}__LABEL__${finalLabel.trim()}`;
982
+ }
983
+ if (finalSigner) {
984
+ name = `${name}__SIGNER__${finalSigner}`;
985
+ }
986
+ return name;
987
+ }
988
+ async function addFormFieldsToPdf(pdfBytes, formFields, options = {}) {
989
+ const { removeExistingFields = false, drawLabels = false } = options;
990
+ const pdfDoc = await pdfLib.PDFDocument.load(pdfBytes);
991
+ const form = pdfDoc.getForm();
992
+ const pages = pdfDoc.getPages();
993
+ if (removeExistingFields) {
994
+ const existingFields = form.getFields();
995
+ for (const field of existingFields) {
996
+ try {
997
+ const acroField = field.acroField;
998
+ if (acroField && typeof acroField.getWidgets === "function") {
999
+ let widgets = acroField.getWidgets();
1000
+ let safetyCounter = 0;
1001
+ const maxIterations = widgets.length + 5;
1002
+ while (widgets.length > 0 && safetyCounter < maxIterations) {
1003
+ try {
1004
+ acroField.removeWidget(widgets.length - 1);
1005
+ widgets = acroField.getWidgets();
1006
+ } catch {
1007
+ break;
1008
+ }
1009
+ safetyCounter++;
1010
+ }
1011
+ }
1012
+ form.removeField(field);
1013
+ } catch (error) {
1014
+ console.warn(`Failed to remove field ${field.getName()}:`, error);
1015
+ try {
1016
+ form.removeField(field);
1017
+ } catch {
1018
+ }
1019
+ }
1020
+ }
1021
+ }
1022
+ const font = await pdfDoc.embedFont(pdfLib.StandardFonts.Helvetica);
1023
+ const fieldNamePages = /* @__PURE__ */ new Map();
1024
+ for (const field of formFields) {
1025
+ const baseName = field.name;
1026
+ if (!fieldNamePages.has(baseName)) {
1027
+ fieldNamePages.set(baseName, /* @__PURE__ */ new Set());
1028
+ }
1029
+ fieldNamePages.get(baseName).add(field.position.page);
1030
+ }
1031
+ const conflictingNames = /* @__PURE__ */ new Set();
1032
+ for (const [name, pages2] of fieldNamePages) {
1033
+ if (pages2.size > 1) {
1034
+ conflictingNames.add(name);
1035
+ }
1036
+ }
1037
+ for (const field of formFields) {
1038
+ const pageIndex = field.position.page - 1;
1039
+ if (pageIndex < 0 || pageIndex >= pages.length) {
1040
+ console.warn(`Field ${field.name} references page ${field.position.page} but PDF only has ${pages.length} pages`);
1041
+ continue;
1042
+ }
1043
+ const page = pages[pageIndex];
1044
+ const { height: pageHeight } = page.getSize();
1045
+ const pdfX = field.position.x;
1046
+ const pdfY = pageHeight - field.position.y - field.position.height;
1047
+ const uniqueFieldName = conflictingNames.has(field.name) ? `${field.name}_p${field.position.page}` : field.name;
1048
+ try {
1049
+ const fieldType = typeof field.type === "string" ? field.type : field.type;
1050
+ switch (fieldType) {
1051
+ case "text" /* TEXT */:
1052
+ case "text": {
1053
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1054
+ const textField = form.createTextField(encodedName);
1055
+ textField.addToPage(page, {
1056
+ x: pdfX,
1057
+ y: pdfY,
1058
+ width: field.position.width,
1059
+ height: field.position.height,
1060
+ borderColor: pdfLib.rgb(0.5, 0.5, 0.5),
1061
+ backgroundColor: pdfLib.rgb(1, 1, 1)
1062
+ });
1063
+ if (field.label && field.label.trim()) {
1064
+ textField.acroField.dict.set(pdfLib.PDFName.of("TU"), pdfLib.PDFString.of(field.label));
1065
+ if (drawLabels) {
1066
+ const fontSize = Math.min(10, field.position.height * 0.4);
1067
+ const labelY = pdfY + field.position.height + 5;
1068
+ page.drawText(field.label, { x: pdfX, y: labelY, size: fontSize, font, color: pdfLib.rgb(0, 0, 0) });
1069
+ }
1070
+ }
1071
+ if (field.defaultValue && field.defaultValue.trim()) {
1072
+ textField.setText(field.defaultValue);
1073
+ }
1074
+ if (field.fontSize && field.fontSize >= 8 && field.fontSize <= 72) {
1075
+ try {
1076
+ textField.setFontSize(field.fontSize);
1077
+ } catch {
1078
+ }
1079
+ }
1080
+ if (field.multiline) {
1081
+ try {
1082
+ textField.enableMultiline();
1083
+ } catch {
1084
+ }
1085
+ }
1086
+ if (field.maxLength && field.maxLength > 0) {
1087
+ try {
1088
+ textField.setMaxLength(field.maxLength);
1089
+ } catch {
1090
+ }
1091
+ }
1092
+ if (field.required) {
1093
+ textField.enableRequired();
1094
+ }
1095
+ break;
1096
+ }
1097
+ case "checkbox" /* CHECKBOX */:
1098
+ case "checkbox": {
1099
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1100
+ const checkBox = form.createCheckBox(encodedName);
1101
+ checkBox.addToPage(page, {
1102
+ x: pdfX,
1103
+ y: pdfY,
1104
+ width: field.position.width,
1105
+ height: field.position.height,
1106
+ borderColor: pdfLib.rgb(0.5, 0.5, 0.5),
1107
+ backgroundColor: pdfLib.rgb(1, 1, 1)
1108
+ });
1109
+ if (field.defaultValue === "true" || field.defaultValue === "checked") {
1110
+ checkBox.check();
1111
+ }
1112
+ if (field.required) {
1113
+ checkBox.enableRequired();
1114
+ }
1115
+ if (field.label && field.label.trim()) {
1116
+ try {
1117
+ checkBox.acroField.dict.set(pdfLib.PDFName.of("TU"), pdfLib.PDFString.of(field.label));
1118
+ } catch {
1119
+ }
1120
+ if (drawLabels) {
1121
+ const fontSize = Math.min(12, field.position.height * 0.6);
1122
+ const labelX = pdfX + field.position.width + 5;
1123
+ const labelY = pdfY + (field.position.height - fontSize) / 2;
1124
+ page.drawText(field.label, { x: labelX, y: labelY, size: fontSize, font, color: pdfLib.rgb(0, 0, 0) });
1125
+ }
1126
+ }
1127
+ break;
1128
+ }
1129
+ case "signature" /* SIGNATURE */:
1130
+ case "signature": {
1131
+ const baseWithSuffix = field.name.endsWith("_signature") ? field.name : `${field.name}_signature`;
1132
+ const finalName = conflictingNames.has(field.name) ? `${baseWithSuffix}_p${field.position.page}` : baseWithSuffix;
1133
+ const encodedName = encodeFieldNameWithLabelAndSigner(finalName, field.label, field.assignedSignerEmail);
1134
+ const sigField = form.createTextField(encodedName);
1135
+ sigField.addToPage(page, {
1136
+ x: pdfX,
1137
+ y: pdfY,
1138
+ width: field.position.width,
1139
+ height: field.position.height,
1140
+ borderColor: pdfLib.rgb(0, 0, 1),
1141
+ backgroundColor: pdfLib.rgb(0.9, 0.9, 1)
1142
+ });
1143
+ if (field.label && field.label.trim()) {
1144
+ sigField.acroField.dict.set(pdfLib.PDFName.of("TU"), pdfLib.PDFString.of(field.label));
1145
+ }
1146
+ sigField.enableReadOnly();
1147
+ if (field.required) {
1148
+ sigField.enableRequired();
1149
+ }
1150
+ break;
1151
+ }
1152
+ case "initials" /* INITIALS */:
1153
+ case "initials": {
1154
+ const baseWithSuffix = field.name.endsWith("_initials") ? field.name : `${field.name}_initials`;
1155
+ const finalName = conflictingNames.has(field.name) ? `${baseWithSuffix}_p${field.position.page}` : baseWithSuffix;
1156
+ const encodedName = encodeFieldNameWithLabelAndSigner(finalName, field.label, field.assignedSignerEmail);
1157
+ const initField = form.createTextField(encodedName);
1158
+ initField.addToPage(page, {
1159
+ x: pdfX,
1160
+ y: pdfY,
1161
+ width: field.position.width,
1162
+ height: field.position.height,
1163
+ borderColor: pdfLib.rgb(0.5, 0, 0.5),
1164
+ backgroundColor: pdfLib.rgb(1, 0.95, 1)
1165
+ });
1166
+ if (field.label && field.label.trim()) {
1167
+ initField.acroField.dict.set(pdfLib.PDFName.of("TU"), pdfLib.PDFString.of(field.label));
1168
+ }
1169
+ initField.enableReadOnly();
1170
+ if (field.required) {
1171
+ initField.enableRequired();
1172
+ }
1173
+ break;
1174
+ }
1175
+ case "date" /* DATE */:
1176
+ case "date": {
1177
+ const baseWithSuffix = field.name.endsWith("_date") ? field.name : `${field.name}_date`;
1178
+ const finalName = conflictingNames.has(field.name) ? `${baseWithSuffix}_p${field.position.page}` : baseWithSuffix;
1179
+ const encodedName = encodeFieldNameWithLabelAndSigner(finalName, field.label, field.assignedSignerEmail);
1180
+ const dateField = form.createTextField(encodedName);
1181
+ dateField.addToPage(page, {
1182
+ x: pdfX,
1183
+ y: pdfY,
1184
+ width: field.position.width,
1185
+ height: field.position.height,
1186
+ borderColor: pdfLib.rgb(0, 0.5, 0),
1187
+ backgroundColor: pdfLib.rgb(0.95, 1, 0.95)
1188
+ });
1189
+ if (field.label && field.label.trim()) {
1190
+ dateField.acroField.dict.set(pdfLib.PDFName.of("TU"), pdfLib.PDFString.of(field.label));
1191
+ }
1192
+ if (field.required) {
1193
+ dateField.enableRequired();
1194
+ }
1195
+ break;
1196
+ }
1197
+ case "dropdown" /* DROPDOWN */:
1198
+ case "dropdown": {
1199
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1200
+ const dropdown = form.createDropdown(encodedName);
1201
+ dropdown.addToPage(page, {
1202
+ x: pdfX,
1203
+ y: pdfY,
1204
+ width: field.position.width,
1205
+ height: field.position.height,
1206
+ borderColor: pdfLib.rgb(0.5, 0.5, 0.5),
1207
+ backgroundColor: pdfLib.rgb(1, 1, 1)
1208
+ });
1209
+ if (field.options && field.options.length > 0) {
1210
+ dropdown.addOptions(field.options);
1211
+ if (field.defaultValue && field.options.includes(field.defaultValue)) {
1212
+ dropdown.select(field.defaultValue);
1213
+ }
1214
+ }
1215
+ if (field.label && field.label.trim()) {
1216
+ try {
1217
+ dropdown.acroField.dict.set(pdfLib.PDFName.of("TU"), pdfLib.PDFString.of(field.label));
1218
+ } catch {
1219
+ }
1220
+ if (drawLabels) {
1221
+ const fontSize = Math.min(10, field.position.height * 0.4);
1222
+ const labelY = pdfY + field.position.height + 5;
1223
+ page.drawText(field.label, { x: pdfX, y: labelY, size: fontSize, font, color: pdfLib.rgb(0, 0, 0) });
1224
+ }
1225
+ }
1226
+ if (field.required) {
1227
+ dropdown.enableRequired();
1228
+ }
1229
+ break;
1230
+ }
1231
+ case "radio" /* RADIO */:
1232
+ case "radio": {
1233
+ const encodedName = encodeFieldNameWithSigner(uniqueFieldName, field.assignedSignerEmail);
1234
+ const radioGroup = form.createRadioGroup(encodedName);
1235
+ if (field.options && field.options.length > 0) {
1236
+ const optionHeight = Math.min(20, field.position.height / field.options.length);
1237
+ const spacing = field.position.height / field.options.length;
1238
+ field.options.forEach((option, index) => {
1239
+ const optionY = pdfY + field.position.height - (index + 1) * spacing + (spacing - optionHeight) / 2;
1240
+ radioGroup.addOptionToPage(option, page, {
1241
+ x: pdfX,
1242
+ y: optionY,
1243
+ width: optionHeight,
1244
+ height: optionHeight,
1245
+ borderColor: pdfLib.rgb(0.5, 0.5, 0.5),
1246
+ backgroundColor: pdfLib.rgb(1, 1, 1)
1247
+ });
1248
+ if (drawLabels) {
1249
+ const labelX = pdfX + optionHeight + 5;
1250
+ const labelY = optionY + optionHeight / 4;
1251
+ page.drawText(option, { x: labelX, y: labelY, size: 10, font, color: pdfLib.rgb(0, 0, 0) });
1252
+ }
1253
+ });
1254
+ if (field.defaultValue && field.options.includes(field.defaultValue)) {
1255
+ radioGroup.select(field.defaultValue);
1256
+ }
1257
+ }
1258
+ if (field.label && field.label.trim()) {
1259
+ try {
1260
+ radioGroup.acroField.dict.set(pdfLib.PDFName.of("TU"), pdfLib.PDFString.of(field.label));
1261
+ } catch {
1262
+ }
1263
+ if (drawLabels) {
1264
+ const fontSize = 10;
1265
+ const labelY = pdfY + field.position.height + 5;
1266
+ page.drawText(field.label, { x: pdfX, y: labelY, size: fontSize, font, color: pdfLib.rgb(0, 0, 0) });
1267
+ }
1268
+ }
1269
+ if (field.required) {
1270
+ radioGroup.enableRequired();
1271
+ }
1272
+ break;
1273
+ }
1274
+ default:
1275
+ console.warn(`Unknown field type: ${fieldType} for field ${field.name}`);
1276
+ }
1277
+ } catch (error) {
1278
+ console.error(`Error adding field ${field.name}:`, error);
1279
+ }
1280
+ }
1281
+ return await pdfDoc.save();
1282
+ }
1283
+ function mapFieldPositionsAfterAssembly(fields, pageMapping) {
1284
+ return fields.map((field) => {
1285
+ const mappingKey = String(field.position.page - 1);
1286
+ const newPageNumber = pageMapping.get(mappingKey);
1287
+ if (newPageNumber !== void 0) {
1288
+ return {
1289
+ ...field,
1290
+ position: { ...field.position, page: newPageNumber }
1291
+ };
1292
+ }
1293
+ return field;
1294
+ }).filter((field) => {
1295
+ const mappingKey = String(field.position.page - 1);
1296
+ return pageMapping.has(mappingKey) || pageMapping.size === 0;
1297
+ });
1298
+ }
725
1299
  var isMultiSelectModifier = (event) => {
726
1300
  return event.ctrlKey || event.metaKey;
727
1301
  };
@@ -1354,6 +1928,7 @@ var PageAssembler = React7.forwardRef(
1354
1928
  const processedInitialPdfRef = React7.useRef(null);
1355
1929
  const isDraggingPage = React7.useRef(false);
1356
1930
  const onChangeRef = React7.useRef(onChange);
1931
+ const originalBytesCache = React7.useRef(/* @__PURE__ */ new Map());
1357
1932
  const summary = React7.useMemo(() => ({
1358
1933
  totalFiles: state.files.length,
1359
1934
  totalPages: state.files.reduce((sum, file) => sum + file.pages.length, 0)
@@ -1423,6 +1998,7 @@ var PageAssembler = React7.forwardRef(
1423
1998
  originalFileId: fileId
1424
1999
  }))
1425
2000
  };
2001
+ originalBytesCache.current.set(fileId, originalBytes);
1426
2002
  dispatch({ type: "ADD_FILE", payload: file });
1427
2003
  } catch (error) {
1428
2004
  console.error("Error processing initial PDF:", error);
@@ -1475,6 +2051,7 @@ var PageAssembler = React7.forwardRef(
1475
2051
  const arrayBuffer = await file.arrayBuffer();
1476
2052
  const pdfBytes = new Uint8Array(arrayBuffer);
1477
2053
  fileInfo.originalBytes = new Uint8Array(pdfBytes);
2054
+ originalBytesCache.current.set(fileInfo.id, fileInfo.originalBytes);
1478
2055
  const defensiveCopy = new Uint8Array(pdfBytes);
1479
2056
  const pages = await pdfToImages(defensiveCopy, { hideFormFields: true });
1480
2057
  fileInfo.pages = pages.map((page, index) => ({
@@ -1491,6 +2068,7 @@ var PageAssembler = React7.forwardRef(
1491
2068
  const arrayBuffer = await file.arrayBuffer();
1492
2069
  const imageBytes = new Uint8Array(arrayBuffer);
1493
2070
  fileInfo.originalBytes = new Uint8Array(imageBytes);
2071
+ originalBytesCache.current.set(fileInfo.id, fileInfo.originalBytes);
1494
2072
  const thumbUrl = URL.createObjectURL(file);
1495
2073
  const img = new Image();
1496
2074
  const dimensions = await new Promise((resolve) => {
@@ -1618,21 +2196,205 @@ var PageAssembler = React7.forwardRef(
1618
2196
  setIsLoading(true);
1619
2197
  setProcessingStatus("Assembling PDF...");
1620
2198
  try {
1621
- const { PDFDocument: PDFDocument2 } = await import('pdf-lib');
1622
- const combinedDoc = await PDFDocument2.create();
2199
+ const { PDFDocument: PDFDocument4, PDFName: PDFName3, PDFString: PDFString3 } = await import('pdf-lib');
1623
2200
  const loadedPdfs = /* @__PURE__ */ new Map();
1624
2201
  const fileMap = /* @__PURE__ */ new Map();
2202
+ const pdfFiles = state.files.filter((f) => f.type === "pdf" && f.originalBytes?.length > 0);
2203
+ const imageFiles = state.files.filter((f) => f.type === "image");
2204
+ const isSinglePdfScenario = pdfFiles.length === 1 && imageFiles.length === 0;
1625
2205
  for (const file of state.files) {
1626
2206
  fileMap.set(file.id, file);
1627
2207
  if (file.type === "pdf" && file.originalBytes && file.originalBytes.length > 0) {
1628
2208
  try {
1629
- const sourcePdf = await PDFDocument2.load(file.originalBytes);
2209
+ const sourcePdf = await PDFDocument4.load(file.originalBytes);
1630
2210
  loadedPdfs.set(file.id, sourcePdf);
1631
2211
  } catch (error) {
1632
2212
  console.error(`Error loading PDF for file ${file.id}:`, error);
1633
2213
  }
1634
2214
  }
1635
2215
  }
2216
+ const referencedFileIds = /* @__PURE__ */ new Set();
2217
+ for (const file of state.files) {
2218
+ for (const page of file.pages) {
2219
+ const originalFileId = page.originalFileId || file.id;
2220
+ if (!loadedPdfs.has(originalFileId)) {
2221
+ referencedFileIds.add(originalFileId);
2222
+ }
2223
+ }
2224
+ }
2225
+ for (const fileId of referencedFileIds) {
2226
+ const cachedBytes = originalBytesCache.current.get(fileId);
2227
+ if (cachedBytes && cachedBytes.length > 0) {
2228
+ try {
2229
+ console.log(`[PageAssembler] Loading PDF from cache for deleted file ${fileId}`);
2230
+ const sourcePdf = await PDFDocument4.load(cachedBytes);
2231
+ loadedPdfs.set(fileId, sourcePdf);
2232
+ } catch (error) {
2233
+ console.error(`Error loading cached PDF for file ${fileId}:`, error);
2234
+ }
2235
+ }
2236
+ }
2237
+ console.log("[PageAssembler] Checking single PDF scenario:", {
2238
+ isSinglePdfScenario,
2239
+ pdfFilesCount: pdfFiles.length,
2240
+ imageFilesCount: imageFiles.length
2241
+ });
2242
+ if (isSinglePdfScenario && pdfFiles[0]) {
2243
+ const sourceFile = pdfFiles[0];
2244
+ const sourcePdf = loadedPdfs.get(sourceFile.id);
2245
+ console.log("[PageAssembler] Single PDF check:", {
2246
+ sourcePdfLoaded: !!sourcePdf,
2247
+ pagesCount: sourceFile.pages.length,
2248
+ originalBytesLength: sourceFile.originalBytes?.length
2249
+ });
2250
+ if (sourcePdf) {
2251
+ const desiredPageIndices = sourceFile.pages.map((p) => p.srcIndex);
2252
+ const originalPageCount = sourcePdf.getPageCount();
2253
+ const allPagesFromSameFile = sourceFile.pages.every(
2254
+ (p) => (p.originalFileId || sourceFile.id) === sourceFile.id
2255
+ );
2256
+ const isOriginalOrder = desiredPageIndices.length === originalPageCount && desiredPageIndices.every((idx, i) => idx === i);
2257
+ console.log("[PageAssembler] Original bytes check:", {
2258
+ allPagesFromSameFile,
2259
+ isOriginalOrder,
2260
+ desiredPageIndices,
2261
+ originalPageCount
2262
+ });
2263
+ if (allPagesFromSameFile && isOriginalOrder) {
2264
+ console.log("[PageAssembler] \u2705 Returning ORIGINAL bytes (form fields preserved)");
2265
+ const arrayBuffer2 = sourceFile.originalBytes.buffer.slice(
2266
+ sourceFile.originalBytes.byteOffset,
2267
+ sourceFile.originalBytes.byteOffset + sourceFile.originalBytes.byteLength
2268
+ );
2269
+ const blob2 = new Blob([arrayBuffer2], { type: "application/pdf" });
2270
+ return blob2;
2271
+ } else {
2272
+ console.log("[PageAssembler] \u26A0\uFE0F Pages modified, will use copyPages (form fields may be lost)");
2273
+ }
2274
+ }
2275
+ }
2276
+ console.log("[PageAssembler] Starting multi-PDF assembly with field preservation");
2277
+ const allExtractedFields = [];
2278
+ const mergedMetadata = {
2279
+ version: "1.0",
2280
+ fields: {},
2281
+ fieldIdIndex: {}
2282
+ };
2283
+ const filePageUsage = /* @__PURE__ */ new Map();
2284
+ for (const file of state.files) {
2285
+ for (const page of file.pages) {
2286
+ const originalFileId = page.originalFileId || file.id;
2287
+ if (!filePageUsage.has(originalFileId)) {
2288
+ filePageUsage.set(originalFileId, /* @__PURE__ */ new Map());
2289
+ }
2290
+ const pageUsage = filePageUsage.get(originalFileId);
2291
+ if (!pageUsage.has(page.srcIndex)) {
2292
+ pageUsage.set(page.srcIndex, []);
2293
+ }
2294
+ pageUsage.get(page.srcIndex).push(page);
2295
+ }
2296
+ }
2297
+ let combinedPageIndex = 0;
2298
+ const pageIdToNewPageNumber = /* @__PURE__ */ new Map();
2299
+ for (const file of state.files) {
2300
+ for (const page of file.pages) {
2301
+ combinedPageIndex++;
2302
+ pageIdToNewPageNumber.set(page.id, combinedPageIndex);
2303
+ }
2304
+ }
2305
+ console.log("[PageAssembler] Page mapping:", Object.fromEntries(pageIdToNewPageNumber));
2306
+ const extractAndMapFields = async (fileId, fileName, pdfBytes2, sourcePdf) => {
2307
+ let sourceMetadata = null;
2308
+ if (sourcePdf) {
2309
+ try {
2310
+ const sourceInfoRef = sourcePdf.context.trailerInfo.Info;
2311
+ if (sourceInfoRef) {
2312
+ const sourceInfoDict = sourcePdf.context.lookup(sourceInfoRef);
2313
+ if (sourceInfoDict && typeof sourceInfoDict.get === "function") {
2314
+ const metadataObj = sourceInfoDict.get(PDFName3.of("SigniphiMetadata"));
2315
+ if (metadataObj) {
2316
+ const metadataStr = metadataObj.toString();
2317
+ let jsonStr = metadataStr;
2318
+ if (metadataStr.startsWith("(") && metadataStr.endsWith(")")) {
2319
+ jsonStr = metadataStr.slice(1, -1);
2320
+ }
2321
+ sourceMetadata = JSON.parse(jsonStr);
2322
+ }
2323
+ }
2324
+ }
2325
+ } catch (metadataError) {
2326
+ console.warn(`Could not read metadata from PDF ${fileName}:`, metadataError);
2327
+ }
2328
+ }
2329
+ console.log(`[PageAssembler] Extracting fields from "${fileName}"`);
2330
+ const extractedFields = await extractFieldsFromPdf(pdfBytes2);
2331
+ console.log(`[PageAssembler] Found ${extractedFields.length} fields in "${fileName}"`);
2332
+ const pageUsageForFile = filePageUsage.get(fileId) || /* @__PURE__ */ new Map();
2333
+ for (const field of extractedFields) {
2334
+ const originalPage = field.page;
2335
+ const srcIndex = originalPage - 1;
2336
+ const pageInstances = pageUsageForFile.get(srcIndex) || [];
2337
+ for (const pageInstance of pageInstances) {
2338
+ const newPageNumber = pageIdToNewPageNumber.get(pageInstance.id);
2339
+ if (newPageNumber !== void 0) {
2340
+ const trackedField = {
2341
+ name: field.name,
2342
+ type: field.type,
2343
+ position: {
2344
+ x: field.x,
2345
+ y: field.y,
2346
+ width: field.width,
2347
+ height: field.height,
2348
+ page: newPageNumber
2349
+ // Updated to new page number
2350
+ },
2351
+ pageId: pageInstance.id,
2352
+ originalFileId: fileId,
2353
+ label: field.label,
2354
+ required: field.required,
2355
+ options: field.options,
2356
+ placeholder: field.placeholder,
2357
+ fieldId: field.fieldId,
2358
+ assignedSignerEmail: field.signer
2359
+ };
2360
+ allExtractedFields.push(trackedField);
2361
+ console.log(`[PageAssembler] Mapped field "${field.name}" from page ${originalPage} to page ${newPageNumber}`);
2362
+ const metadataKey = `${field.name}_p${newPageNumber}`;
2363
+ if (sourceMetadata?.fields?.[field.name]) {
2364
+ mergedMetadata.fields[metadataKey] = sourceMetadata.fields[field.name];
2365
+ }
2366
+ if (sourceMetadata?.fieldIdIndex?.[field.name]) {
2367
+ mergedMetadata.fieldIdIndex[metadataKey] = sourceMetadata.fieldIdIndex[field.name];
2368
+ }
2369
+ }
2370
+ }
2371
+ }
2372
+ };
2373
+ const processedFileIds = /* @__PURE__ */ new Set();
2374
+ for (const file of state.files) {
2375
+ if (file.type !== "pdf" || !file.originalBytes || file.originalBytes.length === 0) continue;
2376
+ try {
2377
+ await extractAndMapFields(file.id, file.name, file.originalBytes, loadedPdfs.get(file.id));
2378
+ processedFileIds.add(file.id);
2379
+ } catch (extractError) {
2380
+ console.error(`Error extracting fields from ${file.name}:`, extractError);
2381
+ }
2382
+ }
2383
+ for (const fileId of referencedFileIds) {
2384
+ if (processedFileIds.has(fileId)) continue;
2385
+ const cachedBytes = originalBytesCache.current.get(fileId);
2386
+ if (cachedBytes && cachedBytes.length > 0) {
2387
+ try {
2388
+ console.log(`[PageAssembler] Extracting fields from cached file ${fileId}`);
2389
+ await extractAndMapFields(fileId, `Cached file ${fileId}`, cachedBytes, loadedPdfs.get(fileId));
2390
+ } catch (extractError) {
2391
+ console.error(`Error extracting fields from cached file ${fileId}:`, extractError);
2392
+ }
2393
+ }
2394
+ }
2395
+ console.log(`[PageAssembler] Total extracted fields: ${allExtractedFields.length}`);
2396
+ console.log(`[PageAssembler] Field names:`, allExtractedFields.map((f) => `${f.name} (page ${f.position.page})`));
2397
+ const combinedDoc = await PDFDocument4.create();
1636
2398
  for (const file of state.files) {
1637
2399
  if (file.pages.length === 0) continue;
1638
2400
  for (const page of file.pages) {
@@ -1652,7 +2414,17 @@ var PageAssembler = React7.forwardRef(
1652
2414
  if (page.srcIndex >= 0 && page.srcIndex < sourcePageCount) {
1653
2415
  try {
1654
2416
  const copiedPages = await combinedDoc.copyPages(sourcePdf, [page.srcIndex]);
1655
- copiedPages.forEach((copiedPage) => combinedDoc.addPage(copiedPage));
2417
+ copiedPages.forEach((copiedPage) => {
2418
+ try {
2419
+ const annotsRef = copiedPage.node.get(PDFName3.of("Annots"));
2420
+ if (annotsRef) {
2421
+ copiedPage.node.delete(PDFName3.of("Annots"));
2422
+ }
2423
+ } catch (annotError) {
2424
+ console.warn("Could not remove annotations from copied page:", annotError);
2425
+ }
2426
+ combinedDoc.addPage(copiedPage);
2427
+ });
1656
2428
  } catch (copyError) {
1657
2429
  console.error(`Error copying page ${page.srcIndex}:`, copyError);
1658
2430
  throw new Error(`Failed to copy page: ${copyError instanceof Error ? copyError.message : String(copyError)}`);
@@ -1661,7 +2433,7 @@ var PageAssembler = React7.forwardRef(
1661
2433
  } else if (sourceFile.type === "image" && sourceFile.originalFile) {
1662
2434
  try {
1663
2435
  const imagePdfBytes = await imageToPdf(sourceFile.originalFile);
1664
- const imagePdf = await PDFDocument2.load(imagePdfBytes);
2436
+ const imagePdf = await PDFDocument4.load(imagePdfBytes);
1665
2437
  const copiedPages = await combinedDoc.copyPages(imagePdf, [0]);
1666
2438
  copiedPages.forEach((copiedPage) => combinedDoc.addPage(copiedPage));
1667
2439
  } catch (imageError) {
@@ -1671,7 +2443,46 @@ var PageAssembler = React7.forwardRef(
1671
2443
  }
1672
2444
  }
1673
2445
  }
1674
- const pdfBytes = await combinedDoc.save();
2446
+ if (Object.keys(mergedMetadata.fields).length > 0) {
2447
+ try {
2448
+ const newInfoRef = combinedDoc.context.trailerInfo.Info;
2449
+ if (newInfoRef) {
2450
+ const newInfoDict = combinedDoc.context.lookup(newInfoRef);
2451
+ if (newInfoDict && typeof newInfoDict.set === "function") {
2452
+ newInfoDict.set(
2453
+ PDFName3.of("SigniphiMetadata"),
2454
+ PDFString3.of(JSON.stringify(mergedMetadata))
2455
+ );
2456
+ }
2457
+ }
2458
+ } catch (metadataError) {
2459
+ console.warn("Could not write merged metadata:", metadataError);
2460
+ }
2461
+ }
2462
+ let pdfBytes = await combinedDoc.save();
2463
+ if (allExtractedFields.length > 0) {
2464
+ console.log(`[PageAssembler] Re-adding ${allExtractedFields.length} fields to combined document`);
2465
+ const fieldsForPdf = allExtractedFields.map((field) => ({
2466
+ name: field.name,
2467
+ type: field.type,
2468
+ position: field.position,
2469
+ label: field.label,
2470
+ required: field.required,
2471
+ options: field.options,
2472
+ placeholder: field.placeholder,
2473
+ assignedSignerEmail: field.assignedSignerEmail
2474
+ }));
2475
+ try {
2476
+ pdfBytes = await addFormFieldsToPdf(pdfBytes, fieldsForPdf, {
2477
+ removeExistingFields: true,
2478
+ // Remove any orphaned field references
2479
+ drawLabels: false
2480
+ });
2481
+ console.log("[PageAssembler] \u2705 Successfully re-added form fields to combined PDF");
2482
+ } catch (addFieldsError) {
2483
+ console.error("[PageAssembler] Error re-adding fields:", addFieldsError);
2484
+ }
2485
+ }
1675
2486
  const arrayBuffer = pdfBytes.buffer.slice(pdfBytes.byteOffset, pdfBytes.byteOffset + pdfBytes.byteLength);
1676
2487
  const blob = new Blob([arrayBuffer], { type: "application/pdf" });
1677
2488
  return blob;
@@ -1863,11 +2674,17 @@ function debounce(func, wait) {
1863
2674
  var PageAssembler_default = PageAssembler;
1864
2675
 
1865
2676
  exports.Button = Button;
2677
+ exports.FormFieldType = FormFieldType;
1866
2678
  exports.PageAssembler = PageAssembler;
2679
+ exports.addFormFieldsToPdf = addFormFieldsToPdf;
1867
2680
  exports.createPdfBlobUrl = createPdfBlobUrl;
1868
2681
  exports.default = PageAssembler_default;
1869
2682
  exports.downloadPdf = downloadPdf;
2683
+ exports.extractFieldsFromPdf = extractFieldsFromPdf;
2684
+ exports.getSigniphiMetadata = getSigniphiMetadata;
1870
2685
  exports.imageToPdf = imageToPdf;
2686
+ exports.mapFieldPositionsAfterAssembly = mapFieldPositionsAfterAssembly;
1871
2687
  exports.pdfToImages = pdfToImages;
2688
+ exports.setSigniphiMetadata = setSigniphiMetadata;
1872
2689
  //# sourceMappingURL=index.js.map
1873
2690
  //# sourceMappingURL=index.js.map