@tensorpass/aiconnect 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +18 -2
- package/dist/callback.d.ts +2 -0
- package/dist/callback.js +4 -0
- package/dist/callback.js.map +1 -0
- package/dist/chatContent.d.ts +9 -0
- package/dist/chatContent.js +23 -0
- package/dist/chatContent.js.map +1 -0
- package/dist/cli/loopbackSignIn.d.ts +11 -0
- package/dist/cli/loopbackSignIn.js +94 -0
- package/dist/cli/loopbackSignIn.js.map +1 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +41 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/siteKeyCommand.d.ts +11 -0
- package/dist/cli/siteKeyCommand.js +31 -0
- package/dist/cli/siteKeyCommand.js.map +1 -0
- package/dist/cli/siteKeyPlacement.d.ts +3 -0
- package/dist/cli/siteKeyPlacement.js +56 -0
- package/dist/cli/siteKeyPlacement.js.map +1 -0
- package/dist/client.d.ts +43 -0
- package/dist/client.js +211 -0
- package/dist/client.js.map +1 -0
- package/dist/connectionState.d.ts +31 -0
- package/dist/connectionState.js +4 -0
- package/dist/connectionState.js.map +1 -0
- package/dist/guards/answerGuard.d.ts +14 -0
- package/dist/guards/answerGuard.js +189 -0
- package/dist/guards/answerGuard.js.map +1 -0
- package/dist/guards/chatGuard.d.ts +18 -0
- package/dist/guards/chatGuard.js +62 -0
- package/dist/guards/chatGuard.js.map +1 -0
- package/dist/guards/envelopes.d.ts +8 -0
- package/dist/guards/envelopes.js +49 -0
- package/dist/guards/envelopes.js.map +1 -0
- package/dist/guards/index.d.ts +8 -0
- package/dist/guards/index.js +8 -0
- package/dist/guards/index.js.map +1 -0
- package/dist/guards/policy.d.ts +28 -0
- package/dist/guards/policy.js +20 -0
- package/dist/guards/policy.js.map +1 -0
- package/dist/guards/questionGuard.d.ts +8 -0
- package/dist/guards/questionGuard.js +53 -0
- package/dist/guards/questionGuard.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/mcpToolSource.d.ts +13 -0
- package/dist/mcpToolSource.js +54 -0
- package/dist/mcpToolSource.js.map +1 -0
- package/dist/toolLoop.d.ts +18 -0
- package/dist/toolLoop.js +153 -0
- package/dist/toolLoop.js.map +1 -0
- package/dist/types.d.ts +98 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/visitorBrowser.d.ts +17 -0
- package/dist/visitorBrowser.js +72 -0
- package/dist/visitorBrowser.js.map +1 -0
- package/dist/walletProvider.d.ts +25 -0
- package/dist/walletProvider.js +42 -0
- package/dist/walletProvider.js.map +1 -0
- package/dist/webAccounts/finishSignIn.d.ts +2 -0
- package/dist/webAccounts/finishSignIn.js +46 -0
- package/dist/webAccounts/finishSignIn.js.map +1 -0
- package/dist/webAccounts/openAiCompatibleSession.d.ts +15 -0
- package/dist/webAccounts/openAiCompatibleSession.js +84 -0
- package/dist/webAccounts/openAiCompatibleSession.js.map +1 -0
- package/dist/webAccounts/openAiWire.d.ts +39 -0
- package/dist/webAccounts/openAiWire.js +133 -0
- package/dist/webAccounts/openAiWire.js.map +1 -0
- package/dist/webAccounts/openRouterAccount.d.ts +3 -0
- package/dist/webAccounts/openRouterAccount.js +64 -0
- package/dist/webAccounts/openRouterAccount.js.map +1 -0
- package/dist/webAccounts/pkce.d.ts +2 -0
- package/dist/webAccounts/pkce.js +17 -0
- package/dist/webAccounts/pkce.js.map +1 -0
- package/dist/webAccounts/serverSentEvents.d.ts +1 -0
- package/dist/webAccounts/serverSentEvents.js +62 -0
- package/dist/webAccounts/serverSentEvents.js.map +1 -0
- package/dist/webAccounts/signInWindow.d.ts +27 -0
- package/dist/webAccounts/signInWindow.js +164 -0
- package/dist/webAccounts/signInWindow.js.map +1 -0
- package/dist/webAccounts/tensorPassAccount.d.ts +9 -0
- package/dist/webAccounts/tensorPassAccount.js +128 -0
- package/dist/webAccounts/tensorPassAccount.js.map +1 -0
- package/dist/webAccounts/tensorPassPlan.d.ts +27 -0
- package/dist/webAccounts/tensorPassPlan.js +36 -0
- package/dist/webAccounts/tensorPassPlan.js.map +1 -0
- package/dist/webAccounts/webAccount.d.ts +30 -0
- package/dist/webAccounts/webAccount.js +19 -0
- package/dist/webAccounts/webAccount.js.map +1 -0
- package/dist/webAccounts/webAccountSource.d.ts +43 -0
- package/dist/webAccounts/webAccountSource.js +216 -0
- package/dist/webAccounts/webAccountSource.js.map +1 -0
- package/dist/webAccounts/webAccountStore.d.ts +27 -0
- package/dist/webAccounts/webAccountStore.js +84 -0
- package/dist/webAccounts/webAccountStore.js.map +1 -0
- package/dist/wireProtocols/anthropicMessages.d.ts +2 -0
- package/dist/wireProtocols/anthropicMessages.js +181 -0
- package/dist/wireProtocols/anthropicMessages.js.map +1 -0
- package/dist/wireProtocols/eventStream.d.ts +4 -0
- package/dist/wireProtocols/eventStream.js +32 -0
- package/dist/wireProtocols/eventStream.js.map +1 -0
- package/dist/wireProtocols/geminiContents.d.ts +2 -0
- package/dist/wireProtocols/geminiContents.js +201 -0
- package/dist/wireProtocols/geminiContents.js.map +1 -0
- package/dist/wireProtocols/openAiChat.d.ts +2 -0
- package/dist/wireProtocols/openAiChat.js +161 -0
- package/dist/wireProtocols/openAiChat.js.map +1 -0
- package/dist/wireProtocols/openAiResponses.d.ts +2 -0
- package/dist/wireProtocols/openAiResponses.js +226 -0
- package/dist/wireProtocols/openAiResponses.js.map +1 -0
- package/dist/wireProtocols/walletAnswer.d.ts +7 -0
- package/dist/wireProtocols/walletAnswer.js +50 -0
- package/dist/wireProtocols/walletAnswer.js.map +1 -0
- package/dist/wireProtocols/walletFetch.d.ts +3 -0
- package/dist/wireProtocols/walletFetch.js +101 -0
- package/dist/wireProtocols/walletFetch.js.map +1 -0
- package/dist/wireProtocols/wireProtocol.d.ts +31 -0
- package/dist/wireProtocols/wireProtocol.js +44 -0
- package/dist/wireProtocols/wireProtocol.js.map +1 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tensorpass/aiconnect
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The core of AI Connect. Your site's AI features run on the AI account each visitor already pays for, through the AI Wallet browser extension, so your site pays nothing for the inference. A visitor without the extension can sign in with OpenRouter, or with the TensorPass plan when you pass a site key.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @tensorpass/aiconnect
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { AiConnect } from '@tensorpass/aiconnect';
|
|
11
|
+
|
|
12
|
+
const client = new AiConnect();
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The package also holds the guards (`@tensorpass/aiconnect/guards`), the sign in return page (`@tensorpass/aiconnect/callback`) and the `aiconnect` command, which creates a site key from your terminal.
|
|
16
|
+
|
|
17
|
+
Docs: https://tensorpass.app/docs. JavaScript quickstart: https://tensorpass.app/docs/quickstart/javascript.
|
|
18
|
+
|
|
19
|
+
Apache License 2.0. The names AI Connect, AI Wallet and TensorPass and the TensorPass mark are not licensed.
|
package/dist/callback.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"callback.js","sourceRoot":"","sources":["../src/callback.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,+DAA+D;AAE/D,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC","sourcesContent":["// The return page of a web sign in on its own: `finishSignIn` with nothing else of the SDK, for a page\n// that imports it as a module, such as a static callback page.\n\nexport { finishSignIn } from './webAccounts/finishSignIn.ts';\nexport type { SignInReturn } from './webAccounts/finishSignIn.ts';\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ContentPart } from './types.ts';
|
|
2
|
+
export interface InlineData {
|
|
3
|
+
mediaType: string;
|
|
4
|
+
data: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function contentParts(content: string | ContentPart[]): ContentPart[];
|
|
7
|
+
export declare function textOf(content: string | ContentPart[]): string;
|
|
8
|
+
export declare function inlineData(url: string): InlineData | null;
|
|
9
|
+
export declare function dataUrl({ mediaType, data }: InlineData): string;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Reads a message's content the same way in every translation: as parts, as plain text, and an
|
|
2
|
+
// image's `data:` URL as its media type and base64 data.
|
|
3
|
+
const DATA_URL = /^data:([^;,]+);base64,(.*)$/s;
|
|
4
|
+
export function contentParts(content) {
|
|
5
|
+
if (typeof content !== 'string') {
|
|
6
|
+
return content;
|
|
7
|
+
}
|
|
8
|
+
return content ? [{ type: 'text', text: content }] : [];
|
|
9
|
+
}
|
|
10
|
+
export function textOf(content) {
|
|
11
|
+
return contentParts(content)
|
|
12
|
+
.map((part) => (part.type === 'text' ? part.text : ''))
|
|
13
|
+
.join('');
|
|
14
|
+
}
|
|
15
|
+
// The media type and data of a base64 `data:` URL, or null for any other URL.
|
|
16
|
+
export function inlineData(url) {
|
|
17
|
+
const match = DATA_URL.exec(url);
|
|
18
|
+
return match ? { mediaType: match[1], data: match[2] } : null;
|
|
19
|
+
}
|
|
20
|
+
export function dataUrl({ mediaType, data }) {
|
|
21
|
+
return `data:${mediaType};base64,${data}`;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=chatContent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chatContent.js","sourceRoot":"","sources":["../src/chatContent.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,yDAAyD;AASzD,MAAM,QAAQ,GAAG,8BAA8B,CAAC;AAEhD,MAAM,UAAU,YAAY,CAAC,OAA+B;IAC1D,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1D,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,OAA+B;IACpD,OAAO,YAAY,CAAC,OAAO,CAAC;SACzB,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;SACtD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACjC,OAAO,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAc;IACrD,OAAO,QAAQ,SAAS,WAAW,IAAI,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["// Reads a message's content the same way in every translation: as parts, as plain text, and an\n// image's `data:` URL as its media type and base64 data.\n\nimport type { ContentPart } from './types.ts';\n\nexport interface InlineData {\n mediaType: string;\n data: string;\n}\n\nconst DATA_URL = /^data:([^;,]+);base64,(.*)$/s;\n\nexport function contentParts(content: string | ContentPart[]): ContentPart[] {\n if (typeof content !== 'string') {\n return content;\n }\n return content ? [{ type: 'text', text: content }] : [];\n}\n\nexport function textOf(content: string | ContentPart[]): string {\n return contentParts(content)\n .map((part) => (part.type === 'text' ? part.text : ''))\n .join('');\n}\n\n// The media type and data of a base64 `data:` URL, or null for any other URL.\nexport function inlineData(url: string): InlineData | null {\n const match = DATA_URL.exec(url);\n return match ? { mediaType: match[1], data: match[2] } : null;\n}\n\nexport function dataUrl({ mediaType, data }: InlineData): string {\n return `data:${mediaType};base64,${data}`;\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const CLI_CLIENT_ID = "aiconnect-cli";
|
|
2
|
+
export declare const SIGN_IN_MS: number;
|
|
3
|
+
export type CliFetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
4
|
+
export interface SignInDeps {
|
|
5
|
+
gateway: string;
|
|
6
|
+
fetch: CliFetch;
|
|
7
|
+
print: (line: string) => void;
|
|
8
|
+
openBrowser: (url: string) => void;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
}
|
|
11
|
+
export declare function signIn(deps: SignInDeps): Promise<string>;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// The command line's sign in to TensorPass, the way a native app signs in (RFC 8252): it serves one request on
|
|
2
|
+
// the computer's loopback, on a port the system picks, and opens TensorPass's sign in in the developer's
|
|
3
|
+
// browser with a PKCE challenge, a state and that address. Once the developer approves, the browser comes back
|
|
4
|
+
// to the address with a code, which the command trades with its verifier for a token of scope `sites`. The
|
|
5
|
+
// server answers that one request and closes. A sign in that does not come back within ten minutes ends the
|
|
6
|
+
// command, through one timer.
|
|
7
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
8
|
+
import { createServer } from 'node:http';
|
|
9
|
+
export const CLI_CLIENT_ID = 'aiconnect-cli';
|
|
10
|
+
export const SIGN_IN_MS = 10 * 60_000;
|
|
11
|
+
const DONE_PAGE = 'You are signed in to TensorPass. The terminal continues, and you may close this tab.\n';
|
|
12
|
+
const DECLINED = 'The sign in was declined on TensorPass.';
|
|
13
|
+
const TIMED_OUT = 'No sign in came back within 10 minutes. Run the command again.';
|
|
14
|
+
const base64Url = (bytes) => bytes.toString('base64url');
|
|
15
|
+
function pkcePair() {
|
|
16
|
+
const verifier = base64Url(randomBytes(32));
|
|
17
|
+
return { verifier, challenge: base64Url(createHash('sha256').update(verifier).digest()) };
|
|
18
|
+
}
|
|
19
|
+
// The code of a request that answers this sign in, the refusal it carries, or null for any other request.
|
|
20
|
+
function callbackResult(params, state) {
|
|
21
|
+
if (params.get('state') !== state) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const code = params.get('code');
|
|
25
|
+
if (code) {
|
|
26
|
+
return code;
|
|
27
|
+
}
|
|
28
|
+
return new Error(params.get('error') === 'access_denied' ? DECLINED : 'TensorPass sent back no code.');
|
|
29
|
+
}
|
|
30
|
+
// Serves the one `/callback` request that carries this sign in's state, then closes.
|
|
31
|
+
async function listenForCallback(state, timeoutMs) {
|
|
32
|
+
const server = createServer();
|
|
33
|
+
await new Promise((resolve, reject) => {
|
|
34
|
+
server.once('error', reject);
|
|
35
|
+
server.listen(0, '127.0.0.1', resolve);
|
|
36
|
+
});
|
|
37
|
+
const { port } = server.address();
|
|
38
|
+
const code = new Promise((resolve, reject) => {
|
|
39
|
+
const finish = (outcome) => {
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
server.close();
|
|
42
|
+
if (typeof outcome === 'string') {
|
|
43
|
+
resolve(outcome);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
reject(outcome);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const timer = setTimeout(() => finish(new Error(TIMED_OUT)), timeoutMs);
|
|
50
|
+
server.on('request', (request, response) => {
|
|
51
|
+
const url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);
|
|
52
|
+
const result = url.pathname === '/callback' ? callbackResult(url.searchParams, state) : null;
|
|
53
|
+
const headers = { 'Content-Type': 'text/plain; charset=utf-8', Connection: 'close' };
|
|
54
|
+
if (result === null) {
|
|
55
|
+
response.writeHead(404, headers).end('This address answers the TensorPass sign in of the command line.\n');
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
response.writeHead(200, headers).end(typeof result === 'string' ? DONE_PAGE : `${result.message}\n`);
|
|
59
|
+
finish(result);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
return { redirectUri: `http://127.0.0.1:${port}/callback`, code };
|
|
63
|
+
}
|
|
64
|
+
function authorizeUrl(gateway, fields) {
|
|
65
|
+
const url = new URL(`${gateway}/signin`);
|
|
66
|
+
url.search = new URLSearchParams({
|
|
67
|
+
response_type: 'code', client_id: CLI_CLIENT_ID, code_challenge_method: 'S256', scope: 'sites', ...fields,
|
|
68
|
+
}).toString();
|
|
69
|
+
return url.toString();
|
|
70
|
+
}
|
|
71
|
+
async function tradeCode(deps, fields) {
|
|
72
|
+
const response = await deps.fetch(`${deps.gateway}/oauth/token`, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
75
|
+
body: new URLSearchParams({ grant_type: 'authorization_code', client_id: CLI_CLIENT_ID, ...fields }).toString(),
|
|
76
|
+
});
|
|
77
|
+
const body = await response.json().catch(() => ({}));
|
|
78
|
+
if (!response.ok || typeof body.access_token !== 'string') {
|
|
79
|
+
throw new Error(`TensorPass refused the sign in (${response.status} ${String(body.error ?? '')})`.trim());
|
|
80
|
+
}
|
|
81
|
+
return body.access_token;
|
|
82
|
+
}
|
|
83
|
+
// The access token of scope `sites`, once the developer signs in and approves in the browser.
|
|
84
|
+
export async function signIn(deps) {
|
|
85
|
+
const { verifier, challenge } = pkcePair();
|
|
86
|
+
const state = base64Url(randomBytes(16));
|
|
87
|
+
const callback = await listenForCallback(state, deps.timeoutMs ?? SIGN_IN_MS);
|
|
88
|
+
const url = authorizeUrl(deps.gateway, { redirect_uri: callback.redirectUri, code_challenge: challenge, state });
|
|
89
|
+
deps.print(`Sign in to TensorPass and approve in your browser: ${url}`);
|
|
90
|
+
deps.openBrowser(url);
|
|
91
|
+
const code = await callback.code;
|
|
92
|
+
return tradeCode(deps, { code, code_verifier: verifier, redirect_uri: callback.redirectUri });
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=loopbackSignIn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loopbackSignIn.js","sourceRoot":"","sources":["../../src/cli/loopbackSignIn.ts"],"names":[],"mappings":"AAAA,+GAA+G;AAC/G,yGAAyG;AACzG,+GAA+G;AAC/G,2GAA2G;AAC3G,4GAA4G;AAC5G,8BAA8B;AAE9B,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAGzC,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC;AAC7C,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,GAAG,MAAM,CAAC;AAkBtC,MAAM,SAAS,GAAG,wFAAwF,CAAC;AAC3G,MAAM,QAAQ,GAAG,yCAAyC,CAAC;AAC3D,MAAM,SAAS,GAAG,gEAAgE,CAAC;AAEnF,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAEjE,SAAS,QAAQ;IACf,MAAM,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;IAC5C,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;AAC5F,CAAC;AAED,0GAA0G;AA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GAAG,MAAM,iBAAiB,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,IAAI,UAAU,CAAC,CAAC;IAC9E,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,YAAY,EAAE,QAAQ,CAAC,WAAW,EAAE,cAAc,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;IACjH,IAAI,CAAC,KAAK,CAAC,sDAAsD,GAAG,EAAE,CAAC,CAAC;IACxE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACtB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC;IACjC,OAAO,SAAS,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;AAChG,CAAC","sourcesContent":["// The command line's sign in to TensorPass, the way a native app signs in (RFC 8252): it serves one request on\n// the computer's loopback, on a port the system picks, and opens TensorPass's sign in in the developer's\n// browser with a PKCE challenge, a state and that address. Once the developer approves, the browser comes back\n// to the address with a code, which the command trades with its verifier for a token of scope `sites`. The\n// server answers that one request and closes. A sign in that does not come back within ten minutes ends the\n// command, through one timer.\n\nimport { createHash, randomBytes } from 'node:crypto';\nimport { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\n\nexport const CLI_CLIENT_ID = 'aiconnect-cli';\nexport const SIGN_IN_MS = 10 * 60_000;\n\nexport type CliFetch = (input: string, init: RequestInit) => Promise<Response>;\n\nexport interface SignInDeps {\n gateway: string;\n fetch: CliFetch;\n print: (line: string) => void;\n // Opens the sign in in the developer's browser, where the computer has one.\n openBrowser: (url: string) => void;\n timeoutMs?: number;\n}\n\ninterface Callback {\n redirectUri: string;\n code: Promise<string>;\n}\n\nconst DONE_PAGE = 'You are signed in to TensorPass. The terminal continues, and you may close this tab.\\n';\nconst DECLINED = 'The sign in was declined on TensorPass.';\nconst TIMED_OUT = 'No sign in came back within 10 minutes. Run the command again.';\n\nconst base64Url = (bytes: Buffer) => bytes.toString('base64url');\n\nfunction pkcePair(): { verifier: string; challenge: string } {\n const verifier = base64Url(randomBytes(32));\n return { verifier, challenge: base64Url(createHash('sha256').update(verifier).digest()) };\n}\n\n// The code of a request that answers this sign in, the refusal it carries, or null for any other request.\nfunction callbackResult(params: URLSearchParams, state: string): string | Error | null {\n if (params.get('state') !== state) {\n return null;\n }\n const code = params.get('code');\n if (code) {\n return code;\n }\n return new Error(params.get('error') === 'access_denied' ? DECLINED : 'TensorPass sent back no code.');\n}\n\n// Serves the one `/callback` request that carries this sign in's state, then closes.\nasync function listenForCallback(state: string, timeoutMs: number): Promise<Callback> {\n const server = createServer();\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', resolve);\n });\n const { port } = server.address() as AddressInfo;\n const code = new Promise<string>((resolve, reject) => {\n const finish = (outcome: string | Error) => {\n clearTimeout(timer);\n server.close();\n if (typeof outcome === 'string') {\n resolve(outcome);\n } else {\n reject(outcome);\n }\n };\n const timer = setTimeout(() => finish(new Error(TIMED_OUT)), timeoutMs);\n server.on('request', (request, response) => {\n const url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);\n const result = url.pathname === '/callback' ? callbackResult(url.searchParams, state) : null;\n const headers = { 'Content-Type': 'text/plain; charset=utf-8', Connection: 'close' };\n if (result === null) {\n response.writeHead(404, headers).end('This address answers the TensorPass sign in of the command line.\\n');\n return;\n }\n response.writeHead(200, headers).end(typeof result === 'string' ? DONE_PAGE : `${result.message}\\n`);\n finish(result);\n });\n });\n return { redirectUri: `http://127.0.0.1:${port}/callback`, code };\n}\n\nfunction authorizeUrl(gateway: string, fields: Record<string, string>): string {\n const url = new URL(`${gateway}/signin`);\n url.search = new URLSearchParams({\n response_type: 'code', client_id: CLI_CLIENT_ID, code_challenge_method: 'S256', scope: 'sites', ...fields,\n }).toString();\n return url.toString();\n}\n\nasync function tradeCode(deps: SignInDeps, fields: Record<string, string>): Promise<string> {\n const response = await deps.fetch(`${deps.gateway}/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },\n body: new URLSearchParams({ grant_type: 'authorization_code', client_id: CLI_CLIENT_ID, ...fields }).toString(),\n });\n const body = await response.json().catch(() => ({})) as Record<string, unknown>;\n if (!response.ok || typeof body.access_token !== 'string') {\n throw new Error(`TensorPass refused the sign in (${response.status} ${String(body.error ?? '')})`.trim());\n }\n return body.access_token;\n}\n\n// The access token of scope `sites`, once the developer signs in and approves in the browser.\nexport async function signIn(deps: SignInDeps): Promise<string> {\n const { verifier, challenge } = pkcePair();\n const state = base64Url(randomBytes(16));\n const callback = await listenForCallback(state, deps.timeoutMs ?? SIGN_IN_MS);\n const url = authorizeUrl(deps.gateway, { redirect_uri: callback.redirectUri, code_challenge: challenge, state });\n deps.print(`Sign in to TensorPass and approve in your browser: ${url}`);\n deps.openBrowser(url);\n const code = await callback.code;\n return tradeCode(deps, { code, code_verifier: verifier, redirect_uri: callback.redirectUri });\n}\n"]}
|
package/dist/cli/main.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The AI Connect command line. `npx @tensorpass/aiconnect site-key <domain>` creates the TensorPass site key of
|
|
3
|
+
// a domain after the developer signs in to TensorPass in their browser, which comes back to the command on
|
|
4
|
+
// this computer. `--gateway <url>` names another TensorPass gateway, and `--no-browser` only prints the sign
|
|
5
|
+
// in's address, for a developer who opens it themselves.
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { PLAN_GATEWAY } from '@tensorpass/aiconnect';
|
|
8
|
+
import { runSiteKey } from "./siteKeyCommand.js";
|
|
9
|
+
const USAGE = 'Usage: npx @tensorpass/aiconnect site-key <domain> [--gateway <url>] [--no-browser]';
|
|
10
|
+
const OPENERS = { darwin: 'open', win32: 'explorer', linux: 'xdg-open' };
|
|
11
|
+
function openBrowser(url) {
|
|
12
|
+
const opener = OPENERS[process.platform];
|
|
13
|
+
if (opener) {
|
|
14
|
+
spawn(opener, [url], { stdio: 'ignore', detached: true }).on('error', () => undefined).unref();
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function optionValue(args, name) {
|
|
18
|
+
const index = args.indexOf(name);
|
|
19
|
+
return index >= 0 ? args[index + 1] : undefined;
|
|
20
|
+
}
|
|
21
|
+
async function main(args) {
|
|
22
|
+
const [command, domain] = args;
|
|
23
|
+
if (command !== 'site-key' || !domain || domain.startsWith('--')) {
|
|
24
|
+
console.error(USAGE);
|
|
25
|
+
process.exitCode = 2;
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
await runSiteKey({
|
|
29
|
+
domain,
|
|
30
|
+
gateway: (optionValue(args, '--gateway') ?? PLAN_GATEWAY).replace(/\/+$/, ''),
|
|
31
|
+
directory: process.cwd(),
|
|
32
|
+
fetch: (input, init) => fetch(input, init),
|
|
33
|
+
print: (line) => console.log(line),
|
|
34
|
+
openBrowser: args.includes('--no-browser') ? () => undefined : openBrowser,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
main(process.argv.slice(2)).catch((error) => {
|
|
38
|
+
console.error(error.message);
|
|
39
|
+
process.exitCode = 1;
|
|
40
|
+
});
|
|
41
|
+
//# sourceMappingURL=main.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"main.js","sourceRoot":"","sources":["../../src/cli/main.ts"],"names":[],"mappings":";AACA,gHAAgH;AAChH,2GAA2G;AAC3G,6GAA6G;AAC7G,yDAAyD;AAEzD,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEjD,MAAM,KAAK,GAAG,qFAAqF,CAAC;AACpG,MAAM,OAAO,GAA2B,EAAE,MAAM,EAAE,MAAM,EAAE,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E,IAAI,CAAC;QAC1C,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;QAClC,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW;KAC3E,CAAC,CAAC;AACL,CAAC;AAED,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAY,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n// The AI Connect command line. `npx @tensorpass/aiconnect site-key <domain>` creates the TensorPass site key of\n// a domain after the developer signs in to TensorPass in their browser, which comes back to the command on\n// this computer. `--gateway <url>` names another TensorPass gateway, and `--no-browser` only prints the sign\n// in's address, for a developer who opens it themselves.\n\nimport { spawn } from 'node:child_process';\nimport { PLAN_GATEWAY } from '@tensorpass/aiconnect';\nimport { runSiteKey } from './siteKeyCommand.ts';\n\nconst USAGE = 'Usage: npx @tensorpass/aiconnect site-key <domain> [--gateway <url>] [--no-browser]';\nconst OPENERS: Record<string, string> = { darwin: 'open', win32: 'explorer', linux: 'xdg-open' };\n\nfunction openBrowser(url: string): void {\n const opener = OPENERS[process.platform];\n if (opener) {\n spawn(opener, [url], { stdio: 'ignore', detached: true }).on('error', () => undefined).unref();\n }\n}\n\nfunction optionValue(args: string[], name: string): string | undefined {\n const index = args.indexOf(name);\n return index >= 0 ? args[index + 1] : undefined;\n}\n\nasync function main(args: string[]): Promise<void> {\n const [command, domain] = args;\n if (command !== 'site-key' || !domain || domain.startsWith('--')) {\n console.error(USAGE);\n process.exitCode = 2;\n return;\n }\n await runSiteKey({\n domain,\n gateway: (optionValue(args, '--gateway') ?? PLAN_GATEWAY).replace(/\\/+$/, ''),\n directory: process.cwd(),\n fetch: (input, init) => fetch(input, init),\n print: (line) => console.log(line),\n openBrowser: args.includes('--no-browser') ? () => undefined : openBrowser,\n });\n}\n\nmain(process.argv.slice(2)).catch((error: Error) => {\n console.error(error.message);\n process.exitCode = 1;\n});\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SignInDeps } from './loopbackSignIn.ts';
|
|
2
|
+
export interface SiteKeyRun extends SignInDeps {
|
|
3
|
+
domain: string;
|
|
4
|
+
directory: string;
|
|
5
|
+
}
|
|
6
|
+
export interface SiteKey {
|
|
7
|
+
key: string;
|
|
8
|
+
domain: string;
|
|
9
|
+
origins: string[];
|
|
10
|
+
}
|
|
11
|
+
export declare function runSiteKey(run: SiteKeyRun): Promise<SiteKey>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// `aiconnect site-key <domain>`: signs in to TensorPass in the developer's browser, creates the site key of
|
|
2
|
+
// the domain, and prints the key with where it goes in this project. The key is public: it names the site in
|
|
3
|
+
// the TensorPass sign in a visitor without AI Wallet opens, and works on https://<domain> and on localhost.
|
|
4
|
+
import { signIn } from "./loopbackSignIn.js";
|
|
5
|
+
import { detectStack, placementOf } from "./siteKeyPlacement.js";
|
|
6
|
+
async function createSiteKey(run, token) {
|
|
7
|
+
const response = await run.fetch(`${run.gateway}/_plan/site-keys`, {
|
|
8
|
+
method: 'POST',
|
|
9
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
|
10
|
+
body: JSON.stringify({ domain: run.domain }),
|
|
11
|
+
});
|
|
12
|
+
const body = await response.json().catch(() => ({}));
|
|
13
|
+
if (!response.ok || typeof body.key !== 'string') {
|
|
14
|
+
const message = body.error?.message ?? `HTTP ${response.status}`;
|
|
15
|
+
throw new Error(`TensorPass did not create the key: ${message}`);
|
|
16
|
+
}
|
|
17
|
+
return { key: body.key, domain: String(body.domain), origins: body.origins ?? [] };
|
|
18
|
+
}
|
|
19
|
+
export async function runSiteKey(run) {
|
|
20
|
+
const token = await signIn(run);
|
|
21
|
+
const siteKey = await createSiteKey(run, token);
|
|
22
|
+
run.print('');
|
|
23
|
+
run.print(`Site key of ${siteKey.domain}: ${siteKey.key}`);
|
|
24
|
+
run.print(`It works on ${siteKey.origins.join(', ')}. It is public, so it may sit in the site's code.`);
|
|
25
|
+
run.print('');
|
|
26
|
+
for (const line of placementOf(detectStack(run.directory), siteKey.key)) {
|
|
27
|
+
run.print(line);
|
|
28
|
+
}
|
|
29
|
+
return siteKey;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=siteKeyCommand.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"siteKeyCommand.js","sourceRoot":"","sources":["../../src/cli/siteKeyCommand.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,6GAA6G;AAC7G,4GAA4G;AAE5G,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAajE,KAAK,UAAU,aAAa,CAAC,GAAe,EAAE,KAAa;IACzD,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,OAAO,kBAAkB,EAAE;QACjE,MAAM,EAAE,MAAM;QACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAE,UAAU,KAAK,EAAE,EAAE;QACjF,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC;KAC7C,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAA4B,CAAC;IAChF,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,OAAO,IAAI,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;QACjD,MAAM,OAAO,GAAI,IAAI,CAAC,KAA0C,EAAE,OAAO,IAAI,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC;QACvG,MAAM,IAAI,KAAK,CAAC,sCAAsC,OAAO,EAAE,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,OAAO,EAAG,IAAI,CAAC,OAAgC,IAAI,EAAE,EAAE,CAAC;AAC/G,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,GAAe;IAC9C,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,GAAG,CAAC,CAAC;IAChC,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAChD,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACd,GAAG,CAAC,KAAK,CAAC,eAAe,OAAO,CAAC,MAAM,KAAK,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAC3D,GAAG,CAAC,KAAK,CAAC,eAAe,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;IACxG,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,WAAW,CAAC,WAAW,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACxE,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["// `aiconnect site-key <domain>`: signs in to TensorPass in the developer's browser, creates the site key of\n// the domain, and prints the key with where it goes in this project. The key is public: it names the site in\n// the TensorPass sign in a visitor without AI Wallet opens, and works on https://<domain> and on localhost.\n\nimport { signIn } from './loopbackSignIn.ts';\nimport type { SignInDeps } from './loopbackSignIn.ts';\nimport { detectStack, placementOf } from './siteKeyPlacement.ts';\n\nexport interface SiteKeyRun extends SignInDeps {\n domain: string;\n directory: string;\n}\n\nexport interface SiteKey {\n key: string;\n domain: string;\n origins: string[];\n}\n\nasync function createSiteKey(run: SiteKeyRun, token: string): Promise<SiteKey> {\n const response = await run.fetch(`${run.gateway}/_plan/site-keys`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify({ domain: run.domain }),\n });\n const body = await response.json().catch(() => ({})) as Record<string, unknown>;\n if (!response.ok || typeof body.key !== 'string') {\n const message = (body.error as { message?: string } | undefined)?.message ?? `HTTP ${response.status}`;\n throw new Error(`TensorPass did not create the key: ${message}`);\n }\n return { key: body.key, domain: String(body.domain), origins: (body.origins as string[] | undefined) ?? [] };\n}\n\nexport async function runSiteKey(run: SiteKeyRun): Promise<SiteKey> {\n const token = await signIn(run);\n const siteKey = await createSiteKey(run, token);\n run.print('');\n run.print(`Site key of ${siteKey.domain}: ${siteKey.key}`);\n run.print(`It works on ${siteKey.origins.join(', ')}. It is public, so it may sit in the site's code.`);\n run.print('');\n for (const line of placementOf(detectStack(run.directory), siteKey.key)) {\n run.print(line);\n }\n return siteKey;\n}\n"]}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Where a site key goes in the project the command runs in, read from its package.json and its files: a
|
|
2
|
+
// Next.js app, a Vite app, a WordPress site, or any page that loads the Web Components script.
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
function dependenciesOf(directory) {
|
|
6
|
+
const file = path.join(directory, 'package.json');
|
|
7
|
+
if (!existsSync(file)) {
|
|
8
|
+
return {};
|
|
9
|
+
}
|
|
10
|
+
try {
|
|
11
|
+
const manifest = JSON.parse(readFileSync(file, 'utf8'));
|
|
12
|
+
return { ...manifest.dependencies, ...manifest.devDependencies };
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return {};
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function detectStack(directory) {
|
|
19
|
+
const dependencies = dependenciesOf(directory);
|
|
20
|
+
if (dependencies.next) {
|
|
21
|
+
return 'next';
|
|
22
|
+
}
|
|
23
|
+
if (dependencies.vite) {
|
|
24
|
+
return 'vite';
|
|
25
|
+
}
|
|
26
|
+
const wordpress = ['wp-config.php', 'wp-content'].some((name) => existsSync(path.join(directory, name)));
|
|
27
|
+
return wordpress ? 'wordpress' : 'script';
|
|
28
|
+
}
|
|
29
|
+
// The lines that tell the developer, or their coding agent, where to put the key.
|
|
30
|
+
export function placementOf(stack, key) {
|
|
31
|
+
switch (stack) {
|
|
32
|
+
case 'next':
|
|
33
|
+
return [
|
|
34
|
+
'Next.js: add this line to .env.local (and to the host\'s environment variables):',
|
|
35
|
+
` NEXT_PUBLIC_TENSORPASS_SITE_KEY=${key}`,
|
|
36
|
+
'then create the client with it:',
|
|
37
|
+
' new AiConnect({ siteKey: process.env.NEXT_PUBLIC_TENSORPASS_SITE_KEY })',
|
|
38
|
+
];
|
|
39
|
+
case 'vite':
|
|
40
|
+
return [
|
|
41
|
+
'Vite: add this line to .env.local (and to the host\'s environment variables):',
|
|
42
|
+
` VITE_TENSORPASS_SITE_KEY=${key}`,
|
|
43
|
+
'then create the client with it:',
|
|
44
|
+
' new AiConnect({ siteKey: import.meta.env.VITE_TENSORPASS_SITE_KEY })',
|
|
45
|
+
];
|
|
46
|
+
case 'wordpress':
|
|
47
|
+
return ['WordPress: paste the key in Settings, AI Connect, TensorPass site key.'];
|
|
48
|
+
case 'script':
|
|
49
|
+
return [
|
|
50
|
+
'Script tag: put the key on the script that loads the Web Components or the loader:',
|
|
51
|
+
` <script src=".../aiconnect-elements.js" data-site-key="${key}" defer></script>`,
|
|
52
|
+
`or on the element itself: <aiconnect-chat site-key="${key}">. Shopify: the app embed's Site key setting.`,
|
|
53
|
+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AO,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC;AAC5C,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,WAAW,CAAC,KAAY,EAAE,GAAW;IACnD,QAAQ,KAAK,EAAE,CAAC;QACd,KAAK,MAAM;YACT,OAAO;gBACL,kFAAkF;gBAClF,qCAAqC,GAAG,EAAE;gBAC1C,iCAAiC;gBACjC,2EAA2E;aAC5E,CAAC;QACJ,KAAK,MAAM;YACT,OAAO;gBACL,+EAA+E;gBAC/E,8BAA8B,GAAG,EAAE;gBACnC,iCAAiC;gBACjC,wEAAwE;aACzE,CAAC;QACJ,KAAK,WAAW;YACd,OAAO,CAAC,wEAAwE,CAAC,CAAC;QACpF,KAAK,QAAQ;YACX,OAAO;gBACL,oFAAoF;gBACpF,4DAA4D,GAAG,mBAAmB;gBAClF,uDAAuD,GAAG,gDAAgD;aAC3G,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["// Where a site key goes in the project the command runs in, read from its package.json and its files: a\n// Next.js app, a Vite app, a WordPress site, or any page that loads the Web Components script.\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\n\nexport type Stack = 'next' | 'vite' | 'wordpress' | 'script';\n\nfunction dependenciesOf(directory: string): Record<string, string> {\n const file = path.join(directory, 'package.json');\n if (!existsSync(file)) {\n return {};\n }\n try {\n const manifest = JSON.parse(readFileSync(file, 'utf8')) as Record<string, Record<string, string> | undefined>;\n return { ...manifest.dependencies, ...manifest.devDependencies };\n } catch {\n return {};\n }\n}\n\nexport function detectStack(directory: string): Stack {\n const dependencies = dependenciesOf(directory);\n if (dependencies.next) {\n return 'next';\n }\n if (dependencies.vite) {\n return 'vite';\n }\n const wordpress = ['wp-config.php', 'wp-content'].some((name) => existsSync(path.join(directory, name)));\n return wordpress ? 'wordpress' : 'script';\n}\n\n// The lines that tell the developer, or their coding agent, where to put the key.\nexport function placementOf(stack: Stack, key: string): string[] {\n switch (stack) {\n case 'next':\n return [\n 'Next.js: add this line to .env.local (and to the host\\'s environment variables):',\n ` NEXT_PUBLIC_TENSORPASS_SITE_KEY=${key}`,\n 'then create the client with it:',\n ' new AiConnect({ siteKey: process.env.NEXT_PUBLIC_TENSORPASS_SITE_KEY })',\n ];\n case 'vite':\n return [\n 'Vite: add this line to .env.local (and to the host\\'s environment variables):',\n ` VITE_TENSORPASS_SITE_KEY=${key}`,\n 'then create the client with it:',\n ' new AiConnect({ siteKey: import.meta.env.VITE_TENSORPASS_SITE_KEY })',\n ];\n case 'wordpress':\n return ['WordPress: paste the key in Settings, AI Connect, TensorPass site key.'];\n case 'script':\n return [\n 'Script tag: put the key on the script that loads the Web Components or the loader:',\n ` <script src=\".../aiconnect-elements.js\" data-site-key=\"${key}\" defer></script>`,\n `or on the element itself: <aiconnect-chat site-key=\"${key}\">. Shopify: the app embed's Site key setting.`,\n ];\n }\n}\n"]}
|