cpee 2.1.136 → 2.1.139

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.
@@ -18,17 +18,29 @@ require 'redis'
18
18
  require 'daemonite'
19
19
  require 'riddl/client'
20
20
  require 'json'
21
+ require 'digest/sha1'
21
22
  require_relative '../../lib/cpee/message'
22
23
  require_relative '../../lib/cpee/redis'
23
24
 
25
+ # one round trip per vote: the controller sends one vote message per subscriber
26
+ # (content.subscription), so only check if that subscriber is still subscribed to
27
+ # exactly this topic/type/name (KEYS[1] is the reverse index). Returns url, sseq
28
+ # or {} if gone. GET needs the or '', a nil (false) would truncate the array.
29
+ MATCH = <<~LUA.freeze
30
+ if redis.call('SISMEMBER', KEYS[1], ARGV[2]) == 0 then return {} end
31
+ local b = ARGV[1] .. '/handlers/' .. ARGV[2]
32
+ return { redis.call('GET', b .. '/url') or '', redis.call('INCR', b .. '/seq') }
33
+ LUA
34
+ MATCH_SHA = Digest::SHA1.hexdigest(MATCH).freeze
35
+
24
36
  def persist_handler(instance,key,mess,redis) #{{{
25
37
  redis.multi do |multi|
26
38
  multi.sadd("instance:#{instance}/callbacks",key)
27
- multi.set("instance:#{instance}/callbacks/#{key}/subscription",mess.dig('content','subscription'))
28
- multi.set("instance:#{instance}/callbacks/#{key}/uuid",mess.dig('content','activity-uuid'))
29
- multi.set("instance:#{instance}/callbacks/#{key}/label",mess.dig('content','label'))
30
- multi.set("instance:#{instance}/callbacks/#{key}/position",mess.dig('content','activity'))
31
- multi.set("instance:#{instance}/callbacks/#{key}/type",'vote')
39
+ multi.set("instance:#{instance}/callbacks/#{key}/subscription",mess.dig('content','subscription'),keepttl: true)
40
+ multi.set("instance:#{instance}/callbacks/#{key}/uuid",mess.dig('content','activity-uuid'),keepttl: true)
41
+ multi.set("instance:#{instance}/callbacks/#{key}/label",mess.dig('content','label'),keepttl: true)
42
+ multi.set("instance:#{instance}/callbacks/#{key}/position",mess.dig('content','activity'),keepttl: true)
43
+ multi.set("instance:#{instance}/callbacks/#{key}/type",'vote',keepttl: true)
32
44
  end
33
45
  end #}}}
34
46
 
@@ -64,7 +76,7 @@ Daemonite.new do |opts|
64
76
  opts[:pubsubredis].psubscribe('vote:*') do |on|
65
77
  on.pmessage do |pat, what, message|
66
78
  index = message.index(' ')
67
- instance, uuid = message[0...index].split(',')
79
+ instance, uuid, seq = message[0...index].split(',')
68
80
  mess = message[index+1..-1]
69
81
 
70
82
  type, worker, event = what.split(':',3)
@@ -72,46 +84,47 @@ Daemonite.new do |opts|
72
84
  name = ::File::basename(event)
73
85
  long = File.join(topic,type,name)
74
86
 
75
- opts[:redis].smembers("instance:#{instance}/handlers").each do |subscription_key|
76
- if opts[:redis].smembers("instance:#{instance}/handlers/#{subscription_key}").include? long
77
- m = JSON.parse(mess)
78
- callback_key = m.dig('content','key')
79
- url = opts[:redis].get("instance:#{instance}/handlers/#{subscription_key}/url")
87
+ m = JSON.parse(mess)
88
+ callback_key = m.dig('content','key')
89
+ subscription_key = m.dig('content','subscription')
90
+ url, sseq = CPEE::redis_script(opts[:redis], MATCH_SHA, MATCH, ["instance:#{instance}/handlers/#{long}"], ["instance:#{instance}", subscription_key.to_s])
80
91
 
81
- if url.nil? || url == ""
82
- persist_handler instance, callback_key, m, opts[:redis]
83
- opts[:redis].publish("forward:#{instance}/#{subscription_key}",mess)
92
+ if url.nil? # unsubscribed in the meantime, nobody would ever answer, so let the instance continue
93
+ send_response instance, callback_key, m['cpee'], true, opts[:redis]
94
+ elsif url == ""
95
+ persist_handler instance, callback_key, m, opts[:redis]
96
+ opts[:redis].publish("forward:#{instance}/#{subscription_key}","#{seq},#{sseq} #{mess}")
97
+ else
98
+ client = Riddl::Client.new(url)
99
+ callback = File.join(m['instance-url'],'/callbacks/',callback_key,'/')
100
+ status, result, headers = (client.post [
101
+ Riddl::Header.new("CPEE-BASE",File.join(m['cpee'],'/')),
102
+ Riddl::Header.new("CPEE-INSTANCE",m['instance']),
103
+ Riddl::Header.new("CPEE-INSTANCE-URL",File.join(m['instance-url'],'/')),
104
+ Riddl::Header.new("CPEE-INSTANCE-UUID",m['instance-uuid']),
105
+ Riddl::Header.new("CPEE-CALLBACK",callback),
106
+ Riddl::Header.new("CPEE-CALLBACK-ID",callback_key),
107
+ Riddl::Header.new("CPEE-SEQ",seq),
108
+ Riddl::Header.new("CPEE-SSEQ",sseq),
109
+ Riddl::Parameter::Simple::new('type',type),
110
+ Riddl::Parameter::Simple::new('topic',topic),
111
+ Riddl::Parameter::Simple::new('vote',name),
112
+ Riddl::Parameter::Simple::new('callback',callback),
113
+ Riddl::Parameter::Complex::new('notification','application/json',mess)
114
+ ] rescue [ 0, [], []])
115
+ if status >= 200 && status < 300
116
+ val = if result[0].class == Riddl::Parameter::Simple
117
+ result[0].value
84
118
  else
