@trpc/server 11.0.0-rc.643 → 11.0.0-rc.648

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 (107) hide show
  1. package/dist/adapters/aws-lambda/index.js +1 -1
  2. package/dist/adapters/aws-lambda/index.mjs +1 -1
  3. package/dist/adapters/express.js +1 -1
  4. package/dist/adapters/express.mjs +1 -1
  5. package/dist/adapters/fastify/fastifyRequestHandler.js +1 -1
  6. package/dist/adapters/fastify/fastifyRequestHandler.mjs +1 -1
  7. package/dist/adapters/fetch/fetchRequestHandler.js +1 -1
  8. package/dist/adapters/fetch/fetchRequestHandler.mjs +1 -1
  9. package/dist/adapters/next-app-dir/nextAppDirCaller.js +1 -1
  10. package/dist/adapters/next-app-dir/nextAppDirCaller.mjs +1 -1
  11. package/dist/adapters/next-app-dir/notFound.js +1 -1
  12. package/dist/adapters/next-app-dir/notFound.mjs +1 -1
  13. package/dist/adapters/next-app-dir/redirect.js +15 -3
  14. package/dist/adapters/next-app-dir/redirect.mjs +14 -2
  15. package/dist/adapters/next.js +1 -1
  16. package/dist/adapters/next.mjs +1 -1
  17. package/dist/adapters/node-http/incomingMessageToRequest.js +1 -1
  18. package/dist/adapters/node-http/incomingMessageToRequest.mjs +1 -1
  19. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +1 -1
  20. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +1 -1
  21. package/dist/adapters/node-http/writeResponse.d.ts.map +1 -1
  22. package/dist/adapters/node-http/writeResponse.js +3 -1
  23. package/dist/adapters/node-http/writeResponse.mjs +3 -1
  24. package/dist/adapters/standalone.js +1 -1
  25. package/dist/adapters/standalone.mjs +1 -1
  26. package/dist/adapters/ws.d.ts.map +1 -1
  27. package/dist/adapters/ws.js +145 -66
  28. package/dist/adapters/ws.mjs +145 -66
  29. package/dist/bundle-analysis.json +194 -201
  30. package/dist/http.js +1 -1
  31. package/dist/http.mjs +1 -1
  32. package/dist/index.js +1 -1
  33. package/dist/index.mjs +1 -1
  34. package/dist/node_modules/.pnpm/@rollup_plugin-typescript@12.1.1_rollup@4.27.4_tslib@2.8.1_typescript@5.6.2/node_modules/tslib/tslib.es6.js +73 -0
  35. package/dist/observable/observable.d.ts +1 -1
  36. package/dist/observable/observable.d.ts.map +1 -1
  37. package/dist/observable/observable.js +16 -4
  38. package/dist/observable/observable.mjs +16 -4
  39. package/dist/rpc.js +1 -1
  40. package/dist/rpc.mjs +1 -1
  41. package/dist/shared.js +1 -1
  42. package/dist/shared.mjs +1 -1
  43. package/dist/unstable-core-do-not-import/error/TRPCError.d.ts +1 -1
  44. package/dist/unstable-core-do-not-import/error/TRPCError.js +14 -2
  45. package/dist/unstable-core-do-not-import/error/TRPCError.mjs +13 -1
  46. package/dist/unstable-core-do-not-import/http/resolveResponse.d.ts.map +1 -1
  47. package/dist/unstable-core-do-not-import/http/resolveResponse.js +7 -18
  48. package/dist/unstable-core-do-not-import/http/resolveResponse.mjs +8 -19
  49. package/dist/unstable-core-do-not-import/stream/jsonl.d.ts +15 -4
  50. package/dist/unstable-core-do-not-import/stream/jsonl.d.ts.map +1 -1
  51. package/dist/unstable-core-do-not-import/stream/jsonl.js +430 -291
  52. package/dist/unstable-core-do-not-import/stream/jsonl.mjs +428 -289
  53. package/dist/unstable-core-do-not-import/stream/sse.d.ts +1 -1
  54. package/dist/unstable-core-do-not-import/stream/sse.d.ts.map +1 -1
  55. package/dist/unstable-core-do-not-import/stream/sse.js +183 -122
  56. package/dist/unstable-core-do-not-import/stream/sse.mjs +183 -122
  57. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.d.ts +1 -0
  58. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.d.ts.map +1 -1
  59. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.js +103 -10
  60. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.mjs +104 -12
  61. package/dist/unstable-core-do-not-import/stream/utils/disposable.d.ts +17 -0
  62. package/dist/unstable-core-do-not-import/stream/utils/disposable.d.ts.map +1 -0
  63. package/dist/unstable-core-do-not-import/stream/utils/disposable.js +44 -0
  64. package/dist/unstable-core-do-not-import/stream/utils/disposable.mjs +41 -0
  65. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.d.ts +8 -0
  66. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.d.ts.map +1 -0
  67. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.js +25 -0
  68. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.mjs +23 -0
  69. package/dist/unstable-core-do-not-import/stream/utils/timerResource.d.ts +1 -2
  70. package/dist/unstable-core-do-not-import/stream/utils/timerResource.d.ts.map +1 -1
  71. package/dist/unstable-core-do-not-import/stream/utils/timerResource.js +8 -10
  72. package/dist/unstable-core-do-not-import/stream/utils/timerResource.mjs +8 -10
  73. package/dist/unstable-core-do-not-import/stream/utils/withPing.d.ts.map +1 -1
  74. package/dist/unstable-core-do-not-import/stream/utils/withPing.js +113 -24
  75. package/dist/unstable-core-do-not-import/stream/utils/withPing.mjs +114 -25
  76. package/dist/unstable-core-do-not-import/transformer.d.ts +1 -1
  77. package/dist/unstable-core-do-not-import.d.ts +1 -0
  78. package/dist/unstable-core-do-not-import.d.ts.map +1 -1
  79. package/dist/unstable-core-do-not-import.js +3 -0
  80. package/dist/unstable-core-do-not-import.mjs +1 -0
  81. package/dist/vendor/unpromise/unpromise.js +17 -6
  82. package/dist/vendor/unpromise/unpromise.mjs +13 -2
  83. package/package.json +2 -3
  84. package/src/adapters/node-http/writeResponse.ts +3 -0
  85. package/src/adapters/ws.ts +8 -9
  86. package/src/observable/observable.ts +17 -2
  87. package/src/unstable-core-do-not-import/http/resolveResponse.ts +8 -21
  88. package/src/unstable-core-do-not-import/stream/jsonl.ts +236 -216
  89. package/src/unstable-core-do-not-import/stream/sse.ts +112 -132
  90. package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +50 -48
  91. package/src/unstable-core-do-not-import/stream/utils/disposable.ts +52 -0
  92. package/src/unstable-core-do-not-import/stream/utils/readableStreamFrom.ts +28 -0
  93. package/src/unstable-core-do-not-import/stream/utils/timerResource.ts +17 -15
  94. package/src/unstable-core-do-not-import/stream/utils/withPing.ts +18 -19
  95. package/src/unstable-core-do-not-import.ts +1 -0
  96. package/dist/node_modules/.pnpm/@swc_helpers@0.5.13/node_modules/@swc/helpers/esm/_define_property.js +0 -11
  97. package/dist/node_modules/.pnpm/@swc_helpers@0.5.13/node_modules/@swc/helpers/esm/_define_property.mjs +0 -9
  98. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.d.ts +0 -9
  99. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.d.ts.map +0 -1
  100. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.js +0 -25
  101. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.mjs +0 -23
  102. package/dist/unstable-core-do-not-import/stream/utils/withRefCount.d.ts +0 -17
  103. package/dist/unstable-core-do-not-import/stream/utils/withRefCount.d.ts.map +0 -1
  104. package/dist/unstable-core-do-not-import/stream/utils/withRefCount.js +0 -59
  105. package/dist/unstable-core-do-not-import/stream/utils/withRefCount.mjs +0 -57
  106. package/src/unstable-core-do-not-import/stream/utils/createReadableStream.ts +0 -25
  107. package/src/unstable-core-do-not-import/stream/utils/withRefCount.ts +0 -93
