@strapi/core 5.23.5 → 5.24.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.
Files changed (46) hide show
  1. package/dist/Strapi.d.ts +1 -0
  2. package/dist/Strapi.d.ts.map +1 -1
  3. package/dist/Strapi.js +16 -0
  4. package/dist/Strapi.js.map +1 -1
  5. package/dist/Strapi.mjs +16 -0
  6. package/dist/Strapi.mjs.map +1 -1
  7. package/dist/constants.d.ts +3 -0
  8. package/dist/constants.d.ts.map +1 -0
  9. package/dist/constants.js +6 -0
  10. package/dist/constants.js.map +1 -0
  11. package/dist/constants.mjs +4 -0
  12. package/dist/constants.mjs.map +1 -0
  13. package/dist/package.json.js +12 -11
  14. package/dist/package.json.js.map +1 -1
  15. package/dist/package.json.mjs +12 -11
  16. package/dist/package.json.mjs.map +1 -1
  17. package/dist/providers/index.d.ts.map +1 -1
  18. package/dist/providers/index.js +2 -0
  19. package/dist/providers/index.js.map +1 -1
  20. package/dist/providers/index.mjs +2 -0
  21. package/dist/providers/index.mjs.map +1 -1
  22. package/dist/providers/sessionManager.d.ts +3 -0
  23. package/dist/providers/sessionManager.d.ts.map +1 -0
  24. package/dist/providers/sessionManager.js +21 -0
  25. package/dist/providers/sessionManager.js.map +1 -0
  26. package/dist/providers/sessionManager.mjs +19 -0
  27. package/dist/providers/sessionManager.mjs.map +1 -0
  28. package/dist/services/document-service/components.d.ts +26 -1
  29. package/dist/services/document-service/components.d.ts.map +1 -1
  30. package/dist/services/document-service/components.js +16 -4
  31. package/dist/services/document-service/components.js.map +1 -1
  32. package/dist/services/document-service/components.mjs +15 -5
  33. package/dist/services/document-service/components.mjs.map +1 -1
  34. package/dist/services/document-service/utils/clean-component-join-table.d.ts +7 -0
  35. package/dist/services/document-service/utils/clean-component-join-table.d.ts.map +1 -0
  36. package/dist/services/document-service/utils/clean-component-join-table.js +138 -0
  37. package/dist/services/document-service/utils/clean-component-join-table.js.map +1 -0
  38. package/dist/services/document-service/utils/clean-component-join-table.mjs +136 -0
  39. package/dist/services/document-service/utils/clean-component-join-table.mjs.map +1 -0
  40. package/dist/services/session-manager.d.ts +160 -0
  41. package/dist/services/session-manager.d.ts.map +1 -0
  42. package/dist/services/session-manager.js +476 -0
  43. package/dist/services/session-manager.js.map +1 -0
  44. package/dist/services/session-manager.mjs +473 -0
  45. package/dist/services/session-manager.mjs.map +1 -0
  46. package/package.json +12 -11
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ var components = require('../components.js');
4
+
5
+ /**
6
+ * Cleans ghost relations with publication state mismatches from a join table
7
+ * Uses schema-based draft/publish checking like prevention fix
8
+ */ const cleanComponentJoinTable = async (db, joinTableName, relation, sourceModel)=>{
9
+ try {
10
+ // Get the target model metadata
11
+ const targetModel = db.metadata.get(relation.target);
12
+ if (!targetModel) {
13
+ db.logger.debug(`Target model ${relation.target} not found, skipping ${joinTableName}`);
14
+ return 0;
15
+ }
16
+ // Check if target supports draft/publish using schema-based approach (like prevention fix)
17
+ const targetContentType = strapi.contentTypes[relation.target];
18
+ const targetSupportsDraftPublish = targetContentType?.options?.draftAndPublish || false;
19
+ if (!targetSupportsDraftPublish) {
20
+ return 0;
21
+ }
22
+ // Find entries with publication state mismatches
23
+ const ghostEntries = await findPublicationStateMismatches(db, joinTableName, relation, targetModel, sourceModel);
24
+ if (ghostEntries.length === 0) {
25
+ return 0;
26
+ }
27
+ // Remove ghost entries
28
+ await db.connection(joinTableName).whereIn('id', ghostEntries).del();
29
+ db.logger.debug(`Removed ${ghostEntries.length} ghost relations with publication state mismatches from ${joinTableName}`);
30
+ return ghostEntries.length;
31
+ } catch (error) {
32
+ const errorMessage = error instanceof Error ? error.message : String(error);
33
+ db.logger.error(`Failed to clean join table "${joinTableName}": ${errorMessage}`);
34
+ return 0;
35
+ }
36
+ };
37
+ const findContentTypeParentForComponentInstance = async (componentSchema, componentId)=>{
38
+ // Get the parent schemas that could contain this component
39
+ const parentSchemas = components.getParentSchemasForComponent(componentSchema);
40
+ if (parentSchemas.length === 0) {
41
+ // No potential parents
42
+ return null;
43
+ }
44
+ // Find the actual parent for THIS specific component instance
45
+ const parent = await components.findComponentParent(componentSchema, componentId, parentSchemas);
46
+ if (!parent) {
47
+ // No parent found for this component instance
48
+ return null;
49
+ }
50
+ if (strapi.components[parent.uid]) {
51
+ // If the parent is a component, we need to check its parents recursively
52
+ const parentComponentSchema = strapi.components[parent.uid];
53
+ return findContentTypeParentForComponentInstance(parentComponentSchema, parent.parentId);
54
+ }
55
+ if (strapi.contentTypes[parent.uid]) {
56
+ // Found a content type parent
57
+ return parent;
58
+ }
59
+ return null;
60
+ };
61
+ /**
62
+ * Finds join table entries with publication state mismatches
63
+ * Uses existing component parent detection from document service
64
+ */ const findPublicationStateMismatches = async (db, joinTableName, relation, targetModel, sourceModel)=>{
65
+ try {
66
+ // Get join column names using proper functions (addressing PR feedback)
67
+ const sourceColumn = relation.joinTable.joinColumn.name;
68
+ const targetColumn = relation.joinTable.inverseJoinColumn.name;
69
+ // Get all join entries with their target entities
70
+ const query = db.connection(joinTableName).select(`${joinTableName}.id as join_id`, `${joinTableName}.${sourceColumn} as source_id`, `${joinTableName}.${targetColumn} as target_id`, `${targetModel.tableName}.published_at as target_published_at`).leftJoin(targetModel.tableName, `${joinTableName}.${targetColumn}`, `${targetModel.tableName}.id`);
71
+ const joinEntries = await query;
72
+ // Group by source_id to find duplicates pointing to draft/published versions of same entity
73
+ const entriesBySource = {};
74
+ for (const entry of joinEntries){
75
+ const sourceId = entry.source_id;
76
+ if (!entriesBySource[sourceId]) {
77
+ entriesBySource[sourceId] = [];
78
+ }
79
+ entriesBySource[sourceId].push(entry);
80
+ }
81
+ const ghostEntries = [];
82
+ // Check if this is a join table (ends with _lnk)
83
+ const isRelationJoinTable = joinTableName.endsWith('_lnk');
84
+ const isComponentModel = !sourceModel.uid?.startsWith('api::') && !sourceModel.uid?.startsWith('plugin::') && sourceModel.uid?.includes('.');
85
+ // Check for draft/publish inconsistencies
86
+ for (const [sourceId, entries] of Object.entries(entriesBySource)){
87
+ // Skip entries with single relations
88
+ if (entries.length <= 1) {
89
+ continue;
90
+ }
91
+ // For component join tables, check if THIS specific component instance's parent supports D&P
92
+ if (isRelationJoinTable && isComponentModel) {
93
+ try {
94
+ const componentSchema = strapi.components[sourceModel.uid];
95
+ if (!componentSchema) {
96
+ continue;
97
+ }
98
+ const parent = await findContentTypeParentForComponentInstance(componentSchema, sourceId);
99
+ if (!parent) {
100
+ continue;
101
+ }
102
+ // Check if THIS component instance's parent supports draft/publish
103
+ const parentContentType = strapi.contentTypes[parent.uid];
104
+ if (!parentContentType?.options?.draftAndPublish) {
105
+ continue;
106
+ }
107
+ // If we reach here, this component instance's parent DOES support D&P
108
+ // Continue to process this component instance for ghost relations
109
+ } catch (error) {
110
+ continue;
111
+ }
112
+ }
113
+ // Find ghost relations (same logic as original but with improved parent checking)
114
+ for (const entry of entries){
115
+ if (entry.target_published_at === null) {
116
+ // This is a draft target - find its published version
117
+ const draftTarget = await db.connection(targetModel.tableName).select('document_id').where('id', entry.target_id).first();
118
+ if (draftTarget) {
119
+ const publishedVersion = await db.connection(targetModel.tableName).select('id', 'document_id').where('document_id', draftTarget.document_id).whereNotNull('published_at').first();
120
+ if (publishedVersion) {
121
+ // Check if we also have a relation to the published version
122
+ const publishedRelation = entries.find((e)=>e.target_id === publishedVersion.id);
123
+ if (publishedRelation) {
124
+ ghostEntries.push(publishedRelation.join_id);
125
+ }
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ return ghostEntries;
132
+ } catch (error) {
133
+ return [];
134
+ }
135
+ };
136
+
137
+ exports.cleanComponentJoinTable = cleanComponentJoinTable;
138
+ //# sourceMappingURL=clean-component-join-table.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clean-component-join-table.js","sources":["../../../../src/services/document-service/utils/clean-component-join-table.ts"],"sourcesContent":["import type { Database } from '@strapi/database';\nimport type { Schema } from '@strapi/types';\nimport { findComponentParent, getParentSchemasForComponent } from '../components';\n\n/**\n * Cleans ghost relations with publication state mismatches from a join table\n * Uses schema-based draft/publish checking like prevention fix\n */\nexport const cleanComponentJoinTable = async (\n db: Database,\n joinTableName: string,\n relation: any,\n sourceModel: any\n): Promise<number> => {\n try {\n // Get the target model metadata\n const targetModel = db.metadata.get(relation.target);\n if (!targetModel) {\n db.logger.debug(`Target model ${relation.target} not found, skipping ${joinTableName}`);\n return 0;\n }\n\n // Check if target supports draft/publish using schema-based approach (like prevention fix)\n const targetContentType =\n strapi.contentTypes[relation.target as keyof typeof strapi.contentTypes];\n const targetSupportsDraftPublish = targetContentType?.options?.draftAndPublish || false;\n\n if (!targetSupportsDraftPublish) {\n return 0;\n }\n\n // Find entries with publication state mismatches\n const ghostEntries = await findPublicationStateMismatches(\n db,\n joinTableName,\n relation,\n targetModel,\n sourceModel\n );\n\n if (ghostEntries.length === 0) {\n return 0;\n }\n\n // Remove ghost entries\n await db.connection(joinTableName).whereIn('id', ghostEntries).del();\n db.logger.debug(\n `Removed ${ghostEntries.length} ghost relations with publication state mismatches from ${joinTableName}`\n );\n\n return ghostEntries.length;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n db.logger.error(`Failed to clean join table \"${joinTableName}\": ${errorMessage}`);\n return 0;\n }\n};\n\nconst findContentTypeParentForComponentInstance = async (\n componentSchema: Schema.Component,\n componentId: number | string\n): Promise<{ uid: string; table: string; parentId: number | string } | null> => {\n // Get the parent schemas that could contain this component\n const parentSchemas = getParentSchemasForComponent(componentSchema);\n if (parentSchemas.length === 0) {\n // No potential parents\n return null;\n }\n\n // Find the actual parent for THIS specific component instance\n const parent = await findComponentParent(componentSchema, componentId, parentSchemas);\n if (!parent) {\n // No parent found for this component instance\n return null;\n }\n\n if (strapi.components[parent.uid as keyof typeof strapi.components]) {\n // If the parent is a component, we need to check its parents recursively\n const parentComponentSchema = strapi.components[parent.uid as keyof typeof strapi.components];\n return findContentTypeParentForComponentInstance(parentComponentSchema, parent.parentId);\n }\n\n if (strapi.contentTypes[parent.uid as keyof typeof strapi.contentTypes]) {\n // Found a content type parent\n return parent;\n }\n\n return null;\n};\n\n/**\n * Finds join table entries with publication state mismatches\n * Uses existing component parent detection from document service\n */\nconst findPublicationStateMismatches = async (\n db: Database,\n joinTableName: string,\n relation: any,\n targetModel: any,\n sourceModel: any\n): Promise<number[]> => {\n try {\n // Get join column names using proper functions (addressing PR feedback)\n const sourceColumn = relation.joinTable.joinColumn.name;\n const targetColumn = relation.joinTable.inverseJoinColumn.name;\n\n // Get all join entries with their target entities\n const query = db\n .connection(joinTableName)\n .select(\n `${joinTableName}.id as join_id`,\n `${joinTableName}.${sourceColumn} as source_id`,\n `${joinTableName}.${targetColumn} as target_id`,\n `${targetModel.tableName}.published_at as target_published_at`\n )\n .leftJoin(\n targetModel.tableName,\n `${joinTableName}.${targetColumn}`,\n `${targetModel.tableName}.id`\n );\n\n const joinEntries = await query;\n\n // Group by source_id to find duplicates pointing to draft/published versions of same entity\n const entriesBySource: { [key: string]: any[] } = {};\n for (const entry of joinEntries) {\n const sourceId = entry.source_id;\n if (!entriesBySource[sourceId]) {\n entriesBySource[sourceId] = [];\n }\n entriesBySource[sourceId].push(entry);\n }\n\n const ghostEntries: number[] = [];\n\n // Check if this is a join table (ends with _lnk)\n const isRelationJoinTable = joinTableName.endsWith('_lnk');\n const isComponentModel =\n !sourceModel.uid?.startsWith('api::') &&\n !sourceModel.uid?.startsWith('plugin::') &&\n sourceModel.uid?.includes('.');\n\n // Check for draft/publish inconsistencies\n for (const [sourceId, entries] of Object.entries(entriesBySource)) {\n // Skip entries with single relations\n if (entries.length <= 1) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n // For component join tables, check if THIS specific component instance's parent supports D&P\n if (isRelationJoinTable && isComponentModel) {\n try {\n const componentSchema = strapi.components[sourceModel.uid] as Schema.Component;\n if (!componentSchema) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n const parent = await findContentTypeParentForComponentInstance(componentSchema, sourceId);\n if (!parent) {\n continue;\n }\n\n // Check if THIS component instance's parent supports draft/publish\n const parentContentType =\n strapi.contentTypes[parent.uid as keyof typeof strapi.contentTypes];\n if (!parentContentType?.options?.draftAndPublish) {\n // This component instance's parent does NOT support D&P - skip cleanup\n // eslint-disable-next-line no-continue\n continue;\n }\n\n // If we reach here, this component instance's parent DOES support D&P\n // Continue to process this component instance for ghost relations\n } catch (error) {\n // Skip this component instance on error\n // eslint-disable-next-line no-continue\n continue;\n }\n }\n\n // Find ghost relations (same logic as original but with improved parent checking)\n for (const entry of entries) {\n if (entry.target_published_at === null) {\n // This is a draft target - find its published version\n const draftTarget = await db\n .connection(targetModel.tableName)\n .select('document_id')\n .where('id', entry.target_id)\n .first();\n\n if (draftTarget) {\n const publishedVersion = await db\n .connection(targetModel.tableName)\n .select('id', 'document_id')\n .where('document_id', draftTarget.document_id)\n .whereNotNull('published_at')\n .first();\n\n if (publishedVersion) {\n // Check if we also have a relation to the published version\n const publishedRelation = entries.find((e) => e.target_id === publishedVersion.id);\n if (publishedRelation) {\n ghostEntries.push(publishedRelation.join_id);\n }\n }\n }\n }\n }\n }\n\n return ghostEntries;\n } catch (error) {\n return [];\n }\n};\n"],"names":["cleanComponentJoinTable","db","joinTableName","relation","sourceModel","targetModel","metadata","get","target","logger","debug","targetContentType","strapi","contentTypes","targetSupportsDraftPublish","options","draftAndPublish","ghostEntries","findPublicationStateMismatches","length","connection","whereIn","del","error","errorMessage","Error","message","String","findContentTypeParentForComponentInstance","componentSchema","componentId","parentSchemas","getParentSchemasForComponent","parent","findComponentParent","components","uid","parentComponentSchema","parentId","sourceColumn","joinTable","joinColumn","name","targetColumn","inverseJoinColumn","query","select","tableName","leftJoin","joinEntries","entriesBySource","entry","sourceId","source_id","push","isRelationJoinTable","endsWith","isComponentModel","startsWith","includes","entries","Object","parentContentType","target_published_at","draftTarget","where","target_id","first","publishedVersion","document_id","whereNotNull","publishedRelation","find","e","id","join_id"],"mappings":";;;;AAIA;;;AAGC,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AAoBX,OAAQY,CAAAA,IAAI,CAAC,CAACC,IAAMA,CAAEP,CAAAA,SAAS,KAAKE,gBAAAA,CAAiBM,EAAE,CAAA;AACjF,4BAAA,IAAIH,iBAAmB,EAAA;gCACrBtD,YAAaqC,CAAAA,IAAI,CAACiB,iBAAAA,CAAkBI,OAAO,CAAA;AAC7C;AACF;AACF;AACF;AACF;AACF;QAEA,OAAO1D,YAAAA;AACT,KAAA,CAAE,OAAOM,KAAO,EAAA;AACd,QAAA,OAAO,EAAE;AACX;AACF,CAAA;;;;"}
@@ -0,0 +1,136 @@
1
+ import { getParentSchemasForComponent, findComponentParent } from '../components.mjs';
2
+
3
+ /**
4
+ * Cleans ghost relations with publication state mismatches from a join table
5
+ * Uses schema-based draft/publish checking like prevention fix
6
+ */ const cleanComponentJoinTable = async (db, joinTableName, relation, sourceModel)=>{
7
+ try {
8
+ // Get the target model metadata
9
+ const targetModel = db.metadata.get(relation.target);
10
+ if (!targetModel) {
11
+ db.logger.debug(`Target model ${relation.target} not found, skipping ${joinTableName}`);
12
+ return 0;
13
+ }
14
+ // Check if target supports draft/publish using schema-based approach (like prevention fix)
15
+ const targetContentType = strapi.contentTypes[relation.target];
16
+ const targetSupportsDraftPublish = targetContentType?.options?.draftAndPublish || false;
17
+ if (!targetSupportsDraftPublish) {
18
+ return 0;
19
+ }
20
+ // Find entries with publication state mismatches
21
+ const ghostEntries = await findPublicationStateMismatches(db, joinTableName, relation, targetModel, sourceModel);
22
+ if (ghostEntries.length === 0) {
23
+ return 0;
24
+ }
25
+ // Remove ghost entries
26
+ await db.connection(joinTableName).whereIn('id', ghostEntries).del();
27
+ db.logger.debug(`Removed ${ghostEntries.length} ghost relations with publication state mismatches from ${joinTableName}`);
28
+ return ghostEntries.length;
29
+ } catch (error) {
30
+ const errorMessage = error instanceof Error ? error.message : String(error);
31
+ db.logger.error(`Failed to clean join table "${joinTableName}": ${errorMessage}`);
32
+ return 0;
33
+ }
34
+ };
35
+ const findContentTypeParentForComponentInstance = async (componentSchema, componentId)=>{
36
+ // Get the parent schemas that could contain this component
37
+ const parentSchemas = getParentSchemasForComponent(componentSchema);
38
+ if (parentSchemas.length === 0) {
39
+ // No potential parents
40
+ return null;
41
+ }
42
+ // Find the actual parent for THIS specific component instance
43
+ const parent = await findComponentParent(componentSchema, componentId, parentSchemas);
44
+ if (!parent) {
45
+ // No parent found for this component instance
46
+ return null;
47
+ }
48
+ if (strapi.components[parent.uid]) {
49
+ // If the parent is a component, we need to check its parents recursively
50
+ const parentComponentSchema = strapi.components[parent.uid];
51
+ return findContentTypeParentForComponentInstance(parentComponentSchema, parent.parentId);
52
+ }
53
+ if (strapi.contentTypes[parent.uid]) {
54
+ // Found a content type parent
55
+ return parent;
56
+ }
57
+ return null;
58
+ };
59
+ /**
60
+ * Finds join table entries with publication state mismatches
61
+ * Uses existing component parent detection from document service
62
+ */ const findPublicationStateMismatches = async (db, joinTableName, relation, targetModel, sourceModel)=>{
63
+ try {
64
+ // Get join column names using proper functions (addressing PR feedback)
65
+ const sourceColumn = relation.joinTable.joinColumn.name;
66
+ const targetColumn = relation.joinTable.inverseJoinColumn.name;
67
+ // Get all join entries with their target entities
68
+ const query = db.connection(joinTableName).select(`${joinTableName}.id as join_id`, `${joinTableName}.${sourceColumn} as source_id`, `${joinTableName}.${targetColumn} as target_id`, `${targetModel.tableName}.published_at as target_published_at`).leftJoin(targetModel.tableName, `${joinTableName}.${targetColumn}`, `${targetModel.tableName}.id`);
69
+ const joinEntries = await query;
70
+ // Group by source_id to find duplicates pointing to draft/published versions of same entity
71
+ const entriesBySource = {};
72
+ for (const entry of joinEntries){
73
+ const sourceId = entry.source_id;
74
+ if (!entriesBySource[sourceId]) {
75
+ entriesBySource[sourceId] = [];
76
+ }
77
+ entriesBySource[sourceId].push(entry);
78
+ }
79
+ const ghostEntries = [];
80
+ // Check if this is a join table (ends with _lnk)
81
+ const isRelationJoinTable = joinTableName.endsWith('_lnk');
82
+ const isComponentModel = !sourceModel.uid?.startsWith('api::') && !sourceModel.uid?.startsWith('plugin::') && sourceModel.uid?.includes('.');
83
+ // Check for draft/publish inconsistencies
84
+ for (const [sourceId, entries] of Object.entries(entriesBySource)){
85
+ // Skip entries with single relations
86
+ if (entries.length <= 1) {
87
+ continue;
88
+ }
89
+ // For component join tables, check if THIS specific component instance's parent supports D&P
90
+ if (isRelationJoinTable && isComponentModel) {
91
+ try {
92
+ const componentSchema = strapi.components[sourceModel.uid];
93
+ if (!componentSchema) {
94
+ continue;
95
+ }
96
+ const parent = await findContentTypeParentForComponentInstance(componentSchema, sourceId);
97
+ if (!parent) {
98
+ continue;
99
+ }
100
+ // Check if THIS component instance's parent supports draft/publish
101
+ const parentContentType = strapi.contentTypes[parent.uid];
102
+ if (!parentContentType?.options?.draftAndPublish) {
103
+ continue;
104
+ }
105
+ // If we reach here, this component instance's parent DOES support D&P
106
+ // Continue to process this component instance for ghost relations
107
+ } catch (error) {
108
+ continue;
109
+ }
110
+ }
111
+ // Find ghost relations (same logic as original but with improved parent checking)
112
+ for (const entry of entries){
113
+ if (entry.target_published_at === null) {
114
+ // This is a draft target - find its published version
115
+ const draftTarget = await db.connection(targetModel.tableName).select('document_id').where('id', entry.target_id).first();
116
+ if (draftTarget) {
117
+ const publishedVersion = await db.connection(targetModel.tableName).select('id', 'document_id').where('document_id', draftTarget.document_id).whereNotNull('published_at').first();
118
+ if (publishedVersion) {
119
+ // Check if we also have a relation to the published version
120
+ const publishedRelation = entries.find((e)=>e.target_id === publishedVersion.id);
121
+ if (publishedRelation) {
122
+ ghostEntries.push(publishedRelation.join_id);
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ }
129
+ return ghostEntries;
130
+ } catch (error) {
131
+ return [];
132
+ }
133
+ };
134
+
135
+ export { cleanComponentJoinTable };
136
+ //# sourceMappingURL=clean-component-join-table.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clean-component-join-table.mjs","sources":["../../../../src/services/document-service/utils/clean-component-join-table.ts"],"sourcesContent":["import type { Database } from '@strapi/database';\nimport type { Schema } from '@strapi/types';\nimport { findComponentParent, getParentSchemasForComponent } from '../components';\n\n/**\n * Cleans ghost relations with publication state mismatches from a join table\n * Uses schema-based draft/publish checking like prevention fix\n */\nexport const cleanComponentJoinTable = async (\n db: Database,\n joinTableName: string,\n relation: any,\n sourceModel: any\n): Promise<number> => {\n try {\n // Get the target model metadata\n const targetModel = db.metadata.get(relation.target);\n if (!targetModel) {\n db.logger.debug(`Target model ${relation.target} not found, skipping ${joinTableName}`);\n return 0;\n }\n\n // Check if target supports draft/publish using schema-based approach (like prevention fix)\n const targetContentType =\n strapi.contentTypes[relation.target as keyof typeof strapi.contentTypes];\n const targetSupportsDraftPublish = targetContentType?.options?.draftAndPublish || false;\n\n if (!targetSupportsDraftPublish) {\n return 0;\n }\n\n // Find entries with publication state mismatches\n const ghostEntries = await findPublicationStateMismatches(\n db,\n joinTableName,\n relation,\n targetModel,\n sourceModel\n );\n\n if (ghostEntries.length === 0) {\n return 0;\n }\n\n // Remove ghost entries\n await db.connection(joinTableName).whereIn('id', ghostEntries).del();\n db.logger.debug(\n `Removed ${ghostEntries.length} ghost relations with publication state mismatches from ${joinTableName}`\n );\n\n return ghostEntries.length;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n db.logger.error(`Failed to clean join table \"${joinTableName}\": ${errorMessage}`);\n return 0;\n }\n};\n\nconst findContentTypeParentForComponentInstance = async (\n componentSchema: Schema.Component,\n componentId: number | string\n): Promise<{ uid: string; table: string; parentId: number | string } | null> => {\n // Get the parent schemas that could contain this component\n const parentSchemas = getParentSchemasForComponent(componentSchema);\n if (parentSchemas.length === 0) {\n // No potential parents\n return null;\n }\n\n // Find the actual parent for THIS specific component instance\n const parent = await findComponentParent(componentSchema, componentId, parentSchemas);\n if (!parent) {\n // No parent found for this component instance\n return null;\n }\n\n if (strapi.components[parent.uid as keyof typeof strapi.components]) {\n // If the parent is a component, we need to check its parents recursively\n const parentComponentSchema = strapi.components[parent.uid as keyof typeof strapi.components];\n return findContentTypeParentForComponentInstance(parentComponentSchema, parent.parentId);\n }\n\n if (strapi.contentTypes[parent.uid as keyof typeof strapi.contentTypes]) {\n // Found a content type parent\n return parent;\n }\n\n return null;\n};\n\n/**\n * Finds join table entries with publication state mismatches\n * Uses existing component parent detection from document service\n */\nconst findPublicationStateMismatches = async (\n db: Database,\n joinTableName: string,\n relation: any,\n targetModel: any,\n sourceModel: any\n): Promise<number[]> => {\n try {\n // Get join column names using proper functions (addressing PR feedback)\n const sourceColumn = relation.joinTable.joinColumn.name;\n const targetColumn = relation.joinTable.inverseJoinColumn.name;\n\n // Get all join entries with their target entities\n const query = db\n .connection(joinTableName)\n .select(\n `${joinTableName}.id as join_id`,\n `${joinTableName}.${sourceColumn} as source_id`,\n `${joinTableName}.${targetColumn} as target_id`,\n `${targetModel.tableName}.published_at as target_published_at`\n )\n .leftJoin(\n targetModel.tableName,\n `${joinTableName}.${targetColumn}`,\n `${targetModel.tableName}.id`\n );\n\n const joinEntries = await query;\n\n // Group by source_id to find duplicates pointing to draft/published versions of same entity\n const entriesBySource: { [key: string]: any[] } = {};\n for (const entry of joinEntries) {\n const sourceId = entry.source_id;\n if (!entriesBySource[sourceId]) {\n entriesBySource[sourceId] = [];\n }\n entriesBySource[sourceId].push(entry);\n }\n\n const ghostEntries: number[] = [];\n\n // Check if this is a join table (ends with _lnk)\n const isRelationJoinTable = joinTableName.endsWith('_lnk');\n const isComponentModel =\n !sourceModel.uid?.startsWith('api::') &&\n !sourceModel.uid?.startsWith('plugin::') &&\n sourceModel.uid?.includes('.');\n\n // Check for draft/publish inconsistencies\n for (const [sourceId, entries] of Object.entries(entriesBySource)) {\n // Skip entries with single relations\n if (entries.length <= 1) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n // For component join tables, check if THIS specific component instance's parent supports D&P\n if (isRelationJoinTable && isComponentModel) {\n try {\n const componentSchema = strapi.components[sourceModel.uid] as Schema.Component;\n if (!componentSchema) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n const parent = await findContentTypeParentForComponentInstance(componentSchema, sourceId);\n if (!parent) {\n continue;\n }\n\n // Check if THIS component instance's parent supports draft/publish\n const parentContentType =\n strapi.contentTypes[parent.uid as keyof typeof strapi.contentTypes];\n if (!parentContentType?.options?.draftAndPublish) {\n // This component instance's parent does NOT support D&P - skip cleanup\n // eslint-disable-next-line no-continue\n continue;\n }\n\n // If we reach here, this component instance's parent DOES support D&P\n // Continue to process this component instance for ghost relations\n } catch (error) {\n // Skip this component instance on error\n // eslint-disable-next-line no-continue\n continue;\n }\n }\n\n // Find ghost relations (same logic as original but with improved parent checking)\n for (const entry of entries) {\n if (entry.target_published_at === null) {\n // This is a draft target - find its published version\n const draftTarget = await db\n .connection(targetModel.tableName)\n .select('document_id')\n .where('id', entry.target_id)\n .first();\n\n if (draftTarget) {\n const publishedVersion = await db\n .connection(targetModel.tableName)\n .select('id', 'document_id')\n .where('document_id', draftTarget.document_id)\n .whereNotNull('published_at')\n .first();\n\n if (publishedVersion) {\n // Check if we also have a relation to the published version\n const publishedRelation = entries.find((e) => e.target_id === publishedVersion.id);\n if (publishedRelation) {\n ghostEntries.push(publishedRelation.join_id);\n }\n }\n }\n }\n }\n }\n\n return ghostEntries;\n } catch (error) {\n return [];\n }\n};\n"],"names":["cleanComponentJoinTable","db","joinTableName","relation","sourceModel","targetModel","metadata","get","target","logger","debug","targetContentType","strapi","contentTypes","targetSupportsDraftPublish","options","draftAndPublish","ghostEntries","findPublicationStateMismatches","length","connection","whereIn","del","error","errorMessage","Error","message","String","findContentTypeParentForComponentInstance","componentSchema","componentId","parentSchemas","getParentSchemasForComponent","parent","findComponentParent","components","uid","parentComponentSchema","parentId","sourceColumn","joinTable","joinColumn","name","targetColumn","inverseJoinColumn","query","select","tableName","leftJoin","joinEntries","entriesBySource","entry","sourceId","source_id","push","isRelationJoinTable","endsWith","isComponentModel","startsWith","includes","entries","Object","parentContentType","target_published_at","draftTarget","where","target_id","first","publishedVersion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AER,wBAAA,IAAIC,gBAAkB,EAAA;;4BAEpB,MAAMG,iBAAAA,GAAoBX,OAAQY,CAAAA,IAAI,CAAC,CAACC,IAAMA,CAAEP,CAAAA,SAAS,KAAKE,gBAAAA,CAAiBM,EAAE,CAAA;AACjF,4BAAA,IAAIH,iBAAmB,EAAA;gCACrBtD,YAAaqC,CAAAA,IAAI,CAACiB,iBAAAA,CAAkBI,OAAO,CAAA;AAC7C;AACF;AACF;AACF;AACF;AACF;QAEA,OAAO1D,YAAAA;AACT,KAAA,CAAE,OAAOM,KAAO,EAAA;AACd,QAAA,OAAO,EAAE;AACX;AACF,CAAA;;;;"}
@@ -0,0 +1,160 @@
1
+ import type { Database } from '@strapi/database';
2
+ export interface SessionProvider {
3
+ create(session: SessionData): Promise<SessionData>;
4
+ findBySessionId(sessionId: string): Promise<SessionData | null>;
5
+ updateBySessionId(sessionId: string, data: Partial<SessionData>): Promise<void>;
6
+ deleteBySessionId(sessionId: string): Promise<void>;
7
+ deleteExpired(): Promise<void>;
8
+ deleteBy(criteria: {
9
+ userId?: string;
10
+ origin?: string;
11
+ deviceId?: string;
12
+ }): Promise<void>;
13
+ }
14
+ export interface SessionData {
15
+ id?: string;
16
+ userId: string;
17
+ sessionId: string;
18
+ deviceId?: string;
19
+ origin: string;
20
+ childId?: string | null;
21
+ type?: 'refresh' | 'session';
22
+ status?: 'active' | 'rotated' | 'revoked';
23
+ expiresAt: Date;
24
+ absoluteExpiresAt?: Date | null;
25
+ createdAt?: Date;
26
+ updatedAt?: Date;
27
+ }
28
+ export interface RefreshTokenPayload {
29
+ userId: string;
30
+ sessionId: string;
31
+ type: 'refresh';
32
+ exp: number;
33
+ iat: number;
34
+ }
35
+ export interface AccessTokenPayload {
36
+ userId: string;
37
+ sessionId: string;
38
+ type: 'access';
39
+ exp: number;
40
+ iat: number;
41
+ }
42
+ export type TokenPayload = RefreshTokenPayload | AccessTokenPayload;
43
+ export interface ValidateRefreshTokenResult {
44
+ isValid: boolean;
45
+ userId?: string;
46
+ sessionId?: string;
47
+ error?: 'invalid_token' | 'token_expired' | 'session_not_found' | 'session_expired' | 'wrong_token_type';
48
+ }
49
+ export interface SessionManagerConfig {
50
+ jwtSecret: string;
51
+ accessTokenLifespan: number;
52
+ maxRefreshTokenLifespan: number;
53
+ idleRefreshTokenLifespan: number;
54
+ maxSessionLifespan: number;
55
+ idleSessionLifespan: number;
56
+ }
57
+ declare class OriginSessionManager {
58
+ private sessionManager;
59
+ private origin;
60
+ constructor(sessionManager: SessionManager, origin: string);
61
+ generateRefreshToken(userId: string, deviceId: string | undefined, options?: {
62
+ type?: 'refresh' | 'session';
63
+ }): Promise<{
64
+ token: string;
65
+ sessionId: string;
66
+ absoluteExpiresAt: string;
67
+ }>;
68
+ generateAccessToken(refreshToken: string): Promise<{
69
+ token: string;
70
+ } | {
71
+ error: string;
72
+ }>;
73
+ rotateRefreshToken(refreshToken: string): Promise<{
74
+ token: string;
75
+ sessionId: string;
76
+ absoluteExpiresAt: string;
77
+ type: 'refresh' | 'session';
78
+ } | {
79
+ error: string;
80
+ }>;
81
+ validateAccessToken(token: string): {
82
+ isValid: true;
83
+ payload: AccessTokenPayload;
84
+ } | {
85
+ isValid: false;
86
+ payload: null;
87
+ };
88
+ validateRefreshToken(token: string): Promise<ValidateRefreshTokenResult>;
89
+ invalidateRefreshToken(userId: string, deviceId?: string): Promise<void>;
90
+ /**
91
+ * Returns true when a session exists and is not expired for this origin.
92
+ * If the session exists but is expired, it will be deleted as part of this check.
93
+ */
94
+ isSessionActive(sessionId: string): Promise<boolean>;
95
+ }
96
+ declare class SessionManager {
97
+ private provider;
98
+ private originConfigs;
99
+ private cleanupInvocationCounter;
100
+ private readonly cleanupEveryCalls;
101
+ constructor(provider: SessionProvider);
102
+ /**
103
+ * Define configuration for a specific origin
104
+ */
105
+ defineOrigin(origin: string, config: SessionManagerConfig): void;
106
+ /**
107
+ * Check if an origin is defined
108
+ */
109
+ hasOrigin(origin: string): boolean;
110
+ /**
111
+ * Get configuration for a specific origin, throw error if not defined
112
+ */
113
+ private getConfigForOrigin;
114
+ generateSessionId(): string;
115
+ private maybeCleanupExpired;
116
+ /**
117
+ * Get the cleanup every calls threshold
118
+ */
119
+ get cleanupThreshold(): number;
120
+ generateRefreshToken(userId: string, deviceId: string | undefined, origin: string, options?: {
121
+ type?: 'refresh' | 'session';
122
+ }): Promise<{
123
+ token: string;
124
+ sessionId: string;
125
+ absoluteExpiresAt: string;
126
+ }>;
127
+ validateAccessToken(token: string, origin: string): {
128
+ isValid: true;
129
+ payload: AccessTokenPayload;
130
+ } | {
131
+ isValid: false;
132
+ payload: null;
133
+ };
134
+ validateRefreshToken(token: string, origin: string): Promise<ValidateRefreshTokenResult>;
135
+ invalidateRefreshToken(origin: string, userId: string, deviceId?: string): Promise<void>;
136
+ generateAccessToken(refreshToken: string, origin: string): Promise<{
137
+ token: string;
138
+ } | {
139
+ error: string;
140
+ }>;
141
+ rotateRefreshToken(refreshToken: string, origin: string): Promise<{
142
+ token: string;
143
+ sessionId: string;
144
+ absoluteExpiresAt: string;
145
+ type: 'refresh' | 'session';
146
+ } | {
147
+ error: string;
148
+ }>;
149
+ /**
150
+ * Returns true when a session exists and is not expired.
151
+ * If the session exists but is expired, it will be deleted as part of this check.
152
+ */
153
+ isSessionActive(sessionId: string, origin: string): Promise<boolean>;
154
+ }
155
+ declare const createDatabaseProvider: (db: Database, contentType: string) => SessionProvider;
156
+ declare const createSessionManager: ({ db, }: {
157
+ db: Database;
158
+ }) => SessionManager & ((origin: string) => OriginSessionManager);
159
+ export { createSessionManager, createDatabaseProvider };
160
+ //# sourceMappingURL=session-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-manager.d.ts","sourceRoot":"","sources":["../../src/services/session-manager.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAGjD,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,OAAO,EAAE,WAAW,GA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