85
- client = Riddl::Client.new(url)
86
- callback = File.join(m['instance-url'],'/callbacks/',subscription_key,'/')
87
- status, result, headers = (client.post [
88
- Riddl::Header.new("CPEE-BASE",File.join(m['cpee'],'/')),
89
- Riddl::Header.new("CPEE-INSTANCE",m['instance']),
90
- Riddl::Header.new("CPEE-INSTANCE-URL",File.join(m['instance-url'],'/')),
91
- Riddl::Header.new("CPEE-INSTANCE-UUID",m['instance-uuid']),
92
- Riddl::Header.new("CPEE-CALLBACK",callback),
93
- Riddl::Header.new("CPEE-CALLBACK-ID",subscription_key),
94
- Riddl::Parameter::Simple::new('type',type),
95
- Riddl::Parameter::Simple::new('topic',topic),
96
- Riddl::Parameter::Simple::new('vote',name),
97
- Riddl::Parameter::Simple::new('callback',callback),
98
- Riddl::Parameter::Complex::new('notification','application/json',mess)
99
- ] rescue [ 0, [], []])
100
- if status >= 200 && status < 300
101
- val = if result[0].class == Riddl::Parameter::Simple
102
- result[0].value
103
- else
104
- result[0].value.read
105
- end
106
- if (headers["CPEE_CALLBACK"] && headers["CPEE_CALLBACK"] == 'true') || val == 'callback'
107
- persist_handler instance, callback_key, m, opts[:redis]
108
- else # they may send true or false
109
- send_response instance, callback_key, m['cpee'], val, opts[:redis]
110
- end
111
- else
112
- send_response instance, callback_key, m['cpee'], true, opts[:redis]
113
- end
119
+ result[0].value.read
120
+ end
121
+ if (headers["CPEE_CALLBACK"] && headers["CPEE_CALLBACK"] == 'true') || val == 'callback'
122
+ persist_handler instance, callback_key, m, opts[:redis]
123
+ else # they may send true or false
124
+ send_response instance, callback_key, m['cpee'], val, opts[:redis]
114
125
  end
126
+ else
127
+ send_response instance, callback_key, m['cpee'], true, opts[:redis]
115
128
  end
116
129
  end
117
130
  rescue => e
@@ -1 +1 @@
1
- 1074992
1
+ 3635877
@@ -38,6 +38,7 @@ Daemonite.new do |opts|
38
38
  'event:' + ('%02i' % w) + ':state/change',
39
39
  'event:' + ('%02i' % w) + ':executionhandler/change',
40
40
  'event:' + ('%02i' % w) + ':description/change',
41
+ 'event:' + ('%02i' % w) + ':description/sync',
41
42
  'event:' + ('%02i' % w) + ':dataelements/change',
42
43
  'event:' + ('%02i' % w) + ':documents/change',
43
44
  'event:' + ('%02i' % w) + ':endpoints/change',
@@ -67,25 +68,41 @@ Daemonite.new do |opts|
67
68
  key = mess.dig('content','key')
68
69
  opts[:redis].multi do |multi|
69
70
  multi.sadd("instance:#{instance}/callbacks",key)
70
- multi.set("instance:#{instance}/callbacks/#{key}/uuid",mess.dig('content','activity-uuid'))
71
- multi.set("instance:#{instance}/callbacks/#{key}/label",mess.dig('content','label'))
72
- multi.set("instance:#{instance}/callbacks/#{key}/position",mess.dig('content','activity'))
73
- multi.set("instance:#{instance}/callbacks/#{key}/type",'callback')
71
+ multi.set("instance:#{instance}/callbacks/#{key}/uuid",mess.dig('content','activity-uuid'),keepttl: true)
72
+ multi.set("instance:#{instance}/callbacks/#{key}/label",mess.dig('content','label'),keepttl: true)
73
+ multi.set("instance:#{instance}/callbacks/#{key}/position",mess.dig('content','activity'),keepttl: true)
74
+ multi.set("instance:#{instance}/callbacks/#{key}/type",'callback',keepttl: true)
74
75
  end
75
76
  when /event:\d+:state\/change/
76
77
  opts[:redis].multi do |multi|
77
78
  unless mess.dig('content','state') == 'purged'