@@ -4,9 +4,76 @@ import { isAbortError } from '../http/isAbortError.mjs';
4
4
  import { run, identity } from '../utils.mjs';
5
5
  import { isTrackedEnvelope } from './tracked.mjs';
6
6
  import { takeWithGrace, withMaxDuration } from './utils/asyncIterable.mjs';
7
- import { createReadableStream } from './utils/createReadableStream.mjs';
7
+ import { makeAsyncResource } from './utils/disposable.mjs';
8
+ import { readableStreamFrom } from './utils/readableStreamFrom.mjs';
9
+ import { timerResource, disposablePromiseTimerResult } from './utils/timerResource.mjs';
8
10
  import { withPing, PING_SYM } from './utils/withPing.mjs';
9
11
 
12
+ function _ts_add_disposable_resource(env, value, async) {
13
+ if (value !== null && value !== void 0) {
14
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
15
+ var dispose, inner;
16
+ if (async) {
17
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
18
+ dispose = value[Symbol.asyncDispose];
19
+ }
20
+ if (dispose === void 0) {
21
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
22
+ dispose = value[Symbol.dispose];
23
+ if (async) inner = dispose;
24
+ }
25
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
26
+ if (inner) dispose = function() {
27
+ try {
28
+ inner.call(this);
29
+ } catch (e) {
30
+ return Promise.reject(e);
31
+ }
32
+ };
33
+ env.stack.push({
34
+ value: value,
35
+ dispose: dispose,
36
+ async: async
37
+ });
38
+ } else if (async) {
39
+ env.stack.push({
40
+ async: true
41
+ });
42
+ }
43
+ return value;
44
+ }
45
+ function _ts_dispose_resources(env) {
46
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
47
+ var e = new Error(message);
48
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
49
+ };
50
+ return (_ts_dispose_resources = function _ts_dispose_resources(env) {
51
+ function fail(e) {
52
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
53
+ env.hasError = true;
54
+ }
55
+ var r, s = 0;
56
+ function next() {
57
+ while(r = env.stack.pop()){
58
+ try {
59
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
60
+ if (r.dispose) {
61
+ var result = r.dispose.call(r.value);
62
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
63
+ fail(e);
64
+ return next();
65
+ });
66
+ } else s |= 1;
67
+ } catch (e) {
68
+ fail(e);
69
+ }
70
+ }
71
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
72
+ if (env.hasError) throw env.error;
73
+ }
74
+ return next();
75
+ })(env);
76
+ }
10
77
  const PING_EVENT = 'ping';
