@sidekickdb/resumable-stream 2.0.1 → 3.0.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.
@@ -1,15 +1,15 @@
1
1
 
2
- > @sidekickdb/resumable-stream@2.0.1 build /home/runner/work/sidekick/sidekick/client/packages/resumable-stream
2
+ > @sidekickdb/resumable-stream@3.0.0 build /home/runner/work/sidekick/sidekick/client/packages/resumable-stream
3
3
  > rm -rf dist; npm run build:tshy && npm run build:standalone && npm run check-exports
4
4
 
5
5
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
6
6
 
7
- > @sidekickdb/resumable-stream@2.0.1 build:tshy
7
+ > @sidekickdb/resumable-stream@3.0.0 build:tshy
8
8
  > tshy
9
9
 
10
10
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
11
11
 
12
- > @sidekickdb/resumable-stream@2.0.1 build:standalone
12
+ > @sidekickdb/resumable-stream@3.0.0 build:standalone
13
13
  > vite build
14
14
 
15
15
  vite v5.4.14 building for production...
@@ -17,16 +17,16 @@ transforming...
17
17
  ✓ 82 modules transformed.
18
18
  rendering chunks...
19
19
  computing gzip size...
20
- dist/standalone/index.umd.cjs 78.37 kB │ gzip: 24.84 kB
21
- dist/standalone/index.js 135.27 kB │ gzip: 36.29 kB
22
- ✓ built in 729ms
20
+ dist/standalone/index.umd.cjs 81.66 kB │ gzip: 26.01 kB
21
+ dist/standalone/index.js 140.18 kB │ gzip: 37.81 kB
22
+ ✓ built in 711ms
23
23
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
24
24
 
25
- > @sidekickdb/resumable-stream@2.0.1 check-exports
25
+ > @sidekickdb/resumable-stream@3.0.0 check-exports
26
26
  > attw --pack .
27
27
 
28
28
 
29
- @sidekickdb/resumable-stream v2.0.1
29
+ @sidekickdb/resumable-stream v3.0.0
30
30
 
31
31
  Build tools:
32
32
  - @arethetypeswrong/cli@^0.18.5
package/README.md CHANGED
@@ -12,7 +12,7 @@ SidekickDB's streams have no dependency on Redis and they never expire.
12
12
 
13
13
  ## Usage
14
14
 
15
- You can provide your `appId`, `adminToken` and `apiURI` as arguments to `createResumableStreamContext` or export `INSTANT_APP_ID`, `INSTANT_APP_ADMIN_TOKEN` and `INSTANT_API_URI`. The server URL is required: there is no default server.
15
+ You can provide your `appId`, `adminToken` and `apiURI` as arguments to `createResumableStreamContext` or export `SIDEKICK_APP_ID`, `SIDEKICK_APP_ADMIN_TOKEN` and `SIDEKICK_API_URI`. The server URL is required: there is no default server.
16
16
 
17
17
  ### Idempotent API
18
18
 
@@ -22,9 +22,9 @@ import { after } from 'next/server';
22
22
 
23
23
  const streamContext = createResumableStreamContext({
24
24
  waitUntil: after,
25
- appId: YOUR_INSTANT_APP_ID, // or export INSTANT_APP_ID
26
- adminToken: YOUR_INSTANT_APP_ADMIN_TOKEN, // or export INSTANT_APP_ADMIN_TOKEN
27
- apiURI: YOUR_SIDEKICK_SERVER_URL, // or export INSTANT_API_URI
25
+ appId: YOUR_SIDEKICK_APP_ID, // or export SIDEKICK_APP_ID
26
+ adminToken: YOUR_SIDEKICK_APP_ADMIN_TOKEN, // or export SIDEKICK_APP_ADMIN_TOKEN
27
+ apiURI: YOUR_SIDEKICK_SERVER_URL, // or export SIDEKICK_API_URI
28
28
  });
29
29
 