78
- multi.set("instance:#{instance}/state",mess.dig('content','state'))
79
- multi.set("instance:#{instance}/state/@changed",mess.dig('timestamp'))
79
+ multi.set("instance:#{instance}/state",mess.dig('content','state'),keepttl: true)
80
+ multi.set("instance:#{instance}/state/@changed",mess.dig('timestamp'),keepttl: true)
80
81
  end
81
82
  end
82
83
  when /event:\d+:executionhandler\/change/
83
- opts[:redis].set("instance:#{instance}/executionhandler",mess.dig('content','executionhandler'))
84
+ opts[:redis].set("instance:#{instance}/executionhandler",mess.dig('content','executionhandler'),keepttl: true)
84
85
  when /event:\d+:description\/change/
85
86
  opts[:redis].multi do |multi|
86
- multi.set("instance:#{instance}/description",mess.dig('content','description'))
87
- multi.set("instance:#{instance}/dslx",mess.dig('content','dslx'))
88
- multi.set("instance:#{instance}/dsl",mess.dig('content','dsl'))
87
+ multi.set("instance:#{instance}/description",mess.dig('content','description'),keepttl: true)
88
+ multi.set("instance:#{instance}/dslx",mess.dig('content','dslx'),keepttl: true)
89
+ multi.set("instance:#{instance}/dsl",mess.dig('content','dsl'),keepttl: true)
90
+ multi.set("instance:#{instance}/dslx/@change_uuid",mess.dig('content','change_uuid'),keepttl: true)
91
+ unless mess.dig('content','change_pending') # otherwise description/sync brings it
92
+ multi.set("instance:#{instance}/description/@change_uuid",mess.dig('content','change_uuid'),keepttl: true)
93
+ end
94
+ end
95
+ when /event:\d+:description\/sync/
96
+ # asynchronous result, only valid when the dslx did not change in the meantime
97
+ opts[:redis].watch("instance:#{instance}/dslx/@change_uuid") do |rd|
98
+ if rd.get("instance:#{instance}/dslx/@change_uuid") == mess.dig('content','change_uuid')
99
+ rd.multi do |multi|
100
+ multi.set("instance:#{instance}/description",mess.dig('content','description'),keepttl: true)
101
+ multi.set("instance:#{instance}/description/@change_uuid",mess.dig('content','change_uuid'),keepttl: true)
102
+ end
103
+ else
104
+ rd.unwatch
105
+ end
89
106
  end
90
107
  when /event:\d+:dataelements\/change/, /event:\d+:documents\/change/, /event:\d+:endpoints\/change/, /event:\d+:attributes\/change/
91
108
  topic = mess.dig('topic')
@@ -101,7 +118,7 @@ Daemonite.new do |opts|
101
118
  mess.dig('content','changed')&.each_with_index do |c,i|
102
119
  unless what =~ /event:\d+:attributes\/change/ && c == 'uuid'
103
120
  multi.zadd("instance:#{instance}/#{topic}",max + 1 + i,c,nx: true)
104
- multi.set("instance:#{instance}/#{topic}/#{c}",CPEE::ValueHelper::generate(mess.dig('content','values',c)))
121
+ multi.set("instance:#{instance}/#{topic}/#{c}",CPEE::ValueHelper::generate(mess.dig('content','values',c)),keepttl: true)
105
122
  end
106
123
  end
107
124
  mess.dig('content','deleted')&.to_a&.each do |c|
@@ -115,19 +132,22 @@ Daemonite.new do |opts|
115
132
  opts[:redis].publish('event:' + $1 + ':transaction/finished',message)
116
133
  when /event:\d+:transformation\/change/
117
134
  opts[:redis].multi do |multi|
118
- multi.set("instance:#{instance}/transformation/description",mess.dig('content','description'))
119
- multi.set("instance:#{instance}/transformation/description/@type",mess.dig('content','description_type'))
120
- multi.set("instance:#{instance}/transformation/dataelements",mess.dig('content','dataelements'))
121
- multi.set("instance:#{instance}/transformation/dataelements/@type",mess.dig('content','dataelements_type'))
122
- multi.set("instance:#{instance}/transformation/endpoints",mess.dig('content','endpoints'))
123
- multi.set("instance:#{instance}/transformation/endpoints/@type",mess.dig('content','endpoints_type'))
124
- multi.set("instance:#{instance}/transformation/dslx",mess.dig('content','dslx'))
125
- multi.set("instance:#{instance}/transformation/dslx/@type",mess.dig('content','dslx_type'))
135
+ multi.set("instance:#{instance}/transformation/description",mess.dig('content','description'),keepttl: true)
136
+ multi.set("instance:#{instance}/transformation/description/@type",mess.dig('content','description_type'),keepttl: true)
137
+ multi.set("instance:#{instance}/transformation/dataelements",mess.dig('content','dataelements'),keepttl: true)
138
+ multi.set("instance:#{instance}/transformation/dataelements/@type",mess.dig('content','dataelements_type'),keepttl: true)
139
+ multi.set("instance:#{instance}/transformation/endpoints",mess.dig('content','endpoints'),keepttl: true)
140
+ multi.set("instance:#{instance}/transformation/endpoints/@type",mess.dig('content','endpoints_type'),keepttl: true)
141
+ multi.set("instance:#{instance}/transformation/dslx",mess.dig('content','dslx'),keepttl: true)
142
+ multi.set("instance:#{instance}/transformation/dslx/@type",mess.dig('content','dslx_type'),keepttl: true)
143
+ if mess.dig('content','change_pending') # same dslx, but the description is no longer the one for it
144
+ multi.del("instance:#{instance}/description/@change_uuid")
145
+ end
126
146
  end