11
78
  const SERIALIZED_ERROR_EVENT = 'serialized-error';
12
79
  const CONNECTED_EVENT = 'connected';
@@ -14,21 +81,20 @@ const CONNECTED_EVENT = 'connected';
14
81
  *
15
82
  * @see https://html.spec.whatwg.org/multipage/server-sent-events.html
16
83
  */ function sseStreamProducer(opts) {
17
- const stream = createReadableStream();
18
84
  const { serialize = identity } = opts;
19
85
  const ping = {
20
86
  enabled: opts.ping?.enabled ?? false,
21
87
  intervalMs: opts.ping?.intervalMs ?? 1000
22
88
  };
23
89
  const client = opts.client ?? {};
24
- stream.controller.enqueue({
25
- event: CONNECTED_EVENT,
26
- data: JSON.stringify(client)
27
- });
28
90
  if (ping.enabled && client.reconnectAfterInactivityMs && ping.intervalMs > client.reconnectAfterInactivityMs) {
29
91
  throw new Error(`Ping interval must be less than client reconnect interval to prevent unnecessary reconnection - ping.intervalMs: ${ping.intervalMs} client.reconnectAfterInactivityMs: ${client.reconnectAfterInactivityMs}`);
30
92
  }
31
- run(async ()=>{
93
+ async function* generator() {
94
+ yield {
95
+ event: CONNECTED_EVENT,
96
+ data: JSON.stringify(client)
97
+ };
32
98
  let iterable = opts.data;
33
99
  if (opts.emitAndEndImmediately) {
34
100
  iterable = takeWithGrace(iterable, {
@@ -44,60 +110,53 @@ const CONNECTED_EVENT = 'connected';
44
110
  if (ping.enabled && ping.intervalMs !== Infinity && ping.intervalMs > 0) {
45
111
  iterable = withPing(iterable, ping.intervalMs);
46
112
  }
47
- try {
48
- // We need those declarations outside the loop for garbage collection reasons. If they were
49
- // declared inside, they would not be freed until the next value is present.
50
- let value;
51
- let chunk;
52
- for await (value of iterable){
53
- if (value === PING_SYM) {
54
- stream.controller.enqueue({
55
- event: PING_EVENT,
56
- data: ''
57
- });
58
- continue;
59
- }
60
- chunk = isTrackedEnvelope(value) ? {
61
- id: value[0],
62
- data: value[1]
63
- } : {
64
- data: value
113
+ // We need those declarations outside the loop for garbage collection reasons. If they were
114
+ // declared inside, they would not be freed until the next value is present.
115
+ let value;
116
+ let chunk;
117
+ for await (value of iterable){
118
+ if (value === PING_SYM) {
119
+ yield {
120
+ event: PING_EVENT,
121
+ data: ''
65
122
  };
66
- if ('data' in chunk) {
67
- chunk.data = JSON.stringify(serialize(chunk.data));
68
- }
69
- stream.controller.enqueue(chunk);
70
- // free up references for garbage collection
71
- value = null;
72
- chunk = null;
123
+ continue;
73
124
  }
74
- } catch (err) {
75
- if (isAbortError(err)) {
125
+ chunk = isTrackedEnvelope(value) ? {
126
+ id: value[0],
127
+ data: value[1]
128
+ } : {
129
+ data: value
130
+ };
131
+ chunk.data = JSON.stringify(serialize(chunk.data));
132
+ yield chunk;
133
+ // free up references for garbage collection
134
+ value = null;
135
+ chunk = null;
136
+ }
137
+ }
138
+ async function* generatorWithErrorHandling() {
139
+ try {
140
+ yield* generator();
141
+ } catch (cause) {
142
+ if (isAbortError(cause)) {
76
143
  // ignore abort errors, send any other errors
77
144
  return;
78
145
  }
79
146
  // `err` must be caused by `opts.data`, `JSON.stringify` or `serialize`.
80
147
  // So, a user error in any case.
81
- const error = getTRPCErrorFromUnknown(err);
148
+ const error = getTRPCErrorFromUnknown(cause);
82
149
  const data = opts.formatError?.({
83
150
  error
84
151
  }) ?? null;
85
- stream.controller.enqueue({
152
+ yield {
86
153
  event: SERIALIZED_ERROR_EVENT,
87
154
  data: JSON.stringify(serialize(data))
88
- });
89
- } finally{
90
- try {
91
- stream.controller.close();
92
- } catch {
93
- // ignore
94
- }
155
+ };
95
156
  }
96
- }).catch((err)=>{
97
- // should not be reached; just in case...
98
- stream.controller.error(err);
99
- });
100
- return stream.readable.pipeThrough(new TransformStream({
157
+ }
158
+ const stream = readableStreamFrom(generatorWithErrorHandling());
159
+ return stream.pipeThrough(new TransformStream({
101
160
  transform (chunk, controller) {
102
161
  if ('event' in chunk) {
103
162
  controller.enqueue(`event: ${chunk.event}\n`);
@@ -116,26 +175,28 @@ const CONNECTED_EVENT = 'connected';
116
175
  }));
117
176
  }
118
177
  async function withTimeout(opts) {
119
- let timeoutId;
120
- const timeoutPromise = new Promise((resolve)=>{
121
- timeoutId = setTimeout(()=>{
122
- resolve(null);
123
- }, opts.timeoutMs);
124
- });
125
- let res;
178
+ const env = {
179
+ stack: [],
180
+ error: void 0,
181
+ hasError: false
182
+ };
126
183
  try {
127
- res = await Unpromise.race([
184
+ const timeoutPromise = _ts_add_disposable_resource(env, timerResource(opts.timeoutMs), false);
185
+ ;
186
+ const res = await Unpromise.race([
128
187
  opts.promise,
129
- timeoutPromise
188
+ timeoutPromise.start()
130
189
  ]);
190
+ if (res === disposablePromiseTimerResult) {
191
+ return await opts.onTimeout();
192
+ }
193
+ return res;
194
+ } catch (e) {
195
+ env.error = e;
196
+ env.hasError = true;
131
197
  } finally{
132
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
133
- clearTimeout(timeoutId);
198
+ _ts_dispose_resources(env);
134
199
  }
135
- if (res === null) {
136
- return await opts.onTimeout();
137
- }
138
- return res;
139
200
  }
140
201
  /**
141
202
  * @see https://html.spec.whatwg.org/multipage/server-sent-events.html
@@ -220,69 +281,69 @@ async function withTimeout(opts) {
220
281
  _es?.close();
221
282
  }
222
283
  });
223
- const getNewStreamAndReader = ()=>{
224
- const stream = createStream();
225
- const reader = stream.getReader();
226
- return {
227
- reader,
228
- cancel: ()=>{
229
- reader.releaseLock();
230
- return stream.cancel();
284
+ const getStreamResource = ()=>{
285
+ let stream = createStream();
286
+ let reader = stream.getReader();
287
+ async function dispose() {
288
+ await reader.cancel();
289
+ _es = null;
290
+ }
291
+ return makeAsyncResource({
292
+ read () {
293
+ return reader.read();
294
+ },
295
+ async recreate () {
296
+ await dispose();
297
+ stream = createStream();
298
+ reader = stream.getReader();
231
299
  }
232
- };
300
+ }, dispose);
233
301
  };
234
- return {
235
- [Symbol.asyncIterator] () {
236
- let stream = getNewStreamAndReader();
237
- const iterator = {
238
- async next () {
239
- let promise = stream.reader.read();
240
- const timeoutMs = clientOptions.reconnectAfterInactivityMs;
241
- if (timeoutMs) {
242
- promise = withTimeout({
243
- promise,
244
- timeoutMs,
245
- onTimeout: async ()=>{
246
- // Close and release old reader
247
- await stream.cancel();
248
- // Create new reader
249
- stream = getNewStreamAndReader();
250
- return {
251
- value: {
252
- type: 'timeout',
253
- ms: timeoutMs,
254
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
255
- eventSource: _es
256
- },
257
- done: false
258
- };
259
- }
260
- });
261
- }
262
- const result = await promise;
263
- // console.debug('result', result, 'done', result.done);
264
- if (result.done) {
265
- return {
266
- value: result.value,
267
- done: true
268
- };
269
- }
270
- return {
271
- value: result.value,
272
- done: false
273
- };
274
- },
275
- async return () {
276
- await stream.cancel();
277
- return {
278
- value: undefined,
279
- done: true
280
- };
302
+ return run(async function*() {
303
+ const env = {
304
+ stack: [],
305
+ error: void 0,
306
+ hasError: false
307
+ };
308
+ try {
309
+ const stream = _ts_add_disposable_resource(env, getStreamResource(), true);
310
+ ;
311
+ while(true){
312
+ let promise = stream.read();
313
+ const timeoutMs = clientOptions.reconnectAfterInactivityMs;
314
+ if (timeoutMs) {
315
+ promise = withTimeout({
316
+ promise,
317
+ timeoutMs,
318
+ onTimeout: async ()=>{
319
+ const res = {
320
+ value: {
321
+ type: 'timeout',
322
+ ms: timeoutMs,
323
+ eventSource: _es
324
+ },
325
+ done: false
326
+ };
327
+ // Close and release old reader
328
+ await stream.recreate();
329
+ return res;
330
+ }
331
+ });
281
332
  }
282
- };
283
- return iterator;
333
+ const result = await promise;
334
+ if (result.done) {
335
+ return result.value;
336
+ }
337
+ yield result.value;
338
+ }
339
+ } catch (e) {
340
+ env.error = e;
341
+ env.hasError = true;
342
+ } finally{
343
+ const result = _ts_dispose_resources(env);
344
+ if (result) await result;
284
345
  }
285
- };
346
+ });
286
347
  }
287
348
  const sseHeaders = {
288
349
  'Content-Type': 'text/event-stream',
@@ -1,3 +1,4 @@
1
+ export declare function iteratorResource<TYield, TReturn, TNext>(iterable: AsyncIterable<TYield, TReturn, TNext>): AsyncIterator<TYield, TReturn, TNext> & AsyncDisposable;
1
2
  /**
2
3
  * Derives a new {@link AsyncGenerator} based on {@link iterable}, that automatically stops after the specified duration.
3
4
  */
@@ -1 +1 @@
1
- {"version":3,"file":"asyncIterable.d.ts","sourceRoot":"","sources":["../../../../src/unstable-core-do-not-import/stream/utils/asyncIterable.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,wBAAuB,eAAe,CAAC,CAAC,EACtC,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,EAC1B,IAAI,EAAE;IAAE,aAAa,EAAE,MAAM,CAAA;CAAE,GAC9B,cAAc,CAAC,CAAC,CAAC,CA8BnB;AAED;;;;GAIG;AACH,wBAAuB,aAAa,CAAC,CAAC,EACpC,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,EAC1B,IAAI,EAAE;IACJ,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;CACvB,GACA,cAAc,CAAC,CAAC,CAAC,CAkCnB"}
1
+ {"version":3,"file":"asyncIterable.d.ts","sourceRoot":"","sources":["../../../../src/unstable-core-do-not-import/stream/utils/asyncIterable.ts"],"names":[],"mappings":"AAIA,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EACrD,QAAQ,EAAE,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,GAC9C,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,GAAG,eAAe,CAMzD;AACD;;GAEG;AACH,wBAAuB,eAAe,CAAC,CAAC,EACtC,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,EAC1B,IAAI,EAAE;IAAE,aAAa,EAAE,MAAM,CAAA;CAAE,GAC9B,cAAc,CAAC,CAAC,CAAC,CAyBnB;AAED;;;;GAIG;AACH,wBAAuB,aAAa,CAAC,CAAC,EACpC,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,EAC1B,IAAI,EAAE;IACJ,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;CACvB,GACA,cAAc,CAAC,CAAC,CAAC,CA+BnB"}
@@ -1,14 +1,93 @@
1
1
  'use strict';
2
2
 
3
3
  var unpromise = require('../../../vendor/unpromise/unpromise.js');
4
+ var disposable = require('./disposable.js');
4
5
  var timerResource = require('./timerResource.js');
5
6
 
7
+ function _ts_add_disposable_resource(env, value, async) {
8
+ if (value !== null && value !== void 0) {
9
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
10
+ var dispose, inner;
11
+ if (async) {
12
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
13
+ dispose = value[Symbol.asyncDispose];
14
+ }
15
+ if (dispose === void 0) {
16
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
17
+ dispose = value[Symbol.dispose];
18
+ if (async) inner = dispose;
19
+ }
20
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
21
+ if (inner) dispose = function() {
22
+ try {
23
+ inner.call(this);
24
+ } catch (e) {
25
+ return Promise.reject(e);
26
+ }
27
+ };
28
+ env.stack.push({
29
+ value: value,
30
+ dispose: dispose,
31
+ async: async
32
+ });
33
+ } else if (async) {
34
+ env.stack.push({
35
+ async: true
36
+ });
37
+ }
38
+ return value;
39
+ }
40
+ function _ts_dispose_resources(env) {
41
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
42
+ var e = new Error(message);
43
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
44
+ };
45
+ return (_ts_dispose_resources = function _ts_dispose_resources(env) {
46
+ function fail(e) {
47
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
48
+ env.hasError = true;
49
+ }
50
+ var r, s = 0;
51
+ function next() {
52
+ while(r = env.stack.pop()){
53
+ try {
54
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
55
+ if (r.dispose) {
56
+ var result = r.dispose.call(r.value);
57
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
58
+ fail(e);
59
+ return next();
60
+ });
61
+ } else s |= 1;
62
+ } catch (e) {
63
+ fail(e);
64
+ }
65
+ }
66
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
67
+ if (env.hasError) throw env.error;
68
+ }
69
+ return next();
70
+ })(env);
71
+ }
72
+ function iteratorResource(iterable) {
73
+ const iterator = iterable[Symbol.asyncIterator]();
74
+ return disposable.makeAsyncResource(iterator, async ()=>{
75
+ await iterator.return?.();
76
+ });
77
+ }
6
78
  /**
7
79
  * Derives a new {@link AsyncGenerator} based on {@link iterable}, that automatically stops after the specified duration.
8
80
  */ async function* withMaxDuration(iterable, opts) {
9
- const iterator = iterable[Symbol.asyncIterator]();
10
- const timer = timerResource.timerResource(opts.maxDurationMs);
81
+ const env = {
82
+ stack: [],
83
+ error: void 0,
84
+ hasError: false
85
+ };
11
86
  try {
87
+ const iterator = _ts_add_disposable_resource(env, iteratorResource(iterable), true);
88
+ ;
89
+ const timer = _ts_add_disposable_resource(env, timerResource.timerResource(opts.maxDurationMs), false);
90
+ ;
12
91
  const timerPromise = timer.start();
13
92
  // declaration outside the loop for garbage collection reasons
14
93
  let result;
@@ -29,10 +108,12 @@ var timerResource = require('./timerResource.js');
29
108
  // free up reference for garbage collection
30
109
  result = null;
31
110
  }
111
+ } catch (e) {
112
+ env.error = e;
113
+ env.hasError = true;
32
114
  } finally{
33
- // dispose timer
34
- // Shouldn't be needed, but build breaks with `using` keyword
35
- timer[Symbol.dispose]();
115
+ const result = _ts_dispose_resources(env);
116
+ if (result) await result;
36
117
  }
37
118
  }
38
119
  /**
@@ -40,11 +121,18 @@ var timerResource = require('./timerResource.js');
40
121
  * {@link count} values. Then, a grace period of {@link gracePeriodMs} is started in which further
41
122
  * values may still come through. After this period, the generator stops.
42
123
  */ async function* takeWithGrace(iterable, opts) {
43
- const iterator = iterable[Symbol.asyncIterator]();
44
- // declaration outside the loop for garbage collection reasons
45
- let result;
46
- const timer = timerResource.timerResource(opts.gracePeriodMs);
124
+ const env = {
125
+ stack: [],
126
+ error: void 0,
127
+ hasError: false
128
+ };
47
129
  try {
130
+ const iterator = _ts_add_disposable_resource(env, iteratorResource(iterable), true);
131
+ ;
132
+ // declaration outside the loop for garbage collection reasons
133
+ let result;
134
+ const timer = _ts_add_disposable_resource(env, timerResource.timerResource(opts.gracePeriodMs), false);
135
+ ;
48
136
  let count = opts.count;
49
137
  let timerPromise = new Promise(()=>{
50
138
  // never resolves
@@ -69,10 +157,15 @@ var timerResource = require('./timerResource.js');
69
157
  // free up reference for garbage collection
70
158
  result = null;
71
159
  }
160
+ } catch (e) {
161
+ env.error = e;
162
+ env.hasError = true;
72
163
  } finally{
73
- timer[Symbol.dispose]();
164
+ const result = _ts_dispose_resources(env);
165
+ if (result) await result;
74
166
  }
75
167
  }
76
168
 
169
+ exports.iteratorResource = iteratorResource;
77
170
  exports.takeWithGrace = takeWithGrace;
78
171
  exports.withMaxDuration = withMaxDuration;