30
30
  export async function GET(
@@ -54,9 +54,9 @@ import { after } from 'next/server';
54
54
 
55
55
  const streamContext = createResumableStreamContext({
56
56
  waitUntil: after,
57
- appId: YOUR_INSTANT_APP_ID, // or export INSTANT_APP_ID
58
- adminToken: YOUR_INSTANT_APP_ADMIN_TOKEN, // or export INSTANT_APP_ADMIN_TOKEN
59
- apiURI: YOUR_SIDEKICK_SERVER_URL, // or export INSTANT_API_URI
57
+ appId: YOUR_SIDEKICK_APP_ID, // or export SIDEKICK_APP_ID
58
+ adminToken: YOUR_SIDEKICK_APP_ADMIN_TOKEN, // or export SIDEKICK_APP_ADMIN_TOKEN
59
+ apiURI: YOUR_SIDEKICK_SERVER_URL, // or export SIDEKICK_API_URI
60
60
  });
61
61
 
62
62
  export async function POST(
@@ -5,9 +5,12 @@ afterEach(() => {
5
5
  vi.unstubAllEnvs();
6
6
  });
7
7
 
8
+ // The prefix the variables had before the rename, spelled in two parts so
9
+ // that the rename leaves it alone.
10
+ const OLD = 'INSTANT' + '_';
11
+
8
12
  describe('resumable stream server URL configuration', () => {
9
13
  test('throws and names the env var when no URL is configured', () => {
10
- vi.stubEnv('INSTANT_API_URI', '');
11
14
  vi.stubEnv('SIDEKICK_API_URI', '');
12
15
  expect(() =>
13
16
  createResumableStreamContext({ appId: 'app-id', adminToken: 'token' }),
@@ -17,38 +20,38 @@ describe('resumable stream server URL configuration', () => {
17
20
  });
18
21
 
19
22
  test('treats a blank SIDEKICK_API_URI as unset', () => {
20
- vi.stubEnv('INSTANT_API_URI', '');
21
23
  vi.stubEnv('SIDEKICK_API_URI', ' ');
22
24
  expect(() =>
23
25
  createResumableStreamContext({ appId: 'app-id', adminToken: 'token' }),
24
- ).toThrow(
25
- "No SidekickDB server URL configured. Pass `apiURI` to createResumableStreamContext() or set the SIDEKICK_API_URI environment variable, for example apiURI: 'https://sidekick.example.com'. SidekickDB has no default server.",
26
- );
26
+ ).toThrow('set the SIDEKICK_API_URI environment variable');
27
27
  });
28
28
 
29
- test('a blank SIDEKICK_API_URI does not hide INSTANT_API_URI', () => {
30
- vi.stubEnv('INSTANT_API_URI', 'https://sidekick.example.com');
31
- vi.stubEnv('SIDEKICK_API_URI', ' ');
29
+ test('reads SIDEKICK_API_URI, not the old name', () => {
30
+ vi.stubEnv('SIDEKICK_API_URI', 'https://sidekick.example.com');
32
31
  expect(() =>
33
32
  createResumableStreamContext({ appId: 'app-id', adminToken: 'token' }),
34
33
  ).not.toThrow();
34
+ vi.stubEnv('SIDEKICK_API_URI', '');
35
+ vi.stubEnv(`${OLD}API_URI`, 'https://sidekick.example.com');
36
+ expect(() =>
37
+ createResumableStreamContext({ appId: 'app-id', adminToken: 'token' }),
38
+ ).toThrow('set the SIDEKICK_API_URI environment variable');
35
39
  });
36
40
 
37
41
  test('names the app id and admin token variables when they are missing', () => {
38
42
  for (const name of [
39
43
  'SIDEKICK_APP_ID',
40
- 'INSTANT_APP_ID',
41
44
  'NEXT_PUBLIC_SIDEKICK_APP_ID',
42
- 'NEXT_PUBLIC_INSTANT_APP_ID',
43
45
  'SIDEKICK_APP_ADMIN_TOKEN',
44
- 'INSTANT_APP_ADMIN_TOKEN',
45
46
  ]) {
46
47
  vi.stubEnv(name, '');
47
48
  }
49
+ vi.stubEnv(`${OLD}APP_ID`, 'old-app-id');
48
50
  expect(() => createResumableStreamContext({ waitUntil: null })).toThrow(
49
51
  'SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID',
50
52
  );
51
- vi.stubEnv('INSTANT_APP_ID', 'old-app-id');
53
+ vi.stubEnv('SIDEKICK_APP_ID', 'app-id');
54
+ vi.stubEnv(`${OLD}APP_ADMIN_TOKEN`, 'old-token');
52
55
  expect(() => createResumableStreamContext({ waitUntil: null })).toThrow(
53
56
  'SIDEKICK_APP_ADMIN_TOKEN',
54
57
  );
@@ -8,23 +8,20 @@ export interface CreateResumableStreamContextOptions {
8
8
  */
9
9
  waitUntil: ((promise: Promise<unknown>) => void) | null;
10
10
  /**
11
- * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable
12
- * (or their older names, INSTANT_APP_ID and NEXT_PUBLIC_INSTANT_APP_ID).
11
+ * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.
13
12
  */
14
13
  appId?: string;
15
14
  /**
16
- * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable
17
- * (or its older name, INSTANT_APP_ADMIN_TOKEN).
15
+ * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable.
18
16
  */
19
17
  adminToken?: string;
20
18
  /**
21
19
  * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI
22
- * environment variable (or its older name, INSTANT_API_URI); one of the two
23
- * is required.
20
+ * environment variable; one of the two is required.
24
21
  */
25
22
  apiURI?: string;
26
23
  /**
27
- * Enable verbose logging from the underlying instant connection
24
+ * Enable verbose logging from the underlying SidekickDB connection
28
25
  */
29
26
  verbose?: boolean;
30
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,mCAAmC;IAClD;;;;;;OAMG;IACH,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACxD;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;;;;;OAYG;IACH,eAAe,EAAE,CACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,cAAc,CAAC,MAAM,CAAC,EACxC,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IAC5C;;;;;;OAMG;IACH,oBAAoB,EAAE,CACpB,QAAQ,EAAE,MAAM,EAChB,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;IACxD;;;;;;;OAOG;IACH,wBAAwB,EAAE,CACxB,QAAQ,EAAE,MAAM,EAChB,UAAU,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EAAE,MAAM,cAAc,CAAC,MAAM,CAAC,EACxC,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,MAAM,CAAC,CAAC;CACxE;AA2BD,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,mCAAmC,GAC3C,sBAAsB,CAgIxB"}
@@ -20,16 +20,10 @@ function skipCharactersTransformer(skipCharacters) {
20
20
  },
21
21
  });
22
22
  }
23
- /**
24
- * Reads an environment variable that can be set under its SidekickDB name
25
- * (`SIDEKICK_APP_ID`) or its older name (`INSTANT_APP_ID`). The SidekickDB name
26
- * wins; a blank value counts as unset.
27
- */
28
- function readEnv(sidekickName) {
29
- return [
30
- process.env[sidekickName],
31
- process.env[sidekickName.replace('SIDEKICK_', 'INSTANT_')],
32
- ].find((v) => v?.trim());
23
+ /** SidekickDB: an environment variable, with a blank value counting as unset. */
24
+ function readEnv(name) {
25
+ const value = process.env[name];
26
+ return value?.trim() ? value : undefined;
33
27
  }
34
28
  function createResumableStreamContext(options) {
35
29
  const appId = options.appId ||
@@ -80,7 +74,7 @@ function createResumableStreamContext(options) {
80
74
  await readStream.streamId();
81
75
  }
82
76
  catch (e) {
83
- if (e instanceof admin_1.InstantError &&
77
+ if (e instanceof admin_1.SidekickError &&
84
78
  e.hint?.errors?.[0]?.message === 'Stream is missing.') {
85
79
  return undefined;
86
80
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAoHA,oEAkIC;AAtPD,6CAA8E;AAqF9E,SAAS,yBAAyB,CAAC,cAAsB;IACvD,IAAI,QAAQ,GAAG,cAAc,CAAC;IAC9B,OAAO,IAAI,eAAe,CAAS;QACjC,SAAS,CAAC,KAAK,EAAE,UAA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QAC3E,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,KAAK,UAAU,iBAAiB,CAC9B,QAAgB;QAEhB,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC;YAC1B,QAAQ,EAAE,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE;SACnD,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,MAAM,EAAE,IAAI,EAAE,CAAC;YACjB,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,eAAe;QACf,oBAAoB;QACpB,wBAAwB;QACxB,iBAAiB;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import { Config, init, InstantError, requireApiURI } from '@sidekickdb/admin';\n\nexport interface CreateResumableStreamContextOptions {\n /**\n * A function that takes a promise and ensures that the current program stays alive\n * until the promise is resolved.\n *\n * If you are deploying to a server environment, where you don't have to worry about\n * the function getting suspended, pass in null.\n */\n waitUntil: ((promise: Promise<unknown>) => void) | null;\n /**\n * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable\n * (or their older names, INSTANT_APP_ID and NEXT_PUBLIC_INSTANT_APP_ID).\n */\n appId?: string;\n /**\n * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable\n * (or its older name, INSTANT_APP_ADMIN_TOKEN).\n */\n adminToken?: string;\n /**\n * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI\n * environment variable (or its older name, INSTANT_API_URI); one of the two\n * is required.\n */\n apiURI?: string;\n /**\n * Enable verbose logging from the underlying instant connection\n */\n verbose?: boolean;\n}\n\nexport interface ResumableStreamContext {\n /**\n * Creates or resumes a resumable stream.\n *\n * Does not throw if the underlying stream is already done. The output can always be read from the\n * stream and does not have to be saved to a separate table after streaming is completed.\n *\n * By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n /**\n * Resumes a stream that was previously created by `createNewResumableStream`.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumeExistingStream: (\n streamId: string,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null | undefined>;\n /**\n * Creates a new resumable stream.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n createNewResumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n\n /**\n * Checks if a stream with the given streamId exists.\n * @param streamId - The ID of the stream.\n * @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. \"DONE\" if the stream is fully done.\n */\n hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;\n}\n\nfunction skipCharactersTransformer(skipCharacters: number) {\n let skipLeft = skipCharacters;\n return new TransformStream<string>({\n transform(chunk, controller) {\n if (!skipLeft) {\n controller.enqueue(chunk);\n return;\n }\n if (skipLeft > chunk.length) {\n skipLeft -= chunk.length;\n return;\n }\n const remaining = chunk.slice(skipLeft);\n skipLeft = 0;\n controller.enqueue(remaining);\n },\n });\n}\n\n/**\n * Reads an environment variable that can be set under its SidekickDB name\n * (`SIDEKICK_APP_ID`) or its older name (`INSTANT_APP_ID`). The SidekickDB name\n * wins; a blank value counts as unset.\n */\nfunction readEnv(sidekickName: string): string | undefined {\n return [\n process.env[sidekickName],\n process.env[sidekickName.replace('SIDEKICK_', 'INSTANT_')],\n ].find((v) => v?.trim());\n}\n\nexport function createResumableStreamContext(\n options: CreateResumableStreamContextOptions,\n): ResumableStreamContext {\n const appId =\n options.appId ||\n readEnv('SIDEKICK_APP_ID') ||\n readEnv('NEXT_PUBLIC_SIDEKICK_APP_ID');\n if (!appId) {\n throw new Error(\n 'Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.',\n );\n }\n const adminToken = options.adminToken || readEnv('SIDEKICK_APP_ADMIN_TOKEN');\n if (!adminToken) {\n throw new Error(\n 'Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.',\n );\n }\n\n const apiURI = requireApiURI(options.apiURI || readEnv('SIDEKICK_API_URI'), {\n target: 'createResumableStreamContext()',\n envVar: 'SIDEKICK_API_URI',\n });\n\n const config: Config = { appId, adminToken, apiURI };\n\n if (options.verbose) {\n config.verbose = options.verbose;\n }\n\n const db = init(config);\n\n async function resumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n try {\n const s = await writeStream.streamId();\n const inputStream = makeStream();\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ streamId: s });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n } catch (e) {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n }\n }\n\n async function resumeExistingStream(\n streamId: string,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null | undefined> {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n try {\n await readStream.streamId();\n } catch (e) {\n if (\n e instanceof InstantError &&\n (e.hint as any)?.errors?.[0]?.message === 'Stream is missing.'\n ) {\n return undefined;\n }\n throw e;\n }\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function createNewResumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const inputStream = makeStream();\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n\n // Wait for stream to be acknowledged by the server\n await writeStream.streamId();\n\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function hasExistingStream(\n streamId: string,\n ): Promise<null | true | 'DONE'> {\n const data = await db.query({\n $streams: { $: { where: { clientId: streamId } } },\n });\n\n const stream = data?.$streams?.[0];\n if (stream?.done) {\n return 'DONE';\n }\n if (stream) {\n return true;\n }\n return null;\n }\n\n return {\n resumableStream,\n resumeExistingStream,\n createNewResumableStream,\n hasExistingStream,\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AA2GA,oEAkIC;AA7OD,6CAA+E;AAkF/E,SAAS,yBAAyB,CAAC,cAAsB;IACvD,IAAI,QAAQ,GAAG,cAAc,CAAC;IAC9B,OAAO,IAAI,eAAe,CAAS;QACjC,SAAS,CAAC,KAAK,EAAE,UAAU;YACzB,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,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Q,EAAE,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE;SACnD,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,MAAM,EAAE,IAAI,EAAE,CAAC;YACjB,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,eAAe;QACf,oBAAoB;QACpB,wBAAwB;QACxB,iBAAiB;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import { Config, init, SidekickError, requireApiURI } from '@sidekickdb/admin';\n\nexport interface CreateResumableStreamContextOptions {\n /**\n * A function that takes a promise and ensures that the current program stays alive\n * until the promise is resolved.\n *\n * If you are deploying to a server environment, where you don't have to worry about\n * the function getting suspended, pass in null.\n */\n waitUntil: ((promise: Promise<unknown>) => void) | null;\n /**\n * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.\n */\n appId?: string;\n /**\n * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable.\n */\n adminToken?: string;\n /**\n * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI\n * environment variable; one of the two is required.\n */\n apiURI?: string;\n /**\n * Enable verbose logging from the underlying SidekickDB connection\n */\n verbose?: boolean;\n}\n\nexport interface ResumableStreamContext {\n /**\n * Creates or resumes a resumable stream.\n *\n * Does not throw if the underlying stream is already done. The output can always be read from the\n * stream and does not have to be saved to a separate table after streaming is completed.\n *\n * By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n /**\n * Resumes a stream that was previously created by `createNewResumableStream`.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumeExistingStream: (\n streamId: string,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null | undefined>;\n /**\n * Creates a new resumable stream.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n createNewResumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n\n /**\n * Checks if a stream with the given streamId exists.\n * @param streamId - The ID of the stream.\n * @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. \"DONE\" if the stream is fully done.\n */\n hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;\n}\n\nfunction skipCharactersTransformer(skipCharacters: number) {\n let skipLeft = skipCharacters;\n return new TransformStream<string>({\n transform(chunk, controller) {\n if (!skipLeft) {\n controller.enqueue(chunk);\n return;\n }\n if (skipLeft > chunk.length) {\n skipLeft -= chunk.length;\n return;\n }\n const remaining = chunk.slice(skipLeft);\n skipLeft = 0;\n controller.enqueue(remaining);\n },\n });\n}\n\n/** SidekickDB: an environment variable, with a blank value counting as unset. */\nfunction readEnv(name: string): string | undefined {\n const value = process.env[name];\n return value?.trim() ? value : undefined;\n}\n\nexport function createResumableStreamContext(\n options: CreateResumableStreamContextOptions,\n): ResumableStreamContext {\n const appId =\n options.appId ||\n readEnv('SIDEKICK_APP_ID') ||\n readEnv('NEXT_PUBLIC_SIDEKICK_APP_ID');\n if (!appId) {\n throw new Error(\n 'Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.',\n );\n }\n const adminToken = options.adminToken || readEnv('SIDEKICK_APP_ADMIN_TOKEN');\n if (!adminToken) {\n throw new Error(\n 'Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.',\n );\n }\n\n const apiURI = requireApiURI(options.apiURI || readEnv('SIDEKICK_API_URI'), {\n target: 'createResumableStreamContext()',\n envVar: 'SIDEKICK_API_URI',\n });\n\n const config: Config = { appId, adminToken, apiURI };\n\n if (options.verbose) {\n config.verbose = options.verbose;\n }\n\n const db = init(config);\n\n async function resumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n try {\n const s = await writeStream.streamId();\n const inputStream = makeStream();\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ streamId: s });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n } catch (e) {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n }\n }\n\n async function resumeExistingStream(\n streamId: string,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null | undefined> {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n try {\n await readStream.streamId();\n } catch (e) {\n if (\n e instanceof SidekickError &&\n (e.hint as any)?.errors?.[0]?.message === 'Stream is missing.'\n ) {\n return undefined;\n }\n throw e;\n }\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function createNewResumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const inputStream = makeStream();\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n\n // Wait for stream to be acknowledged by the server\n await writeStream.streamId();\n\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function hasExistingStream(\n streamId: string,\n ): Promise<null | true | 'DONE'> {\n const data = await db.query({\n $streams: { $: { where: { clientId: streamId } } },\n });\n\n const stream = data?.$streams?.[0];\n if (stream?.done) {\n return 'DONE';\n }\n if (stream) {\n return true;\n }\n return null;\n }\n\n return {\n resumableStream,\n resumeExistingStream,\n createNewResumableStream,\n hasExistingStream,\n };\n}\n"]}
@@ -8,23 +8,20 @@ export interface CreateResumableStreamContextOptions {
8
8
  */
9
9
  waitUntil: ((promise: Promise<unknown>) => void) | null;
10
10
  /**
11
- * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable
12
- * (or their older names, INSTANT_APP_ID and NEXT_PUBLIC_INSTANT_APP_ID).
11
+ * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.
13
12
  */
14
13
  appId?: string;
15
14
  /**
16
- * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable
17
- * (or its older name, INSTANT_APP_ADMIN_TOKEN).
15
+ * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable.
18
16
  */
19
17
  adminToken?: string;
20
18
  /**
21
19
  * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI
22
- * environment variable (or its older name, INSTANT_API_URI); one of the two
23
- * is required.
20
+ * environment variable; one of the two is required.
24
21
  */
25
22
  apiURI?: string;
26
23
  /**
27
- * Enable verbose logging from the underlying instant connection
24
+ * Enable verbose logging from the underlying SidekickDB connection
28
25
  */
29
26
  verbose?: boolean;
30
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,mCAAmC;IAClD;;;;;;OAMG;IACH,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACxD;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;;;;;OAYG;IACH,eAAe,EAAE,CACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,cAAc,CAAC,MAAM,CAAC,EACxC,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IAC5C;;;;;;OAMG;IACH,oBAAoB,EAAE,CACpB,QAAQ,EAAE,MAAM,EAChB,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;IACxD;;;;;;;OAOG;IACH,wBAAwB,EAAE,CACxB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,cAAc,CAAC,MAAM,CAAC,EACxC,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,MAAM,CAAC,CA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AC;CACxE;AA2BD,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,mCAAmC,GAC3C,sBAAsB,CAgIxB"}
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { init, InstantError, requireApiURI } from '@sidekickdb/admin';
1
+ import { init, SidekickError, requireApiURI } from '@sidekickdb/admin';
2
2
  function skipCharactersTransformer(skipCharacters) {
3
3
  let skipLeft = skipCharacters;
4
4
  return new TransformStream({
@@ -17,16 +17,10 @@ function skipCharactersTransformer(skipCharacters) {
17
17
  },
18
18
  });
19
19
  }
20
- /**
21
- * Reads an environment variable that can be set under its SidekickDB name
22
- * (`SIDEKICK_APP_ID`) or its older name (`INSTANT_APP_ID`). The SidekickDB name
23
- * wins; a blank value counts as unset.
24
- */
25
- function readEnv(sidekickName) {
26
- return [
27
- process.env[sidekickName],
28
- process.env[sidekickName.replace('SIDEKICK_', 'INSTANT_')],
29
- ].find((v) => v?.trim());
20
+ /** SidekickDB: an environment variable, with a blank value counting as unset. */
21
+ function readEnv(name) {
22
+ const value = process.env[name];
23
+ return value?.trim() ? value : undefined;
30
24
  }
31
25
  export function createResumableStreamContext(options) {
32
26
  const appId = options.appId ||
@@ -77,7 +71,7 @@ export function createResumableStreamContext(options) {
77
71
  await readStream.streamId();
78
72
  }
79
73
  catch (e) {
80
- if (e instanceof InstantError &&
74
+ if (e instanceof SidekickError &&
81
75
  e.hint?.errors?.[0]?.message === 'Stream is missing.') {
82
76
  return undefined;
83
77
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,IAAI,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAqF9E,SAAS,yBAAyB,CAAC,cAAsB;IACvD,IAAI,QAAQ,GAAG,cAAc,CAAC;IAC9B,OAAO,IAAI,eAAe,CAAS;QACjC,SAAS,CAAC,KAAK,EAAE,UAAU;YACzB,IAAI,CAAC,QAA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C;IACpB,CAAC;IAED,KAAK,UAAU,iBAAiB,CAC9B,QAAgB;QAEhB,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC;YAC1B,QAAQ,EAAE,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE;SACnD,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,MAAM,EAAE,IAAI,EAAE,CAAC;YACjB,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,eAAe;QACf,oBAAoB;QACpB,wBAAwB;QACxB,iBAAiB;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import { Config, init, InstantError, requireApiURI } from '@sidekickdb/admin';\n\nexport interface CreateResumableStreamContextOptions {\n /**\n * A function that takes a promise and ensures that the current program stays alive\n * until the promise is resolved.\n *\n * If you are deploying to a server environment, where you don't have to worry about\n * the function getting suspended, pass in null.\n */\n waitUntil: ((promise: Promise<unknown>) => void) | null;\n /**\n * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable\n * (or their older names, INSTANT_APP_ID and NEXT_PUBLIC_INSTANT_APP_ID).\n */\n appId?: string;\n /**\n * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable\n * (or its older name, INSTANT_APP_ADMIN_TOKEN).\n */\n adminToken?: string;\n /**\n * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI\n * environment variable (or its older name, INSTANT_API_URI); one of the two\n * is required.\n */\n apiURI?: string;\n /**\n * Enable verbose logging from the underlying instant connection\n */\n verbose?: boolean;\n}\n\nexport interface ResumableStreamContext {\n /**\n * Creates or resumes a resumable stream.\n *\n * Does not throw if the underlying stream is already done. The output can always be read from the\n * stream and does not have to be saved to a separate table after streaming is completed.\n *\n * By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n /**\n * Resumes a stream that was previously created by `createNewResumableStream`.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumeExistingStream: (\n streamId: string,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null | undefined>;\n /**\n * Creates a new resumable stream.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n createNewResumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n\n /**\n * Checks if a stream with the given streamId exists.\n * @param streamId - The ID of the stream.\n * @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. \"DONE\" if the stream is fully done.\n */\n hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;\n}\n\nfunction skipCharactersTransformer(skipCharacters: number) {\n let skipLeft = skipCharacters;\n return new TransformStream<string>({\n transform(chunk, controller) {\n if (!skipLeft) {\n controller.enqueue(chunk);\n return;\n }\n if (skipLeft > chunk.length) {\n skipLeft -= chunk.length;\n return;\n }\n const remaining = chunk.slice(skipLeft);\n skipLeft = 0;\n controller.enqueue(remaining);\n },\n });\n}\n\n/**\n * Reads an environment variable that can be set under its SidekickDB name\n * (`SIDEKICK_APP_ID`) or its older name (`INSTANT_APP_ID`). The SidekickDB name\n * wins; a blank value counts as unset.\n */\nfunction readEnv(sidekickName: string): string | undefined {\n return [\n process.env[sidekickName],\n process.env[sidekickName.replace('SIDEKICK_', 'INSTANT_')],\n ].find((v) => v?.trim());\n}\n\nexport function createResumableStreamContext(\n options: CreateResumableStreamContextOptions,\n): ResumableStreamContext {\n const appId =\n options.appId ||\n readEnv('SIDEKICK_APP_ID') ||\n readEnv('NEXT_PUBLIC_SIDEKICK_APP_ID');\n if (!appId) {\n throw new Error(\n 'Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.',\n );\n }\n const adminToken = options.adminToken || readEnv('SIDEKICK_APP_ADMIN_TOKEN');\n if (!adminToken) {\n throw new Error(\n 'Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.',\n );\n }\n\n const apiURI = requireApiURI(options.apiURI || readEnv('SIDEKICK_API_URI'), {\n target: 'createResumableStreamContext()',\n envVar: 'SIDEKICK_API_URI',\n });\n\n const config: Config = { appId, adminToken, apiURI };\n\n if (options.verbose) {\n config.verbose = options.verbose;\n }\n\n const db = init(config);\n\n async function resumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n try {\n const s = await writeStream.streamId();\n const inputStream = makeStream();\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ streamId: s });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n } catch (e) {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n }\n }\n\n async function resumeExistingStream(\n streamId: string,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null | undefined> {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n try {\n await readStream.streamId();\n } catch (e) {\n if (\n e instanceof InstantError &&\n (e.hint as any)?.errors?.[0]?.message === 'Stream is missing.'\n ) {\n return undefined;\n }\n throw e;\n }\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function createNewResumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const inputStream = makeStream();\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n\n // Wait for stream to be acknowledged by the server\n await writeStream.streamId();\n\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function hasExistingStream(\n streamId: string,\n ): Promise<null | true | 'DONE'> {\n const data = await db.query({\n $streams: { $: { where: { clientId: streamId } } },\n });\n\n const stream = data?.$streams?.[0];\n if (stream?.done) {\n return 'DONE';\n }\n if (stream) {\n return true;\n }\n return null;\n }\n\n return {\n resumableStream,\n resumeExistingStream,\n createNewResumableStream,\n hasExistingStream,\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,IAAI,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAkF/E,SAAS,yBAAyB,CAAC,cAAsB;IACvD,IAAI,QAAQ,GAAG,cAAc,CAAC;IAC9B,OAAO,IAAI,eAAe,CAAS;QACjC,SAAS,CAAC,KAAK,EAAE,UAAU;YACzB,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,UAAU,CAAC,OAAO,CAAC,KAA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,EAAE,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE;SACnD,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,MAAM,EAAE,IAAI,EAAE,CAAC;YACjB,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,eAAe;QACf,oBAAoB;QACpB,wBAAwB;QACxB,iBAAiB;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import { Config, init, SidekickError, requireApiURI } from '@sidekickdb/admin';\n\nexport interface CreateResumableStreamContextOptions {\n /**\n * A function that takes a promise and ensures that the current program stays alive\n * until the promise is resolved.\n *\n * If you are deploying to a server environment, where you don't have to worry about\n * the function getting suspended, pass in null.\n */\n waitUntil: ((promise: Promise<unknown>) => void) | null;\n /**\n * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.\n */\n appId?: string;\n /**\n * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable.\n */\n adminToken?: string;\n /**\n * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI\n * environment variable; one of the two is required.\n */\n apiURI?: string;\n /**\n * Enable verbose logging from the underlying SidekickDB connection\n */\n verbose?: boolean;\n}\n\nexport interface ResumableStreamContext {\n /**\n * Creates or resumes a resumable stream.\n *\n * Does not throw if the underlying stream is already done. The output can always be read from the\n * stream and does not have to be saved to a separate table after streaming is completed.\n *\n * By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n /**\n * Resumes a stream that was previously created by `createNewResumableStream`.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumeExistingStream: (\n streamId: string,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null | undefined>;\n /**\n * Creates a new resumable stream.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n createNewResumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n\n /**\n * Checks if a stream with the given streamId exists.\n * @param streamId - The ID of the stream.\n * @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. \"DONE\" if the stream is fully done.\n */\n hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;\n}\n\nfunction skipCharactersTransformer(skipCharacters: number) {\n let skipLeft = skipCharacters;\n return new TransformStream<string>({\n transform(chunk, controller) {\n if (!skipLeft) {\n controller.enqueue(chunk);\n return;\n }\n if (skipLeft > chunk.length) {\n skipLeft -= chunk.length;\n return;\n }\n const remaining = chunk.slice(skipLeft);\n skipLeft = 0;\n controller.enqueue(remaining);\n },\n });\n}\n\n/** SidekickDB: an environment variable, with a blank value counting as unset. */\nfunction readEnv(name: string): string | undefined {\n const value = process.env[name];\n return value?.trim() ? value : undefined;\n}\n\nexport function createResumableStreamContext(\n options: CreateResumableStreamContextOptions,\n): ResumableStreamContext {\n const appId =\n options.appId ||\n readEnv('SIDEKICK_APP_ID') ||\n readEnv('NEXT_PUBLIC_SIDEKICK_APP_ID');\n if (!appId) {\n throw new Error(\n 'Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.',\n );\n }\n const adminToken = options.adminToken || readEnv('SIDEKICK_APP_ADMIN_TOKEN');\n if (!adminToken) {\n throw new Error(\n 'Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.',\n );\n }\n\n const apiURI = requireApiURI(options.apiURI || readEnv('SIDEKICK_API_URI'), {\n target: 'createResumableStreamContext()',\n envVar: 'SIDEKICK_API_URI',\n });\n\n const config: Config = { appId, adminToken, apiURI };\n\n if (options.verbose) {\n config.verbose = options.verbose;\n }\n\n const db = init(config);\n\n async function resumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n try {\n const s = await writeStream.streamId();\n const inputStream = makeStream();\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ streamId: s });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n } catch (e) {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n }\n }\n\n async function resumeExistingStream(\n streamId: string,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null | undefined> {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n try {\n await readStream.streamId();\n } catch (e) {\n if (\n e instanceof SidekickError &&\n (e.hint as any)?.errors?.[0]?.message === 'Stream is missing.'\n ) {\n return undefined;\n }\n throw e;\n }\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function createNewResumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const inputStream = makeStream();\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n\n // Wait for stream to be acknowledged by the server\n await writeStream.streamId();\n\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function hasExistingStream(\n streamId: string,\n ): Promise<null | true | 'DONE'> {\n const data = await db.query({\n $streams: { $: { where: { clientId: streamId } } },\n });\n\n const stream = data?.$streams?.[0];\n if (stream?.done) {\n return 'DONE';\n }\n if (stream) {\n return true;\n }\n return null;\n }\n\n return {\n resumableStream,\n resumeExistingStream,\n createNewResumableStream,\n hasExistingStream,\n };\n}\n"]}