127
147
  when /event:\d+:status\/change/
128
148
  opts[:redis].multi do |multi|
129
- multi.set("instance:#{instance}/status/id",mess.dig('content','id'))
130
- multi.set("instance:#{instance}/status/message",mess.dig('content','message'))
149
+ multi.set("instance:#{instance}/status/id",mess.dig('content','id'),keepttl: true)
150
+ multi.set("instance:#{instance}/status/message",mess.dig('content','message'),keepttl: true)
131
151
  end
132
152
  when /event:\d+:position\/change/
133
153
  opts[:redis].multi do |multi|
@@ -139,21 +159,21 @@ Daemonite.new do |opts|
139
159
  end
140
160
  c.dig('before')&.each do |ele|
141
161
  multi.sadd("instance:#{instance}/positions",ele['position'])
142
- multi.set("instance:#{instance}/positions/#{ele['position']}",'before')
162
+ multi.set("instance:#{instance}/positions/#{ele['position']}",'before',keepttl: true)
143
163
  end
144
164
  c.dig('at')&.each do |ele|
145
165
  multi.sadd("instance:#{instance}/positions",ele['position'])
146
- multi.set("instance:#{instance}/positions/#{ele['position']}",'at')
147
- multi.set("instance:#{instance}/positions/#{ele['position']}/@passthrough",ele['passthrough']) if ele['passthrough']
166
+ multi.set("instance:#{instance}/positions/#{ele['position']}",'at',keepttl: true)
167
+ multi.set("instance:#{instance}/positions/#{ele['position']}/@passthrough",ele['passthrough'],keepttl: true) if ele['passthrough']
148
168
  end
149
169
  c.dig('wait')&.each do |ele|
150
170
  multi.sadd("instance:#{instance}/positions",ele['position'])
151
- multi.set("instance:#{instance}/positions/#{ele['position']}",'at')
152
- multi.set("instance:#{instance}/positions/#{ele['position']}/@passthrough",ele['passthrough']) if ele['passthrough']
171
+ multi.set("instance:#{instance}/positions/#{ele['position']}",'at',keepttl: true)
172
+ multi.set("instance:#{instance}/positions/#{ele['position']}/@passthrough",ele['passthrough'],keepttl: true) if ele['passthrough']
153
173
  end
154
174
  c.dig('after')&.each do |ele|
155
175
  multi.sadd("instance:#{instance}/positions",ele['position'])
156
- multi.set("instance:#{instance}/positions/#{ele['position']}",'after')
176
+ multi.set("instance:#{instance}/positions/#{ele['position']}",'after',keepttl: true)
157
177
  end
158
178
  end
159
179
  when /event:\d+:handler\/change/
@@ -161,7 +181,7 @@ Daemonite.new do |opts|
161
181
  mess.dig('content','changed').each do |c|
162
182
  multi.sadd("instance:#{instance}/handlers",mess.dig('content','key'))
163
183
  multi.sadd("instance:#{instance}/handlers/#{mess.dig('content','key')}",c)
164
- multi.set("instance:#{instance}/handlers/#{mess.dig('content','key')}/url",mess.dig('content','url'))
184
+ multi.set("instance:#{instance}/handlers/#{mess.dig('content','key')}/url",mess.dig('content','url'),keepttl: true)
165
185
  multi.sadd("instance:#{instance}/handlers/#{c}",mess.dig('content','key'))
166
186
  end
167
187
  mess.dig('content','deleted').to_a.each do |c|
@@ -172,6 +192,7 @@ Daemonite.new do |opts|
172
192
  if opts[:redis].scard("instance:#{instance}/handlers/#{mess.dig('content','key')}") < 1
173
193
  opts[:redis].multi do |multi|
174
194
  multi.del("instance:#{instance}/handlers/#{mess.dig('content','key')}/url")
195
+ multi.del("instance:#{instance}/handlers/#{mess.dig('content','key')}/seq")
175
196
  multi.srem("instance:#{instance}/handlers",mess.dig('content','key'))
176
197
  end
177
198
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cpee
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.1.136
4
+ version: 2.1.139
5
5
  platform: ruby
6
6
  authors:
7
7
  - Juergen eTM Mangler
@@ -18,6 +18,9 @@ dependencies:
18
18
  - - "~>"
19
19
  - !ruby/object:Gem::Version
20
20
  version: '1.0'
21
+ - - ">="
22
+ - !ruby/object:Gem::Version
23
+ version: 1.0.21
21
24
  type: :runtime
22
25
  prerelease: false
23
26
  version_requirements: !ruby/object:Gem::Requirement
@@ -25,6 +28,9 @@ dependencies:
25
28
  - - "~>"
26
29
  - !ruby/object:Gem::Version
27
30
  version: '1.0'
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: 1.0.21
28
34
  - !ruby/object:Gem::Dependency
29
35
  name: weel
30
36
  requirement: !ruby/object:Gem::Requirement
@@ -267,7 +273,6 @@ files:
267
273
  - cockpit/edit.html
268
274
  - cockpit/graph.html
269
275
  - cockpit/index.html
270
- - cockpit/js/build-bpmn2.js
271
276
  - cockpit/js/compliance.js
272
277
  - cockpit/js/details.js
273
278
  - cockpit/js/edit.js
@@ -1244,6 +1249,7 @@ files:
1244
1249
  - lib/cpee/implementation_callbacks.rb
1245
1250
  - lib/cpee/implementation_notifications.rb
1246
1251
  - lib/cpee/implementation_properties.rb
1252
+ - lib/cpee/json_pointer.rb
1247
1253
  - lib/cpee/message.rb
1248
1254
  - lib/cpee/persistence.rb
1249
1255
  - lib/cpee/redis.rb
@@ -1,302 +0,0 @@
1
- /*
2
- This file is part of cpee-layout.
3
-
4
- cpee-layout is free software: you can redistribute it and/or modify it under
5
- the terms of the GNU Lesser General Public License as published by the Free
6
- Software Foundation, either version 3 of the License, or (at your option) any
7
- later version.
8
-
9
- cpee-layout is distributed in the hope that it will be useful, but WITHOUT
10
- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11
- FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12
- details.
13
-
14
- You should have received a copy of the GNU Lesser General Public License
15
- along with cpee-layout (file LICENSE in the main directory). If not, see
16
- <http://www.gnu.org/licenses/>.
17
-
18
- The CPEE type mapping and the BPMN output follow build-bpmn.js,
19
- Copyright 2026 David Kindermann (Apache-2.0).
20
- */
21
-
22
- //
23
- // build-bpmn2.js
24
- //
25
- // Creates BPMN XML from wfadaptor's get_svg_metrics():
26
- // bpmn2_convert(pos_matrix, con_list, lr, geometry), like david_bpmn_convert of
27
- // build-bpmn.js plus the orientation and the geometry of the drawing. Rows and columns are
28
- // 0-indexed.
29
- //
30
- // Unlike build-bpmn.js, the layout is not computed again: every symbol is
31
- // placed where the metrics (and so the SVG) have it, and the flows are drawn
32
- // with right angles only, entering their targets perpendicularly.
33
- //
34
- // 1) nodes cells → BPMN shapes, or placeholders that flows pass through
35
- // 2) flows con_list, followed through placeholders from shape to shape
36
- // 3) route right-angled waypoints, bending where the placeholders are
37
- // 4) xml process and diagram interchange
38
- //
39
-
40
- // the svg rows (geometry.row apart) are spread to ROW here, so that tasks have
41
- // the bpmn-js default height (rows are vertical in lr as well)
42
- const SYM = 30; // symbol size
43
- const TASK_H = 80; // task height, as bpmn-js; its icon is in the top left corner, so one line of text stays below it
44
- const ROW = TASK_H + 10; // row distance, the gap stays as in the svg
45
- const GAP = 10; // space between a task and the next symbol
46
- const SPACE = 10; // extra space in front of every column, the svg is a bit tight for bpmn
47
- const PAD = 20; // tasks are this much wider on both sides, bpmn-js puts its text close to the border
48
- const BACK = 20; // flows that go around (loops) go back this far right of the target's line
49
-
50
- // cpee types → BPMN element (kind) and event definition (def), or placeholder.
51
- // Tasks, and all types not listed, get their kind from the subtype
52
- const TYPE_MAP = {
53
- description: { kind: "startEvent" },
54
- start_event: { kind: "startEvent", def: "message" },
55
- event_start: { kind: "startEvent", def: "signal" }, // the start of a signal branch
56
- end: { kind: "endEvent" },
57
- end_event: { kind: "endEvent", def: "message" },
58
- event_end: { kind: "endEvent", def: "terminate" },
59
- terminate: { kind: "endEvent", def: "terminate" },
60
- call: { task: true },
61
- callmanipulate: { task: true },
62
- manipulate: { task: true },
63
- loop_head: { kind: "exclusiveGateway" },
64
- loop_tail: { kind: "exclusiveGateway" },
65
- loop_finish: { kind: "exclusiveGateway" },
66
- loop_tail_pre: { kind: "exclusiveGateway" }, // presetlr: pre_test loops
67
- loop_finish_pre: { kind: "exclusiveGateway" },
68
- parallel_start: { kind: "parallelGateway" },
69
- parallel_simple: { kind: "parallelGateway" },
70
- parallel_complex: { kind: "complexGateway" },
71
- parallel_eventbased_parallel: { kind: "complexGateway" },
72
- parallel_branch_event: { kind: "intermediateThrowEvent", def: "signal" },
73
- parallel_branch_event_rev: { kind: "intermediateThrowEvent", def: "signal" },
74
- parallel_branch_normal: { placeholder: "pass" },
75
- choose_inclusive: { kind: "inclusiveGateway" },
76
- choose_inclusive_finish: { kind: "inclusiveGateway" },
77
- choose_exclusive: { kind: "exclusiveGateway" },
78
- choose_exclusive_finish: { kind: "exclusiveGateway" },
79
- alternative: { placeholder: "case" }, // its label names the flow
80
- otherwise: { placeholder: "default" }, // its label names the flow, without one the flow is the default
81
- stop: { placeholder: "pass" }
82
- };
83
- const TASK_SUBTYPES = { user: "userTask", service: "serviceTask", script: "scriptTask" };
84
- const EVENT_SUBTYPES = {
85
- timer: { kind: "intermediateCatchEvent", def: "timer" },
86
- message_receive: { kind: "intermediateCatchEvent", def: "message" },
87
- message_send: { kind: "intermediateThrowEvent", def: "message" }
88
- };
89
-
90
- const fmt = (n) => Number(n).toFixed(2).replace(/\.?0+$/, "");
91
- const key = (r, c) => r + "," + c;
92
- function xmlEscape(s = "") {
93
- return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
94
- }
95
- function xmlEventDef(def, id) {
96
- return def ? `<${def}EventDefinition id="${id}_def"/>` : "";
97
- }
98
- function xmlSignavioBg(color) { // Signavio: background color per shape
99
- return `<extensionElements><signavio:signavioMetaData metaKey="bgcolor" metaValue="${xmlEscape(color || "#ffffff")}"/></extensionElements>`;
100
- }
101
-
102
- // 1) nodes: kind is the BPMN element, or null for placeholders. Names are the
103
- // labels only, the svg has no room for more. x is where the symbol is drawn,
104
- // mid the middle of its row, labelBox where its label is, relative to the symbol
105
- function buildNodes(matrix, geometry) {
106
- const nodes = new Map();
107
- let n = 0;
108
- matrix.forEach((row, r) => (row || []).forEach((cell, c) => {
109
- if (!cell) return;
110
- const t = TYPE_MAP[cell.type] || { task: true };
111
- const node = { r, c, x: cell.x - geometry.shift + SPACE * c, mid: r * ROW + geometry.top + TASK_H / 2, width: cell.width, fill: cell.fill, id: "n" + (++n), kind: null, label: cell.label || null };
112
- const l = cell.label_box;
113
- if (l) node.labelBox = { dx: l.x - (cell.x - geometry.shift), dy: l.y - (geometry.top + r * geometry.row), w: l.width, h: l.height };
114
- if (!t.task) {
115
- Object.assign(node, t);
116
- } else { // the subtype comes from the endpoint's properties (cockpit only)
117
- const sub = typeof cell.subtype === "string" ? cell.subtype : "";
118
- const ev = sub.startsWith("event/") ? (EVENT_SUBTYPES[sub.split("/").slice(1).join("_")] || EVENT_SUBTYPES[sub.split("/")[1]] || { kind: "intermediateCatchEvent" }) : null;
119
- if (ev) {
120
- Object.assign(node, { kind: ev.kind, def: ev.def });
121
- } else {
122
- node.kind = sub == "marker/subprocess" ? "subProcess"
123
- : sub.startsWith("task/") ? (TASK_SUBTYPES[sub.split("/")[1]] || "serviceTask")
124
- : cell.type == "manipulate" ? "scriptTask" : "serviceTask";
125
- }
126
- }
127
- nodes.set(key(r, c), node);
128
- }));
129
- // every column after one with a task moves by the width tasks gain
130
- const taskCols = new Set([...nodes.values()].filter(isTask).map((n) => n.c));
131
- for (const n of nodes.values()) n.x += 2 * PAD * [...taskCols].filter((c) => c < n.c).length;
132
- return nodes;
133
- }
134
-
135
- // bounds as in the svg: tasks span their label and the row, everything else
136
- // is a symbol in the middle of the row
137
- function bounds(node) {
138
- const x = node.x;
139
- if (!node.kind) return { x: x + SYM / 2, y: node.mid, w: 0, h: 0 }; // placeholders are points
140
- if (isTask(node)) return { x, y: node.mid - TASK_H / 2, w: Math.max(SYM, node.width - GAP) + 2 * PAD, h: TASK_H };
141
- return { x, y: node.mid - SYM / 2, w: SYM, h: SYM };
142
- }
143
- const isTask = (node) => /Task$|^subProcess$/.test(node.kind);
144
-
145
- // labels of events, gateways and placeholders are where the svg shows them,
146
- // relative to their symbol. Labels the svg does not show have no bounds
147
- function labelBounds(node) {
148
- const l = node.labelBox;
149
- return l ? { x: node.x + l.dx, y: node.mid - SYM / 2 + l.dy, w: l.w, h: l.h } : null;
150
- }
151
-
152
- // 2) flows from shape to shape, following con_list through placeholders
153
- function buildFlows(nodes, conlist) {
154
- const out = new Map();
155
- for (const e of conlist) {
156
- const f = key(e.from.row, e.from.col), t = key(e.to.row, e.to.col);
157
- if (!nodes.has(f) || !nodes.has(t)) throw new Error("bpmn2_convert: con_list connects an empty cell, " + f + " -> " + t);
158
- if (!out.has(f)) out.set(f, []);
159
- out.get(f).push(t);
160
- }
161
- const flows = [];
162
- const seen = new Set();
163
- for (const [k, src] of nodes) {
164
- if (!src.kind) continue;
165
- const walk = (from, via, anchor, visited) => {
166
- for (const t of out.get(from) || []) {
167
- const n = nodes.get(t);
168
- if (n.kind) {
169
- const sig = src.id + ">" + n.id;
170
- if (seen.has(sig)) continue;
171
- seen.add(sig);
172
- flows.push({ src, dst: n, via, anchor });
173
- } else if (!visited.has(t)) {
174
- visited.add(t);
175
- walk(t, via.concat([n]), n.placeholder != "pass" ? n : anchor, visited);
176
- }
177
- }
178
- };
179
- walk(k, [], null, new Set([k]));
180
- }
181
- for (const f of flows) {
182
- if (!f.anchor) continue;
183
- if (f.anchor.label) f.name = f.anchor.label;
184
- else if (f.anchor.placeholder == "default" && f.src.kind == "exclusiveGateway") f.isDefault = true;
185
- }
186
- return flows;
187
- }
188
-
189
- // 3) right angles only. a is the position along the flow, c across it
190
- function route(flow, lr, nodes) {
191
- const P = (a, c) => lr ? { x: a, y: c } : { x: c, y: a };
192
- const box = (n) => {
193
- const b = bounds(n);
194
- const s = { x: n.kind ? b.x + SYM / 2 : b.x, y: n.mid }; // the symbol, not the label
195
- const next = n.mid + ROW / 2; // between this row and the next
196
- return lr ? { n, a: s.x, c: s.y, a0: b.x, a1: b.x + b.w, c0: b.y, c1: b.y + b.h, turn: GAP / 2 }
197
- : { n, a: s.y, c: s.x, a0: b.y, a1: b.y + b.h, c0: b.x, c1: b.x + b.w, turn: next - (b.y + b.h) };
198
- };
199
- const shapes = [...nodes.values()].filter((n) => n.kind).map(box);
200
- const blocking = (c, from, to, except) => shapes.filter((b) => !except.includes(b.n) && b.c0 <= c && c <= b.c1 && b.a1 > Math.min(from, to) && b.a0 < Math.max(from, to));
201
- // a leg follows its own direction (dir), forwards or backwards along the flow
202
- const leg = (s, d) => {
203
- const dA = d.a - s.a, dC = d.c - s.c, dir = dA < 0 ? -1 : 1, except = [s.n, d.n];
204
- const out = dir > 0 ? s.a1 : s.a0, into = dir > 0 ? d.a0 : d.a1; // the sides facing each other
205
- if (Math.abs(dA) < 0.5) return dC > 0 ? [P(s.a, s.c1), P(d.a, d.c0)] : [P(s.a, s.c0), P(d.a, d.c1)]; // straight across
206
- if (Math.abs(dC) < 0.5 && !blocking(s.c, s.a, d.a, except).length) return [P(out, s.c), P(into, d.c)]; // straight along
207
- if (dC > 0 && !blocking(d.c, s.a, d.a, except).length) return [P(s.a, s.c1), P(s.a, d.c), P(into, d.c)]; // branch out: across, then along into the target
208
- if (dC < 0 && !blocking(s.c, s.a, d.a, except).length) return [P(out, s.c), P(d.a, s.c), P(d.a, d.c1)]; // join: along, then across into the target
209
- // shapes in the way (e.g. the content of a loop): leave on the far side, turn,
210
- // and go back parallel to the target's line, BACK beside it on the right (or
211
- // beside what is in the way). Symbols are entered at 45 degrees
212
- const far = dir > 0 ? s.a0 : s.a1, turn = far - dir * s.turn;
213
- const inway = blocking(d.c + BACK, turn, into, except);
214
- const lane = inway.length ? Math.max(...inway.map((b) => b.c1)) + BACK : d.c + BACK;
215
- if (d.n.kind && !isTask(d.n)) {
216
- const edge = /Gateway$/.test(d.n.kind) ? SYM / 4 : SYM / 2 / Math.SQRT2; // the border at 45 degrees: diamond or circle
217
- return [P(far, s.c), P(turn, s.c), P(turn, lane), P(d.a - dir * (lane - d.c), lane), P(d.a - dir * edge, d.c + edge)];
218
- }
219
- const end = lane <= d.c1 ? [P(into, lane)] : [P(d.a, lane), P(d.a, d.c1)];
220
- return [P(far, s.c), P(turn, s.c), P(turn, lane)].concat(end);
221
- };
222
- // source and target on one line, along or across the flow: straight, unless
223
- // another shape is in the way (e.g. the content of a loop)
224
- const s = box(flow.src), d = box(flow.dst), except = [flow.src, flow.dst];
225
- const across = shapes.some((b) => !except.includes(b.n) && b.a0 <= s.a && s.a <= b.a1 && b.c1 > Math.min(s.c, d.c) && b.c0 < Math.max(s.c, d.c));
226
- if (flow.src !== flow.dst) {
227
- if (Math.abs(d.c - s.c) < 0.5 && !blocking(s.c, s.a, d.a, except).length) return d.a > s.a ? [P(s.a1, s.c), P(d.a0, d.c)] : [P(s.a0, s.c), P(d.a1, d.c)];
228
- if (Math.abs(d.a - s.a) < 0.5 && !across) return d.c > s.c ? [P(s.a, s.c1), P(d.a, d.c0)] : [P(s.a, s.c0), P(d.a, d.c1)];
229
- }
230
-
231
- const stops = [flow.src].concat(flow.via, [flow.dst]).map(box);
232
- let pts = [];
233
- for (let i = 0; i < stops.length - 1; i++) pts = pts.concat(leg(stops[i], stops[i + 1]));
234
- // drop repeated points and points in the middle of a straight line
235
- pts = pts.filter((p, i) => i == 0 || p.x != pts[i - 1].x || p.y != pts[i - 1].y);
236
- return pts.filter((p, i) => {
237
- if (i == 0 || i == pts.length - 1) return true;
238
- const a = pts[i - 1], b = pts[i + 1];
239
- return !((a.x == p.x && p.x == b.x) || (a.y == p.y && p.y == b.y));
240
- });
241
- }
242
-
243
- // 4) xml
244
- function generateXML(nodes, flows, lr) {
245
- const shapes = [...nodes.values()].filter((n) => n.kind);
246
- flows.forEach((f, i) => { f.id = "e" + (i + 1); });
247
- const defaults = new Map(flows.filter((f) => f.isDefault).map((f) => [f.src.id, f.id]));
248
- const nameAttr = (s) => s ? ` name="${xmlEscape(s)}"` : "";
249
-
250
- const proc = shapes.map((s) => {
251
- const def = defaults.has(s.id) ? ` default="${defaults.get(s.id)}"` : "";
252
- return ` <${s.kind} id="${s.id}"${nameAttr(s.label)}${def}>${xmlSignavioBg(s.fill)}${xmlEventDef(s.def, s.id)}</${s.kind}>`;
253
- }).concat(flows.map((f) =>
254
- ` <sequenceFlow id="${f.id}" sourceRef="${f.src.id}" targetRef="${f.dst.id}"${nameAttr(f.name)}/>`
255
- )).join("\n");
256
-
257
- const xmlBounds = (b, indent) => `${indent}<omgdc:Bounds x="${fmt(b.x)}" y="${fmt(b.y)}" width="${fmt(b.w)}" height="${fmt(b.h)}"/>\n`;
258
- const xmlLabel = (b) => b ? ` <bpmndi:BPMNLabel>\n${xmlBounds(b, " ")} </bpmndi:BPMNLabel>\n` : "";
259
- const di = shapes.map((s) => {
260
- const marker = /Gateway$/.test(s.kind) ? ' isMarkerVisible="true"' : "";
261
- return ` <bpmndi:BPMNShape id="${s.id}_gui" bpmnElement="${s.id}"${marker}>\n` +
262
- xmlBounds(bounds(s), " ") +
263
- xmlLabel(s.label && !isTask(s) ? labelBounds(s) : null) +
264
- ` </bpmndi:BPMNShape>`;
265
- }).concat(flows.map((f) =>
266
- ` <bpmndi:BPMNEdge id="${f.id}_gui" bpmnElement="${f.id}">\n` +
267
- route(f, lr, nodes).map((p) => ` <omgdi:waypoint x="${fmt(p.x)}" y="${fmt(p.y)}"/>`).join("\n") + "\n" +
268
- xmlLabel(f.name ? labelBounds(f.anchor) : null) +
269
- ` </bpmndi:BPMNEdge>`
270
- )).join("\n");
271
-
272
- return `<?xml version="1.0" encoding="UTF-8"?>
273
- <definitions
274
- xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
275
- xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
276
- xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI"
277
- xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC"
278
- xmlns:signavio="http://www.signavio.com"
279
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
280
- targetNamespace="https://example.com/bpmn"
281
- >
282
- <process id="process1" isExecutable="false">
283
- ${proc}
284
- </process>
285
- <bpmndi:BPMNDiagram id="diagram1">
286
- <bpmndi:BPMNPlane id="plane1" bpmnElement="process1">
287
- ${di}
288
- </bpmndi:BPMNPlane>
289
- </bpmndi:BPMNDiagram>
290
- </definitions>`;
291
- }
292
-
293
- // returns the BPMN XML as a string
294
- function bpmn2_convert(dpm, dcl, lr, geometry) {
295
- if (!Array.isArray(dpm) || !Array.isArray(dcl) || typeof lr !== "boolean" || !geometry) throw new Error("bpmn2_convert: needs pos_matrix, con_list, lr and geometry of get_svg_metrics");
296
- const nodes = buildNodes(dpm, geometry);
297
- return generateXML(nodes, buildFlows(nodes, dcl), lr);
298
- }
299
-
300
- if (typeof window !== "undefined") {
301
- window.bpmn2_convert = bpmn2_convert;
302
- }